Scene.cs 259 KB

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