Scene.cs 259 KB

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