Scene.cs 252 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.IO;
  31. using System.Runtime;
  32. using System.Runtime.CompilerServices;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Timers;
  36. using Nini.Config;
  37. using OpenMetaverse;
  38. using OpenMetaverse.StructuredData;
  39. using OpenSim.Framework;
  40. using OpenSim.Framework.Monitoring;
  41. using OpenSim.Services.Interfaces;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes.Serialization;
  44. using OpenSim.Region.PhysicsModules.SharedBase;
  45. using Timer = System.Timers.Timer;
  46. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  47. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  48. using PermissionMask = OpenSim.Framework.PermissionMask;
  49. namespace OpenSim.Region.Framework.Scenes
  50. {
  51. public delegate bool FilterAvatarList(ScenePresence avatar);
  52. public partial class Scene : SceneBase
  53. {
  54. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  55. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  56. public delegate void SynchronizeSceneHandler(Scene scene);
  57. #region Fields
  58. /// <summary>
  59. /// Show debug information about animations.
  60. /// </summary>
  61. public bool DebugAnimations { get; set; }
  62. /// <summary>
  63. /// Show debug information about teleports.
  64. /// </summary>
  65. public bool DebugTeleporting { get; set; }
  66. /// <summary>
  67. /// Show debug information about the scene loop.
  68. /// </summary>
  69. public bool DebugUpdates { get; set; }
  70. /// <summary>
  71. /// If true then the scene is saved to persistent storage periodically, every m_update_backup frames and
  72. /// if objects meet required conditions (m_dontPersistBefore and m_dontPersistAfter).
  73. /// </summary>
  74. /// <remarks>
  75. /// Even if false, the scene will still be saved on clean shutdown.
  76. /// FIXME: Currently, setting this to false will mean that objects are not periodically returned from parcels.
  77. /// This needs to be fixed.
  78. /// </remarks>
  79. public bool PeriodicBackup { get; set; }
  80. /// <summary>
  81. /// If false then the scene is never saved to persistence storage even if PeriodicBackup == true and even
  82. /// if the scene is being shut down for the final time.
  83. /// </summary>
  84. public bool UseBackup { get; set; }
  85. /// <summary>
  86. /// If false then physical objects are disabled, though collisions will continue as normal.
  87. /// </summary>
  88. public bool PhysicsEnabled
  89. {
  90. get
  91. {
  92. return m_physicsEnabled;
  93. }
  94. set
  95. {
  96. m_physicsEnabled = value;
  97. if (PhysicsScene is IPhysicsParameters parameters)
  98. {
  99. parameters.SetPhysicsParameter(
  100. "Active", m_physicsEnabled.ToString(), PhysParameterEntry.APPLY_TO_NONE);
  101. }
  102. }
  103. }
  104. private bool m_physicsEnabled;
  105. /// <summary>
  106. /// If false then scripts are not enabled on the simulator
  107. /// </summary>
  108. public bool ScriptsEnabled
  109. {
  110. get { return m_scripts_enabled; }
  111. set
  112. {
  113. if (m_scripts_enabled != value)
  114. {
  115. if (!value)
  116. {
  117. m_log.Info("Stopping all Scripts in Scene");
  118. EntityBase[] entities = Entities.GetEntities();
  119. foreach (EntityBase ent in entities)
  120. {
  121. if (ent is SceneObjectGroup group)
  122. group.RemoveScriptInstances(false);
  123. }
  124. }
  125. else
  126. {
  127. m_log.Info("Starting all Scripts in Scene");
  128. EntityBase[] entities = Entities.GetEntities();
  129. foreach (EntityBase ent in entities)
  130. {
  131. if (ent is SceneObjectGroup sog)
  132. {
  133. sog.CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  134. sog.ResumeScripts();
  135. }
  136. }
  137. }
  138. m_scripts_enabled = value;
  139. }
  140. }
  141. }
  142. private bool m_scripts_enabled;
  143. public bool ClampNegativeZ
  144. {
  145. get { return m_clampNegativeZ; }
  146. }
  147. private readonly bool m_clampNegativeZ = false;
  148. /// <summary>
  149. /// Used to prevent simultaneous calls to code that adds and removes agents.
  150. /// </summary>
  151. private readonly object m_removeClientLock = new();
  152. /// <summary>
  153. /// Statistical information for this scene.
  154. /// </summary>
  155. public SimStatsReporter StatsReporter { get; private set; }
  156. /// <summary>
  157. /// Controls whether physics can be applied to prims. Even if false, prims still have entries in a
  158. /// PhysicsScene in order to perform collision detection
  159. /// </summary>
  160. public bool PhysicalPrims { get; private set; }
  161. /// <summary>
  162. /// Controls whether prims can be collided with.
  163. /// </summary>
  164. /// <remarks>
  165. /// If this is set to false then prims cannot be subject to physics either.
  166. /// </summary>
  167. public bool CollidablePrims { get; private set; }
  168. /// <summary>
  169. /// Minimum value of the size of a non-physical prim in each axis
  170. /// </summary>
  171. public float m_minNonphys = 0.001f;
  172. /// <summary>
  173. /// Maximum value of the size of a non-physical prim in each axis
  174. /// </summary>
  175. public float m_maxNonphys = 256;
  176. /// <summary>
  177. /// Minimum value of the size of a physical prim in each axis
  178. /// </summary>
  179. public float m_minPhys = 0.01f;
  180. /// <summary>
  181. /// Maximum value of the size of a physical prim in each axis
  182. /// </summary>
  183. public float m_maxPhys = 10;
  184. /// <summary>
  185. /// Max prims an object will hold
  186. /// </summary>
  187. public int m_linksetCapacity = 0;
  188. public bool m_clampPrimSize;
  189. public bool m_trustBinaries;
  190. public bool m_allowScriptCrossings = true;
  191. /// <summary>
  192. /// use legacy sittarget offsets to avoid contents breaks
  193. /// to compensate for SL bug
  194. /// </summary>
  195. public bool LegacySitOffsets = true;
  196. /// <summary>
  197. /// Can avatars cross from and to this region?
  198. /// </summary>
  199. public bool AllowAvatarCrossing { get; set; }
  200. /// Max prims an Physical object will hold
  201. /// </summary>
  202. ///
  203. public int m_linksetPhysCapacity = 0;
  204. public int m_LinkSetDataLimit = 32 * 1024;
  205. /// <summary>
  206. /// When placed outside the region's border, do we transfer the objects or
  207. /// do we keep simulating them here?
  208. /// </summary>
  209. public bool DisableObjectTransfer { get; set; }
  210. public bool m_useFlySlow;
  211. public bool m_useTrashOnDelete = true;
  212. protected float m_defaultDrawDistance = 255f;
  213. protected float m_defaultCullingDrawDistance = 16f;
  214. public float DefaultDrawDistance
  215. {
  216. get { return ObjectsCullingByDistance?m_defaultCullingDrawDistance:m_defaultDrawDistance; }
  217. }
  218. protected float m_maxDrawDistance = 512.0f;
  219. // protected float m_maxDrawDistance = 256.0f;
  220. public float MaxDrawDistance
  221. {
  222. get { return m_maxDrawDistance; }
  223. }
  224. protected float m_maxRegionViewDistance = 255f;
  225. public float MaxRegionViewDistance
  226. {
  227. get { return m_maxRegionViewDistance; }
  228. }
  229. protected float m_minRegionViewDistance = 96f;
  230. public float MinRegionViewDistance
  231. {
  232. get { return m_minRegionViewDistance; }
  233. }
  234. private readonly List<string> m_AllowedViewers = new();
  235. private readonly List<string> m_BannedViewers = new();
  236. // TODO: need to figure out how allow client agents but deny
  237. // root agents when ACL denies access to root agent
  238. public bool m_strictAccessControl = true;
  239. public bool m_seeIntoBannedRegion = false;
  240. public int MaxUndoCount = 5;
  241. public bool SeeIntoRegion { get; set; }
  242. // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
  243. public bool LoginLock = false;
  244. public bool StartDisabled = false;
  245. public bool LoadingPrims;
  246. public IXfer XferManager;
  247. // the minimum time that must elapse before a changed object will be considered for persisted
  248. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  249. // the maximum time that must elapse before a changed object will be considered for persisted
  250. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  251. protected int m_splitRegionID;
  252. protected Timer m_restartWaitTimer = new();
  253. protected Timer m_timerWatchdog = new();
  254. protected List<RegionInfo> m_regionRestartNotifyList = new();
  255. protected List<RegionInfo> m_neighbours = new();
  256. protected string m_simulatorVersion = "OpenSimulator Server";
  257. protected AgentCircuitManager m_authenticateHandler;
  258. protected SceneCommunicationService m_sceneGridService;
  259. protected ISnmpModule m_snmpService = null;
  260. protected ISimulationDataService m_SimulationDataService;
  261. protected IEstateDataService m_EstateDataService;
  262. protected IAssetService m_AssetService;
  263. protected IAuthorizationService m_AuthorizationService;
  264. protected IInventoryService m_InventoryService;
  265. protected IGridService m_GridService;
  266. protected ILibraryService m_LibraryService;
  267. protected ISimulationService m_simulationService;
  268. protected IAuthenticationService m_AuthenticationService;
  269. protected IPresenceService m_PresenceService;
  270. protected IUserAccountService m_UserAccountService;
  271. protected IAvatarService m_AvatarService;
  272. protected IGridUserService m_GridUserService;
  273. protected IAgentPreferencesService m_AgentPreferencesService;
  274. protected IXMLRPC m_xmlrpcModule;
  275. protected IWorldComm m_worldCommModule;
  276. protected IAvatarFactoryModule m_AvatarFactory;
  277. protected IConfigSource m_config;
  278. protected IRegionSerialiserModule m_serialiser;
  279. protected IDialogModule m_dialogModule;
  280. protected ICapabilitiesModule m_capsModule;
  281. protected IGroupsModule m_groupsModule;
  282. private readonly Dictionary<string, string> m_extraSettings;
  283. /// <summary>
  284. /// Current scene frame number
  285. /// </summary>
  286. public uint Frame
  287. {
  288. get;
  289. protected set;
  290. }
  291. /// <summary>
  292. /// Frame time
  293. /// </remarks>
  294. public float FrameTime { get; private set; }
  295. public int FrameTimeWarnPercent { get; private set; }
  296. public int FrameTimeCritPercent { get; private set; }
  297. // Normalize the frame related stats to nominal 55fps for viewer and scripts option
  298. // see SimStatsReporter.cs
  299. public bool Normalized55FPS { get; private set; }
  300. private readonly int m_update_physics = 1;
  301. private readonly int m_update_entitymovement = 1;
  302. private readonly int m_update_objects = 1;
  303. private readonly int m_update_presences = 1; // Update scene presence movements
  304. private readonly int m_update_events = 1;
  305. private readonly int m_update_backup = 200;
  306. private readonly int m_update_terrain = 1000;
  307. private readonly int m_update_coarse_locations = 5;
  308. private readonly int m_update_temp_cleaning = 180;
  309. private float agentMS;
  310. private float frameMS;
  311. private float physicsMS2;
  312. private float physicsMS;
  313. private float otherMS;
  314. private float tempOnRezMS;
  315. private float eventMS;
  316. private float backupMS;
  317. private float terrainMS;
  318. private float landMS;
  319. /// <summary>
  320. /// Tick at which the last frame was processed.
  321. /// </summary>
  322. private int m_lastFrameTick;
  323. /// <summary>
  324. /// Total script execution time (in Stopwatch Ticks) since the last frame
  325. /// </summary>
  326. private long m_scriptExecutionTime = 0;
  327. /// <summary>
  328. /// Signals whether temporary objects are currently being cleaned up. Needed because this is launched
  329. /// asynchronously from the update loop.
  330. /// </summary>
  331. private bool m_cleaningTemps = false;
  332. private bool m_sendingCoarseLocations = false; // same for async course locations sending
  333. // TODO: Possibly stop other classes being able to manipulate this directly.
  334. private readonly SceneGraph m_sceneGraph;
  335. private readonly Timer m_restartTimer = new(15000); // Wait before firing
  336. private volatile bool m_backingup;
  337. private readonly Dictionary<UUID, ReturnInfo> m_returns = new();
  338. private readonly HashSet<UUID> m_groupsWithTargets = new();
  339. private readonly string m_defaultScriptEngine;
  340. private int m_unixStartTime;
  341. public int UnixStartTime
  342. {
  343. get { return m_unixStartTime; }
  344. }
  345. /// <summary>
  346. /// Tick at which the last login occurred.
  347. /// </summary>
  348. private int m_LastLogin;
  349. private int m_lastIncoming;
  350. private int m_lastOutgoing;
  351. private int m_hbRestarts = 0;
  352. /// <summary>
  353. /// Thread that runs the scene loop.
  354. /// </summary>
  355. private Thread m_heartbeatThread;
  356. /// <summary>
  357. /// True if these scene is in the process of shutting down or is shutdown.
  358. /// </summary>
  359. public bool ShuttingDown
  360. {
  361. get { return m_shuttingDown; }
  362. }
  363. private volatile bool m_shuttingDown;
  364. /// <summary>
  365. /// Is the scene active?
  366. /// </summary>
  367. /// <remarks>
  368. /// If false, update loop is not being run, though after setting to false update may still
  369. /// be active for a period (and IsRunning will still be true). Updates can still be triggered manually if
  370. /// the scene is not active.
  371. /// </remarks>
  372. public bool Active
  373. {
  374. get { return m_active; }
  375. set
  376. {
  377. if (value)
  378. {
  379. if (!m_active)
  380. Start(false);
  381. }
  382. else
  383. {
  384. // This appears assymetric with Start() above but is not - setting m_active = false stops the loops
  385. // XXX: Possibly this should be in an explicit Stop() method for symmetry.
  386. m_active = false;
  387. }
  388. }
  389. }
  390. private volatile bool m_active;
  391. /// <summary>
  392. /// If true then updates are running. This may be true for a short period after a scene is de-activated.
  393. /// </summary>
  394. public bool IsRunning
  395. {
  396. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  397. get { return m_isRunning; }
  398. }
  399. private volatile bool m_isRunning;
  400. private bool m_firstHeartbeat = true;
  401. // private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
  402. // private bool m_reprioritizationEnabled = true;
  403. // private double m_reprioritizationInterval = 5000.0;
  404. // private double m_rootReprioritizationDistance = 10.0;
  405. // private double m_childReprioritizationDistance = 20.0;
  406. private readonly Timer m_mapGenerationTimer = new();
  407. private readonly bool m_generateMaptiles;
  408. protected int m_lastHealth = -1;
  409. protected int m_lastUsers = -1;
  410. #endregion Fields
  411. #region Properties
  412. /* Used by the loadbalancer plugin on GForge */
  413. public int SplitRegionID
  414. {
  415. get { return m_splitRegionID; }
  416. set { m_splitRegionID = value; }
  417. }
  418. public new float TimeDilation
  419. {
  420. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  421. }
  422. public void setThreadCount(int inUseThreads)
  423. {
  424. // Just pass the thread count information on its way as the Scene
  425. // does not require the value for anything at this time
  426. StatsReporter.SetThreadCount(inUseThreads);
  427. }
  428. public SceneCommunicationService SceneGridService
  429. {
  430. get { return m_sceneGridService; }
  431. }
  432. public ISnmpModule SnmpService
  433. {
  434. get
  435. {
  436. m_snmpService ??= RequestModuleInterface<ISnmpModule>();
  437. return m_snmpService;
  438. }
  439. }
  440. public ISimulationDataService SimulationDataService
  441. {
  442. get
  443. {
  444. if (m_SimulationDataService is null)
  445. {
  446. m_SimulationDataService = RequestModuleInterface<ISimulationDataService>();
  447. if (m_SimulationDataService is null)
  448. {
  449. throw new Exception("No ISimulationDataService available.");
  450. }
  451. }
  452. return m_SimulationDataService;
  453. }
  454. }
  455. public IEstateDataService EstateDataService
  456. {
  457. get
  458. {
  459. if (m_EstateDataService is null)
  460. {
  461. m_EstateDataService = EstateDataServiceSafe;
  462. if (m_EstateDataService is null)
  463. {
  464. throw new Exception("No IEstateDataService available.");
  465. }
  466. }
  467. return m_EstateDataService;
  468. }
  469. }
  470. /// <summary>
  471. /// Similar to 'EstateDataService', but if the service isn't found returns null instead of throwing an exception.
  472. /// </summary>
  473. public IEstateDataService EstateDataServiceSafe
  474. {
  475. get
  476. {
  477. m_EstateDataService ??= RequestModuleInterface<IEstateDataService>();
  478. return m_EstateDataService;
  479. }
  480. }
  481. public IAssetService AssetService
  482. {
  483. get
  484. {
  485. if (m_AssetService is null)
  486. {
  487. m_AssetService = RequestModuleInterface<IAssetService>();
  488. if (m_AssetService is null)
  489. {
  490. throw new Exception("No IAssetService available.");
  491. }
  492. }
  493. return m_AssetService;
  494. }
  495. }
  496. public IAuthorizationService AuthorizationService
  497. {
  498. get
  499. {
  500. m_AuthorizationService ??= RequestModuleInterface<IAuthorizationService>();
  501. return m_AuthorizationService;
  502. }
  503. }
  504. public IInventoryService InventoryService
  505. {
  506. get
  507. {
  508. if (m_InventoryService is null)
  509. {
  510. m_InventoryService = RequestModuleInterface<IInventoryService>();
  511. if (m_InventoryService is null)
  512. {
  513. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  514. }
  515. }
  516. return m_InventoryService;
  517. }
  518. }
  519. public IGridService GridService
  520. {
  521. get
  522. {
  523. if (m_GridService is null)
  524. {
  525. m_GridService = RequestModuleInterface<IGridService>();
  526. if (m_GridService is null)
  527. {
  528. throw new Exception("No IGridService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  529. }
  530. }
  531. return m_GridService;
  532. }
  533. }
  534. public ILibraryService LibraryService
  535. {
  536. get
  537. {
  538. m_LibraryService ??= RequestModuleInterface<ILibraryService>();
  539. return m_LibraryService;
  540. }
  541. }
  542. public ISimulationService SimulationService
  543. {
  544. get
  545. {
  546. m_simulationService ??= RequestModuleInterface<ISimulationService>();
  547. return m_simulationService;
  548. }
  549. }
  550. public IAuthenticationService AuthenticationService
  551. {
  552. get
  553. {
  554. m_AuthenticationService ??= RequestModuleInterface<IAuthenticationService>();
  555. return m_AuthenticationService;
  556. }
  557. }
  558. public IPresenceService PresenceService
  559. {
  560. get
  561. {
  562. m_PresenceService ??= RequestModuleInterface<IPresenceService>();
  563. return m_PresenceService;
  564. }
  565. }
  566. public IUserAccountService UserAccountService
  567. {
  568. get
  569. {
  570. m_UserAccountService ??= RequestModuleInterface<IUserAccountService>();
  571. return m_UserAccountService;
  572. }
  573. }
  574. public IAvatarService AvatarService
  575. {
  576. get
  577. {
  578. m_AvatarService ??= RequestModuleInterface<IAvatarService>();
  579. return m_AvatarService;
  580. }
  581. }
  582. public IGridUserService GridUserService
  583. {
  584. get
  585. {
  586. m_GridUserService ??= RequestModuleInterface<IGridUserService>();
  587. return m_GridUserService;
  588. }
  589. }
  590. public IAgentPreferencesService AgentPreferencesService
  591. {
  592. get
  593. {
  594. m_AgentPreferencesService ??= RequestModuleInterface<IAgentPreferencesService>();
  595. return m_AgentPreferencesService;
  596. }
  597. }
  598. public IAttachmentsModule AttachmentsModule { get; set; }
  599. public IEntityTransferModule EntityTransferModule { get; private set; }
  600. public IAgentAssetTransactions AgentTransactionsModule { get; private set; }
  601. public IUserManagement UserManagementModule { get; private set; }
  602. public IAvatarFactoryModule AvatarFactory
  603. {
  604. get { return m_AvatarFactory; }
  605. }
  606. public ICapabilitiesModule CapsModule
  607. {
  608. get { return m_capsModule; }
  609. }
  610. public int MonitorFrameTime { get { return (int)frameMS; } }
  611. public int MonitorPhysicsUpdateTime { get { return (int)physicsMS; } }
  612. public int MonitorPhysicsSyncTime { get { return (int)physicsMS2; } }
  613. public int MonitorOtherTime { get { return (int)otherMS; } }
  614. public int MonitorTempOnRezTime { get { return (int)tempOnRezMS; } }
  615. public int MonitorEventTime { get { return (int)eventMS; } } // This may need to be divided into each event?
  616. public int MonitorBackupTime { get { return (int)backupMS; } }
  617. public int MonitorTerrainTime { get { return (int)terrainMS; } }
  618. public int MonitorLandTime { get { return (int)landMS; } }
  619. public int MonitorLastFrameTick { get { return m_lastFrameTick; } }
  620. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get; set; }
  621. public bool IsReprioritizationEnabled { get; set; }
  622. public float ReprioritizationInterval { get; set; }
  623. public float ReprioritizationDistance { get; set; }
  624. private readonly float m_minReprioritizationDistance = 32f;
  625. public bool ObjectsCullingByDistance = false;
  626. private readonly ExpiringCacheOS<UUID, UUID> TeleportTargetsCoolDown = new();
  627. public AgentCircuitManager AuthenticateHandler
  628. {
  629. get { return m_authenticateHandler; }
  630. }
  631. // an instance to the physics plugin's Scene object.
  632. public PhysicsScene PhysicsScene
  633. {
  634. get { return m_sceneGraph.PhysicsScene; }
  635. set
  636. {
  637. m_sceneGraph.PhysicsScene = value;
  638. }
  639. }
  640. public string DefaultScriptEngine
  641. {
  642. get { return m_defaultScriptEngine; }
  643. }
  644. public EntityManager Entities
  645. {
  646. get { return m_sceneGraph.Entities; }
  647. }
  648. // used in sequence see: SpawnPoint()
  649. private int m_SpawnPoint;
  650. // can be closest/random/sequence
  651. public string SpawnPointRouting
  652. {
  653. get;
  654. private set;
  655. }
  656. // allow landmarks to pass
  657. public bool TelehubAllowLandmarks
  658. {
  659. get;
  660. private set;
  661. }
  662. public GridInfo SceneGridInfo;
  663. #endregion Properties
  664. #region Constructors
  665. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  666. ISimulationDataService simDataService, IEstateDataService estateDataService,
  667. IConfigSource config, string simulatorVersion)
  668. : this(regInfo)
  669. {
  670. m_config = config;
  671. FrameTime = 0.0908f;
  672. FrameTimeWarnPercent = 60;
  673. FrameTimeCritPercent = 40;
  674. Normalized55FPS = true;
  675. SeeIntoRegion = true;
  676. m_lastAllocatedLocalId = (int)(Random.Shared.NextDouble() * (uint.MaxValue / 4));
  677. m_lastAllocatedIntId = (int)(Random.Shared.NextDouble() * (int.MaxValue / 4));
  678. m_authenticateHandler = authen;
  679. m_sceneGridService = new SceneCommunicationService();
  680. m_SimulationDataService = simDataService;
  681. m_EstateDataService = estateDataService;
  682. m_lastIncoming = 0;
  683. m_lastOutgoing = 0;
  684. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this)
  685. {
  686. Enabled = true
  687. };
  688. m_asyncInventorySender = new AsyncInventorySender(this);
  689. #region Region Settings
  690. // Load region settings
  691. // LoadRegionSettings creates new region settings in persistence if they don't already exist for this region.
  692. // However, in this case, the default textures are not set in memory properly, so we need to do it here and
  693. // resave.
  694. // FIXME: It shouldn't be up to the database plugins to create this data - we should do it when a new
  695. // region is set up and avoid these gyrations.
  696. RegionSettings rs = simDataService.LoadRegionSettings(RegionInfo.RegionID);
  697. m_extraSettings = simDataService.GetExtra(RegionInfo.RegionID);
  698. bool updatedTerrainTextures = false;
  699. if (rs.TerrainTexture1.IsZero())
  700. {
  701. rs.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
  702. updatedTerrainTextures = true;
  703. }
  704. if (rs.TerrainTexture2.IsZero())
  705. {
  706. rs.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
  707. updatedTerrainTextures = true;
  708. }
  709. if (rs.TerrainTexture3.IsZero())
  710. {
  711. rs.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
  712. updatedTerrainTextures = true;
  713. }
  714. if (rs.TerrainTexture4.IsZero())
  715. {
  716. rs.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
  717. updatedTerrainTextures = true;
  718. }
  719. if (rs.TerrainPBR1.IsZero() &&
  720. rs.TerrainPBR2.IsZero() &&
  721. rs.TerrainPBR3.IsZero() &&
  722. rs.TerrainPBR4.IsZero())
  723. {
  724. rs.TerrainPBR1 = rs.TerrainTexture1;
  725. rs.TerrainPBR2 = rs.TerrainTexture2;
  726. rs.TerrainPBR3 = rs.TerrainTexture3;
  727. rs.TerrainPBR4 = rs.TerrainTexture4;
  728. updatedTerrainTextures = true;
  729. }
  730. if (updatedTerrainTextures)
  731. rs.Save();
  732. RegionInfo.RegionSettings = rs;
  733. if (estateDataService is not null)
  734. {
  735. EstateSettings es = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  736. if (es == null)
  737. m_log.Error($"[SCENE]: Region {Name} failed to load estate settings. Using defaults");
  738. RegionInfo.EstateSettings = es;
  739. }
  740. SceneGridInfo = new GridInfo(config, RegionInfo.ServerURI);
  741. #endregion Region Settings
  742. //Bind Storage Manager functions to some land manager functions for this scene
  743. EventManager.OnLandObjectAdded += new EventManager.LandObjectAdded(simDataService.StoreLandObject);
  744. EventManager.OnLandObjectRemoved += new EventManager.LandObjectRemoved(simDataService.RemoveLandObject);
  745. RegisterDefaultSceneEvents();
  746. // XXX: Don't set the public property since we don't want to activate here. This needs to be handled
  747. // better in the future.
  748. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  749. PhysicsEnabled = !RegionInfo.RegionSettings.DisablePhysics;
  750. m_simulatorVersion = simulatorVersion + " (" + Util.RuntimeInformationStr + ")";
  751. #region Region Config
  752. // Region config overrides global config
  753. //
  754. if (m_config.Configs["Startup"] is not null)
  755. {
  756. IConfig startupConfig = m_config.Configs["Startup"];
  757. StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
  758. m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
  759. m_maxDrawDistance = startupConfig.GetFloat("MaxDrawDistance", m_maxDrawDistance);
  760. m_maxRegionViewDistance = startupConfig.GetFloat("MaxRegionsViewDistance", m_maxRegionViewDistance);
  761. m_minRegionViewDistance = startupConfig.GetFloat("MinRegionsViewDistance", m_minRegionViewDistance);
  762. // old versions compatibility
  763. LegacySitOffsets = startupConfig.GetBoolean("LegacySitOffsets", LegacySitOffsets);
  764. if (m_defaultDrawDistance > m_maxDrawDistance)
  765. m_defaultDrawDistance = m_maxDrawDistance;
  766. if (m_maxRegionViewDistance > m_maxDrawDistance)
  767. m_maxRegionViewDistance = m_maxDrawDistance;
  768. if(m_minRegionViewDistance < 96f)
  769. m_minRegionViewDistance = 96f;
  770. if(m_minRegionViewDistance > m_maxRegionViewDistance)
  771. m_minRegionViewDistance = m_maxRegionViewDistance;
  772. UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
  773. if (!UseBackup)
  774. m_log.Info($"[SCENE]: Backup has been disabled for {RegionInfo.RegionName}");
  775. //Animation states
  776. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  777. SeeIntoRegion = startupConfig.GetBoolean("see_into_region", SeeIntoRegion);
  778. MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20);
  779. PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
  780. CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
  781. m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
  782. if (RegionInfo.NonphysPrimMin > 0)
  783. {
  784. m_minNonphys = RegionInfo.NonphysPrimMin;
  785. }
  786. // don't allow nonsense values
  787. if(m_minNonphys < 0.001f)
  788. m_minNonphys = 0.001f;
  789. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  790. if (RegionInfo.NonphysPrimMax > 0)
  791. {
  792. m_maxNonphys = RegionInfo.NonphysPrimMax;
  793. }
  794. if (m_maxNonphys > 65536)
  795. m_maxNonphys = 65536;
  796. m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
  797. if (RegionInfo.PhysPrimMin > 0)
  798. {
  799. m_minPhys = RegionInfo.PhysPrimMin;
  800. }
  801. if(m_minPhys < 0.01f)
  802. m_minPhys = 0.01f;
  803. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  804. if (RegionInfo.PhysPrimMax > 0)
  805. {
  806. m_maxPhys = RegionInfo.PhysPrimMax;
  807. }
  808. if (m_maxPhys > 2048)
  809. m_maxPhys = 2048;
  810. m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
  811. if (RegionInfo.LinksetCapacity > 0)
  812. {
  813. m_linksetCapacity = RegionInfo.LinksetCapacity;
  814. }
  815. m_linksetPhysCapacity = startupConfig.GetInt("LinksetPhysPrims", m_linksetPhysCapacity);
  816. SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
  817. TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
  818. // Here, if clamping is requested in either global or
  819. // local config, it will be used
  820. //
  821. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  822. if (RegionInfo.ClampPrimSize)
  823. {
  824. m_clampPrimSize = true;
  825. }
  826. m_clampNegativeZ = startupConfig.GetBoolean("ClampNegativeZ", m_clampNegativeZ);
  827. m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
  828. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  829. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  830. m_dontPersistBefore = startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  831. m_dontPersistBefore *= 10000000;
  832. m_persistAfter = startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  833. m_persistAfter *= 10000000;
  834. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "YEngine");
  835. m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
  836. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  837. m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
  838. string[] possibleMapConfigSections = new string[] { "Map", "Startup" };
  839. m_generateMaptiles
  840. = Util.GetConfigVarFromSections<bool>(config, "GenerateMaptiles", possibleMapConfigSections, true);
  841. if (m_generateMaptiles)
  842. {
  843. int maptileRefresh = Util.GetConfigVarFromSections<int>(config, "MaptileRefresh", possibleMapConfigSections, 0);
  844. m_log.InfoFormat("[SCENE]: Region {0}, WORLD MAP refresh time set to {1} seconds", RegionInfo.RegionName, maptileRefresh);
  845. if (maptileRefresh != 0)
  846. {
  847. m_mapGenerationTimer.Interval = maptileRefresh * 1000;
  848. m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
  849. m_mapGenerationTimer.AutoReset = false;
  850. m_mapGenerationTimer.Start();
  851. }
  852. }
  853. else
  854. {
  855. string tile = Util.GetConfigVarFromSections<string>(
  856. config, "MaptileStaticUUID", possibleMapConfigSections, Util.UUIDZeroString);
  857. if (tile != Util.UUIDZeroString && UUID.TryParse(tile, out UUID tileID))
  858. {
  859. RegionInfo.RegionSettings.TerrainImageID = tileID;
  860. }
  861. else
  862. {
  863. RegionInfo.RegionSettings.TerrainImageID = RegionInfo.MaptileStaticUUID;
  864. m_log.InfoFormat("[SCENE]: Region {0}, maptile set to {1}", RegionInfo.RegionName, RegionInfo.MaptileStaticUUID.ToString());
  865. }
  866. }
  867. string[] possibleAccessControlConfigSections = new string[] { "Startup", "AccessControl"};
  868. string grant = Util.GetConfigVarFromSections<string>(
  869. config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
  870. if (grant.Length > 0)
  871. {
  872. foreach (string viewer in grant.Split(','))
  873. {
  874. m_AllowedViewers.Add(viewer.Trim().ToLower());
  875. }
  876. }
  877. grant = Util.GetConfigVarFromSections<string>(config, "DeniedClients", possibleAccessControlConfigSections, string.Empty);
  878. // Deal with the mess of someone having used a different word at some point
  879. if (string.IsNullOrWhiteSpace(grant))
  880. grant = Util.GetConfigVarFromSections<string>(config, "BannedClients", possibleAccessControlConfigSections, string.Empty);
  881. if (grant.Length > 0)
  882. {
  883. foreach (string viewer in grant.Split(','))
  884. {
  885. m_BannedViewers.Add(viewer.Trim().ToLower());
  886. }
  887. }
  888. FrameTime = startupConfig.GetFloat( "FrameTime", FrameTime);
  889. FrameTimeWarnPercent = startupConfig.GetInt( "FrameTimeWarnPercent", FrameTimeWarnPercent);
  890. FrameTimeCritPercent = startupConfig.GetInt( "FrameTimeCritPercent", FrameTimeCritPercent);
  891. Normalized55FPS = startupConfig.GetBoolean( "Normalized55FPS", Normalized55FPS);
  892. m_update_backup = startupConfig.GetInt("UpdateStorageEveryNFrames", m_update_backup);
  893. m_update_coarse_locations = startupConfig.GetInt("UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
  894. m_update_entitymovement = startupConfig.GetInt("UpdateEntityMovementEveryNFrames", m_update_entitymovement);
  895. m_update_events = startupConfig.GetInt("UpdateEventsEveryNFrames", m_update_events);
  896. m_update_objects = startupConfig.GetInt("UpdateObjectsEveryNFrames", m_update_objects);
  897. m_update_physics = startupConfig.GetInt("UpdatePhysicsEveryNFrames", m_update_physics);
  898. m_update_presences = startupConfig.GetInt("UpdateAgentsEveryNFrames", m_update_presences);
  899. m_update_terrain = startupConfig.GetInt("UpdateTerrainEveryNFrames", m_update_terrain);
  900. m_update_temp_cleaning = startupConfig.GetInt("UpdateTempCleaningEveryNSeconds", m_update_temp_cleaning);
  901. string[] possibleScriptConfigSections = new string[] { "YEngine", "Xengine", "Scripts" };
  902. m_LinkSetDataLimit = Util.GetConfigVarFromSections<int>(config, "LinksetDataLimit", possibleScriptConfigSections, m_LinkSetDataLimit);
  903. }
  904. #endregion Region Config
  905. IConfig entityTransferConfig = m_config.Configs["EntityTransfer"];
  906. if (entityTransferConfig is not null)
  907. {
  908. AllowAvatarCrossing = entityTransferConfig.GetBoolean("AllowAvatarCrossing", AllowAvatarCrossing);
  909. DisableObjectTransfer = entityTransferConfig.GetBoolean("DisableObjectTransfer", false);
  910. }
  911. #region Interest Management
  912. IConfig interestConfig = m_config.Configs["InterestManagement"];
  913. if (interestConfig is not null)
  914. {
  915. string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  916. try
  917. {
  918. UpdatePrioritizationScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
  919. }
  920. catch (Exception)
  921. {
  922. m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default BestAvatarResponsiveness");
  923. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness;
  924. }
  925. IsReprioritizationEnabled
  926. = interestConfig.GetBoolean("ReprioritizationEnabled", IsReprioritizationEnabled);
  927. ReprioritizationInterval
  928. = interestConfig.GetFloat("ReprioritizationInterval", ReprioritizationInterval);
  929. ReprioritizationDistance
  930. = interestConfig.GetFloat("RootReprioritizationDistance", ReprioritizationDistance);
  931. if(ReprioritizationDistance < m_minReprioritizationDistance)
  932. ReprioritizationDistance = m_minReprioritizationDistance;
  933. ObjectsCullingByDistance
  934. = interestConfig.GetBoolean("ObjectsCullingByDistance", ObjectsCullingByDistance);
  935. }
  936. m_log.DebugFormat("[SCENE]: Using the {0} prioritization scheme", UpdatePrioritizationScheme);
  937. #endregion Interest Management
  938. StatsReporter = new SimStatsReporter(this);
  939. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  940. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  941. IConfig restartConfig = config.Configs["RestartModule"];
  942. if (restartConfig is not null)
  943. {
  944. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  945. if (!string.IsNullOrEmpty(markerPath))
  946. {
  947. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".started");
  948. try
  949. {
  950. string pidstring = Environment.ProcessId.ToString();
  951. FileStream fs = File.Create(path);
  952. System.Text.ASCIIEncoding enc = new();
  953. Byte[] buf = enc.GetBytes(pidstring);
  954. fs.Write(buf, 0, buf.Length);
  955. fs.Close();
  956. }
  957. catch (Exception)
  958. {
  959. }
  960. }
  961. }
  962. StartTimerWatchdog();
  963. }
  964. public Scene(RegionInfo regInfo)
  965. : base(regInfo)
  966. {
  967. m_sceneGraph = new SceneGraph(this);
  968. // If the scene graph has an Unrecoverable error, restart this sim.
  969. // Currently the only thing that causes it to happen is two kinds of specific
  970. // Physics based crashes.
  971. //
  972. // Out of memory
  973. // Operating system has killed the plugin
  974. m_sceneGraph.UnRecoverableError += () =>
  975. {
  976. m_log.Error($"[SCENE]: Restarting region {Name} due to unrecoverable physics crash");
  977. RestartNow();
  978. };
  979. PhysicalPrims = true;
  980. CollidablePrims = true;
  981. PhysicsEnabled = true;
  982. AllowAvatarCrossing = true;
  983. PeriodicBackup = true;
  984. UseBackup = true;
  985. IsReprioritizationEnabled = true;
  986. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness;
  987. ReprioritizationInterval = 5000;
  988. ReprioritizationDistance = m_minReprioritizationDistance;
  989. m_eventManager = new EventManager();
  990. m_permissions = new ScenePermissions(this);
  991. }
  992. #endregion
  993. #region Startup / Close Methods
  994. /// <value>
  995. /// The scene graph for this scene
  996. /// </value>
  997. /// TODO: Possibly stop other classes being able to manipulate this directly.
  998. public SceneGraph SceneGraph
  999. {
  1000. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1001. get { return m_sceneGraph; }
  1002. }
  1003. /// <summary>
  1004. /// Called by the module loader when all modules are loaded, after each module's
  1005. /// RegionLoaded hook is called. This is the earliest time where RequestModuleInterface
  1006. /// may be used.
  1007. /// </summary>
  1008. public void AllModulesLoaded()
  1009. {
  1010. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  1011. if (dm is not null)
  1012. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  1013. ISimulatorFeaturesModule fm = RequestModuleInterface<ISimulatorFeaturesModule>();
  1014. if (fm is not null)
  1015. {
  1016. float statisticsFPSfactor = 1.0f;
  1017. if(Normalized55FPS)
  1018. statisticsFPSfactor = 55.0f * FrameTime;
  1019. fm.AddOpenSimExtraFeature("SimulatorFPS", OSD.FromReal(1.0f / FrameTime));
  1020. fm.AddOpenSimExtraFeature("SimulatorFPSFactor", OSD.FromReal(statisticsFPSfactor));
  1021. fm.AddOpenSimExtraFeature("SimulatorFPSWarnPercent", OSD.FromInteger(FrameTimeWarnPercent));
  1022. fm.AddOpenSimExtraFeature("SimulatorFPSCritPercent", OSD.FromInteger(FrameTimeCritPercent));
  1023. fm.AddOpenSimExtraFeature("MinPrimScale", OSD.FromReal(m_minNonphys));
  1024. fm.AddOpenSimExtraFeature("MaxPrimScale", OSD.FromReal(m_maxNonphys));
  1025. fm.AddOpenSimExtraFeature("MinPhysPrimScale", OSD.FromReal(m_minPhys));
  1026. fm.AddOpenSimExtraFeature("MaxPhysPrimScale", OSD.FromReal(m_maxPhys));
  1027. if(SceneGridInfo is not null)
  1028. {
  1029. if (!fm.OpenSimExtraFeatureContains("GridName"))
  1030. {
  1031. if (!string.IsNullOrEmpty(SceneGridInfo.GridName))
  1032. fm.AddOpenSimExtraFeature("GridName", SceneGridInfo.GridName);
  1033. }
  1034. if (!fm.OpenSimExtraFeatureContains("GridNick"))
  1035. {
  1036. if (!string.IsNullOrEmpty(SceneGridInfo.GridNick))
  1037. fm.AddOpenSimExtraFeature("GridNick", SceneGridInfo.GridNick);
  1038. }
  1039. if (!fm.OpenSimExtraFeatureContains("GridURL"))
  1040. {
  1041. fm.AddOpenSimExtraFeature("GridURL", SceneGridInfo.GridUrl);
  1042. }
  1043. if (!fm.OpenSimExtraFeatureContains("GridURLAlias"))
  1044. {
  1045. string[] alias = SceneGridInfo.GridUrlAlias;
  1046. if(alias is not null && alias.Length > 0)
  1047. {
  1048. StringBuilder sb = osStringBuilderCache.Acquire();
  1049. int i = 0;
  1050. while(i < alias.Length - 1)
  1051. {
  1052. sb.Append(alias[i++]);
  1053. sb.Append(',');
  1054. }
  1055. sb.Append(alias[i]);
  1056. fm.AddOpenSimExtraFeature("GridURLAlias", osStringBuilderCache.GetStringAndRelease(sb));
  1057. }
  1058. else
  1059. fm.AddOpenSimExtraFeature("GridURLAlias", string.Empty);
  1060. }
  1061. if (!fm.OpenSimExtraFeatureContains("search-server-url"))
  1062. {
  1063. if (!string.IsNullOrEmpty(SceneGridInfo.SearchURL))
  1064. fm.AddOpenSimExtraFeature("search-server-url", SceneGridInfo.SearchURL);
  1065. }
  1066. if (!fm.OpenSimExtraFeatureContains("destination-guide-url"))
  1067. {
  1068. if (!string.IsNullOrEmpty(SceneGridInfo.DestinationGuideURL))
  1069. fm.AddOpenSimExtraFeature("destination-guide-url", SceneGridInfo.DestinationGuideURL);
  1070. }
  1071. if (!fm.OpenSimExtraFeatureContains("currency-base-uri"))
  1072. {
  1073. if (!string.IsNullOrEmpty(SceneGridInfo.EconomyURL))
  1074. fm.AddOpenSimExtraFeature("currency-base-uri", SceneGridInfo.EconomyURL);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. protected virtual void RegisterDefaultSceneEvents()
  1080. {
  1081. //m_eventManager.OnSignificantClientMovement += HandleOnSignificantClientMovement;
  1082. }
  1083. public override string GetSimulatorVersion()
  1084. {
  1085. return m_simulatorVersion;
  1086. }
  1087. /// <summary>
  1088. /// Process the fact that a neighbouring region has come up.
  1089. /// </summary>
  1090. /// <remarks>
  1091. /// We only add it to the neighbor list if it's within 1 region from here.
  1092. /// Agents may have draw distance values that cross two regions though, so
  1093. /// we add it to the notify list regardless of distance. We'll check
  1094. /// the agent's draw distance before notifying them though.
  1095. /// </remarks>
  1096. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  1097. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  1098. public override void OtherRegionUp(GridRegion otherRegion)
  1099. {
  1100. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  1101. {
  1102. if (isNeighborRegion(otherRegion))
  1103. {
  1104. // Let the grid service module know, so this can be cached
  1105. m_eventManager.TriggerOnRegionUp(otherRegion);
  1106. if (EntityTransferModule is not null)
  1107. {
  1108. try
  1109. {
  1110. List<ulong> old = new() { otherRegion.RegionHandle };
  1111. ForEachRootScenePresence(delegate(ScenePresence agent)
  1112. {
  1113. if(agent.IsNPC)
  1114. return;
  1115. agent.DropOldNeighbours(old);
  1116. EntityTransferModule.EnableChildAgent(agent, otherRegion);
  1117. });
  1118. }
  1119. catch
  1120. {
  1121. m_log.Error("[SCENE]: Couldn't inform clients of regionup");
  1122. }
  1123. }
  1124. }
  1125. else
  1126. {
  1127. m_log.Info(
  1128. $"[SCENE]: Got notice about far away Region: {otherRegion.RegionName} at ({otherRegion.RegionLocX}, {otherRegion.RegionLocY})");
  1129. }
  1130. }
  1131. }
  1132. public bool isNeighborRegion(GridRegion otherRegion)
  1133. {
  1134. int tmp = otherRegion.RegionLocX - (int)RegionInfo.WorldLocX;
  1135. if (tmp < -otherRegion.RegionSizeX || tmp > RegionInfo.RegionSizeX)
  1136. return false;
  1137. tmp = otherRegion.RegionLocY - (int)RegionInfo.WorldLocY;
  1138. if (tmp < -otherRegion.RegionSizeY || tmp > RegionInfo.RegionSizeY)
  1139. return false;
  1140. return true;
  1141. }
  1142. public void AddNeighborRegion(RegionInfo region)
  1143. {
  1144. lock (m_neighbours)
  1145. {
  1146. if (!CheckNeighborRegion(region))
  1147. {
  1148. m_neighbours.Add(region);
  1149. }
  1150. }
  1151. }
  1152. public bool CheckNeighborRegion(RegionInfo region)
  1153. {
  1154. bool found = false;
  1155. lock (m_neighbours)
  1156. {
  1157. foreach (RegionInfo reg in m_neighbours)
  1158. {
  1159. if (reg.RegionHandle == region.RegionHandle)
  1160. {
  1161. found = true;
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. return found;
  1167. }
  1168. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  1169. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  1170. {
  1171. OtherRegionUp(new GridRegion(neighbour));
  1172. return new GridRegion(RegionInfo);
  1173. }
  1174. // This causes the region to restart immediatley.
  1175. public void RestartNow()
  1176. {
  1177. IConfig startupConfig = m_config.Configs["Startup"];
  1178. if (startupConfig is not null)
  1179. {
  1180. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  1181. {
  1182. MainConsole.Instance.RunCommand("shutdown");
  1183. return;
  1184. }
  1185. }
  1186. m_log.Info($"[REGION]: Restarting region {Name}");
  1187. Close();
  1188. base.Restart();
  1189. }
  1190. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  1191. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  1192. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  1193. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  1194. // subsequently the agent will never see the region come back online.
  1195. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  1196. {
  1197. m_restartWaitTimer.Stop();
  1198. lock (m_regionRestartNotifyList)
  1199. {
  1200. if(EntityTransferModule is not null)
  1201. {
  1202. foreach (RegionInfo region in m_regionRestartNotifyList)
  1203. {
  1204. GridRegion r = new(region);
  1205. try
  1206. {
  1207. ForEachRootScenePresence(delegate(ScenePresence agent)
  1208. {
  1209. if (!agent.IsNPC)
  1210. EntityTransferModule.EnableChildAgent(agent, r);
  1211. });
  1212. }
  1213. catch (NullReferenceException)
  1214. {
  1215. // This means that we're not booted up completely yet.
  1216. // This shouldn't happen too often anymore.
  1217. }
  1218. }
  1219. }
  1220. // Reset list to nothing.
  1221. m_regionRestartNotifyList.Clear();
  1222. }
  1223. }
  1224. public int GetInaccurateNeighborCount()
  1225. {
  1226. return m_neighbours.Count;
  1227. }
  1228. // This is the method that shuts down the scene.
  1229. public override void Close()
  1230. {
  1231. if (m_shuttingDown)
  1232. {
  1233. m_log.Warn($"[SCENE]: Ignoring close request because already closing {Name}");
  1234. return;
  1235. }
  1236. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  1237. if (etcd is not null)
  1238. {
  1239. etcd.Delete("Health");
  1240. etcd.Delete("HealthFlags");
  1241. etcd.Delete("RootAgents");
  1242. }
  1243. m_log.Info($"[SCENE]: Closing down the single simulator: {Name}");
  1244. StatsReporter.Close();
  1245. m_restartTimer.Stop();
  1246. m_restartTimer.Close();
  1247. if (!GridService.DeregisterRegion(RegionInfo.RegionID))
  1248. m_log.Warn($"[SCENE]: Deregister from grid failed for region {Name}");
  1249. // Kick all ROOT agents with the message, 'The simulator is going down'
  1250. ForEachScenePresence(delegate(ScenePresence avatar)
  1251. {
  1252. avatar.RemoveNeighbourRegion(RegionInfo.RegionHandle);
  1253. if (!avatar.IsChildAgent)
  1254. avatar.ControllingClient.Kick("The simulator is going down.");
  1255. avatar.ControllingClient.SendShutdownConnectionNotice();
  1256. });
  1257. // Stop updating the scene objects and agents.
  1258. m_shuttingDown = true;
  1259. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  1260. // We also need to wait to avoid a race condition with the scene update loop which might not yet
  1261. // have checked ShuttingDown.
  1262. Thread.Sleep(500);
  1263. // Stop all client threads.
  1264. ForEachScenePresence(delegate(ScenePresence avatar) { CloseAgent(avatar.UUID, false); });
  1265. m_log.Debug("[SCENE]: TriggerSceneShuttingDown");
  1266. EventManager.TriggerSceneShuttingDown(this);
  1267. m_log.Debug("[SCENE]: Persisting changed objects");
  1268. Backup(true);
  1269. m_log.Debug("[SCENE]: Closing scene");
  1270. m_sceneGraph.Close();
  1271. base.Close();
  1272. // XEngine currently listens to the EventManager.OnShutdown event to trigger script stop and persistence.
  1273. // Therefore. we must dispose of the PhysicsScene after this to prevent a window where script code can
  1274. // attempt to reference a null or disposed physics scene.
  1275. if (PhysicsScene is not null)
  1276. {
  1277. m_log.Debug("[SCENE]: Dispose Physics");
  1278. PhysicsScene phys = PhysicsScene;
  1279. // remove the physics engine from both Scene and SceneGraph
  1280. PhysicsScene = null;
  1281. phys.Dispose();
  1282. phys = null;
  1283. }
  1284. }
  1285. public override void Start()
  1286. {
  1287. Start(true);
  1288. }
  1289. /// <summary>
  1290. /// Start the scene
  1291. /// </summary>
  1292. /// <param name='startScripts'>
  1293. /// Start the scripts within the scene.
  1294. /// </param>
  1295. public void Start(bool startScripts)
  1296. {
  1297. if (IsRunning)
  1298. return;
  1299. m_isRunning = true;
  1300. m_active = true;
  1301. m_unixStartTime = Util.UnixTimeSinceEpoch();
  1302. // m_log.DebugFormat("[SCENE]: Starting Heartbeat timer for {0}", RegionInfo.RegionName);
  1303. if (m_heartbeatThread is not null)
  1304. {
  1305. m_hbRestarts++;
  1306. if(m_hbRestarts > 10)
  1307. Environment.Exit(1);
  1308. m_log.Error($"[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {Name}");
  1309. //int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  1310. //System.Diagnostics.Process proc = new System.Diagnostics.Process();
  1311. //proc.EnableRaisingEvents=false;
  1312. //proc.StartInfo.FileName = "/bin/kill";
  1313. //proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  1314. //proc.Start();
  1315. //proc.WaitForExit();
  1316. //Thread.Sleep(1000);
  1317. //Environment.Exit(1);
  1318. //m_heartbeatThread.Abort();
  1319. Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
  1320. m_heartbeatThread = null;
  1321. }
  1322. GC.Collect();
  1323. GC.WaitForPendingFinalizers();
  1324. GC.Collect();
  1325. // tell physics to finish building actor
  1326. m_sceneGraph.ProcessPhysicsPreSimulation();
  1327. m_heartbeatThread = WorkManager.StartThread(
  1328. Heartbeat, $"Heartbeat-({Name.Replace(" ", "_")})", ThreadPriority.Normal, false,
  1329. false, null, 20000, false);
  1330. StartScripts();
  1331. }
  1332. /// <summary>
  1333. /// Sets up references to modules required by the scene
  1334. /// </summary>
  1335. public void SetModuleInterfaces()
  1336. {
  1337. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  1338. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  1339. XferManager = RequestModuleInterface<IXfer>();
  1340. m_AvatarFactory = RequestModuleInterface<IAvatarFactoryModule>();
  1341. AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
  1342. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  1343. m_dialogModule = RequestModuleInterface<IDialogModule>();
  1344. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  1345. EntityTransferModule = RequestModuleInterface<IEntityTransferModule>();
  1346. m_groupsModule = RequestModuleInterface<IGroupsModule>();
  1347. AgentTransactionsModule = RequestModuleInterface<IAgentAssetTransactions>();
  1348. UserManagementModule = RequestModuleInterface<IUserManagement>();
  1349. }
  1350. #endregion
  1351. #region Update Methods
  1352. /// <summary>
  1353. /// Activate the various loops necessary to continually update the scene.
  1354. /// </summary>
  1355. private void Heartbeat()
  1356. {
  1357. m_eventManager.TriggerOnRegionStarted(this);
  1358. // The first frame can take a very long time due to physics actors being added on startup. Therefore,
  1359. // don't turn on the watchdog alarm for this thread until the second frame, in order to prevent false
  1360. // alarms for scenes with many objects.
  1361. Update(1);
  1362. Watchdog.GetCurrentThreadInfo().AlarmIfTimeout = true;
  1363. m_lastFrameTick = Util.EnvironmentTickCount();
  1364. Update(-1);
  1365. Watchdog.RemoveThread();
  1366. }
  1367. public override void Update(int frames)
  1368. {
  1369. long endFrame;
  1370. if (frames >= 0)
  1371. endFrame = Frame + frames;
  1372. else
  1373. endFrame = long.MaxValue;
  1374. float physicsFPS = 0f;
  1375. float frameTimeMS = FrameTime * 1000.0f;
  1376. int previousFrameTick;
  1377. double lastMS;
  1378. double nowMS;
  1379. double framestart;
  1380. float sleepMS;
  1381. float sleepError = 0;
  1382. while (!m_shuttingDown && ((endFrame == long.MaxValue && Active) || Frame < endFrame))
  1383. {
  1384. framestart = Util.GetTimeStampMS();
  1385. ++Frame;
  1386. // m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
  1387. otherMS = agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0f;
  1388. try
  1389. {
  1390. EventManager.TriggerRegionHeartbeatStart(this);
  1391. // Apply taints in terrain module to terrain in physics scene
  1392. lastMS = Util.GetTimeStampMS();
  1393. if (Frame % 4 == 0)
  1394. {
  1395. CheckTerrainUpdates();
  1396. }
  1397. if (Frame % m_update_terrain == 0)
  1398. {
  1399. UpdateTerrain();
  1400. }
  1401. nowMS = Util.GetTimeStampMS();
  1402. terrainMS = (float)(nowMS - lastMS);
  1403. lastMS = nowMS;
  1404. if (m_physicsEnabled && Frame % m_update_physics == 0)
  1405. m_sceneGraph.UpdatePreparePhysics();
  1406. nowMS = Util.GetTimeStampMS();
  1407. physicsMS2 = (float)(nowMS - lastMS);
  1408. lastMS = nowMS;
  1409. /*
  1410. // Apply any pending avatar force input to the avatar's velocity
  1411. if (Frame % m_update_entitymovement == 0)
  1412. m_sceneGraph.UpdateScenePresenceMovement();
  1413. */
  1414. if (!m_sendingCoarseLocations && GetNumberOfClients() > 0 && Frame % m_update_coarse_locations == 0)
  1415. {
  1416. m_sendingCoarseLocations = true;
  1417. WorkManager.RunInThreadPool(
  1418. delegate
  1419. {
  1420. SceneGraph.GetCoarseLocations(out List<Vector3> coarseLocations, out List<UUID> avatarUUIDs, 60);
  1421. // Send coarse locations to clients
  1422. ForEachScenePresence(delegate(ScenePresence presence)
  1423. {
  1424. if(!presence.IsNPC)
  1425. presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
  1426. });
  1427. m_sendingCoarseLocations = false;
  1428. }, null, string.Format("SendCoarseLocations ({0})", Name));
  1429. }
  1430. // Get the simulation frame time that the avatar force input
  1431. // took
  1432. nowMS = Util.GetTimeStampMS();
  1433. agentMS = (float)(nowMS - lastMS);
  1434. lastMS = nowMS;
  1435. // Perform the main physics update. This will do the actual work of moving objects and avatars according to their
  1436. // velocity
  1437. if (m_physicsEnabled && Frame % m_update_physics == 0)
  1438. {
  1439. physicsFPS = m_sceneGraph.UpdatePhysics(FrameTime);
  1440. }
  1441. nowMS = Util.GetTimeStampMS();
  1442. physicsMS = (float)(nowMS - lastMS);
  1443. lastMS = nowMS;
  1444. //CheckKFM(FrameTime);
  1445. // Check if any objects have reached their targets
  1446. CheckAtTargets();
  1447. // Update SceneObjectGroups that have scheduled themselves for updates
  1448. // Objects queue their updates onto all scene presences
  1449. if (Frame % m_update_objects == 0)
  1450. m_sceneGraph.UpdateObjectGroups();
  1451. nowMS = Util.GetTimeStampMS();
  1452. otherMS = (float)(nowMS - lastMS);
  1453. lastMS = nowMS;
  1454. // Run through all ScenePresences looking for updates
  1455. // Presence updates and queued object updates for each presence are sent to clients
  1456. if (Frame % m_update_presences == 0)
  1457. m_sceneGraph.UpdatePresences();
  1458. nowMS = Util.GetTimeStampMS();
  1459. agentMS += (float)(nowMS - lastMS);
  1460. lastMS = nowMS;
  1461. // Delete temp-on-rez stuff
  1462. if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
  1463. {
  1464. m_cleaningTemps = true;
  1465. WorkManager.RunInThreadPool(
  1466. delegate { CleanTempObjects(); m_cleaningTemps = false; }, null, $"CleanTempObjects ({Name})");
  1467. nowMS = Util.GetTimeStampMS();
  1468. tempOnRezMS = (float)(nowMS - lastMS); // bad.. counts the FireAndForget, not CleanTempObjects
  1469. lastMS = nowMS;
  1470. }
  1471. if (Frame % m_update_events == 0)
  1472. {
  1473. UpdateEvents();
  1474. nowMS = Util.GetTimeStampMS();
  1475. eventMS = (float)(nowMS - lastMS);
  1476. lastMS = nowMS;
  1477. }
  1478. if (PeriodicBackup && Frame % m_update_backup == 0)
  1479. {
  1480. UpdateStorageBackup();
  1481. nowMS = Util.GetTimeStampMS();
  1482. backupMS = (float)(nowMS - lastMS);
  1483. lastMS = nowMS;
  1484. }
  1485. //if (Frame % m_update_land == 0)
  1486. //{
  1487. // int ldMS = Util.EnvironmentTickCount();
  1488. // UpdateLand();
  1489. // landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1490. //}
  1491. if (!LoginsEnabled && Frame == 20)
  1492. {
  1493. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  1494. GC.Collect();
  1495. GC.WaitForPendingFinalizers();
  1496. GC.Collect();
  1497. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
  1498. if (!LoginLock)
  1499. {
  1500. if (!StartDisabled)
  1501. {
  1502. m_log.Info($"[REGION]: Enabling logins for {Name}");
  1503. LoginsEnabled = true;
  1504. }
  1505. m_sceneGridService.InformNeighborsThatRegionisUp(
  1506. RequestModuleInterface<INeighbourService>(), RegionInfo);
  1507. // Region ready should always be set
  1508. Ready = true;
  1509. IConfig restartConfig = m_config.Configs["RestartModule"];
  1510. if (restartConfig is not null)
  1511. {
  1512. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  1513. if (!string.IsNullOrEmpty(markerPath))
  1514. {
  1515. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".ready");
  1516. try
  1517. {
  1518. string pidstring = Environment.ProcessId.ToString();
  1519. FileStream fs = File.Create(path);
  1520. System.Text.ASCIIEncoding enc = new();
  1521. Byte[] buf = enc.GetBytes(pidstring);
  1522. fs.Write(buf, 0, buf.Length);
  1523. fs.Close();
  1524. }
  1525. catch (Exception)
  1526. {
  1527. }
  1528. }
  1529. }
  1530. }
  1531. else
  1532. {
  1533. // This handles a case of a region having no scripts for the RegionReady module
  1534. if (m_sceneGraph.GetActiveScriptsCount() == 0)
  1535. {
  1536. // In this case, we leave it to the IRegionReadyModule to enable logins
  1537. // LoginLock can currently only be set by a region module implementation.
  1538. // If somehow this hasn't been done then the quickest way to bugfix is to see the
  1539. // NullReferenceException
  1540. IRegionReadyModule rrm = RequestModuleInterface<IRegionReadyModule>();
  1541. rrm.TriggerRegionReady(this);
  1542. }
  1543. }
  1544. }
  1545. }
  1546. catch (Exception e)
  1547. {
  1548. m_log.Error($"[SCENE]: Failed on region {Name}: {e.Message}:{e.StackTrace}");
  1549. }
  1550. EventManager.TriggerRegionHeartbeatEnd(this);
  1551. m_firstHeartbeat = false;
  1552. Watchdog.UpdateThread();
  1553. otherMS += tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1554. lastMS = Util.GetTimeStampMS();
  1555. previousFrameTick = m_lastFrameTick;
  1556. m_lastFrameTick = (int)(lastMS + 0.5);
  1557. // estimate sleep time
  1558. nowMS = lastMS - framestart;
  1559. nowMS = (double)frameTimeMS - nowMS - sleepError;
  1560. // reuse frameMS as temporary
  1561. frameMS = (float)nowMS;
  1562. // sleep if we can
  1563. if (nowMS > 0)
  1564. {
  1565. Thread.Sleep((int)(nowMS + 0.5));
  1566. nowMS = Util.GetTimeStampMS();
  1567. sleepMS = (float)(nowMS - lastMS);
  1568. sleepError = sleepMS - frameMS;
  1569. sleepError = Math.Clamp(sleepError, 0.0f, 20f);
  1570. frameMS = (float)(nowMS - framestart);
  1571. }
  1572. else
  1573. {
  1574. nowMS = Util.GetTimeStampMS();
  1575. frameMS = (float)(nowMS - framestart);
  1576. sleepMS = 0.0f;
  1577. sleepError = 0.0f;
  1578. }
  1579. // script time is not scene frame time, but is displayed per frame
  1580. float scriptTimeMS = GetAndResetScriptExecutionTime();
  1581. StatsReporter.AddFrameStats(TimeDilation, physicsFPS, agentMS,
  1582. physicsMS + physicsMS2, otherMS , sleepMS, frameMS, scriptTimeMS);
  1583. // Optionally warn if a frame takes double the amount of time that it should.
  1584. if (DebugUpdates
  1585. && Util.EnvironmentTickCountSubtract(
  1586. m_lastFrameTick, previousFrameTick) > (int)(FrameTime * 1000 * 2))
  1587. m_log.WarnFormat(
  1588. "[SCENE]: Frame took {0} ms (desired max {1} ms) in {2}",
  1589. Util.EnvironmentTickCountSubtract(m_lastFrameTick, previousFrameTick),
  1590. FrameTime * 1000,
  1591. RegionInfo.RegionName);
  1592. }
  1593. }
  1594. /// <summary>
  1595. /// Adds the execution time of one script to the total scripts execution time for this region.
  1596. /// </summary>
  1597. /// <param name="ticks">Elapsed Stopwatch ticks</param>
  1598. public void AddScriptExecutionTime(long ticks)
  1599. {
  1600. StatsReporter.addScriptEvents(1);
  1601. Interlocked.Add(ref m_scriptExecutionTime, ticks);
  1602. }
  1603. public void AddScriptEvents(int cntr)
  1604. {
  1605. StatsReporter.addScriptEvents(cntr);
  1606. }
  1607. /// <summary>
  1608. /// Returns the total execution time of all the scripts in the region since the last call
  1609. /// (in milliseconds), and clears the value in preparation for the next call.
  1610. /// </summary>
  1611. /// <returns>Time in milliseconds</returns>
  1612. // Warning: this is now called from StatsReporter, and can't be shared
  1613. public long GetAndResetScriptExecutionTime()
  1614. {
  1615. long ticks = Interlocked.Exchange(ref m_scriptExecutionTime, 0);
  1616. return (ticks * 1000L) / Stopwatch.Frequency;
  1617. }
  1618. public void AddGroupTarget(SceneObjectGroup grp)
  1619. {
  1620. lock (m_groupsWithTargets)
  1621. m_groupsWithTargets.Add(grp.UUID);
  1622. }
  1623. public void RemoveGroupTarget(SceneObjectGroup grp)
  1624. {
  1625. lock (m_groupsWithTargets)
  1626. m_groupsWithTargets.Remove(grp.UUID);
  1627. }
  1628. private void CheckAtTargets()
  1629. {
  1630. List<UUID> objs = null;
  1631. lock (m_groupsWithTargets)
  1632. {
  1633. if (m_groupsWithTargets.Count != 0)
  1634. objs = new List<UUID>(m_groupsWithTargets);
  1635. }
  1636. if (objs is not null)
  1637. {
  1638. for(int i = 0; i< objs.Count; ++i)
  1639. {
  1640. UUID entry = objs[i];
  1641. SceneObjectGroup grp = GetSceneObjectGroup(entry);
  1642. if (grp is null)
  1643. m_groupsWithTargets.Remove(entry);
  1644. else
  1645. grp.CheckAtTargets();
  1646. }
  1647. }
  1648. }
  1649. /// <summary>
  1650. /// Send out simstats data to all clients
  1651. /// </summary>
  1652. /// <param name="stats">Stats on the Simulator's performance</param>
  1653. private void SendSimStatsPackets(SimStats stats)
  1654. {
  1655. ForEachRootClient(delegate(IClientAPI client)
  1656. {
  1657. client.SendSimStats(stats);
  1658. });
  1659. }
  1660. /// <summary>
  1661. /// Update the terrain if it needs to be updated.
  1662. /// </summary>
  1663. private void UpdateTerrain()
  1664. {
  1665. EventManager.TriggerTerrainTick();
  1666. }
  1667. private void CheckTerrainUpdates()
  1668. {
  1669. EventManager.TriggerTerrainCheckUpdates();
  1670. }
  1671. /// <summary>
  1672. /// Back up queued up changes
  1673. /// </summary>
  1674. private void UpdateStorageBackup()
  1675. {
  1676. if (!m_backingup)
  1677. {
  1678. WorkManager.RunInThreadPool(o => Backup(false), null, string.Format("BackupWorker ({0})", Name), false);
  1679. }
  1680. }
  1681. /// <summary>
  1682. /// Sends out the OnFrame event to the modules
  1683. /// </summary>
  1684. private void UpdateEvents()
  1685. {
  1686. m_eventManager.TriggerOnFrame();
  1687. }
  1688. /// <summary>
  1689. /// Backup the scene.
  1690. /// </summary>
  1691. /// <remarks>
  1692. /// This acts as the main method of the backup thread. In a regression test whether the backup thread is not
  1693. /// running independently this can be invoked directly.
  1694. /// </remarks>
  1695. /// <param name="forced">
  1696. /// If true, then any changes that have not yet been persisted are persisted. If false,
  1697. /// then the persistence decision is left to the backup code (in some situations, such as object persistence,
  1698. /// it's much more efficient to backup multiple changes at once rather than every single one).
  1699. /// <returns></returns>
  1700. public void Backup(bool forced)
  1701. {
  1702. lock (m_returns)
  1703. {
  1704. if(m_backingup)
  1705. {
  1706. m_log.Warn($"[Scene] Backup of {Name} already running. New call skipped");
  1707. return;
  1708. }
  1709. m_backingup = true;
  1710. try
  1711. {
  1712. EventManager.TriggerOnBackup(SimulationDataService, forced);
  1713. if(m_returns.Count == 0)
  1714. return;
  1715. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1716. if (tr is null)
  1717. return;
  1718. uint unixtime = (uint)Util.UnixTimeSinceEpoch();
  1719. uint estateid = RegionInfo.EstateSettings.ParentEstateID;
  1720. Guid regionguid = RegionInfo.RegionID.Guid;
  1721. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1722. {
  1723. GridInstantMessage msg = new()
  1724. {
  1725. fromAgentID = Guid.Empty, // From server
  1726. toAgentID = ret.Key.Guid,
  1727. imSessionID = Guid.NewGuid(),
  1728. timestamp = unixtime,
  1729. fromAgentName = "Server",
  1730. dialog = 19, // Object msg
  1731. fromGroup = false,
  1732. offline = 1,
  1733. ParentEstateID = estateid,
  1734. Position = Vector3.Zero,
  1735. RegionID = regionguid,
  1736. // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
  1737. binaryBucket = new Byte[1] {0}
  1738. };
  1739. if (ret.Value.count > 1)
  1740. msg.message = $"Your {ret.Value.count} objects were returned from {ret.Value.location} in region {Name} due to {ret.Value.reason}";
  1741. else
  1742. msg.message = $"Your object {ret.Value.objectName} was returned from {ret.Value.location} in region {Name} due to {ret.Value.reason}";
  1743. tr.SendInstantMessage(msg, delegate(bool success) { });
  1744. }
  1745. m_returns.Clear();
  1746. }
  1747. finally
  1748. {
  1749. m_backingup = false;
  1750. }
  1751. }
  1752. }
  1753. /// <summary>
  1754. /// Synchronous force backup. For deletes and links/unlinks
  1755. /// </summary>
  1756. /// <param name="group">Object to be backed up</param>
  1757. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1758. {
  1759. if (group is not null)
  1760. {
  1761. group.HasGroupChanged = true;
  1762. group.ProcessBackup(SimulationDataService, true);
  1763. }
  1764. }
  1765. /// <summary>
  1766. /// Tell an agent that their object has been returned.
  1767. /// </summary>
  1768. /// <remarks>
  1769. /// The actual return is handled by the caller.
  1770. /// </remarks>
  1771. /// <param name="agentID">Avatar Unique Id</param>
  1772. /// <param name="objectName">Name of object returned</param>
  1773. /// <param name="location">Location of object returned</param>
  1774. /// <param name="reason">Reasion for object return</param>
  1775. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1776. {
  1777. lock (m_returns)
  1778. {
  1779. if (m_returns.TryGetValue(agentID, out ReturnInfo info))
  1780. {
  1781. info.count++;
  1782. }
  1783. else
  1784. {
  1785. info = new ReturnInfo()
  1786. {
  1787. count = 1,
  1788. objectName = objectName,
  1789. location = location,
  1790. reason = reason
  1791. };
  1792. }
  1793. m_returns[agentID] = info;
  1794. }
  1795. }
  1796. #endregion
  1797. #region Load Terrain
  1798. /// <summary>
  1799. /// Store the terrain in the persistant data store
  1800. /// </summary>
  1801. public void SaveTerrain()
  1802. {
  1803. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1804. }
  1805. /// <summary>
  1806. /// Store the terrain in the persistant data store
  1807. /// </summary>
  1808. public void SaveBakedTerrain()
  1809. {
  1810. if(Bakedmap is not null)
  1811. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1812. }
  1813. private ViewerEnvironment m_regionEnvironment;
  1814. public ViewerEnvironment RegionEnvironment
  1815. {
  1816. get
  1817. {
  1818. return m_regionEnvironment;
  1819. }
  1820. set
  1821. {
  1822. m_regionEnvironment = value;
  1823. }
  1824. }
  1825. /// <summary>
  1826. /// Loads the World heightmap
  1827. /// </summary>
  1828. public override void LoadWorldMap()
  1829. {
  1830. try
  1831. {
  1832. Bakedmap = null;
  1833. TerrainData map = SimulationDataService.LoadBakedTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1834. if (map is not null)
  1835. {
  1836. Bakedmap = new TerrainChannel(map);
  1837. }
  1838. }
  1839. catch (Exception e)
  1840. {
  1841. m_log.WarnFormat(
  1842. "[TERRAIN]: Scene.cs: LoadWorldMap() baked terrain - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1843. }
  1844. try
  1845. {
  1846. TerrainData map = SimulationDataService.LoadTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1847. if (map is null)
  1848. {
  1849. if(Bakedmap is not null)
  1850. {
  1851. m_log.Warn("[TERRAIN]: terrain not found. Used stored baked terrain.");
  1852. Heightmap = Bakedmap.MakeCopy();
  1853. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1854. }
  1855. else
  1856. {
  1857. // This should be in the Terrain module, but it isn't because
  1858. // the heightmap is needed _way_ before the modules are initialized...
  1859. IConfig terrainConfig = m_config.Configs["Terrain"];
  1860. String m_InitialTerrain = "pinhead-island";
  1861. if (terrainConfig is not null)
  1862. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  1863. m_log.InfoFormat("[TERRAIN]: No default terrain. Generating a new terrain {0}.", m_InitialTerrain);
  1864. Heightmap = new TerrainChannel(m_InitialTerrain, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1865. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1866. }
  1867. }
  1868. else
  1869. {
  1870. Heightmap = new TerrainChannel(map);
  1871. }
  1872. }
  1873. catch (IOException e)
  1874. {
  1875. m_log.WarnFormat(
  1876. "[TERRAIN]: Scene.cs: LoadWorldMap() - Regenerating as failed with exception {0}{1}",
  1877. e.Message, e.StackTrace);
  1878. #pragma warning disable 0162
  1879. if ((int)Constants.RegionSize != 256)
  1880. {
  1881. Heightmap = new TerrainChannel();
  1882. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1883. }
  1884. }
  1885. catch (Exception e)
  1886. {
  1887. m_log.WarnFormat(
  1888. "[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1889. }
  1890. if(Bakedmap is null && Heightmap is not null)
  1891. {
  1892. Bakedmap = Heightmap.MakeCopy();
  1893. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1894. }
  1895. }
  1896. /// <summary>
  1897. /// Register this region with a grid service
  1898. /// </summary>
  1899. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1900. public void RegisterRegionWithGrid()
  1901. {
  1902. m_sceneGridService.SetScene(this);
  1903. //// Unfortunately this needs to be here and it can't be async.
  1904. //// The map tile image is stored in RegionSettings, but it also needs to be
  1905. //// stored in the GridService, because that's what the world map module uses
  1906. //// to send the map image UUIDs (of other regions) to the viewer...
  1907. if (m_generateMaptiles)
  1908. RegenerateMaptile();
  1909. GridRegion region = new(RegionInfo);
  1910. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1911. // m_log.DebugFormat("[SCENE]: RegisterRegionWithGrid. name={0},id={1},loc=<{2},{3}>,size=<{4},{5}>",
  1912. // m_regionName,
  1913. // RegionInfo.RegionID,
  1914. // RegionInfo.RegionLocX, RegionInfo.RegionLocY,
  1915. // RegionInfo.RegionSizeX, RegionInfo.RegionSizeY);
  1916. if (error != String.Empty)
  1917. throw new Exception(error);
  1918. }
  1919. #endregion
  1920. #region Load Land
  1921. /// <summary>
  1922. /// Loads all Parcel data from the datastore for region identified by regionID
  1923. /// </summary>
  1924. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1925. public void loadAllLandObjectsFromStorage(UUID regionID)
  1926. {
  1927. m_log.Info("[SCENE]: Loading land objects from storage");
  1928. List<LandData> landData = SimulationDataService.LoadLandObjects(regionID);
  1929. if (LandChannel is not null)
  1930. {
  1931. if (landData.Count == 0)
  1932. {
  1933. EventManager.TriggerNoticeNoLandDataFromStorage();
  1934. }
  1935. else
  1936. {
  1937. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1938. }
  1939. }
  1940. else
  1941. {
  1942. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1943. }
  1944. }
  1945. #endregion
  1946. #region Primitives Methods
  1947. /// <summary>
  1948. /// Loads the World's objects
  1949. /// </summary>
  1950. /// <param name="regionID"></param>
  1951. public virtual void LoadPrimsFromStorage(UUID regionID)
  1952. {
  1953. LoadingPrims = true;
  1954. m_log.Info("[SCENE]: Loading objects from datastore");
  1955. List<SceneObjectGroup> PrimsFromDB = SimulationDataService.LoadObjects(regionID);
  1956. m_log.InfoFormat("[SCENE]: Loaded {0} objects from the datastore", PrimsFromDB.Count);
  1957. foreach (SceneObjectGroup group in PrimsFromDB)
  1958. {
  1959. AddRestoredSceneObject(group, true, true);
  1960. SceneObjectPart rootPart = group.GetPart(group.UUID);
  1961. rootPart.Flags &= ~(PrimFlags.Scripted | PrimFlags.CreateSelected);
  1962. rootPart.TrimPermissions();
  1963. group.InvalidateDeepEffectivePerms();
  1964. EventManager.TriggerOnSceneObjectLoaded(group);
  1965. }
  1966. LoadingPrims = false;
  1967. EventManager.TriggerPrimsLoaded(this);
  1968. }
  1969. public bool SupportsRayCastFiltered()
  1970. {
  1971. if (PhysicsScene is null)
  1972. return false;
  1973. return PhysicsScene.SupportsRaycastWorldFiltered();
  1974. }
  1975. public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  1976. {
  1977. if (PhysicsScene is null)
  1978. return null;
  1979. return PhysicsScene.RaycastWorld(position, direction, length, Count, filter);
  1980. }
  1981. /// <summary>
  1982. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1983. /// </summary>
  1984. /// <param name="RayStart"></param>
  1985. /// <param name="RayEnd"></param>
  1986. /// <param name="RayTargetID"></param>
  1987. /// <param name="rot"></param>
  1988. /// <param name="bypassRayCast"></param>
  1989. /// <param name="RayEndIsIntersection"></param>
  1990. /// <param name="frontFacesOnly"></param>
  1991. /// <param name="scale"></param>
  1992. /// <param name="FaceCenter"></param>
  1993. /// <returns></returns>
  1994. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1995. {
  1996. Vector3 dir = RayEnd - RayStart;
  1997. float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
  1998. Vector3 wpos = Vector3.Zero;
  1999. // Check for water surface intersection from above
  2000. if ((RayStart.Z > wheight) && (RayEnd.Z < wheight))
  2001. {
  2002. float ratio = (wheight - RayStart.Z) / dir.Z;
  2003. wpos.X = RayStart.X + (ratio * dir.X);
  2004. wpos.Y = RayStart.Y + (ratio * dir.Y);
  2005. wpos.Z = wheight;
  2006. }
  2007. Vector3 pos;
  2008. if (RayEndIsIntersection != (byte)1)
  2009. {
  2010. float dist = dir.Length();
  2011. if (dist != 0)
  2012. {
  2013. Vector3 direction = dir * (1 / dist);
  2014. dist += 1.0f;
  2015. if (SupportsRayCastFiltered())
  2016. {
  2017. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  2018. rayfilter |= RayFilterFlags.land;
  2019. rayfilter |= RayFilterFlags.physical;
  2020. rayfilter |= RayFilterFlags.nonphysical;
  2021. rayfilter |= RayFilterFlags.LSLPhantom; // ubODE will only see volume detectors
  2022. // get some more contacts ???
  2023. int physcount = 4;
  2024. List<ContactResult> physresults =
  2025. (List<ContactResult>)RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  2026. if (physresults is not null && physresults.Count > 0)
  2027. {
  2028. // look for terrain ?
  2029. if(RayTargetID.IsZero())
  2030. {
  2031. foreach (ContactResult r in physresults)
  2032. {
  2033. if (r.ConsumerID == 0)
  2034. {
  2035. pos = r.Normal * scale;
  2036. pos *= 0.5f;
  2037. pos = r.Pos + pos;
  2038. if (wpos.Z > pos.Z) pos = wpos;
  2039. return pos;
  2040. }
  2041. }
  2042. }
  2043. else
  2044. {
  2045. foreach (ContactResult r in physresults)
  2046. {
  2047. SceneObjectPart part = GetSceneObjectPart(r.ConsumerID);
  2048. if (part is null)
  2049. continue;
  2050. if (part.UUID == RayTargetID)
  2051. {
  2052. pos = r.Normal * scale;
  2053. pos *= 0.5f;
  2054. pos = r.Pos + pos;
  2055. if (wpos.Z > pos.Z) pos = wpos;
  2056. return pos;
  2057. }
  2058. }
  2059. }
  2060. // else the first we got
  2061. pos = physresults[0].Normal * scale;
  2062. pos *= 0.5f;
  2063. pos = physresults[0].Pos + pos;
  2064. if (wpos.Z > pos.Z)
  2065. pos = wpos;
  2066. return pos;
  2067. }
  2068. }
  2069. if (!RayTargetID.IsZero())
  2070. {
  2071. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  2072. Ray NewRay = new(RayStart, direction);
  2073. if (target is not null)
  2074. {
  2075. // Ray Trace against target here
  2076. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  2077. // Un-comment out the following line to Get Raytrace results printed to the console.
  2078. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2079. float ScaleOffset = 0.5f;
  2080. // If we hit something
  2081. if (ei.HitTF)
  2082. {
  2083. Vector3 scaleComponent = ei.AAfaceNormal;
  2084. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2085. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2086. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2087. ScaleOffset = Math.Abs(ScaleOffset);
  2088. Vector3 intersectionpoint = ei.ipoint;
  2089. Vector3 normal = ei.normal;
  2090. // Set the position to the intersection point
  2091. Vector3 offset = (normal * (ScaleOffset / 2f));
  2092. pos = (intersectionpoint + offset);
  2093. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  2094. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  2095. // Un-offset the prim (it gets offset later by the consumer method)
  2096. //pos.Z -= 0.25F;
  2097. if (wpos.Z > pos.Z) pos = wpos;
  2098. return pos;
  2099. }
  2100. }
  2101. else
  2102. {
  2103. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  2104. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(NewRay, true, false);
  2105. // Un-comment the following line to print the raytrace results to the console.
  2106. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2107. if (ei.HitTF)
  2108. {
  2109. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2110. }
  2111. else
  2112. {
  2113. // fall back to our stupid functionality
  2114. pos = RayEnd;
  2115. }
  2116. if (wpos.Z > pos.Z) pos = wpos;
  2117. return pos;
  2118. }
  2119. }
  2120. }
  2121. }
  2122. pos = RayEnd;
  2123. //increase height so its above the ground.
  2124. //should be getting the normal of the ground at the rez point and using that?
  2125. pos.Z += scale.Z / 2f;
  2126. // return pos;
  2127. // check against posible water intercept
  2128. if (wpos.Z > pos.Z) pos = wpos;
  2129. return pos;
  2130. }
  2131. /// <summary>
  2132. /// Create a New SceneObjectGroup/Part by raycasting
  2133. /// </summary>
  2134. /// <param name="ownerID"></param>
  2135. /// <param name="groupID"></param>
  2136. /// <param name="RayEnd"></param>
  2137. /// <param name="rot"></param>
  2138. /// <param name="shape"></param>
  2139. /// <param name="bypassRaycast"></param>
  2140. /// <param name="RayStart"></param>
  2141. /// <param name="RayTargetID"></param>
  2142. /// <param name="RayEndIsIntersection"></param>
  2143. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  2144. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  2145. byte RayEndIsIntersection, uint addFlags)
  2146. {
  2147. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  2148. if (Permissions.CanRezObject(1, ownerID, pos))
  2149. {
  2150. // rez ON the ground, not IN the ground
  2151. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  2152. AddNewPrim(ownerID, groupID, pos, rot, shape, addFlags);
  2153. }
  2154. else
  2155. {
  2156. if (TryGetClient(ownerID, out IClientAPI client))
  2157. client.SendAlertMessage("You cannot create objects here.");
  2158. }
  2159. }
  2160. public virtual SceneObjectGroup AddNewPrim(UUID ownerID, UUID groupID,
  2161. Vector3 pos, Quaternion rot, PrimitiveBaseShape shape, uint addFlags = 0)
  2162. {
  2163. //m_log.DebugFormat(
  2164. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  2165. SceneObjectGroup sceneObject;
  2166. // If an entity creator has been registered for this prim type then use that
  2167. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  2168. {
  2169. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  2170. }
  2171. else
  2172. {
  2173. // Otherwise, use this default creation code;
  2174. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  2175. sceneObject.SetGroup(groupID, null);
  2176. if ((addFlags & (uint)PrimFlags.CreateSelected) != 0)
  2177. {
  2178. sceneObject.IsSelected = true;
  2179. sceneObject.RootPart.CreateSelected = true;
  2180. }
  2181. if (AgentPreferencesService is not null) // This will override the brave new full perm world!
  2182. {
  2183. AgentPrefs prefs = AgentPreferencesService.GetAgentPreferences(ownerID);
  2184. // Only apply user selected prefs if the user set them
  2185. if (prefs is not null && prefs.PermNextOwner != 0)
  2186. {
  2187. sceneObject.RootPart.GroupMask = (uint)prefs.PermGroup;
  2188. sceneObject.RootPart.EveryoneMask = (uint)prefs.PermEveryone;
  2189. sceneObject.RootPart.NextOwnerMask = (uint)prefs.PermNextOwner;
  2190. }
  2191. }
  2192. AddNewSceneObject(sceneObject, true, false);
  2193. }
  2194. if (UserManagementModule is not null)
  2195. sceneObject.RootPart.CreatorIdentification = UserManagementModule.GetUserUUI(ownerID);
  2196. sceneObject.InvalidateDeepEffectivePerms();
  2197. sceneObject.ScheduleGroupForUpdate(PrimUpdateFlags.FullUpdatewithAnimMatOvr);
  2198. return sceneObject;
  2199. }
  2200. /// <summary>
  2201. /// Add an object into the scene that has come from storage
  2202. /// </summary>
  2203. ///
  2204. /// <param name="sceneObject"></param>
  2205. /// <param name="attachToBackup">
  2206. /// If true, changes to the object will be reflected in its persisted data
  2207. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2208. /// </param>
  2209. /// <param name="alreadyPersisted">
  2210. /// If true, we won't persist this object until it changes
  2211. /// If false, we'll persist this object immediately
  2212. /// </param>
  2213. /// <param name="sendClientUpdates">
  2214. /// If true, we send updates to the client to tell it about this object
  2215. /// If false, we leave it up to the caller to do this
  2216. /// </param>
  2217. /// <returns>
  2218. /// true if the object was added, false if an object with the same uuid was already in the scene
  2219. /// </returns>
  2220. public bool AddRestoredSceneObject(
  2221. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
  2222. {
  2223. if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
  2224. {
  2225. sceneObject.IsDeleted = false;
  2226. EventManager.TriggerObjectAddedToScene(sceneObject);
  2227. return true;
  2228. }
  2229. return false;
  2230. }
  2231. /// <summary>
  2232. /// Add an object into the scene that has come from storage
  2233. /// </summary>
  2234. ///
  2235. /// <param name="sceneObject"></param>
  2236. /// <param name="attachToBackup">
  2237. /// If true, changes to the object will be reflected in its persisted data
  2238. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2239. /// </param>
  2240. /// <param name="alreadyPersisted">
  2241. /// If true, we won't persist this object until it changes
  2242. /// If false, we'll persist this object immediately
  2243. /// </param>
  2244. /// <returns>
  2245. /// true if the object was added, false if an object with the same uuid was already in the scene
  2246. /// </returns>
  2247. public bool AddRestoredSceneObject(
  2248. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  2249. {
  2250. return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
  2251. }
  2252. /// <summary>
  2253. /// Add a newly created object to the scene. Updates are also sent to viewers.
  2254. /// </summary>
  2255. /// <param name="sceneObject"></param>
  2256. /// <param name="attachToBackup">
  2257. /// If true, the object is made persistent into the scene.
  2258. /// If false, the object will not persist over server restarts
  2259. /// </param>
  2260. /// <returns>true if the object was added. false if not</returns>
  2261. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  2262. {
  2263. return AddNewSceneObject(sceneObject, attachToBackup, true);
  2264. }
  2265. /// <summary>
  2266. /// Add a newly created object to the scene
  2267. /// </summary>
  2268. /// <param name="sceneObject"></param>
  2269. /// <param name="attachToBackup">
  2270. /// If true, the object is made persistent into the scene.
  2271. /// If false, the object will not persist over server restarts
  2272. /// </param>
  2273. /// <param name="sendClientUpdates">
  2274. /// If true, updates for the new scene object are sent to all viewers in range.
  2275. /// If false, it is left to the caller to schedule the update
  2276. /// </param>
  2277. /// <returns>true if the object was added. false if not</returns>
  2278. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  2279. {
  2280. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates))
  2281. {
  2282. EventManager.TriggerObjectAddedToScene(sceneObject);
  2283. return true;
  2284. }
  2285. return false;
  2286. }
  2287. /// <summary>
  2288. /// Add a newly created object to the scene.
  2289. /// </summary>
  2290. /// <remarks>
  2291. /// This method does not send updates to the client - callers need to handle this themselves.
  2292. /// </remarks>
  2293. /// <param name="sceneObject"></param>
  2294. /// <param name="attachToBackup"></param>
  2295. /// <param name="pos">Position of the object. If null then the position stored in the object is used.</param>
  2296. /// <param name="rot">Rotation of the object. If null then the rotation stored in the object is used.</param>
  2297. /// <param name="vel">Velocity of the object. This parameter only has an effect if the object is physical</param>
  2298. /// <returns></returns>
  2299. public bool AddNewSceneObject(
  2300. SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel)
  2301. {
  2302. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, pos, rot, vel))
  2303. {
  2304. EventManager.TriggerObjectAddedToScene(sceneObject);
  2305. return true;
  2306. }
  2307. return false;
  2308. }
  2309. /// <summary>
  2310. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2311. /// </summary>
  2312. public void DeleteAllSceneObjects()
  2313. {
  2314. DeleteAllSceneObjects(false);
  2315. }
  2316. /// <summary>
  2317. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2318. /// </summary>
  2319. public void DeleteAllSceneObjects(bool exceptNoCopy)
  2320. {
  2321. List<SceneObjectGroup> toReturn = new();
  2322. lock (Entities)
  2323. {
  2324. EntityBase[] entities = Entities.GetEntities();
  2325. foreach (EntityBase e in entities)
  2326. {
  2327. if (e is SceneObjectGroup sog)
  2328. {
  2329. if (!sog.IsAttachment)
  2330. {
  2331. if (!exceptNoCopy || ((sog.EffectiveOwnerPerms & (uint)PermissionMask.Copy) != 0))
  2332. {
  2333. DeleteSceneObject(sog, false);
  2334. }
  2335. else
  2336. {
  2337. toReturn.Add(sog);
  2338. }
  2339. }
  2340. }
  2341. }
  2342. }
  2343. if (toReturn.Count > 0)
  2344. {
  2345. returnObjects(toReturn.ToArray(), null);
  2346. }
  2347. }
  2348. /// <summary>
  2349. /// Synchronously delete the given object from the scene.
  2350. /// </summary>
  2351. /// <remarks>
  2352. /// Scripts are also removed.
  2353. /// </remarks>
  2354. /// <param name="group">Object Id</param>
  2355. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2356. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  2357. {
  2358. DeleteSceneObject(group, silent, true);
  2359. }
  2360. /// <summary>
  2361. /// Synchronously delete the given object from the scene.
  2362. /// </summary>
  2363. /// <param name="group">Object Id</param>
  2364. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2365. /// <param name="removeScripts">If true, then scripts are removed. If false, then they are only stopped.</para>
  2366. public void DeleteSceneObject(SceneObjectGroup group, bool silent, bool removeScripts)
  2367. {
  2368. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  2369. if (removeScripts)
  2370. group.RemoveScriptInstances(true);
  2371. else
  2372. group.StopScriptInstances();
  2373. SceneObjectPart[] partList = group.Parts;
  2374. for(int i = 0; i < partList.Length; ++i)
  2375. {
  2376. SceneObjectPart part = partList[i];
  2377. if (part is null)
  2378. continue;
  2379. if (removeScripts)
  2380. part.Inventory?.SendReleaseScriptsControl();
  2381. if (part.KeyframeMotion is not null)
  2382. {
  2383. part.KeyframeMotion.Delete();
  2384. part.KeyframeMotion = null;
  2385. }
  2386. if ((part.AggregatedScriptEvents & scriptEvents.email) != 0)
  2387. {
  2388. IEmailModule imm = RequestModuleInterface<IEmailModule>();
  2389. imm?.RemovePartMailBox(part.UUID);
  2390. }
  2391. if (part.PhysActor is not null)
  2392. {
  2393. part.RemoveFromPhysics();
  2394. }
  2395. }
  2396. if (UnlinkSceneObject(group, false))
  2397. {
  2398. EventManager.TriggerObjectBeingRemovedFromScene(group);
  2399. EventManager.TriggerParcelPrimCountTainted();
  2400. }
  2401. group.DeleteGroupFromScene(silent);
  2402. // use this to mean also full delete
  2403. if (removeScripts)
  2404. group.Dispose();
  2405. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  2406. }
  2407. /// <summary>
  2408. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  2409. /// object itself is not destroyed.
  2410. /// </summary>
  2411. /// <param name="so">The scene object.</param>
  2412. /// <param name="softDelete">If true, only deletes from scene, but keeps the object in the database.</param>
  2413. /// <returns>true if the object was in the scene, false if it was not</returns>
  2414. public bool UnlinkSceneObject(SceneObjectGroup so, bool softDelete)
  2415. {
  2416. if (m_sceneGraph.DeleteSceneObject(so.UUID, softDelete))
  2417. {
  2418. if (!softDelete)
  2419. {
  2420. // If the group contains prims whose SceneGroupID is incorrect then force a
  2421. // database update, because RemoveObject() works by searching on the SceneGroupID.
  2422. // This is an expensive thing to do so only do it if absolutely necessary.
  2423. if (so.GroupContainsForeignPrims)
  2424. ForceSceneObjectBackup(so);
  2425. so.DetachFromBackup();
  2426. SimulationDataService.RemoveObject(so.UUID, RegionInfo.RegionID);
  2427. }
  2428. // We need to keep track of this state in case this group is still queued for further backup.
  2429. so.IsDeleted = true;
  2430. return true;
  2431. }
  2432. return false;
  2433. }
  2434. /* not in use, outdate by async method
  2435. /// <summary>
  2436. /// Move the given scene object into a new region depending on which region its absolute position has moved
  2437. /// into.
  2438. ///
  2439. /// </summary>
  2440. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  2441. /// <param name="grp">the scene object that we're crossing</param>
  2442. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  2443. {
  2444. if (grp is null)
  2445. return;
  2446. if (grp.IsDeleted)
  2447. return;
  2448. if (grp.RootPart.DIE_AT_EDGE)
  2449. {
  2450. // We remove the object here
  2451. try
  2452. {
  2453. DeleteSceneObject(grp, false);
  2454. }
  2455. catch (Exception)
  2456. {
  2457. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  2458. }
  2459. return;
  2460. }
  2461. if (grp.RootPart.RETURN_AT_EDGE)
  2462. {
  2463. // We remove the object here
  2464. try
  2465. {
  2466. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  2467. objects.Add(grp);
  2468. SceneObjectGroup[] objectsArray = objects.ToArray();
  2469. returnObjects(objectsArray, UUID.Zero);
  2470. }
  2471. catch (Exception)
  2472. {
  2473. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  2474. }
  2475. return;
  2476. }
  2477. if (EntityTransferModule is not null)
  2478. EntityTransferModule.Cross(grp, attemptedPosition, silent);
  2479. }
  2480. */
  2481. // Simple test to see if a position is in the current region.
  2482. // This test is mostly used to see if a region crossing is necessary.
  2483. // Assuming the position is relative to the region so anything outside its bounds.
  2484. // Return 'true' if position inside region.
  2485. public bool PositionIsInCurrentRegion(Vector3 pos)
  2486. {
  2487. float t = pos.X;
  2488. if (t < 0 || t >= RegionInfo.RegionSizeX)
  2489. return false;
  2490. t = pos.Y;
  2491. if (t < 0 || t >= RegionInfo.RegionSizeY)
  2492. return false;
  2493. return true;
  2494. }
  2495. /// <summary>
  2496. /// Called when objects or attachments cross the border, or teleport, between regions.
  2497. /// </summary>
  2498. /// <param name="sog"></param>
  2499. /// <returns></returns>
  2500. public bool IncomingCreateObject(Vector3 newPosition, ISceneObject sog)
  2501. {
  2502. //m_log.DebugFormat(" >>> IncomingCreateObject(sog) <<< {0} deleted? {1} isAttach? {2}", ((SceneObjectGroup)sog).AbsolutePosition,
  2503. // ((SceneObjectGroup)sog).IsDeleted, ((SceneObjectGroup)sog).RootPart.IsAttachment);
  2504. SceneObjectGroup newObject;
  2505. try
  2506. {
  2507. newObject = (SceneObjectGroup)sog;
  2508. }
  2509. catch (Exception e)
  2510. {
  2511. m_log.WarnFormat("[INTERREGION]: Problem casting object, exception {0}{1}", e.Message, e.StackTrace);
  2512. return false;
  2513. }
  2514. if (!EntityTransferModule.HandleIncomingSceneObject(newObject, newPosition))
  2515. return false;
  2516. // Do this as late as possible so that listeners have full access to the incoming object
  2517. EventManager.TriggerOnIncomingSceneObject(newObject);
  2518. return true;
  2519. }
  2520. public bool IncomingAttechments(ScenePresence sp, List<SceneObjectGroup> attachments)
  2521. {
  2522. //m_log.DebugFormat(" >>> IncomingCreateObject(sog) <<< {0} deleted? {1} isAttach? {2}", ((SceneObjectGroup)sog).AbsolutePosition,
  2523. // ((SceneObjectGroup)sog).IsDeleted, ((SceneObjectGroup)sog).RootPart.IsAttachment);
  2524. if (!EntityTransferModule.HandleIncomingAttachments(sp, attachments) || sp.IsDeleted)
  2525. return false;
  2526. // Do this as late as possible so that listeners have full access to the incoming object
  2527. foreach(SceneObjectGroup newObject in attachments)
  2528. EventManager.TriggerOnIncomingSceneObject(newObject);
  2529. return true;
  2530. }
  2531. /// <summary>
  2532. /// Adds a Scene Object group to the Scene.
  2533. /// Verifies that the creator of the object is not banned from the simulator.
  2534. /// Checks if the item is an Attachment
  2535. /// </summary>
  2536. /// <param name="sceneObject"></param>
  2537. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2538. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2539. {
  2540. if (sceneObject.OwnerID.IsZero())
  2541. {
  2542. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
  2543. return false;
  2544. }
  2545. // If the user is banned, we won't let any of their objects
  2546. // enter. Period.
  2547. //
  2548. int flags = GetUserFlags(sceneObject.OwnerID);
  2549. if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
  2550. {
  2551. m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
  2552. return false;
  2553. }
  2554. // Force allocation of new LocalId
  2555. //
  2556. SceneObjectPart[] parts = sceneObject.Parts;
  2557. for (int i = 0; i < parts.Length; i++)
  2558. parts[i].LocalId = 0;
  2559. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2560. {
  2561. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2562. // Don't sent a full update here because this will cause full updates to be sent twice for
  2563. // attachments on region crossings, resulting in viewer glitches.
  2564. AddRestoredSceneObject(sceneObject, false, false, false);
  2565. // Handle attachment special case
  2566. SceneObjectPart RootPrim = sceneObject.RootPart;
  2567. // Fix up attachment Parent Local ID
  2568. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2569. if (sp is not null)
  2570. {
  2571. SceneObjectGroup grp = sceneObject;
  2572. // m_log.DebugFormat(
  2573. // "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.FromItemID, grp.UUID);
  2574. // m_log.DebugFormat(
  2575. // "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2576. // We must currently not resume scripts at this stage since AttachmentsModule does not have the
  2577. // information that this is due to a teleport/border cross rather than an ordinary attachment.
  2578. // We currently do this in Scene.MakeRootAgent() instead.
  2579. bool attached = false;
  2580. if (AttachmentsModule is not null)
  2581. attached = AttachmentsModule.AttachObject(sp, grp, 0, false, false, true);
  2582. if (attached)
  2583. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2584. else
  2585. m_log.DebugFormat("[SCENE]: Attachment {0} arrived but failed to attach, setting to temp", sceneObject.UUID);
  2586. }
  2587. else
  2588. {
  2589. m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
  2590. // RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2591. // RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2592. }
  2593. if (sceneObject.OwnerID.IsZero())
  2594. {
  2595. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
  2596. return false;
  2597. }
  2598. }
  2599. else
  2600. {
  2601. if (sceneObject.OwnerID.IsZero())
  2602. {
  2603. m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
  2604. return false;
  2605. }
  2606. AddRestoredSceneObject(sceneObject, true, false);
  2607. }
  2608. return true;
  2609. }
  2610. private int GetStateSource(SceneObjectGroup sog)
  2611. {
  2612. if(!sog.IsAttachmentCheckFull())
  2613. return 2; // StateSource.PrimCrossing
  2614. ScenePresence sp = GetScenePresence(sog.OwnerID);
  2615. if (sp is not null)
  2616. return sp.GetStateSource();
  2617. return 2; // StateSource.PrimCrossing
  2618. }
  2619. public int GetUserFlags(UUID user)
  2620. {
  2621. //Unfortunately the SP approach means that the value is cached until region is restarted
  2622. /*
  2623. ScenePresence sp;
  2624. if (TryGetScenePresence(user, out sp))
  2625. {
  2626. return sp.UserFlags;
  2627. }
  2628. else
  2629. {
  2630. */
  2631. UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
  2632. if (uac is null)
  2633. return 0;
  2634. return uac.UserFlags;
  2635. //}
  2636. }
  2637. #endregion
  2638. #region Add/Remove Avatar Methods
  2639. public override ISceneAgent AddNewAgent(IClientAPI client, PresenceType type)
  2640. {
  2641. ScenePresence sp;
  2642. bool vialogin;
  2643. bool reallyNew = true;
  2644. // Update the number of users attempting to login
  2645. StatsReporter.UpdateUsersLoggingIn(true);
  2646. // Validation occurs in LLUDPServer
  2647. //
  2648. // XXX: A race condition exists here where two simultaneous calls to AddNewAgent can interfere with
  2649. // each other. In practice, this does not currently occur in the code.
  2650. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2651. // We lock here on AgentCircuitData to prevent a race condition between the thread adding a new connection
  2652. // and a simultaneous one that removes it (as can happen if the client is closed at a particular point
  2653. // whilst connecting).
  2654. //
  2655. // It would be easier to lock across all NewUserConnection(), AddNewAgent() and
  2656. // RemoveClient() calls for all agents, but this would allow a slow call (e.g. because of slow service
  2657. // response in some module listening to AddNewAgent()) from holding up unrelated agent calls.
  2658. //
  2659. // In practice, the lock (this) in LLUDPServer.AddNewClient() currently lock across all
  2660. // AddNewClient() operations (though not other ops).
  2661. // In the future this can be relieved once locking per agent (not necessarily on AgentCircuitData) is improved.
  2662. lock (aCircuit)
  2663. {
  2664. vialogin = (aCircuit.teleportFlags & (uint)(Constants.TeleportFlags.ViaHGLogin | Constants.TeleportFlags.ViaLogin)) != 0;
  2665. CheckHeartbeat();
  2666. sp = GetScenePresence(client.AgentId);
  2667. if (sp is null)
  2668. {
  2669. m_log.DebugFormat(
  2670. "[SCENE]: Adding new child scene presence {0} {1} to scene {2} at pos {3}, tpflags: {4}",
  2671. client.Name, client.AgentId, RegionInfo.RegionName, client.StartPos,
  2672. ((TPFlags)aCircuit.teleportFlags).ToString());
  2673. m_clientManager.Add(client);
  2674. SubscribeToClientEvents(client);
  2675. sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type);
  2676. aCircuit.Appearance = null;
  2677. sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags;
  2678. m_eventManager.TriggerOnNewPresence(sp);
  2679. }
  2680. else
  2681. {
  2682. // We must set this here so that TriggerOnNewClient and TriggerOnClientLogin can determine whether the
  2683. // client is for a root or child agent.
  2684. // XXX: This may be better set for a new client before that client is added to the client manager.
  2685. // But need to know what happens in the case where a ScenePresence is already present (and if this
  2686. // actually occurs).
  2687. m_log.WarnFormat(
  2688. "[SCENE]: Already found {0} scene presence for {1} in {2} when asked to add new scene presence",
  2689. sp.IsChildAgent ? "child" : "root", sp.Name, RegionInfo.RegionName);
  2690. reallyNew = false;
  2691. }
  2692. client.SceneAgent = sp;
  2693. // This is currently also being done earlier in NewUserConnection for real users to see if this
  2694. // resolves problems where HG agents are occasionally seen by others as "Unknown user" in chat and other
  2695. // places. However, we still need to do it here for NPCs.
  2696. CacheUserName(sp, aCircuit);
  2697. if (reallyNew)
  2698. EventManager.TriggerOnNewClient(client);
  2699. if (vialogin)
  2700. EventManager.TriggerOnClientLogin(client);
  2701. }
  2702. // User has logged into the scene so update the list of users logging
  2703. // in
  2704. StatsReporter.UpdateUsersLoggingIn(false);
  2705. m_LastLogin = Util.EnvironmentTickCount();
  2706. return sp;
  2707. }
  2708. /// <summary>
  2709. /// Returns the Home URI of the agent, or null if unknown.
  2710. /// </summary>
  2711. public string GetAgentHomeURI(UUID agentID)
  2712. {
  2713. AgentCircuitData circuit = AuthenticateHandler.GetAgentCircuitData(agentID);
  2714. if (circuit is not null && circuit.ServiceURLs is not null && circuit.ServiceURLs.ContainsKey("HomeURI"))
  2715. return circuit.ServiceURLs["HomeURI"].ToString();
  2716. else
  2717. return null;
  2718. }
  2719. /// <summary>
  2720. /// Cache the user name for later use.
  2721. /// </summary>
  2722. /// <param name="sp"></param>
  2723. /// <param name="aCircuit"></param>
  2724. private void CacheUserName(ScenePresence sp, AgentCircuitData aCircuit)
  2725. {
  2726. if (UserManagementModule is not null)
  2727. {
  2728. string first = aCircuit.firstname;
  2729. string last = aCircuit.lastname;
  2730. if (sp is not null && sp.PresenceType == PresenceType.Npc)
  2731. {
  2732. UserManagementModule.AddNPCUser(aCircuit.AgentID, first, last);
  2733. }
  2734. else
  2735. {
  2736. string homeURL = string.Empty;
  2737. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  2738. homeURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  2739. if (aCircuit.lastname.StartsWith("@"))
  2740. {
  2741. string[] parts = aCircuit.firstname.Split('.');
  2742. if (parts.Length >= 2)
  2743. {
  2744. first = parts[0];
  2745. last = parts[1];
  2746. }
  2747. }
  2748. UserManagementModule.AddUser(aCircuit.AgentID, first, last, homeURL);
  2749. }
  2750. }
  2751. }
  2752. private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin)
  2753. {
  2754. vialogin = false;
  2755. // Do the verification here
  2756. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0)
  2757. {
  2758. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via HG login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2759. vialogin = true;
  2760. IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
  2761. if (userVerification is not null && ep is not null)
  2762. {
  2763. if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString()))
  2764. {
  2765. // uh-oh, this is fishy
  2766. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2767. return false;
  2768. }
  2769. else
  2770. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2771. }
  2772. }
  2773. else if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
  2774. {
  2775. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via regular login. Client IP verification not performed.",
  2776. aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2777. vialogin = true;
  2778. }
  2779. return true;
  2780. }
  2781. // Called by Caps, on the first HTTP contact from the client
  2782. public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep)
  2783. {
  2784. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  2785. if (aCircuit is null)
  2786. return false;
  2787. if (VerifyClient(aCircuit, ep, out bool _))
  2788. return true;
  2789. // if it doesn't pass, we remove the agentcircuitdata altogether
  2790. // and the scene presence and the client, if they exist
  2791. try
  2792. {
  2793. ScenePresence sp = WaitGetScenePresence(agentID);
  2794. if (sp is not null)
  2795. {
  2796. PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  2797. CloseAgent(sp.UUID, false);
  2798. }
  2799. // BANG! SLASH!
  2800. m_authenticateHandler.RemoveCircuit(agentID);
  2801. }
  2802. catch (Exception e)
  2803. {
  2804. m_log.DebugFormat("[SCENE]: Exception while closing aborted client: {0}", e.StackTrace);
  2805. }
  2806. return false;
  2807. }
  2808. /// <summary>
  2809. /// Register for events from the client
  2810. /// </summary>
  2811. /// <param name="client">The IClientAPI of the connected client</param>
  2812. public virtual void SubscribeToClientEvents(IClientAPI client)
  2813. {
  2814. SubscribeToClientTerrainEvents(client);
  2815. SubscribeToClientPrimEvents(client);
  2816. SubscribeToClientPrimRezEvents(client);
  2817. SubscribeToClientInventoryEvents(client);
  2818. SubscribeToClientTeleportEvents(client);
  2819. SubscribeToClientScriptEvents(client);
  2820. SubscribeToClientParcelEvents(client);
  2821. SubscribeToClientGridEvents(client);
  2822. SubscribeToClientNetworkEvents(client);
  2823. }
  2824. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2825. {
  2826. // client.OnRegionHandShakeReply += SendLayerData;
  2827. }
  2828. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2829. {
  2830. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
  2831. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2832. client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
  2833. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2834. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2835. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2836. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2837. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2838. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2839. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2840. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2841. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2842. client.OnObjectRequest += RequestPrim;
  2843. client.OnObjectSelect += SelectPrim;
  2844. client.OnObjectDeselect += DeselectPrim;
  2845. client.OnDeRezObject += DeRezObjects;
  2846. client.OnObjectName += m_sceneGraph.PrimName;
  2847. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2848. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2849. client.OnLinkObjects += LinkObjects;
  2850. client.OnDelinkObjects += DelinkObjects;
  2851. client.OnObjectDuplicate += DuplicateObject;
  2852. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2853. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2854. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2855. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2856. client.OnGrabObject += ProcessObjectGrab;
  2857. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2858. client.OnDeGrabObject += ProcessObjectDeGrab;
  2859. client.OnSpinStart += ProcessSpinStart;
  2860. client.OnSpinUpdate += ProcessSpinObject;
  2861. client.OnSpinStop += ProcessSpinObjectStop;
  2862. client.OnUndo += m_sceneGraph.HandleUndo;
  2863. client.OnRedo += m_sceneGraph.HandleRedo;
  2864. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2865. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2866. client.OnObjectOwner += ObjectOwner;
  2867. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  2868. }
  2869. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2870. {
  2871. client.OnAddPrim += AddNewPrim;
  2872. client.OnRezObject += RezObject;
  2873. }
  2874. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2875. {
  2876. client.OnLinkInventoryItem += HandleLinkInventoryItem;
  2877. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2878. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2879. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2880. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2881. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2882. client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
  2883. client.OnUpdateInventoryItem += UpdateInventoryItem;
  2884. client.OnCopyInventoryItem += CopyInventoryItem;
  2885. client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
  2886. client.OnMoveInventoryItem += MoveInventoryItem;
  2887. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2888. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2889. client.OnRezScript += RezScript;
  2890. client.OnRequestTaskInventory += RequestTaskInventory;
  2891. client.OnRemoveTaskItem += RemoveTaskInventory;
  2892. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2893. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2894. }
  2895. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2896. {
  2897. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2898. }
  2899. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2900. {
  2901. client.OnScriptReset += ProcessScriptReset;
  2902. client.OnGetScriptRunning += GetScriptRunning;
  2903. client.OnSetScriptRunning += SetScriptRunning;
  2904. }
  2905. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2906. {
  2907. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2908. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2909. client.OnParcelBuy += ProcessParcelBuy;
  2910. }
  2911. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2912. {
  2913. //client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
  2914. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2915. }
  2916. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2917. {
  2918. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2919. client.OnViewerEffect += ProcessViewerEffect;
  2920. }
  2921. /// <summary>
  2922. /// Unsubscribe the client from events.
  2923. /// </summary>
  2924. /// FIXME: Not called anywhere!
  2925. /// <param name="client">The IClientAPI of the client</param>
  2926. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2927. {
  2928. UnSubscribeToClientTerrainEvents(client);
  2929. UnSubscribeToClientPrimEvents(client);
  2930. UnSubscribeToClientPrimRezEvents(client);
  2931. UnSubscribeToClientInventoryEvents(client);
  2932. UnSubscribeToClientTeleportEvents(client);
  2933. UnSubscribeToClientScriptEvents(client);
  2934. UnSubscribeToClientParcelEvents(client);
  2935. UnSubscribeToClientGridEvents(client);
  2936. UnSubscribeToClientNetworkEvents(client);
  2937. }
  2938. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2939. {
  2940. // client.OnRegionHandShakeReply -= SendLayerData;
  2941. }
  2942. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2943. {
  2944. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
  2945. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2946. client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
  2947. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2948. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2949. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2950. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2951. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2952. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2953. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2954. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2955. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2956. client.OnObjectRequest -= RequestPrim;
  2957. client.OnObjectSelect -= SelectPrim;
  2958. client.OnObjectDeselect -= DeselectPrim;
  2959. client.OnDeRezObject -= DeRezObjects;
  2960. client.OnObjectName -= m_sceneGraph.PrimName;
  2961. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2962. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2963. client.OnLinkObjects -= LinkObjects;
  2964. client.OnDelinkObjects -= DelinkObjects;
  2965. client.OnObjectDuplicate -= DuplicateObject;
  2966. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2967. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2968. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2969. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2970. client.OnGrabObject -= ProcessObjectGrab;
  2971. client.OnGrabUpdate -= ProcessObjectGrabUpdate;
  2972. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2973. client.OnSpinStart -= ProcessSpinStart;
  2974. client.OnSpinUpdate -= ProcessSpinObject;
  2975. client.OnSpinStop -= ProcessSpinObjectStop;
  2976. client.OnUndo -= m_sceneGraph.HandleUndo;
  2977. client.OnRedo -= m_sceneGraph.HandleRedo;
  2978. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2979. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2980. client.OnObjectOwner -= ObjectOwner;
  2981. }
  2982. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2983. {
  2984. client.OnAddPrim -= AddNewPrim;
  2985. client.OnRezObject -= RezObject;
  2986. }
  2987. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2988. {
  2989. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2990. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  2991. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  2992. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  2993. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  2994. client.OnFetchInventory -= m_asyncInventorySender.HandleFetchInventory;
  2995. client.OnUpdateInventoryItem -= UpdateInventoryItem;
  2996. client.OnCopyInventoryItem -= CopyInventoryItem;
  2997. client.OnMoveInventoryItem -= MoveInventoryItem;
  2998. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  2999. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  3000. client.OnRezScript -= RezScript;
  3001. client.OnRequestTaskInventory -= RequestTaskInventory;
  3002. client.OnRemoveTaskItem -= RemoveTaskInventory;
  3003. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  3004. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  3005. }
  3006. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  3007. {
  3008. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  3009. //client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  3010. //client.OnTeleportHomeRequest -= TeleportClientHome;
  3011. }
  3012. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  3013. {
  3014. client.OnScriptReset -= ProcessScriptReset;
  3015. client.OnGetScriptRunning -= GetScriptRunning;
  3016. client.OnSetScriptRunning -= SetScriptRunning;
  3017. }
  3018. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  3019. {
  3020. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  3021. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  3022. client.OnParcelBuy -= ProcessParcelBuy;
  3023. }
  3024. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  3025. {
  3026. //client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
  3027. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  3028. }
  3029. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  3030. {
  3031. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  3032. client.OnViewerEffect -= ProcessViewerEffect;
  3033. }
  3034. /// <summary>
  3035. /// Teleport an avatar to their home region
  3036. /// </summary>
  3037. /// <param name="agentId">The avatar's Unique ID</param>
  3038. /// <param name="client">The IClientAPI for the client</param>
  3039. public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
  3040. {
  3041. if (EntityTransferModule is not null)
  3042. {
  3043. return EntityTransferModule.TeleportHome(agentId, client);
  3044. }
  3045. else
  3046. {
  3047. m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
  3048. client.SendTeleportFailed("Unable to perform teleports on this simulator.");
  3049. }
  3050. return false;
  3051. }
  3052. /// <summary>
  3053. /// Duplicates object specified by localID. This is the event handler for IClientAPI.
  3054. /// </summary>
  3055. /// <param name="originalPrim">ID of object to duplicate</param>
  3056. /// <param name="offset"></param>
  3057. /// <param name="flags"></param>
  3058. /// <param name="AgentID">Agent doing the duplication</param>
  3059. /// <param name="GroupID">Group of new object</param>
  3060. public void DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID)
  3061. {
  3062. bool createSelected = (flags & (uint)PrimFlags.CreateSelected) != 0;
  3063. SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, AgentID,
  3064. GroupID, Quaternion.Identity, createSelected);
  3065. if (copy is not null)
  3066. EventManager.TriggerObjectAddedToScene(copy);
  3067. }
  3068. /// <summary>
  3069. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  3070. /// RayEnd and RayStart to determine what the angle of the ray is
  3071. /// </summary>
  3072. /// <param name="localID">ID of object to duplicate</param>
  3073. /// <param name="dupeFlags"></param>
  3074. /// <param name="AgentID">Agent doing the duplication</param>
  3075. /// <param name="GroupID">Group of new object</param>
  3076. /// <param name="RayTargetObj">The target of the Ray</param>
  3077. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  3078. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  3079. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  3080. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  3081. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  3082. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  3083. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  3084. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  3085. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  3086. {
  3087. Vector3 pos;
  3088. const bool frontFacesOnly = true;
  3089. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  3090. SceneObjectPart target = GetSceneObjectPart(localID);
  3091. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  3092. bool createSelected = (dupeFlags & (uint)PrimFlags.CreateSelected) != 0;
  3093. if (target is not null && target2 is not null)
  3094. {
  3095. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  3096. //pos = target2.AbsolutePosition;
  3097. //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString());
  3098. // TODO: Raytrace better here
  3099. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  3100. Ray NewRay = new(RayStart,direction);
  3101. // Ray Trace against target here
  3102. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  3103. // Un-comment out the following line to Get Raytrace results printed to the console.
  3104. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  3105. float ScaleOffset = 0.5f;
  3106. // If we hit something
  3107. if (ei.HitTF)
  3108. {
  3109. Vector3 scale = target.Scale;
  3110. Vector3 scaleComponent = ei.AAfaceNormal;
  3111. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  3112. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  3113. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  3114. ScaleOffset = Math.Abs(ScaleOffset);
  3115. Vector3 intersectionpoint = ei.ipoint;
  3116. Vector3 normal = ei.normal;
  3117. Vector3 offset = normal * (ScaleOffset / 2f);
  3118. pos = intersectionpoint + offset;
  3119. // stick in offset format from the original prim
  3120. pos -= target.ParentGroup.AbsolutePosition;
  3121. SceneObjectGroup copy;
  3122. if (CopyRotates)
  3123. {
  3124. Quaternion worldRot = target2.GetWorldRotation();
  3125. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  3126. copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, worldRot, createSelected);
  3127. //obj.Rotation = worldRot;
  3128. //obj.UpdateGroupRotationR(worldRot);
  3129. }
  3130. else
  3131. {
  3132. copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, Quaternion.Identity, createSelected);
  3133. }
  3134. if (copy is not null)
  3135. EventManager.TriggerObjectAddedToScene(copy);
  3136. }
  3137. }
  3138. }
  3139. /// <summary>
  3140. /// Get the avatar appearance for the given client.
  3141. /// </summary>
  3142. /// <param name="client"></param>
  3143. /// <param name="appearance"></param>
  3144. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  3145. {
  3146. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  3147. if (aCircuit is null)
  3148. {
  3149. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  3150. appearance = new AvatarAppearance();
  3151. return;
  3152. }
  3153. appearance = aCircuit.Appearance;
  3154. if (appearance is null)
  3155. {
  3156. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  3157. appearance = new AvatarAppearance();
  3158. }
  3159. }
  3160. /// <summary>
  3161. /// Remove the given client from the scene.
  3162. /// </summary>
  3163. /// <remarks>
  3164. /// Only clientstack code should call this directly. All other code should call IncomingCloseAgent() instead
  3165. /// to properly operate the state machine and avoid race conditions with other close requests (such as directly
  3166. /// from viewers).
  3167. /// </remarks>
  3168. /// <param name='agentID'>ID of agent to close</param>
  3169. /// <param name='closeChildAgents'>
  3170. /// Close the neighbour child agents associated with this client.
  3171. /// </param>
  3172. ///
  3173. private readonly object m_removeClientPrivLock = new();
  3174. public void RemoveClient(UUID agentID, bool closeChildAgents)
  3175. {
  3176. AgentCircuitData acd = m_authenticateHandler.GetAgentCircuitData(agentID);
  3177. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3178. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3179. // However, will keep for now just in case.
  3180. if (acd is null)
  3181. {
  3182. m_log.ErrorFormat(
  3183. "[SCENE]: No agent circuit found for {0} in {1}, aborting Scene.RemoveClient", agentID, Name);
  3184. return;
  3185. }
  3186. // TODO: Can we now remove this lock?
  3187. lock (m_removeClientPrivLock)
  3188. {
  3189. bool isChildAgent = false;
  3190. ScenePresence avatar = GetScenePresence(agentID);
  3191. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3192. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3193. // However, will keep for now just in case.
  3194. if (avatar is null)
  3195. {
  3196. m_log.ErrorFormat(
  3197. "[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in the scene.", agentID);
  3198. m_authenticateHandler.RemoveCircuit(agentID);
  3199. return;
  3200. }
  3201. try
  3202. {
  3203. isChildAgent = avatar.IsChildAgent;
  3204. m_log.DebugFormat(
  3205. "[SCENE]: Removing {0} agent {1} {2} from {3}",
  3206. isChildAgent ? "child" : "root", avatar.Name, agentID, Name);
  3207. // Don't do this to root agents, it's not nice for the viewer
  3208. if (closeChildAgents && isChildAgent)
  3209. {
  3210. // Tell a single agent to disconnect from the region.
  3211. // Let's do this via UDP
  3212. avatar.ControllingClient.SendShutdownConnectionNotice();
  3213. }
  3214. // Only applies to root agents.
  3215. if (avatar.ParentID != 0)
  3216. {
  3217. avatar.StandUp();
  3218. }
  3219. m_sceneGraph.removeUserCount(!isChildAgent);
  3220. if (closeChildAgents && !isChildAgent)
  3221. {
  3222. List<ulong> regions = avatar.KnownRegionHandles;
  3223. regions.Remove(RegionInfo.RegionHandle);
  3224. // This ends up being done asynchronously so that a logout isn't held up where there are many present but unresponsive neighbours.
  3225. m_sceneGridService.SendCloseChildAgentConnections(agentID, acd.SessionID.ToString(), regions);
  3226. }
  3227. m_eventManager.TriggerClientClosed(agentID, this);
  3228. // m_log.Debug("[Scene]TriggerClientClosed done");
  3229. m_eventManager.TriggerOnRemovePresence(agentID);
  3230. // m_log.Debug("[Scene]TriggerOnRemovePresence done");
  3231. if (!isChildAgent)
  3232. {
  3233. AttachmentsModule?.DeRezAttachments(avatar);
  3234. ForEachClient(
  3235. delegate(IClientAPI client)
  3236. {
  3237. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  3238. try { client.SendKillObject(new List<uint> { avatar.LocalId }); }
  3239. catch (NullReferenceException) { }
  3240. });
  3241. }
  3242. // It's possible for child agents to have transactions if changes are being made cross-border.
  3243. // m_log.Debug("[Scene]RemoveAgentAssetTransactions");
  3244. AgentTransactionsModule?.RemoveAgentAssetTransactions(agentID);
  3245. m_log.Debug("[Scene] The avatar has left the building");
  3246. }
  3247. catch (Exception e)
  3248. {
  3249. m_log.Error(
  3250. string.Format("[SCENE]: Exception removing {0} from {1}. Cleaning up. Exception ", avatar.Name, Name), e);
  3251. }
  3252. finally
  3253. {
  3254. try
  3255. {
  3256. // Always clean these structures up so that any failure above doesn't cause them to remain in the
  3257. // scene with possibly bad effects (e.g. continually timing out on unacked packets and triggering
  3258. // the same cleanup exception continually.
  3259. m_authenticateHandler.RemoveCircuit(acd);
  3260. m_sceneGraph.RemoveScenePresence(agentID);
  3261. m_clientManager.Remove(agentID);
  3262. if (m_capsModule is not null)
  3263. {
  3264. if(avatar is null || !avatar.IsNPC)
  3265. m_capsModule.RemoveCaps(agentID, acd.circuitcode);
  3266. }
  3267. avatar.Dispose();
  3268. }
  3269. catch (Exception e)
  3270. {
  3271. m_log.Error(
  3272. string.Format("[SCENE]: Exception in final clean up of {0} in {1}. Exception ", avatar.Name, Name), e);
  3273. }
  3274. }
  3275. }
  3276. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  3277. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  3278. }
  3279. /// <summary>
  3280. /// Removes region from an avatar's known region list. This coincides with child agents. For each child agent, there will be a known region entry.
  3281. ///
  3282. /// </summary>
  3283. /// <param name="avatarID"></param>
  3284. /// <param name="regionslst"></param>
  3285. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  3286. {
  3287. ScenePresence av = GetScenePresence(avatarID);
  3288. if (av is not null)
  3289. {
  3290. lock (av)
  3291. {
  3292. for (int i = 0; i < regionslst.Count; i++)
  3293. {
  3294. av.RemoveNeighbourRegion(regionslst[i]);
  3295. }
  3296. }
  3297. }
  3298. }
  3299. #endregion
  3300. #region Entities
  3301. public void SendKillObject(List<uint> localIDs)
  3302. {
  3303. List<uint> deleteIDs = new();
  3304. foreach (uint localID in localIDs)
  3305. {
  3306. SceneObjectPart part = GetSceneObjectPart(localID);
  3307. if (part is not null && part.ParentGroup is not null &&
  3308. part.ParentGroup.RootPart == part)
  3309. deleteIDs.Add(localID);
  3310. }
  3311. ForEachClient(c => c.SendKillObject(deleteIDs));
  3312. }
  3313. #endregion
  3314. #region RegionComms
  3315. /// <summary>
  3316. /// Do the work necessary to initiate a new user connection for a particular scene.
  3317. /// </summary>
  3318. /// <param name="agent">CircuitData of the agent who is connecting</param>
  3319. /// <param name="teleportFlags"></param>
  3320. /// <param name="source">Source region (may be null)</param>
  3321. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3322. /// <returns>True if the region accepts this agent. False if it does not. False will
  3323. /// also return a reason.</returns>
  3324. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, GridRegion source, out string reason)
  3325. {
  3326. return NewUserConnection(agent, teleportFlags, source, out reason, true);
  3327. }
  3328. /// <summary>
  3329. /// Do the work necessary to initiate a new user connection for a particular scene.
  3330. /// </summary>
  3331. /// <remarks>
  3332. /// The return bool should allow for connections to be refused, but as not all calling paths
  3333. /// take proper notice of it yet, we still allowed banned users in.
  3334. ///
  3335. /// At the moment this method consists of setting up the caps infrastructure
  3336. /// The return bool should allow for connections to be refused, but as not all calling paths
  3337. /// take proper notice of it let, we allowed banned users in still.
  3338. ///
  3339. /// This method is called by the login service (in the case of login) or another simulator (in the case of region
  3340. /// cross or teleport) to initiate the connection. It is not triggered by the viewer itself - the connection
  3341. /// is activated later when the viewer sends the initial UseCircuitCodePacket UDP packet (in the case of
  3342. /// the LLUDP stack).
  3343. /// </remarks>
  3344. /// <param name="acd">CircuitData of the agent who is connecting</param>
  3345. /// <param name="source">Source region (may be null)</param>
  3346. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3347. /// <param name="requirePresenceLookup">True for normal presence. False for NPC
  3348. /// or other applications where a full grid/Hypergrid presence may not be required.</param>
  3349. /// <returns>True if the region accepts this agent. False if it does not. False will
  3350. /// also return a reason.</returns>
  3351. ///
  3352. private readonly object m_newUserConnLock = new();
  3353. public bool NewUserConnection(AgentCircuitData acd, uint teleportFlags, GridRegion source, out string reason, bool requirePresenceLookup)
  3354. {
  3355. bool vialogin = (teleportFlags & (uint)(TPFlags.ViaLogin | TPFlags.ViaHGLogin)) != 0;
  3356. bool viahome = (teleportFlags & (uint)TPFlags.ViaHome) != 0;
  3357. //bool godlike = ((teleportFlags & (uint)TPFlags.Godlike) != 0);
  3358. reason = String.Empty;
  3359. //Teleport flags:
  3360. //
  3361. // TeleportFlags.ViaGodlikeLure - Border Crossing
  3362. // TeleportFlags.ViaLogin - Login
  3363. // TeleportFlags.ViaLure - Teleport request sent by another user
  3364. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  3365. // Don't disable this log message - it's too helpful
  3366. string curViewer = Util.GetViewerName(acd);
  3367. m_log.DebugFormat(
  3368. "[SCENE]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, IP {6}, viewer {7}, teleportflags ({8}), position {9}. {10}",
  3369. RegionInfo.RegionName,
  3370. (acd.child ? "child" : "root"),
  3371. acd.firstname,
  3372. acd.lastname,
  3373. acd.AgentID,
  3374. acd.circuitcode,
  3375. acd.IPAddress,
  3376. curViewer,
  3377. ((TPFlags)teleportFlags).ToString(),
  3378. acd.startpos,
  3379. (source is null) ? "" : string.Format("From region {0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI is null) ? "" : " @ " + source.ServerURI)
  3380. );
  3381. //m_log.DebugFormat("NewUserConnection stack {0}", Environment.StackTrace);
  3382. if (!LoginsEnabled)
  3383. {
  3384. reason = "Logins to this region are disabled";
  3385. return false;
  3386. }
  3387. //Check if the viewer is banned or in the viewer access list
  3388. //We check if the substring is listed for higher flexebility
  3389. bool ViewerDenied = true;
  3390. string cV = null;
  3391. //Check if the specific viewer is listed in the allowed viewer list
  3392. if (m_AllowedViewers.Count > 0)
  3393. {
  3394. cV = curViewer.Trim().ToLower();
  3395. foreach (string viewer in m_AllowedViewers)
  3396. {
  3397. if (viewer == cV[..Math.Min(viewer.Length, curViewer.Length)])
  3398. {
  3399. ViewerDenied = false;
  3400. break;
  3401. }
  3402. }
  3403. }
  3404. else
  3405. {
  3406. ViewerDenied = false;
  3407. }
  3408. //Check if the viewer is in the banned list
  3409. if (m_BannedViewers.Count > 0)
  3410. {
  3411. cV ??= curViewer.Trim().ToLower();
  3412. foreach (string viewer in m_BannedViewers)
  3413. {
  3414. if (viewer == cV[..Math.Min(viewer.Length, curViewer.Length)])
  3415. {
  3416. ViewerDenied = true;
  3417. break;
  3418. }
  3419. }
  3420. }
  3421. if (ViewerDenied)
  3422. {
  3423. m_log.DebugFormat(
  3424. "[SCENE]: Access denied for {0} {1} using {2}",
  3425. acd.firstname, acd.lastname, curViewer);
  3426. reason = "Access denied, your viewer is banned";
  3427. return false;
  3428. }
  3429. ScenePresence sp;
  3430. lock (m_removeClientLock)
  3431. {
  3432. sp = GetScenePresence(acd.AgentID);
  3433. // We need to ensure that we are not already removing the scene presence before we ask it not to be
  3434. // closed.
  3435. if (sp is not null && !sp.IsDeleted && sp.IsChildAgent &&
  3436. (sp.LifecycleState == ScenePresenceState.Running || sp.LifecycleState == ScenePresenceState.PreRemove))
  3437. {
  3438. m_log.Debug($"[SCENE]: Reusing existing child scene presence for {sp.Name}, state {sp.LifecycleState} in {Name}");
  3439. // In the case where, for example, an A B C D region layout, an avatar may
  3440. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. When C
  3441. // renews the lease on the child agent at B, we must make sure that the close from A does not succeed.
  3442. //
  3443. // XXX: In the end, this should not be necessary if child agents are closed without delay on
  3444. // teleport, since realistically, the close request should always be processed before any other
  3445. // region tried to re-establish a child agent. This is much simpler since the logic below is
  3446. // vulnerable to an issue when a viewer quits a region without sending a proper logout but then
  3447. // re-establishes the connection on a relogin. This could wrongly set the DoNotCloseAfterTeleport
  3448. // flag when no teleport had taken place (and hence no close was going to come).
  3449. //if (!acd.ChildrenCapSeeds.ContainsKey(RegionInfo.RegionHandle))
  3450. //{
  3451. // m_log.DebugFormat(
  3452. // "[SCENE]: Setting DoNotCloseAfterTeleport for child scene presence {0} in {1} because source will attempt close.",
  3453. // sp.Name, Name);
  3454. // sp.DoNotCloseAfterTeleport = true;
  3455. //}
  3456. //else if (EntityTransferModule.IsInTransit(sp.UUID))
  3457. sp.LifecycleState = ScenePresenceState.Running;
  3458. if (EntityTransferModule.IsInTransit(sp.UUID))
  3459. {
  3460. sp.DoNotCloseAfterTeleport = true;
  3461. m_log.Debug($"[SCENE]: Set DoNotCloseAfterTeleport for child scene presence {sp.Name} in {Name} because this region will attempt end-of-teleport close from a previous close.");
  3462. }
  3463. }
  3464. }
  3465. // Need to poll here in case we are currently deleting an sp. Letting threads run over each other will
  3466. // allow unpredictable things to happen.
  3467. if (sp is not null && sp.LifecycleState == ScenePresenceState.Removing)
  3468. {
  3469. const int polls = 10;
  3470. const int pollInterval = 1000;
  3471. int pollsLeft = polls;
  3472. try
  3473. {
  3474. while (!sp.IsDeleted && sp.LifecycleState == ScenePresenceState.Removing && pollsLeft-- > 0)
  3475. Thread.Sleep(pollInterval);
  3476. if (!sp.IsDeleted && sp.LifecycleState == ScenePresenceState.Removing)
  3477. {
  3478. m_log.WarnFormat(
  3479. "[SCENE]: Agent {0} in {1} was still being removed after {2}s. Aborting NewUserConnection.",
  3480. sp.Name, Name, polls * pollInterval / 1000);
  3481. return false;
  3482. }
  3483. else if (polls != pollsLeft)
  3484. {
  3485. m_log.DebugFormat(
  3486. "[SCENE]: NewUserConnection for agent {0} in {1} had to wait {2}s for in-progress removal to complete on an old presence.",
  3487. sp.Name, Name, polls * pollInterval / 1000);
  3488. }
  3489. }
  3490. catch
  3491. {
  3492. sp = null;
  3493. }
  3494. }
  3495. if (teleportFlags != (uint)TPFlags.Default)
  3496. {
  3497. // Make sure root avatar position is in the region
  3498. if (acd.startpos.X < 0)
  3499. acd.startpos.X = 1f;
  3500. else if (acd.startpos.X >= RegionInfo.RegionSizeX)
  3501. acd.startpos.X = RegionInfo.RegionSizeX - 1f;
  3502. if (acd.startpos.Y < 0)
  3503. acd.startpos.Y = 1f;
  3504. else if (acd.startpos.Y >= RegionInfo.RegionSizeY)
  3505. acd.startpos.Y = RegionInfo.RegionSizeY - 1f;
  3506. }
  3507. // only check access, actual relocations will happen later on ScenePresence MakeRoot
  3508. // allow child agents creation
  3509. //if(!godlike && teleportFlags != (uint) TPFlags.Default)
  3510. if (teleportFlags != (uint)TPFlags.Default)
  3511. {
  3512. bool checkTeleHub;
  3513. // don't check hubs if via home or via lure
  3514. if ((teleportFlags & (uint)(TPFlags.ViaHome | TPFlags.ViaLure)) != 0)
  3515. checkTeleHub = false;
  3516. else
  3517. checkTeleHub = vialogin
  3518. || (TelehubAllowLandmarks != true && ((teleportFlags & (uint)(TPFlags.ViaLandmark | TPFlags.ViaLocation)) != 0));
  3519. if (!CheckLandPositionAccess(acd.AgentID, true, checkTeleHub, false, acd.startpos, out reason))
  3520. {
  3521. m_authenticateHandler.RemoveCircuit(acd);
  3522. return false;
  3523. }
  3524. }
  3525. // TODO: can we remove this lock?
  3526. lock (m_newUserConnLock)
  3527. {
  3528. if(sp is not null && sp.IsDeleted)
  3529. sp = null;
  3530. if (sp is not null && !sp.IsChildAgent)
  3531. {
  3532. // We have a root agent. Is it in transit?
  3533. if (!EntityTransferModule.IsInTransit(sp.UUID))
  3534. {
  3535. // We have a zombie from a crashed session.
  3536. // Or the same user is trying to be root twice here, won't work.
  3537. // Kill it.
  3538. m_log.WarnFormat(
  3539. "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
  3540. sp.Name, sp.UUID, RegionInfo.RegionName);
  3541. if (sp.ControllingClient is not null)
  3542. CloseAgent(sp.UUID, true);
  3543. sp = null;
  3544. }
  3545. //else
  3546. // m_log.WarnFormat("[SCENE]: Existing root scene presence for {0} {1} in {2}, but agent is in trasit", sp.Name, sp.UUID, RegionInfo.RegionName);
  3547. }
  3548. // Optimistic: add or update the circuit data with the new agent circuit data and teleport flags.
  3549. // We need the circuit data here for some of the subsequent checks. (groups, for example)
  3550. // If the checks fail, we remove the circuit.
  3551. acd.teleportFlags = teleportFlags;
  3552. if (vialogin)
  3553. {
  3554. IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
  3555. cache?.Remove(acd.AgentID);
  3556. }
  3557. m_authenticateHandler.AddNewCircuit(acd);
  3558. if (sp is null) // We don't have an [child] agent here already
  3559. {
  3560. if (requirePresenceLookup)
  3561. {
  3562. try
  3563. {
  3564. if (!VerifyUserPresence(acd, out reason))
  3565. {
  3566. m_authenticateHandler.RemoveCircuit(acd);
  3567. return false;
  3568. }
  3569. }
  3570. catch (Exception e)
  3571. {
  3572. m_log.ErrorFormat(
  3573. "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
  3574. m_authenticateHandler.RemoveCircuit(acd);
  3575. return false;
  3576. }
  3577. }
  3578. try
  3579. {
  3580. if (!AuthorizeUser(acd, (!vialogin && SeeIntoRegion), out reason))
  3581. {
  3582. m_authenticateHandler.RemoveCircuit(acd);
  3583. return false;
  3584. }
  3585. }
  3586. catch (Exception e)
  3587. {
  3588. m_log.ErrorFormat(
  3589. "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
  3590. m_authenticateHandler.RemoveCircuit(acd);
  3591. return false;
  3592. }
  3593. m_log.InfoFormat(
  3594. "[SCENE {0}]: authorized {1} agent {2} {3} {4} (circuit code {5})",
  3595. Name, (acd.child ? "child" : "root"), acd.firstname, acd.lastname,
  3596. acd.AgentID, acd.circuitcode);
  3597. if (m_capsModule is not null)
  3598. {
  3599. m_capsModule.SetAgentCapsSeeds(acd);
  3600. m_capsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3601. }
  3602. }
  3603. else
  3604. {
  3605. sp.TeleportFlags = (TPFlags)teleportFlags;
  3606. if (sp.IsChildAgent)
  3607. {
  3608. m_log.DebugFormat(
  3609. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  3610. acd.AgentID, RegionInfo.RegionName);
  3611. if (m_capsModule is not null)
  3612. {
  3613. m_capsModule.SetAgentCapsSeeds(acd);
  3614. m_capsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3615. }
  3616. sp.AdjustKnownSeeds();
  3617. }
  3618. }
  3619. // Try caching an incoming user name much earlier on to see if this helps with an issue
  3620. // where HG users are occasionally seen by others as "Unknown User" because their UUIDName
  3621. // request for the HG avatar appears to trigger before the user name is cached.
  3622. CacheUserName(null, acd);
  3623. }
  3624. m_capsModule?.ActivateCaps(acd.circuitcode);
  3625. return true;
  3626. }
  3627. private bool IsPositionAllowed(UUID agentID, Vector3 pos, ref string reason)
  3628. {
  3629. ILandObject land = LandChannel.GetLandObject(pos);
  3630. if (land is null)
  3631. return true;
  3632. if (land.IsBannedFromLand(agentID) || land.IsRestrictedFromLand(agentID))
  3633. {
  3634. reason = "You are banned from the region.";
  3635. return false;
  3636. }
  3637. return true;
  3638. }
  3639. public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
  3640. {
  3641. if (posX < 0)
  3642. posX = 0;
  3643. else if (posX >= RegionInfo.RegionSizeX)
  3644. posX = RegionInfo.RegionSizeX - 0.5f;
  3645. if (posY < 0)
  3646. posY = 0;
  3647. else if (posY >= RegionInfo.RegionSizeY)
  3648. posY = RegionInfo.RegionSizeY - 0.5f;
  3649. reason = String.Empty;
  3650. if (Permissions.IsGod(agentID))
  3651. return true;
  3652. ILandObject land = LandChannel.GetLandObject(posX, posY);
  3653. if (land is null)
  3654. return false;
  3655. bool banned = land.IsBannedFromLand(agentID);
  3656. bool restricted = land.IsRestrictedFromLand(agentID);
  3657. if (banned || restricted)
  3658. {
  3659. ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
  3660. Vector2? newPosition = null;
  3661. if (nearestParcel is not null)
  3662. {
  3663. //Move agent to nearest allowed
  3664. // Vector2 newPosition = GetParcelSafeCorner(nearestParcel);
  3665. newPosition = nearestParcel.GetNearestPoint(new Vector3(posX, posY,0));
  3666. }
  3667. if(newPosition is null)
  3668. {
  3669. if (banned)
  3670. {
  3671. reason = "Cannot regioncross into banned parcel.";
  3672. }
  3673. else
  3674. {
  3675. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3676. RegionInfo.RegionName);
  3677. }
  3678. return false;
  3679. }
  3680. else
  3681. {
  3682. posX = newPosition.Value.X;
  3683. posY = newPosition.Value.Y;
  3684. }
  3685. }
  3686. reason = "";
  3687. return true;
  3688. }
  3689. /// <summary>
  3690. /// Verifies that the user has a presence on the Grid
  3691. /// </summary>
  3692. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3693. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3694. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3695. /// also return a reason.</returns>
  3696. public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
  3697. {
  3698. IPresenceService presencesvc = RequestModuleInterface<IPresenceService>();
  3699. if (presencesvc is null)
  3700. {
  3701. reason = String.Format("Failed to verify user presence in the grid for {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3702. return false;
  3703. }
  3704. OpenSim.Services.Interfaces.PresenceInfo pinfo = presencesvc.GetAgent(agent.SessionID);
  3705. if (pinfo is null)
  3706. {
  3707. reason = String.Format("Failed to verify user presence in the grid for {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3708. return false;
  3709. }
  3710. if(pinfo.UserID != agent.AgentID.ToString())
  3711. {
  3712. reason = String.Format("Failed to verify user presence in the grid for {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3713. return false;
  3714. }
  3715. reason = string.Empty;
  3716. return true;
  3717. }
  3718. /// <summary>
  3719. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3720. /// </summary>
  3721. /// <param name="agent">The circuit data for the agent</param>
  3722. /// <param name="reason">outputs the reason to this string</param>
  3723. /// <returns>True if the region accepts this agent. False if it does not. False will
  3724. /// also return a reason.</returns>
  3725. protected virtual bool AuthorizeUser(AgentCircuitData agent, bool bypassAccessControl, out string reason)
  3726. {
  3727. reason = string.Empty;
  3728. if(agent.AgentID.Equals(Constants.servicesGodAgentID))
  3729. return false;
  3730. if (!m_strictAccessControl)
  3731. return true;
  3732. if (Permissions.IsGod(agent.AgentID))
  3733. return true;
  3734. if (AuthorizationService is not null)
  3735. {
  3736. if (!AuthorizationService.IsAuthorizedForRegion(
  3737. agent.AgentID.ToString(), agent.firstname, agent.lastname, RegionInfo.RegionID.ToString(), out reason))
  3738. {
  3739. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because: {4}",
  3740. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName, reason);
  3741. return false;
  3742. }
  3743. }
  3744. // We only test the things below when we want to cut off
  3745. // child agents from being present in the scene for which their root
  3746. // agent isn't allowed. Otherwise, we allow child agents. The test for
  3747. // the root is done elsewhere (QueryAccess)
  3748. if (!bypassAccessControl)
  3749. {
  3750. if(RegionInfo.EstateSettings is null)
  3751. {
  3752. // something is broken? let it get in
  3753. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
  3754. return true;
  3755. }
  3756. // check estate ban
  3757. int flags = GetUserFlags(agent.AgentID);
  3758. if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, flags))
  3759. {
  3760. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3761. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3762. reason = string.Format("Denied access to region {0}: You have been banned from that region.",
  3763. RegionInfo.RegionName);
  3764. return false;
  3765. }
  3766. // public access
  3767. if (RegionInfo.EstateSettings.PublicAccess)
  3768. return true;
  3769. // in access list / owner / manager
  3770. if (RegionInfo.EstateSettings.HasAccess(agent.AgentID))
  3771. return true;
  3772. // finally test groups
  3773. bool groupAccess = false;
  3774. // some say GOTO is ugly
  3775. if(m_groupsModule is null) // if no groups refuse
  3776. goto Label_GroupsDone;
  3777. UUID[] estateGroups = RegionInfo.EstateSettings.EstateGroups;
  3778. if(estateGroups is null)
  3779. {
  3780. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate GroupMembership is null!");
  3781. goto Label_GroupsDone;
  3782. }
  3783. if(estateGroups.Length == 0)
  3784. goto Label_GroupsDone;
  3785. List<UUID> agentGroups = new();
  3786. GroupMembershipData[] GroupMembership = m_groupsModule.GetMembershipData(agent.AgentID);
  3787. if(GroupMembership is null)
  3788. {
  3789. m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
  3790. goto Label_GroupsDone;
  3791. }
  3792. if(GroupMembership.Length == 0)
  3793. goto Label_GroupsDone;
  3794. for(int i = 0;i < GroupMembership.Length;i++)
  3795. agentGroups.Add(GroupMembership[i].GroupID);
  3796. foreach(UUID group in estateGroups)
  3797. {
  3798. if(agentGroups.Contains(group))
  3799. {
  3800. groupAccess = true;
  3801. break;
  3802. }
  3803. }
  3804. Label_GroupsDone:
  3805. if (!groupAccess)
  3806. {
  3807. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3808. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3809. reason = String.Format("Denied access to private region {0}: You do not have access to that region.",
  3810. RegionInfo.RegionName);
  3811. return false;
  3812. }
  3813. }
  3814. return true;
  3815. }
  3816. /// <summary>
  3817. /// Update an AgentCircuitData object with new information
  3818. /// </summary>
  3819. /// <param name="data">Information to update the AgentCircuitData with</param>
  3820. public void UpdateCircuitData(AgentCircuitData data)
  3821. {
  3822. m_authenticateHandler.UpdateAgentData(data);
  3823. }
  3824. /// <summary>
  3825. /// Change the Circuit Code for the user's Circuit Data
  3826. /// </summary>
  3827. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3828. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3829. /// <returns>True if we successfully changed it. False if we did not</returns>
  3830. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3831. {
  3832. return m_authenticateHandler.TryChangeCircuitCode(oldcc, newcc);
  3833. }
  3834. // /// <summary>
  3835. // /// The Grid has requested that we log-off a user. Log them off.
  3836. // /// </summary>
  3837. // /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3838. // /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3839. // /// <param name="message">message to display to the user. Reason for being logged off</param>
  3840. // public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3841. // {
  3842. // ScenePresence loggingOffUser = GetScenePresence(AvatarID);
  3843. // if (loggingOffUser is not null)
  3844. // {
  3845. // UUID localRegionSecret = UUID.Zero;
  3846. // bool parsedsecret = UUID.TryParse(RegionInfo.regionSecret, out localRegionSecret);
  3847. //
  3848. // // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3849. // // Will update the user server in a few revisions to use it.
  3850. //
  3851. // if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3852. // {
  3853. // m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, loggingOffUser.KnownRegionHandles);
  3854. // loggingOffUser.ControllingClient.Kick(message);
  3855. // // Give them a second to receive the message!
  3856. // Thread.Sleep(1000);
  3857. // loggingOffUser.ControllingClient.Close();
  3858. // }
  3859. // else
  3860. // {
  3861. // m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3862. // }
  3863. // }
  3864. // else
  3865. // {
  3866. // m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  3867. // }
  3868. // }
  3869. // /// <summary>
  3870. // /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3871. // /// </summary>
  3872. // /// <param name="agentID"></param>
  3873. // /// <param name="position"></param>
  3874. // /// <param name="isFlying"></param>
  3875. // public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3876. // {
  3877. // ScenePresence presence = GetScenePresence(agentID);
  3878. // if (presence is not null)
  3879. // {
  3880. // try
  3881. // {
  3882. // presence.MakeRootAgent(position, isFlying);
  3883. // }
  3884. // catch (Exception e)
  3885. // {
  3886. // m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}{1}", e.Message, e.StackTrace);
  3887. // }
  3888. // }
  3889. // else
  3890. // {
  3891. // m_log.ErrorFormat(
  3892. // "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3893. // agentID, RegionInfo.RegionName);
  3894. // }
  3895. // }
  3896. /// <summary>
  3897. /// We've got an update about an agent that sees into this region,
  3898. /// send it to ScenePresence for processing It's the full data.
  3899. /// </summary>
  3900. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3901. /// Appearance, animations, position, etc.</param>
  3902. /// <returns>true if we handled it.</returns>
  3903. public virtual bool IncomingUpdateChildAgent(AgentData cAgentData)
  3904. {
  3905. m_log.DebugFormat(
  3906. "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3907. if (!LoginsEnabled)
  3908. {
  3909. // reason = "Logins Disabled";
  3910. m_log.DebugFormat(
  3911. "[SCENE]: update for {0} in {1} refused: Logins Disabled", cAgentData.AgentID, RegionInfo.RegionName);
  3912. return false;
  3913. }
  3914. int flags = GetUserFlags(cAgentData.AgentID);
  3915. if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
  3916. {
  3917. m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
  3918. return false;
  3919. }
  3920. // TODO: This check should probably be in QueryAccess().
  3921. ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID,
  3922. (float)RegionInfo.RegionSizeX * 0.5f, (float)RegionInfo.RegionSizeY * 0.5f);
  3923. if (nearestParcel is null)
  3924. {
  3925. m_log.InfoFormat(
  3926. "[SCENE]: Denying root agent entry to {0} in {1}: no allowed parcel",
  3927. cAgentData.AgentID, RegionInfo.RegionName);
  3928. return false;
  3929. }
  3930. // We have to wait until the viewer contacts this region
  3931. // after receiving the EnableSimulator HTTP Event Queue message (for the v1 teleport protocol)
  3932. // or TeleportFinish (for the v2 teleport protocol). This triggers the viewer to send
  3933. // a UseCircuitCode packet which in turn calls AddNewAgent which finally creates the ScenePresence.
  3934. ScenePresence sp = WaitGetScenePresence(cAgentData.AgentID);
  3935. if (sp is not null)
  3936. {
  3937. if (!sp.IsChildAgent)
  3938. {
  3939. m_log.WarnFormat("[SCENE]: Ignoring a child update on a root agent {0} {1} in {2}",
  3940. sp.Name, sp.UUID, Name);
  3941. return false;
  3942. }
  3943. if (cAgentData.SessionID.NotEqual(sp.ControllingClient.SessionId))
  3944. {
  3945. m_log.WarnFormat(
  3946. "[SCENE]: Attempt to update agent {0} with diferent session id {1} != {2}",
  3947. sp.UUID, sp.ControllingClient.SessionId, cAgentData.SessionID);
  3948. return false;
  3949. }
  3950. sp.UpdateChildAgent(cAgentData);
  3951. int ntimes = 100;
  3952. if (cAgentData.SenderWantsToWaitForRoot)
  3953. {
  3954. while (sp.IsChildAgent && ntimes-- > 0)
  3955. Thread.Sleep(250);
  3956. if (sp.IsChildAgent)
  3957. {
  3958. m_log.WarnFormat(
  3959. "[SCENE]: Found presence {0} {1} unexpectedly still child in {2}",
  3960. sp.Name, sp.UUID, Name);
  3961. return false;
  3962. }
  3963. }
  3964. return true;
  3965. }
  3966. return false;
  3967. }
  3968. /// <summary>
  3969. /// We've got an update about an agent that sees into this region,
  3970. /// send it to ScenePresence for processing It's only positional data
  3971. /// </summary>
  3972. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3973. /// <returns>true if we handled it.</returns>
  3974. public virtual bool IncomingUpdateChildAgent(AgentPosition cAgentData)
  3975. {
  3976. // m_log.DebugFormat(
  3977. // "[SCENE PRESENCE]: IncomingChildAgentDataUpdate POSITION for {0} in {1}, position {2}",
  3978. // cAgentData.AgentID, Name, cAgentData.Position);
  3979. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  3980. if (childAgentUpdate is not null)
  3981. {
  3982. // if (childAgentUpdate.ControllingClient.SessionId != cAgentData.SessionID)
  3983. // // Only warn for now
  3984. // m_log.WarnFormat("[SCENE]: Attempt at updating position of agent {0} with invalid session id {1}. Neighbor running older version?",
  3985. // childAgentUpdate.UUID, cAgentData.SessionID);
  3986. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  3987. // however to avoid a race condition crossing borders..
  3988. if (childAgentUpdate.IsChildAgent)
  3989. {
  3990. //Send Data to ScenePresence
  3991. childAgentUpdate.UpdateChildAgent(cAgentData);
  3992. // Not Implemented:
  3993. //TODO: Do we need to pass the message on to one of our neighbors?
  3994. }
  3995. return true;
  3996. }
  3997. return false;
  3998. }
  3999. /// <summary>
  4000. /// Poll until the requested ScenePresence appears or we timeout.
  4001. /// </summary>
  4002. /// <returns>The scene presence is found, else null.</returns>
  4003. /// <param name='agentID'></param>
  4004. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  4005. {
  4006. int ntimes = 120; // 30s
  4007. ScenePresence sp;
  4008. while ((sp = GetScenePresence(agentID)) is null && (ntimes-- > 0))
  4009. Thread.Sleep(250);
  4010. if (sp is null)
  4011. m_log.WarnFormat(
  4012. "[SCENE PRESENCE]: Did not find presence with id {0} in {1} before timeout",
  4013. agentID, RegionInfo.RegionName);
  4014. return sp;
  4015. }
  4016. /// <summary>
  4017. /// Authenticated close (via network)
  4018. /// </summary>
  4019. /// <param name="agentID"></param>
  4020. /// <param name="force"></param>
  4021. /// <param name="auth_token"></param>
  4022. /// <returns></returns>
  4023. public bool CloseAgent(UUID agentID, bool force, string auth_token)
  4024. {
  4025. //m_log.DebugFormat("[SCENE]: Processing incoming close agent {0} in region {1} with auth_token {2}", agentID, RegionInfo.RegionName, auth_token);
  4026. // Check that the auth_token is valid
  4027. AgentCircuitData acd = AuthenticateHandler.GetAgentCircuitData(agentID);
  4028. if (acd is null)
  4029. {
  4030. m_log.DebugFormat(
  4031. "[SCENE]: Request to close agent {0} but no such agent in scene {1}. May have been closed previously.",
  4032. agentID, Name);
  4033. return false;
  4034. }
  4035. if (acd.SessionID.ToString() == auth_token)
  4036. {
  4037. return CloseAgent(agentID, force);
  4038. }
  4039. else
  4040. {
  4041. m_log.WarnFormat(
  4042. "[SCENE]: Request to close agent {0} with invalid authorization token {1} in {2}",
  4043. agentID, auth_token, Name);
  4044. }
  4045. return false;
  4046. }
  4047. /// <summary>
  4048. /// Tell a single client to prepare to close.
  4049. /// </summary>
  4050. /// <remarks>
  4051. /// This should only be called if we may close the client but there will be some delay in so doing. Meant for
  4052. /// internal use - other callers should almost certainly called CloseClient().
  4053. /// </remarks>
  4054. /// <param name="sp"></param>
  4055. /// <returns>true if pre-close state notification was successful. false if the agent
  4056. /// was not in a state where it could transition to pre-close.</returns>
  4057. public bool IncomingPreCloseClient(ScenePresence sp)
  4058. {
  4059. lock (m_removeClientLock)
  4060. {
  4061. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4062. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4063. // want to obey this close since C may have renewed the child agent lease on B.
  4064. if (sp.DoNotCloseAfterTeleport)
  4065. {
  4066. m_log.DebugFormat(
  4067. "[SCENE]: Not pre-closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4068. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4069. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4070. sp.DoNotCloseAfterTeleport = false;
  4071. return false;
  4072. }
  4073. if (sp.LifecycleState != ScenePresenceState.Running)
  4074. {
  4075. m_log.DebugFormat(
  4076. "[SCENE]: Called IncomingPreCloseAgent() for {0} in {1} but presence is already in state {2}",
  4077. sp.Name, Name, sp.LifecycleState);
  4078. return false;
  4079. }
  4080. sp.LifecycleState = ScenePresenceState.PreRemove;
  4081. return true;
  4082. }
  4083. }
  4084. /// <summary>
  4085. /// Tell a single agent to disconnect from the region.
  4086. /// </summary>
  4087. /// <param name="agentID"></param>
  4088. /// <param name="force">
  4089. /// Force the agent to close even if it might be in the middle of some other operation. You do not want to
  4090. /// force unless you are absolutely sure that the agent is dead and a normal close is not working.
  4091. /// </param>
  4092. public override bool CloseAgent(UUID agentID, bool force)
  4093. {
  4094. ScenePresence sp;
  4095. lock (m_removeClientLock)
  4096. {
  4097. sp = GetScenePresence(agentID);
  4098. if (sp is null)
  4099. {
  4100. // If there is no scene presence, we may be handling a dead
  4101. // client. These can keep an avatar from reentering a region
  4102. // and since they don't get cleaned up they will stick
  4103. // around until region restart. So, if there is no SP,
  4104. // remove the client as well.
  4105. bool ret = false;
  4106. if (m_clientManager.TryGetValue(agentID, out IClientAPI client))
  4107. {
  4108. client.Close(force, force);
  4109. m_log.DebugFormat( "[SCENE]: Dead client for agent ID {0} was cleaned up in {1}", agentID, Name);
  4110. ret = true;
  4111. }
  4112. // need to try this again, bc client close may had not done it
  4113. m_authenticateHandler?.RemoveCircuit(agentID);
  4114. m_clientManager.Remove(agentID);
  4115. m_capsModule?.RemoveCaps(agentID, 0);
  4116. return ret;
  4117. }
  4118. if (sp.LifecycleState != ScenePresenceState.Running && sp.LifecycleState != ScenePresenceState.PreRemove)
  4119. {
  4120. m_log.DebugFormat(
  4121. "[SCENE]: Called CloseClient() for {0} in {1} but presence is already in state {2}",
  4122. sp.Name, Name, sp.LifecycleState);
  4123. return false;
  4124. }
  4125. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4126. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4127. // want to obey this close since C may have renewed the child agent lease on B.
  4128. if (sp.DoNotCloseAfterTeleport)
  4129. {
  4130. m_log.DebugFormat(
  4131. "[SCENE]: Not closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4132. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4133. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4134. sp.DoNotCloseAfterTeleport = false;
  4135. return false;
  4136. }
  4137. sp.LifecycleState = ScenePresenceState.Removing;
  4138. }
  4139. if (sp is not null)
  4140. {
  4141. sp.ControllingClient.Close(force, force);
  4142. if(sp.IsNPC && UserManagementModule is not null)
  4143. UserManagementModule.RemoveUser(sp.UUID);
  4144. return true;
  4145. }
  4146. return false;
  4147. }
  4148. /// <summary>
  4149. /// Tries to teleport agent within region.
  4150. /// </summary>
  4151. /// <param name="remoteClient"></param>
  4152. /// <param name="position"></param>
  4153. /// <param name="lookAt"></param>
  4154. /// <param name="teleportFlags"></param>
  4155. public void RequestLocalTeleport(ScenePresence sp, Vector3 position, Vector3 vel,
  4156. Vector3 lookat, int flags)
  4157. {
  4158. sp.LocalTeleport(position, vel, lookat, flags);
  4159. }
  4160. /// <summary>
  4161. /// Tries to teleport agent to another region.
  4162. /// </summary>
  4163. /// <remarks>
  4164. /// The region name must exactly match that given.
  4165. /// </remarks>
  4166. /// <param name="remoteClient"></param>
  4167. /// <param name="regionName"></param>
  4168. /// <param name="position"></param>
  4169. /// <param name="lookAt"></param>
  4170. /// <param name="teleportFlags"></param>
  4171. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  4172. Vector3 lookat, uint teleportFlags)
  4173. {
  4174. if (EntityTransferModule is null)
  4175. {
  4176. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4177. return;
  4178. }
  4179. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4180. if (sp is null || sp.IsDeleted || sp.IsInTransit)
  4181. return;
  4182. ulong regionHandle = 0;
  4183. if(regionName == RegionInfo.RegionName)
  4184. regionHandle = RegionInfo.RegionHandle;
  4185. else
  4186. {
  4187. GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
  4188. if (region is not null)
  4189. regionHandle = region.RegionHandle;
  4190. }
  4191. if(regionHandle == 0)
  4192. {
  4193. // can't find the region: Tell viewer and abort
  4194. remoteClient.SendTeleportFailed($"The region '{regionName}' could not be found.");
  4195. return;
  4196. }
  4197. EntityTransferModule.Teleport(sp, regionHandle, position, lookat, teleportFlags);
  4198. }
  4199. /// <summary>
  4200. /// Tries to teleport agent to other region.
  4201. /// </summary>
  4202. /// <param name="remoteClient"></param>
  4203. /// <param name="regionHandle"></param>
  4204. /// <param name="position"></param>
  4205. /// <param name="lookAt"></param>
  4206. /// <param name="teleportFlags"></param>
  4207. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  4208. Vector3 lookAt, uint teleportFlags)
  4209. {
  4210. if (EntityTransferModule is null)
  4211. {
  4212. m_log.Debug("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4213. return;
  4214. }
  4215. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4216. if (sp is null || sp.IsDeleted || sp.IsInTransit)
  4217. return;
  4218. EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
  4219. }
  4220. public void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm, Vector3 lookAt)
  4221. {
  4222. if (EntityTransferModule is null)
  4223. {
  4224. m_log.Debug("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4225. return;
  4226. }
  4227. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4228. if (sp is null || sp.IsDeleted || sp.IsInTransit)
  4229. return;
  4230. EntityTransferModule.RequestTeleportLandmark(remoteClient, lm, lookAt);
  4231. }
  4232. public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  4233. {
  4234. if(!AllowAvatarCrossing)
  4235. return false;
  4236. if (EntityTransferModule is not null)
  4237. {
  4238. return EntityTransferModule.Cross(agent, isFlying);
  4239. }
  4240. else
  4241. {
  4242. m_log.Debug("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
  4243. }
  4244. return false;
  4245. }
  4246. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  4247. {
  4248. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  4249. }
  4250. #endregion
  4251. #region Other Methods
  4252. protected override IConfigSource GetConfig()
  4253. {
  4254. return m_config;
  4255. }
  4256. #endregion
  4257. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  4258. {
  4259. // Check for spoofing.. since this is permissions we're talking about here!
  4260. if (controller.SessionId.Equals(sessionID) && controller.AgentId.Equals(agentID))
  4261. {
  4262. // Tell the object to do permission update
  4263. if (localId != 0)
  4264. {
  4265. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  4266. chObjectGroup?.UpdatePermissions(agentID, field, localId, mask, set);
  4267. }
  4268. }
  4269. }
  4270. /// <summary>
  4271. /// Causes all clients to get a full object update on all of the objects in the scene.
  4272. /// </summary>
  4273. public void ForceClientUpdate()
  4274. {
  4275. EntityBase[] entityList = GetEntities();
  4276. foreach (EntityBase ent in entityList)
  4277. {
  4278. if (ent is SceneObjectGroup sog)
  4279. {
  4280. sog.ScheduleGroupForFullUpdate();
  4281. }
  4282. }
  4283. }
  4284. /// <summary>
  4285. /// This is currently only used for scale (to scale to MegaPrim size)
  4286. /// There is a console command that calls this in OpenSimMain
  4287. /// </summary>
  4288. /// <param name="cmdparams"></param>
  4289. public void HandleEditCommand(string[] cmdparams)
  4290. {
  4291. m_log.Debug($"Searching for Primitive: '{cmdparams[2]}'");
  4292. EntityBase[] entityList = GetEntities();
  4293. foreach (EntityBase ent in entityList)
  4294. {
  4295. if (ent is SceneObjectGroup sog)
  4296. {
  4297. SceneObjectPart part = sog.GetPart(sog.UUID);
  4298. if (part is not null)
  4299. {
  4300. if (part.Name == cmdparams[2])
  4301. {
  4302. part.Resize(
  4303. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  4304. Convert.ToSingle(cmdparams[5])));
  4305. m_log.Debug($"Edited scale of Primitive: {part.Name}");
  4306. }
  4307. }
  4308. }
  4309. }
  4310. }
  4311. #region Script Handling Methods
  4312. /// <summary>
  4313. /// Console command handler to send script command to script engine.
  4314. /// </summary>
  4315. /// <param name="args"></param>
  4316. public void SendCommandToPlugins(string[] args)
  4317. {
  4318. m_eventManager.TriggerOnPluginConsole(args);
  4319. }
  4320. public LandData GetLandData(float x, float y)
  4321. {
  4322. ILandObject parcel = LandChannel.GetLandObject(x, y);
  4323. if (parcel is null)
  4324. return null;
  4325. return parcel.LandData;
  4326. }
  4327. /// <summary>
  4328. /// Get LandData by position.
  4329. /// </summary>
  4330. /// <param name="pos"></param>
  4331. /// <returns></returns>
  4332. public LandData GetLandData(Vector3 pos)
  4333. {
  4334. return GetLandData(pos.X, pos.Y);
  4335. }
  4336. public LandData GetLandData(uint x, uint y)
  4337. {
  4338. // m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  4339. ILandObject parcel = LandChannel.GetLandObject((int)x, (int)y);
  4340. if (parcel is null)
  4341. return null;
  4342. return parcel.LandData;
  4343. }
  4344. #endregion
  4345. #region Script Engine
  4346. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4347. public bool LSLScriptDanger(SceneObjectPart part, Vector3 pos)
  4348. {
  4349. ILandObject parcel = LandChannel.GetLandObject(pos);
  4350. return LSLScriptDanger(part, parcel);
  4351. }
  4352. public bool LSLScriptDanger(SceneObjectPart part, ILandObject parcel)
  4353. {
  4354. if (parcel is null)
  4355. return true;
  4356. LandData ldata = parcel.LandData;
  4357. if (ldata is null)
  4358. return true;
  4359. uint landflags = ldata.Flags;
  4360. uint mask = (uint)(ParcelFlags.CreateObjects | ParcelFlags.AllowAPrimitiveEntry);
  4361. if((landflags & mask) != mask)
  4362. return true;
  4363. if((landflags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4364. return false;
  4365. if(part is null)
  4366. return true;
  4367. if(part.GroupID == ldata.GroupID && (landflags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4368. return false;
  4369. return true;
  4370. }
  4371. private bool ScriptDanger(SceneObjectPart part, Vector3 pos)
  4372. {
  4373. if (part is null)
  4374. return false;
  4375. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4376. if (parcel is not null)
  4377. {
  4378. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4379. return true;
  4380. if ((part.OwnerID.Equals(parcel.LandData.OwnerID)) || Permissions.IsGod(part.OwnerID))
  4381. return true;
  4382. if (((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4383. && (!parcel.LandData.GroupID.IsZero()) && (parcel.LandData.GroupID.Equals(part.GroupID)))
  4384. return true;
  4385. }
  4386. else
  4387. {
  4388. if (pos.X > 0f && pos.X < RegionInfo.RegionSizeX && pos.Y > 0f && pos.Y < RegionInfo.RegionSizeY)
  4389. return true;
  4390. }
  4391. return false;
  4392. }
  4393. public bool PipeEventsForScript(uint localID)
  4394. {
  4395. SceneObjectPart part = GetSceneObjectPart(localID);
  4396. if (part is not null)
  4397. {
  4398. SceneObjectPart parent = part.ParentGroup.RootPart;
  4399. return ScriptDanger(parent, parent.GetWorldPosition());
  4400. }
  4401. else
  4402. {
  4403. return false;
  4404. }
  4405. }
  4406. #endregion
  4407. #region SceneGraph wrapper methods
  4408. public void SwapRootAgentCount(bool direction_RoottoChild, bool isnpc)
  4409. {
  4410. m_sceneGraph.SwapRootChildAgent(direction_RoottoChild, isnpc);
  4411. }
  4412. public void AddPhysicalPrim(int num)
  4413. {
  4414. m_sceneGraph.AddPhysicalPrim(num);
  4415. }
  4416. public void RemovePhysicalPrim(int num)
  4417. {
  4418. m_sceneGraph.RemovePhysicalPrim(num);
  4419. }
  4420. public int GetRootAgentCount()
  4421. {
  4422. return m_sceneGraph.GetRootAgentCount();
  4423. }
  4424. public int GetRootNPCCount()
  4425. {
  4426. return m_sceneGraph.GetRootAgentCount();
  4427. }
  4428. public int GetChildAgentCount()
  4429. {
  4430. return m_sceneGraph.GetChildAgentCount();
  4431. }
  4432. /// <summary>
  4433. /// Request a scene presence by UUID. Fast, indexed lookup.
  4434. /// </summary>
  4435. /// <param name="agentID"></param>
  4436. /// <returns>null if the presence was not found</returns>
  4437. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4438. public ScenePresence GetScenePresence(UUID agentID)
  4439. {
  4440. return m_sceneGraph.GetScenePresence(agentID);
  4441. }
  4442. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4443. public override bool TryGetScenePresence(UUID agentID, out ScenePresence presence)
  4444. {
  4445. return m_sceneGraph.TryGetScenePresence(agentID, out presence);
  4446. }
  4447. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4448. public bool TryGetSceneRootPresence(UUID agentID, out ScenePresence presence)
  4449. {
  4450. return m_sceneGraph.TryGetSceneRootPresence(agentID, out presence);
  4451. }
  4452. /// <summary>
  4453. /// Request the scene presence by name.
  4454. /// </summary>
  4455. /// <param name="firstName"></param>
  4456. /// <param name="lastName"></param>
  4457. /// <returns>null if the presence was not found</returns>
  4458. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4459. public ScenePresence GetScenePresence(string firstName, string lastName)
  4460. {
  4461. return m_sceneGraph.GetScenePresence(firstName, lastName);
  4462. }
  4463. /// <summary>
  4464. /// Request the scene presence by localID.
  4465. /// </summary>
  4466. /// <param name="localID"></param>
  4467. /// <returns>null if the presence was not found</returns>
  4468. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4469. public ScenePresence GetScenePresence(uint localID)
  4470. {
  4471. return m_sceneGraph.GetScenePresence(localID);
  4472. }
  4473. /// <summary>
  4474. /// Gets all the scene presences in this scene.
  4475. /// </summary>
  4476. /// <remarks>
  4477. /// This method will return both root and child scene presences.
  4478. ///
  4479. /// Consider using only on ForEachScenePresence() or ForEachRootScenePresence() if possible since these will not
  4480. /// involving creating a new List object.
  4481. /// </remarks>
  4482. /// <returns>
  4483. /// The shared list of the scene presences.
  4484. /// </returns>
  4485. /// WARNING DO NOT MODIFY RETURNED VALUE
  4486. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4487. public List<ScenePresence> GetScenePresences()
  4488. {
  4489. //return new List<ScenePresence>(m_sceneGraph.GetScenePresences());
  4490. return m_sceneGraph.GetScenePresences();
  4491. }
  4492. /// <summary>
  4493. /// Performs action on all avatars in the scene (root scene presences)
  4494. /// Avatars may be an NPC or a 'real' client.
  4495. /// </summary>
  4496. /// <param name="action"></param>
  4497. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4498. public void ForEachRootScenePresence(Action<ScenePresence> action)
  4499. {
  4500. m_sceneGraph.ForEachRootScenePresence(action);
  4501. }
  4502. /// <summary>
  4503. /// Performs action on all scene presences (root and child)
  4504. /// </summary>
  4505. /// <param name="action"></param>
  4506. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4507. public void ForEachScenePresence(Action<ScenePresence> action)
  4508. {
  4509. m_sceneGraph.ForEachScenePresence(action);
  4510. }
  4511. /// <summary>
  4512. /// Get all the scene object groups.
  4513. /// </summary>
  4514. /// <returns>
  4515. /// The scene object groups. If the scene is empty then an empty list is returned.
  4516. /// </returns>
  4517. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4518. public List<SceneObjectGroup> GetSceneObjectGroups()
  4519. {
  4520. return m_sceneGraph.GetSceneObjectGroups();
  4521. }
  4522. /// <summary>
  4523. /// Get a group via its UUID
  4524. /// </summary>
  4525. /// <param name="fullID"></param>
  4526. /// <returns>null if no group with that id exists</returns>
  4527. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4528. public SceneObjectGroup GetSceneObjectGroup(UUID fullID)
  4529. {
  4530. return m_sceneGraph.GetSceneObjectGroup(fullID);
  4531. }
  4532. /// <summary>
  4533. /// Get a group via its local ID
  4534. /// </summary>
  4535. /// <remarks>This will only return a group if the local ID matches a root part</remarks>
  4536. /// <param name="localID"></param>
  4537. /// <returns>null if no group with that id exists</returns>
  4538. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4539. public SceneObjectGroup GetSceneObjectGroup(uint localID)
  4540. {
  4541. return m_sceneGraph.GetSceneObjectGroup(localID);
  4542. }
  4543. /// <summary>
  4544. /// Get a group by name from the scene (will return the first
  4545. /// found, if there are more than one prim with the same name)
  4546. /// </summary>
  4547. /// <param name="name"></param>
  4548. /// <returns>null if no group with that name exists</returns>
  4549. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4550. public SceneObjectGroup GetSceneObjectGroup(string name)
  4551. {
  4552. return m_sceneGraph.GetSceneObjectGroup(name);
  4553. }
  4554. /// <summary>
  4555. /// Attempt to get the SOG via its UUID
  4556. /// </summary>
  4557. /// <param name="fullID"></param>
  4558. /// <param name="sog"></param>
  4559. /// <returns></returns>
  4560. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4561. public bool TryGetSceneObjectGroup(UUID fullID, out SceneObjectGroup sog)
  4562. {
  4563. sog = GetSceneObjectGroup(fullID);
  4564. return sog is not null;
  4565. }
  4566. /// <summary>
  4567. /// Get a prim by name from the scene (will return the first
  4568. /// found, if there are more than one prim with the same name)
  4569. /// </summary>
  4570. /// <param name="name"></param>
  4571. /// <returns></returns>
  4572. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4573. public SceneObjectPart GetSceneObjectPart(string name)
  4574. {
  4575. return m_sceneGraph.GetSceneObjectPart(name);
  4576. }
  4577. /// <summary>
  4578. /// Get a prim via its local id
  4579. /// </summary>
  4580. /// <param name="localID"></param>
  4581. /// <returns></returns>
  4582. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4583. public SceneObjectPart GetSceneObjectPart(uint localID)
  4584. {
  4585. return m_sceneGraph.GetSceneObjectPart(localID);
  4586. }
  4587. /// <summary>
  4588. /// Get a prim via its UUID
  4589. /// </summary>
  4590. /// <param name="fullID"></param>
  4591. /// <returns></returns>
  4592. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4593. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  4594. {
  4595. return m_sceneGraph.GetSceneObjectPart(fullID);
  4596. }
  4597. /// <summary>
  4598. /// Attempt to get a prim via its UUID
  4599. /// </summary>
  4600. /// <param name="fullID"></param>
  4601. /// <param name="sop"></param>
  4602. /// <returns></returns>
  4603. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4604. public bool TryGetSceneObjectPart(UUID fullID, out SceneObjectPart sop)
  4605. {
  4606. return m_sceneGraph.TryGetSceneObjectPart(fullID, out sop);
  4607. }
  4608. /// <summary>
  4609. /// Get a scene object group that contains the prim with the given local id
  4610. /// </summary>
  4611. /// <param name="localID"></param>
  4612. /// <returns>null if no scene object group containing that prim is found</returns>
  4613. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4614. public SceneObjectGroup GetGroupByPrim(uint localID)
  4615. {
  4616. return m_sceneGraph.GetGroupByPrim(localID);
  4617. }
  4618. /// <summary>
  4619. /// Get a scene object group that contains the prim with the given uuid
  4620. /// </summary>
  4621. /// <param name="fullID"></param>
  4622. /// <returns>null if no scene object group containing that prim is found</returns>
  4623. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4624. public SceneObjectGroup GetGroupByPrim(UUID fullID)
  4625. {
  4626. return m_sceneGraph.GetGroupByPrim(fullID);
  4627. }
  4628. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4629. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  4630. {
  4631. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  4632. }
  4633. /// <summary>
  4634. /// Perform an action on all clients with an avatar in this scene (root only)
  4635. /// </summary>
  4636. /// <param name="action"></param>
  4637. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4638. public void ForEachRootClient(Action<IClientAPI> action)
  4639. {
  4640. ForEachRootScenePresence(delegate(ScenePresence presence)
  4641. {
  4642. action(presence.ControllingClient);
  4643. });
  4644. }
  4645. /// <summary>
  4646. /// Perform an action on all clients connected to the region (root and child)
  4647. /// </summary>
  4648. /// <param name="action"></param>
  4649. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4650. public void ForEachClient(Action<IClientAPI> action)
  4651. {
  4652. m_clientManager.ForEach(action);
  4653. }
  4654. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4655. public int GetNumberOfClients()
  4656. {
  4657. return m_clientManager.Count;
  4658. }
  4659. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4660. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  4661. {
  4662. return m_clientManager.TryGetValue(avatarID, out client);
  4663. }
  4664. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4665. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  4666. {
  4667. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  4668. }
  4669. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4670. public void ForEachSOG(Action<SceneObjectGroup> action)
  4671. {
  4672. m_sceneGraph.ForEachSOG(action);
  4673. }
  4674. /// <summary>
  4675. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  4676. /// will not affect the original list of objects in the scene.
  4677. /// </summary>
  4678. /// <returns></returns>
  4679. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4680. public EntityBase[] GetEntities()
  4681. {
  4682. return m_sceneGraph.GetEntities();
  4683. }
  4684. #endregion
  4685. // Commented pending deletion since this method no longer appears to do anything at all
  4686. // public bool NeedSceneCacheClear(UUID agentID)
  4687. // {
  4688. // IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  4689. // if (inv is null)
  4690. // return true;
  4691. //
  4692. // return inv.NeedSceneCacheClear(agentID, this);
  4693. // }
  4694. public void CleanTempObjects()
  4695. {
  4696. DateTime now = DateTime.UtcNow;
  4697. EntityBase[] entities = GetEntities();
  4698. foreach (EntityBase obj in entities)
  4699. {
  4700. if (obj is SceneObjectGroup)
  4701. {
  4702. SceneObjectGroup grp = obj as SceneObjectGroup;
  4703. if (!grp.IsDeleted)
  4704. {
  4705. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4706. {
  4707. if (grp.GetSittingAvatarsCount() == 0 && grp.RootPart.Expires <= now)
  4708. DeleteSceneObject(grp, false);
  4709. }
  4710. }
  4711. }
  4712. }
  4713. }
  4714. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4715. public void DeleteFromStorage(UUID uuid)
  4716. {
  4717. SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
  4718. }
  4719. public int GetHealth(out int flags, out string message)
  4720. {
  4721. // Returns:
  4722. // 1 = sim is up and accepting http requests. The heartbeat has
  4723. // stopped and the sim is probably locked up, but a remote
  4724. // admin restart may succeed
  4725. //
  4726. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4727. // usable for people within
  4728. //
  4729. // 3 = Sim is up and one packet thread is running. Sim is
  4730. // unstable and will not accept new logins
  4731. //
  4732. // 4 = Sim is up and both packet threads are running. Sim is
  4733. // likely usable
  4734. //
  4735. // 5 = We have seen a new user enter within the past 4 minutes
  4736. // which can be seen as positive confirmation of sim health
  4737. //
  4738. int health = 1; // Start at 1, means we're up
  4739. flags = 0;
  4740. message = String.Empty;
  4741. CheckHeartbeat();
  4742. if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
  4743. {
  4744. // We're still starting
  4745. // 0 means "in startup", it can't happen another way, since
  4746. // to get here, we must be able to accept http connections
  4747. return 0;
  4748. }
  4749. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 4000)
  4750. {
  4751. health+=1;
  4752. flags |= 1;
  4753. }
  4754. if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 6000)
  4755. {
  4756. health+=1;
  4757. flags |= 2;
  4758. }
  4759. if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 6000)
  4760. {
  4761. health+=1;
  4762. flags |= 4;
  4763. }
  4764. /*
  4765. else
  4766. {
  4767. int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  4768. System.Diagnostics.Process proc = new System.Diagnostics.Process();
  4769. proc.EnableRaisingEvents=false;
  4770. proc.StartInfo.FileName = "/bin/kill";
  4771. proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  4772. proc.Start();
  4773. proc.WaitForExit();
  4774. Thread.Sleep(1000);
  4775. Environment.Exit(1);
  4776. }
  4777. */
  4778. if (flags != 7)
  4779. return health;
  4780. // A login in the last 4 mins? We can't be doing too badly
  4781. //
  4782. if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
  4783. health++;
  4784. else
  4785. return health;
  4786. return health;
  4787. }
  4788. public Scene ConsoleScene()
  4789. {
  4790. if (MainConsole.Instance?.ConsoleScene is Scene sc)
  4791. return sc;
  4792. return null;
  4793. }
  4794. // Get terrain height at the specified <x,y> location.
  4795. // Presumes the underlying implementation is a heightmap which is a 1m grid.
  4796. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4797. public float GetGroundHeight(float x, float y)
  4798. {
  4799. return Heightmap.GetHeight(x, y);
  4800. }
  4801. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4802. private void CheckHeartbeat()
  4803. {
  4804. if (m_firstHeartbeat)
  4805. return;
  4806. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
  4807. Start();
  4808. }
  4809. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4810. public override ISceneObject DeserializeObject(string representation)
  4811. {
  4812. return SceneObjectSerializer.FromXml2Format(representation);
  4813. }
  4814. public override bool AllowScriptCrossings
  4815. {
  4816. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4817. get { return m_allowScriptCrossings; }
  4818. }
  4819. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4820. public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
  4821. {
  4822. return GetNearestAllowedPosition(avatar, null);
  4823. }
  4824. public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
  4825. {
  4826. Vector3 pos = avatar.AbsolutePosition;
  4827. ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, pos.X, pos.Y, excludeParcel);
  4828. if (nearestParcel is not null)
  4829. {
  4830. Vector2? nearestPoint = null;
  4831. Vector3 dir = -avatar.Velocity;
  4832. float dirlen = dir.Length();
  4833. if(dirlen > 1.0f)
  4834. //Try to get a location that feels like where they came from
  4835. nearestPoint = nearestParcel.GetNearestPointAlongDirection(pos, dir);
  4836. nearestPoint ??= nearestParcel.GetNearestPoint(pos);
  4837. if (nearestPoint is not null)
  4838. {
  4839. return GetPositionAtAvatarHeightOrGroundHeight(avatar,
  4840. nearestPoint.Value.X, nearestPoint.Value.Y);
  4841. }
  4842. ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
  4843. if (dest != excludeParcel)
  4844. {
  4845. // Ultimate backup if we have no idea where they are and
  4846. // the last allowed position was in another parcel
  4847. m_log.Debug("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
  4848. return avatar.lastKnownAllowedPosition;
  4849. }
  4850. // else fall through to region edge
  4851. }
  4852. //Go to the edge, this happens in teleporting to a region with no available parcels
  4853. Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
  4854. //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
  4855. return nearestRegionEdgePoint;
  4856. }
  4857. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4858. private Vector3 GetParcelCenterAtGround(ILandObject parcel)
  4859. {
  4860. Vector2 center = parcel.CenterPoint;
  4861. return GetPositionAtGround(center.X, center.Y);
  4862. }
  4863. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4864. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
  4865. {
  4866. return GetNearestAllowedParcel(avatarId, x, y, null);
  4867. }
  4868. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
  4869. {
  4870. if(LandChannel is null)
  4871. return null;
  4872. List<ILandObject> all = LandChannel.AllParcels();
  4873. if(all is null || all.Count == 0)
  4874. return null;
  4875. float minParcelDistanceSQ = float.MaxValue;
  4876. ILandObject nearestParcel = null;
  4877. Vector2 curCenter;
  4878. float parcelDistanceSQ;
  4879. foreach (var parcel in all)
  4880. {
  4881. if (parcel != excludeParcel && !parcel.IsEitherBannedOrRestricted(avatarId))
  4882. {
  4883. curCenter = parcel.CenterPoint;
  4884. curCenter.X -= x;
  4885. curCenter.Y -= y;
  4886. parcelDistanceSQ = curCenter.LengthSquared();
  4887. if (parcelDistanceSQ < minParcelDistanceSQ)
  4888. {
  4889. minParcelDistanceSQ = parcelDistanceSQ;
  4890. nearestParcel = parcel;
  4891. }
  4892. }
  4893. }
  4894. return nearestParcel;
  4895. }
  4896. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4897. private static Vector2 GetParcelSafeCorner(ILandObject parcel)
  4898. {
  4899. Vector2 place = parcel.StartPoint;
  4900. place.X += 2f;
  4901. place.Y += 2f;
  4902. return place;
  4903. }
  4904. private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
  4905. {
  4906. float posX = avatar.AbsolutePosition.X;
  4907. float posY = avatar.AbsolutePosition.Y;
  4908. float regionSizeX = RegionInfo.RegionSizeX;
  4909. float halfRegionSizeX = regionSizeX * 0.5f;
  4910. float regionSizeY = RegionInfo.RegionSizeY;
  4911. float halfRegionSizeY = regionSizeY * 0.5f;
  4912. float xdistance = posX < halfRegionSizeX ? posX : regionSizeX - posX;
  4913. float ydistance = posY < halfRegionSizeY ? posY : regionSizeY - posY;
  4914. //find out what vertical edge to go to
  4915. if (xdistance < ydistance)
  4916. {
  4917. if (posX < halfRegionSizeX)
  4918. return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.5f, posY);
  4919. else
  4920. return GetPositionAtAvatarHeightOrGroundHeight(avatar, regionSizeX - 0.5f, posY);
  4921. }
  4922. //find out what horizontal edge to go to
  4923. else
  4924. {
  4925. if (posY < halfRegionSizeY)
  4926. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, 0.5f);
  4927. else
  4928. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, regionSizeY - 0.5f);
  4929. }
  4930. }
  4931. private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
  4932. {
  4933. Vector3 ground = GetPositionAtGround(x, y);
  4934. if(avatar.Appearance is not null)
  4935. ground.Z += avatar.Appearance.AvatarHeight * 0.5f;
  4936. else
  4937. ground.Z += 0.8f;
  4938. if (avatar.AbsolutePosition.Z > ground.Z)
  4939. {
  4940. ground.Z = avatar.AbsolutePosition.Z;
  4941. }
  4942. return ground;
  4943. }
  4944. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4945. private Vector3 GetPositionAtGround(float x, float y)
  4946. {
  4947. return new Vector3(x, y, GetGroundHeight(x, y));
  4948. }
  4949. public List<UUID> GetEstateRegions(int estateID)
  4950. {
  4951. IEstateDataService estateDataService = EstateDataService;
  4952. if (estateDataService is null)
  4953. return new List<UUID>(0);
  4954. return estateDataService.GetRegions(estateID);
  4955. }
  4956. public void ReloadEstateData()
  4957. {
  4958. IEstateDataService estateDataService = EstateDataService;
  4959. if (estateDataService is not null)
  4960. {
  4961. bool parcelEnvOvr = RegionInfo.EstateSettings.AllowEnvironmentOverride;
  4962. EstateSettings es = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  4963. if (es == null)
  4964. m_log.Error($"[SCENE]: Region {RegionInfo.RegionName} failed to reload estate settings. Using defaults");
  4965. RegionInfo.EstateSettings = es;
  4966. if(parcelEnvOvr && !RegionInfo.EstateSettings.AllowEnvironmentOverride)
  4967. ClearAllParcelEnvironments();
  4968. }
  4969. }
  4970. public void ClearAllParcelEnvironments()
  4971. {
  4972. IEnvironmentModule envM = RequestModuleInterface<IEnvironmentModule>();
  4973. if(LandChannel is not null && envM is not null)
  4974. {
  4975. LandChannel.ClearAllEnvironments();
  4976. envM.WindlightRefresh(1,false);
  4977. }
  4978. }
  4979. private void HandleReloadEstate(string module, string[] cmd)
  4980. {
  4981. if (MainConsole.Instance.ConsoleScene is null ||
  4982. (MainConsole.Instance.ConsoleScene is Scene sc &&
  4983. sc == this))
  4984. {
  4985. ReloadEstateData();
  4986. }
  4987. }
  4988. /// <summary>
  4989. /// Get the volume of space that will encompass all the given objects.
  4990. /// </summary>
  4991. /// <param name="objects"></param>
  4992. /// <param name="minX"></param>
  4993. /// <param name="maxX"></param>
  4994. /// <param name="minY"></param>
  4995. /// <param name="maxY"></param>
  4996. /// <param name="minZ"></param>
  4997. /// <param name="maxZ"></param>
  4998. /// <returns></returns>
  4999. public static Vector3[] GetCombinedBoundingBox(
  5000. List<SceneObjectGroup> objects,
  5001. out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  5002. {
  5003. minX = float.MaxValue;
  5004. maxX = float.MinValue;
  5005. minY = float.MaxValue;
  5006. maxY = float.MinValue;
  5007. minZ = float.MaxValue;
  5008. maxZ = float.MinValue;
  5009. List<Vector3> offsets = new();
  5010. foreach (SceneObjectGroup g in objects)
  5011. {
  5012. Vector3 vec = g.AbsolutePosition;
  5013. g.GetAxisAlignedBoundingBoxRaw(out float ominX, out float omaxX, out float ominY,
  5014. out float omaxY, out float ominZ, out float omaxZ);
  5015. // m_log.DebugFormat(
  5016. // "[SCENE]: For {0} found AxisAlignedBoundingBoxRaw {1}, {2}",
  5017. // g.Name, new Vector3(ominX, ominY, ominZ), new Vector3(omaxX, omaxY, omaxZ));
  5018. ominX += vec.X;
  5019. omaxX += vec.X;
  5020. ominY += vec.Y;
  5021. omaxY += vec.Y;
  5022. ominZ += vec.Z;
  5023. omaxZ += vec.Z;
  5024. if (minX > ominX)
  5025. minX = ominX;
  5026. if (minY > ominY)
  5027. minY = ominY;
  5028. if (minZ > ominZ)
  5029. minZ = ominZ;
  5030. if (maxX < omaxX)
  5031. maxX = omaxX;
  5032. if (maxY < omaxY)
  5033. maxY = omaxY;
  5034. if (maxZ < omaxZ)
  5035. maxZ = omaxZ;
  5036. }
  5037. foreach (SceneObjectGroup g in objects)
  5038. {
  5039. Vector3 vec = g.AbsolutePosition;
  5040. vec.X -= minX;
  5041. vec.Y -= minY;
  5042. vec.Z -= minZ;
  5043. offsets.Add(vec);
  5044. }
  5045. return offsets.ToArray();
  5046. }
  5047. /// <summary>
  5048. /// Regenerate the maptile for this scene.
  5049. /// </summary>
  5050. /// <param name="sender"></param>
  5051. /// <param name="e"></param>
  5052. private void RegenerateMaptile()
  5053. {
  5054. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  5055. mapModule?.GenerateMaptile();
  5056. }
  5057. // public void CleanDroppedAttachments()
  5058. // {
  5059. // List<SceneObjectGroup> objectsToDelete =
  5060. // new List<SceneObjectGroup>();
  5061. //
  5062. // lock (m_cleaningAttachments)
  5063. // {
  5064. // ForEachSOG(delegate (SceneObjectGroup grp)
  5065. // {
  5066. // if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
  5067. // {
  5068. // UUID agentID = grp.OwnerID;
  5069. // if (agentID.IsZero())
  5070. // {
  5071. // objectsToDelete.Add(grp);
  5072. // return;
  5073. // }
  5074. //
  5075. // ScenePresence sp = GetScenePresence(agentID);
  5076. // if (sp is null)
  5077. // {
  5078. // objectsToDelete.Add(grp);
  5079. // return;
  5080. // }
  5081. // }
  5082. // });
  5083. // }
  5084. //
  5085. // foreach (SceneObjectGroup grp in objectsToDelete)
  5086. // {
  5087. // m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
  5088. // DeleteSceneObject(grp, true);
  5089. // }
  5090. // }
  5091. public void ThreadAlive(int threadCode)
  5092. {
  5093. switch(threadCode)
  5094. {
  5095. case 1: // Incoming
  5096. m_lastIncoming = Util.EnvironmentTickCount();
  5097. break;
  5098. case 2: // Outgoing
  5099. m_lastOutgoing = Util.EnvironmentTickCount();
  5100. break;
  5101. }
  5102. }
  5103. public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
  5104. {
  5105. RegenerateMaptile();
  5106. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  5107. GC.Collect();
  5108. GC.WaitForPendingFinalizers();
  5109. GC.Collect();
  5110. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
  5111. // We need to propagate the new image UUID to the grid service
  5112. // so that all simulators can retrieve it
  5113. string error = GridService.RegisterRegion(RegionInfo.ScopeID, new GridRegion(RegionInfo));
  5114. if (error != string.Empty)
  5115. throw new Exception(error);
  5116. if(m_generateMaptiles)
  5117. m_mapGenerationTimer.Start();
  5118. }
  5119. /// <summary>
  5120. /// This method is called across the simulation connector to
  5121. /// determine if a given agent is allowed in this region
  5122. /// AS A ROOT AGENT
  5123. /// </summary>
  5124. /// <remarks>
  5125. /// Returning false here will prevent them
  5126. /// from logging into the region, teleporting into the region
  5127. /// or corssing the broder walking, but will NOT prevent
  5128. /// child agent creation, thereby emulating the SL behavior.
  5129. /// </remarks>
  5130. /// <param name='agentID'>The visitor's User ID</param>
  5131. /// <param name="agentHomeURI">The visitor's Home URI (may be null)</param>
  5132. /// <param name='position'></param>
  5133. /// <param name='reason'></param>
  5134. /// <returns></returns>
  5135. public bool QueryAccess(UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List<UUID> features, out string reason)
  5136. {
  5137. reason = string.Empty;
  5138. if (Permissions.IsGod(agentID))
  5139. return true;
  5140. if (!AllowAvatarCrossing && !viaTeleport)
  5141. {
  5142. reason = "Region Crossing not allowed";
  5143. return false;
  5144. }
  5145. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  5146. // Fake AgentCircuitData to keep IAuthorizationModule smiling
  5147. aCircuit ??= new AgentCircuitData()
  5148. {
  5149. AgentID = agentID,
  5150. firstname = string.Empty,
  5151. lastname = string.Empty
  5152. };
  5153. try
  5154. {
  5155. if (!AuthorizeUser(aCircuit, false, out reason))
  5156. {
  5157. //m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
  5158. // reason = "Region authorization fail";
  5159. return false;
  5160. }
  5161. }
  5162. catch (Exception e)
  5163. {
  5164. m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} " + e.StackTrace, e.Message);
  5165. reason = "Error authorizing agent: " + e.Message;
  5166. return false;
  5167. }
  5168. // last check aditional land access restrictions and relocations
  5169. // if crossing (viaTeleport false) check only the specified parcel
  5170. return CheckLandPositionAccess(agentID, viaTeleport, true, true, position, out reason);
  5171. }
  5172. // check access to land.
  5173. public bool CheckLandPositionAccess(UUID agentID, bool NotCrossing, bool checkTeleHub, bool checkRegionAgentCount, Vector3 position, out string reason)
  5174. {
  5175. reason = string.Empty;
  5176. if (Permissions.IsGod(agentID))
  5177. return true;
  5178. // Permissions.IsAdministrator is the same as IsGod for now
  5179. //bool isAdmin = Permissions.IsAdministrator(agentID);
  5180. //if(isAdmin)
  5181. // return true;
  5182. // also honor estate managers access rights
  5183. bool isManager = Permissions.IsEstateManager(agentID);
  5184. if(isManager)
  5185. return true;
  5186. // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
  5187. // However, the long term fix is to make sure root agent count is always accurate.
  5188. m_sceneGraph.RecalculateStats();
  5189. int num = m_sceneGraph.GetRootAgentCount();
  5190. num -= m_sceneGraph.GetRootNPCCount();
  5191. if (num >= RegionInfo.RegionSettings.AgentLimit)
  5192. {
  5193. reason = "The region is full";
  5194. m_log.DebugFormat(
  5195. "[SCENE]: Denying presence with id {0} entry into {1} since region is at agent limit of {2}",
  5196. agentID, RegionInfo.RegionName, RegionInfo.RegionSettings.AgentLimit);
  5197. return false;
  5198. }
  5199. if (NotCrossing)
  5200. {
  5201. if (!RegionInfo.EstateSettings.AllowDirectTeleport)
  5202. {
  5203. SceneObjectGroup telehub;
  5204. if (!RegionInfo.RegionSettings.TelehubObject.IsZero() && (telehub = GetSceneObjectGroup (RegionInfo.RegionSettings.TelehubObject)) is not null && checkTeleHub)
  5205. {
  5206. bool banned = true;
  5207. bool validTelehub = false;
  5208. List<SpawnPoint> spawnPoints = RegionInfo.RegionSettings.SpawnPoints();
  5209. Vector3 spawnPoint;
  5210. ILandObject land;
  5211. Vector3 telehubPosition = telehub.AbsolutePosition;
  5212. if(spawnPoints.Count == 0)
  5213. {
  5214. // will this ever happen?
  5215. // if so use the telehub object position
  5216. spawnPoint = telehubPosition;
  5217. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5218. if(land is not null && !land.IsEitherBannedOrRestricted(agentID))
  5219. {
  5220. banned = false;
  5221. validTelehub = true;
  5222. }
  5223. }
  5224. else
  5225. {
  5226. Quaternion telehubRotation = telehub.GroupRotation;
  5227. foreach (SpawnPoint spawn in spawnPoints)
  5228. {
  5229. spawnPoint = spawn.GetLocation(telehubPosition, telehubRotation);
  5230. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5231. if (land is null)
  5232. continue;
  5233. validTelehub = true;
  5234. if (!land.IsEitherBannedOrRestricted(agentID))
  5235. {
  5236. banned = false;
  5237. break;
  5238. }
  5239. }
  5240. }
  5241. if(validTelehub)
  5242. {
  5243. if (banned)
  5244. {
  5245. reason = "No suitable landing point found";
  5246. return false;
  5247. }
  5248. else
  5249. return true;
  5250. }
  5251. // possible broken telehub, fall into normal check
  5252. }
  5253. }
  5254. float posX = position.X;
  5255. float posY = position.Y;
  5256. // allow position relocation
  5257. if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
  5258. {
  5259. // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
  5260. reason = "You dont have access to the region parcels";
  5261. return false;
  5262. }
  5263. }
  5264. else // check for query region crossing only
  5265. {
  5266. // no relocation allowed on crossings
  5267. ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
  5268. if (land is null)
  5269. {
  5270. reason = "No parcel found";
  5271. return false;
  5272. }
  5273. bool banned = land.IsBannedFromLand(agentID);
  5274. bool restricted = land.IsRestrictedFromLand(agentID);
  5275. if (banned || restricted)
  5276. {
  5277. if (banned)
  5278. reason = "You are banned from the parcel";
  5279. else
  5280. reason = "The parcel is restricted";
  5281. return false;
  5282. }
  5283. }
  5284. return true;
  5285. }
  5286. public void StartTimerWatchdog()
  5287. {
  5288. m_timerWatchdog.Interval = 1000;
  5289. m_timerWatchdog.Elapsed += TimerWatchdog;
  5290. m_timerWatchdog.AutoReset = true;
  5291. m_timerWatchdog.Start();
  5292. }
  5293. public void TimerWatchdog(object sender, ElapsedEventArgs e)
  5294. {
  5295. CheckHeartbeat();
  5296. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  5297. if (etcd is not null)
  5298. {
  5299. int health = GetHealth(out int flags, out string _);
  5300. if (health != m_lastHealth)
  5301. {
  5302. m_lastHealth = health;
  5303. etcd.Store("Health", health.ToString(), 300000);
  5304. etcd.Store("HealthFlags", flags.ToString(), 300000);
  5305. }
  5306. int roots = 0;
  5307. foreach (ScenePresence sp in GetScenePresences())
  5308. if (!sp.IsChildAgent && !sp.IsNPC)
  5309. roots++;
  5310. if (m_lastUsers != roots)
  5311. {
  5312. m_lastUsers = roots;
  5313. etcd.Store("RootAgents", roots.ToString(), 300000);
  5314. }
  5315. }
  5316. }
  5317. // manage and select spawn points in sequence
  5318. public int SpawnPoint()
  5319. {
  5320. int spawnpoints = RegionInfo.RegionSettings.SpawnPoints().Count;
  5321. if (spawnpoints == 0)
  5322. return 0;
  5323. m_SpawnPoint++;
  5324. if (m_SpawnPoint > spawnpoints)
  5325. m_SpawnPoint = 1;
  5326. return m_SpawnPoint - 1;
  5327. }
  5328. private static void HandleGcCollect(string module, string[] args)
  5329. {
  5330. GC.Collect();
  5331. }
  5332. /// <summary>
  5333. /// Wrappers to get physics modules retrieve assets.
  5334. /// </summary>
  5335. /// <remarks>
  5336. /// Has to be done this way
  5337. /// because we can't assign the asset service to physics directly - at the
  5338. /// time physics are instantiated it's not registered but it will be by
  5339. /// the time the first prim exists.
  5340. /// </remarks>
  5341. /// <param name="assetID"></param>
  5342. /// <param name="callback"></param>
  5343. public void PhysicsRequestAsset(UUID assetID, AssetReceivedDelegate callback)
  5344. {
  5345. AssetService.Get(assetID.ToString(), callback, PhysicsAssetReceived);
  5346. }
  5347. private void PhysicsAssetReceived(string id, Object sender, AssetBase asset)
  5348. {
  5349. AssetReceivedDelegate callback = (AssetReceivedDelegate)sender;
  5350. callback(asset);
  5351. }
  5352. public string GetExtraSetting(string name)
  5353. {
  5354. if (m_extraSettings is not null && m_extraSettings.TryGetValue(name, out string val))
  5355. return val;
  5356. return String.Empty;
  5357. }
  5358. public void StoreExtraSetting(string name, string val)
  5359. {
  5360. if (m_extraSettings is null)
  5361. return;
  5362. if (m_extraSettings.TryGetValue(name, out string oldVal))
  5363. {
  5364. if (oldVal == val)
  5365. return;
  5366. }
  5367. m_extraSettings[name] = val;
  5368. m_SimulationDataService.SaveExtra(RegionInfo.RegionID, name, val);
  5369. m_eventManager.TriggerExtraSettingChanged(this, name, val);
  5370. }
  5371. public void RemoveExtraSetting(string name)
  5372. {
  5373. if (m_extraSettings is null)
  5374. return;
  5375. if (!m_extraSettings.ContainsKey(name))
  5376. return;
  5377. m_extraSettings.Remove(name);
  5378. m_SimulationDataService.RemoveExtra(RegionInfo.RegionID, name);
  5379. m_eventManager.TriggerExtraSettingChanged(this, name, String.Empty);
  5380. }
  5381. public bool InTeleportTargetsCoolDown(UUID sourceID, UUID targetID, int timeout)
  5382. {
  5383. if(TeleportTargetsCoolDown.TryGetValue(targetID, timeout, out UUID lastSource))
  5384. return lastSource == sourceID;
  5385. return false;
  5386. }
  5387. }
  5388. }