1
0

Scene.cs 248 KB

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