Scene.cs 252 KB

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