Scene.cs 220 KB

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