Scene.cs 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008
  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.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Text;
  33. using System.Threading;
  34. using System.Timers;
  35. using System.Xml;
  36. using Nini.Config;
  37. using OpenMetaverse;
  38. using OpenMetaverse.Imaging;
  39. using OpenSim.Framework;
  40. using OpenSim.Services.Interfaces;
  41. using OpenSim.Framework.Communications;
  42. using OpenSim.Framework.Communications.Cache;
  43. using OpenSim.Framework.Communications.Clients;
  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. namespace OpenSim.Region.Framework.Scenes
  52. {
  53. public delegate bool FilterAvatarList(ScenePresence avatar);
  54. public partial class Scene : SceneBase
  55. {
  56. public delegate void SynchronizeSceneHandler(Scene scene);
  57. public SynchronizeSceneHandler SynchronizeScene = null;
  58. /* Used by the loadbalancer plugin on GForge */
  59. protected int m_splitRegionID = 0;
  60. public int SplitRegionID
  61. {
  62. get { return m_splitRegionID; }
  63. set { m_splitRegionID = value; }
  64. }
  65. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  66. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  67. #region Fields
  68. protected Timer m_restartWaitTimer = new Timer();
  69. protected Thread m_updateEntitiesThread;
  70. public SimStatsReporter StatsReporter;
  71. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  72. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  73. /// <value>
  74. /// The scene graph for this scene
  75. /// </value>
  76. /// TODO: Possibly stop other classes being able to manipulate this directly.
  77. private SceneGraph m_sceneGraph;
  78. /// <summary>
  79. /// Are we applying physics to any of the prims in this scene?
  80. /// </summary>
  81. public bool m_physicalPrim;
  82. public float m_maxNonphys = 256;
  83. public float m_maxPhys = 10;
  84. public bool m_clampPrimSize = false;
  85. public bool m_trustBinaries = false;
  86. public bool m_allowScriptCrossings = false;
  87. public bool m_useFlySlow = false;
  88. public bool m_usePreJump = false;
  89. public bool m_seeIntoRegionFromNeighbor;
  90. // TODO: need to figure out how allow client agents but deny
  91. // root agents when ACL denies access to root agent
  92. public bool m_strictAccessControl = true;
  93. public int MaxUndoCount = 5;
  94. private int m_RestartTimerCounter;
  95. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  96. private int m_incrementsof15seconds = 0;
  97. private volatile bool m_backingup = false;
  98. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  99. protected string m_simulatorVersion = "OpenSimulator Server";
  100. protected ModuleLoader m_moduleLoader;
  101. protected StorageManager m_storageManager;
  102. protected AgentCircuitManager m_authenticateHandler;
  103. public CommunicationsManager CommsManager;
  104. protected SceneCommunicationService m_sceneGridService;
  105. public SceneCommunicationService SceneGridService
  106. {
  107. get { return m_sceneGridService; }
  108. }
  109. public IXfer XferManager;
  110. protected IAssetService m_AssetService = null;
  111. public IAssetService AssetService
  112. {
  113. get
  114. {
  115. if (m_AssetService == null)
  116. {
  117. m_AssetService = RequestModuleInterface<IAssetService>();
  118. if (m_AssetService == null)
  119. {
  120. throw new Exception("No IAssetService available.");
  121. }
  122. }
  123. return m_AssetService;
  124. }
  125. }
  126. protected IInventoryService m_InventoryService = null;
  127. public IInventoryService InventoryService
  128. {
  129. get
  130. {
  131. if (m_InventoryService == null)
  132. {
  133. m_InventoryService = RequestModuleInterface<IInventoryService>();
  134. if (m_InventoryService == null)
  135. {
  136. 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.");
  137. }
  138. }
  139. return m_InventoryService;
  140. }
  141. }
  142. protected IXMLRPC m_xmlrpcModule;
  143. protected IWorldComm m_worldCommModule;
  144. protected IAvatarFactory m_AvatarFactory;
  145. protected IConfigSource m_config;
  146. protected IRegionSerialiserModule m_serialiser;
  147. protected IInterregionCommsOut m_interregionCommsOut;
  148. protected IInterregionCommsIn m_interregionCommsIn;
  149. protected IDialogModule m_dialogModule;
  150. protected ITeleportModule m_teleportModule;
  151. protected ICapabilitiesModule m_capsModule;
  152. public ICapabilitiesModule CapsModule
  153. {
  154. get { return m_capsModule; }
  155. }
  156. protected override IConfigSource GetConfig()
  157. {
  158. return m_config;
  159. }
  160. // Central Update Loop
  161. protected int m_fps = 10;
  162. protected int m_frame = 0;
  163. protected float m_timespan = 0.089f;
  164. protected DateTime m_lastupdate = DateTime.Now;
  165. private int m_update_physics = 1;
  166. private int m_update_entitymovement = 1;
  167. private int m_update_entities = 1; // Run through all objects checking for updates
  168. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  169. private int m_update_presences = 1; // Update scene presence movements
  170. private int m_update_events = 1;
  171. private int m_update_backup = 200;
  172. private int m_update_terrain = 50;
  173. private int m_update_land = 1;
  174. private int frameMS = 0;
  175. private int physicsMS2 = 0;
  176. private int physicsMS = 0;
  177. private int otherMS = 0;
  178. private bool m_physics_enabled = true;
  179. private bool m_scripts_enabled = true;
  180. private string m_defaultScriptEngine;
  181. private int m_LastLogin = 0;
  182. private Thread HeartbeatThread;
  183. private volatile bool shuttingdown = false;
  184. private int m_lastUpdate = Environment.TickCount;
  185. private int m_maxPrimsPerFrame = 200;
  186. private object m_deleting_scene_object = new object();
  187. // the minimum time that must elapse before a changed object will be considered for persisted
  188. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  189. // the maximum time that must elapse before a changed object will be considered for persisted
  190. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  191. #endregion
  192. #region Properties
  193. public AgentCircuitManager AuthenticateHandler
  194. {
  195. get { return m_authenticateHandler; }
  196. }
  197. public SceneGraph SceneContents
  198. {
  199. get { return m_sceneGraph; }
  200. }
  201. // an instance to the physics plugin's Scene object.
  202. public PhysicsScene PhysicsScene
  203. {
  204. get { return m_sceneGraph.PhysicsScene; }
  205. set
  206. {
  207. // If we're not doing the initial set
  208. // Then we've got to remove the previous
  209. // event handler
  210. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  211. {
  212. PhysicsScene.OnJointMoved -= jointMoved;
  213. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  214. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  215. }
  216. m_sceneGraph.PhysicsScene = value;
  217. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  218. {
  219. // register event handlers to respond to joint movement/deactivation
  220. PhysicsScene.OnJointMoved += jointMoved;
  221. PhysicsScene.OnJointDeactivated += jointDeactivated;
  222. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  223. }
  224. }
  225. }
  226. // This gets locked so things stay thread safe.
  227. public object SyncRoot
  228. {
  229. get { return m_sceneGraph.m_syncRoot; }
  230. }
  231. public int MaxPrimsPerFrame
  232. {
  233. get { return m_maxPrimsPerFrame; }
  234. set { m_maxPrimsPerFrame = value; }
  235. }
  236. /// <summary>
  237. /// This is for llGetRegionFPS
  238. /// </summary>
  239. public float SimulatorFPS
  240. {
  241. get { return StatsReporter.getLastReportedSimFPS(); }
  242. }
  243. public string DefaultScriptEngine
  244. {
  245. get { return m_defaultScriptEngine; }
  246. }
  247. // Reference to all of the agents in the scene (root and child)
  248. protected Dictionary<UUID, ScenePresence> m_scenePresences
  249. {
  250. get { return m_sceneGraph.ScenePresences; }
  251. set { m_sceneGraph.ScenePresences = value; }
  252. }
  253. public EntityManager Entities
  254. {
  255. get { return m_sceneGraph.Entities; }
  256. }
  257. public Dictionary<UUID, ScenePresence> m_restorePresences
  258. {
  259. get { return m_sceneGraph.RestorePresences; }
  260. set { m_sceneGraph.RestorePresences = value; }
  261. }
  262. public int objectCapacity = 45000;
  263. #endregion
  264. #region Constructors
  265. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  266. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  267. StorageManager storeManager,
  268. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  269. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  270. {
  271. m_config = config;
  272. Random random = new Random();
  273. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  274. m_moduleLoader = moduleLoader;
  275. m_authenticateHandler = authen;
  276. CommsManager = commsMan;
  277. m_sceneGridService = sceneGridService;
  278. m_storageManager = storeManager;
  279. m_regInfo = regInfo;
  280. m_regionHandle = m_regInfo.RegionHandle;
  281. m_regionName = m_regInfo.RegionName;
  282. m_datastore = m_regInfo.DataStore;
  283. m_physicalPrim = physicalPrim;
  284. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  285. m_eventManager = new EventManager();
  286. m_permissions = new ScenePermissions(this);
  287. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  288. m_asyncSceneObjectDeleter.Enabled = true;
  289. // Load region settings
  290. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  291. if (m_storageManager.EstateDataStore != null)
  292. {
  293. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
  294. }
  295. //Bind Storage Manager functions to some land manager functions for this scene
  296. EventManager.OnLandObjectAdded +=
  297. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  298. EventManager.OnLandObjectRemoved +=
  299. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  300. m_sceneGraph = new SceneGraph(this, m_regInfo);
  301. // If the scene graph has an Unrecoverable error, restart this sim.
  302. // Currently the only thing that causes it to happen is two kinds of specific
  303. // Physics based crashes.
  304. //
  305. // Out of memory
  306. // Operating system has killed the plugin
  307. m_sceneGraph.UnRecoverableError += RestartNow;
  308. RegisterDefaultSceneEvents();
  309. DumpAssetsToFile = dumpAssetsToFile;
  310. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  311. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  312. StatsReporter = new SimStatsReporter(this);
  313. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  314. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  315. StatsReporter.SetObjectCapacity(objectCapacity);
  316. m_simulatorVersion = simulatorVersion
  317. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  318. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  319. + " PhysPrim:" + m_physicalPrim.ToString();
  320. try
  321. {
  322. // Region config overrides global config
  323. //
  324. IConfig startupConfig = m_config.Configs["Startup"];
  325. //Animation states
  326. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  327. // TODO: Change default to true once the feature is supported
  328. m_usePreJump = startupConfig.GetBoolean("enableprejump", false);
  329. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  330. if (RegionInfo.NonphysPrimMax > 0)
  331. {
  332. m_maxNonphys = RegionInfo.NonphysPrimMax;
  333. }
  334. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  335. if (RegionInfo.PhysPrimMax > 0)
  336. {
  337. m_maxPhys = RegionInfo.PhysPrimMax;
  338. }
  339. // Here, if clamping is requested in either global or
  340. // local config, it will be used
  341. //
  342. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  343. if (RegionInfo.ClampPrimSize)
  344. {
  345. m_clampPrimSize = true;
  346. }
  347. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  348. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  349. m_dontPersistBefore =
  350. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  351. m_dontPersistBefore *= 10000000;
  352. m_persistAfter =
  353. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  354. m_persistAfter *= 10000000;
  355. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "DotNetEngine");
  356. m_maxPrimsPerFrame = startupConfig.GetInt("MaxPrimsPerFrame", 200);
  357. IConfig packetConfig = m_config.Configs["PacketPool"];
  358. if (packetConfig != null)
  359. {
  360. PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
  361. PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
  362. }
  363. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  364. }
  365. catch
  366. {
  367. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  368. }
  369. }
  370. /// <summary>
  371. /// Mock constructor for scene group persistency unit tests.
  372. /// SceneObjectGroup RegionId property is delegated to Scene.
  373. /// </summary>
  374. /// <param name="regInfo"></param>
  375. public Scene(RegionInfo regInfo)
  376. {
  377. m_regInfo = regInfo;
  378. m_eventManager = new EventManager();
  379. }
  380. #endregion
  381. #region Startup / Close Methods
  382. public bool ShuttingDown
  383. {
  384. get { return shuttingdown; }
  385. }
  386. /// <value>
  387. /// The scene graph for this scene
  388. /// </value>
  389. /// TODO: Possibly stop other classes being able to manipulate this directly.
  390. public SceneGraph SceneGraph
  391. {
  392. get { return m_sceneGraph; }
  393. }
  394. protected virtual void RegisterDefaultSceneEvents()
  395. {
  396. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  397. if (dm != null)
  398. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  399. }
  400. public override string GetSimulatorVersion()
  401. {
  402. return m_simulatorVersion;
  403. }
  404. /// <summary>
  405. /// Another region is up. Gets called from Grid Comms:
  406. /// (OGS1 -> LocalBackEnd -> RegionListened -> SceneCommunicationService)
  407. /// We have to tell all our ScenePresences about it, and add it to the
  408. /// neighbor list.
  409. ///
  410. /// We only add it to the neighbor list if it's within 1 region from here.
  411. /// Agents may have draw distance values that cross two regions though, so
  412. /// we add it to the notify list regardless of distance. We'll check
  413. /// the agent's draw distance before notifying them though.
  414. /// </summary>
  415. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  416. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  417. public override bool OtherRegionUp(RegionInfo otherRegion)
  418. {
  419. m_log.InfoFormat("[SCENE]: Region {0} up in coords {1}-{2}", otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);
  420. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  421. {
  422. for (int i = 0; i < m_neighbours.Count; i++)
  423. {
  424. // The purpose of this loop is to re-update the known neighbors
  425. // when another region comes up on top of another one.
  426. // The latest region in that location ends up in the
  427. // 'known neighbors list'
  428. // Additionally, the commFailTF property gets reset to false.
  429. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  430. {
  431. lock (m_neighbours)
  432. {
  433. m_neighbours[i] = otherRegion;
  434. }
  435. }
  436. }
  437. // If the value isn't in the neighbours, add it.
  438. // If the RegionInfo isn't exact but is for the same XY World location,
  439. // then the above loop will fix that.
  440. if (!(CheckNeighborRegion(otherRegion)))
  441. {
  442. lock (m_neighbours)
  443. {
  444. m_neighbours.Add(otherRegion);
  445. //m_log.Info("[UP]: " + otherRegion.RegionHandle.ToString());
  446. }
  447. }
  448. // If these are cast to INT because long + negative values + abs returns invalid data
  449. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  450. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  451. if (resultX <= 1 && resultY <= 1)
  452. {
  453. try
  454. {
  455. ForEachScenePresence(delegate(ScenePresence agent)
  456. {
  457. // If agent is a root agent.
  458. if (!agent.IsChildAgent)
  459. {
  460. //agent.ControllingClient.new
  461. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  462. List<ulong> old = new List<ulong>();
  463. old.Add(otherRegion.RegionHandle);
  464. agent.DropOldNeighbours(old);
  465. InformClientOfNeighbor(agent, otherRegion);
  466. }
  467. }
  468. );
  469. }
  470. catch (NullReferenceException)
  471. {
  472. // This means that we're not booted up completely yet.
  473. // This shouldn't happen too often anymore.
  474. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  475. }
  476. }
  477. else
  478. {
  479. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  480. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  481. otherRegion.RegionLocY.ToString() + ")");
  482. }
  483. }
  484. return true;
  485. }
  486. public void AddNeighborRegion(RegionInfo region)
  487. {
  488. lock (m_neighbours)
  489. {
  490. if (!CheckNeighborRegion(region))
  491. {
  492. m_neighbours.Add(region);
  493. }
  494. }
  495. }
  496. public bool CheckNeighborRegion(RegionInfo region)
  497. {
  498. bool found = false;
  499. lock (m_neighbours)
  500. {
  501. foreach (RegionInfo reg in m_neighbours)
  502. {
  503. if (reg.RegionHandle == region.RegionHandle)
  504. {
  505. found = true;
  506. break;
  507. }
  508. }
  509. }
  510. return found;
  511. }
  512. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  513. public bool IncomingHelloNeighbour(RegionInfo neighbour)
  514. {
  515. return OtherRegionUp(neighbour);
  516. }
  517. /// <summary>
  518. /// Given float seconds, this will restart the region.
  519. /// </summary>
  520. /// <param name="seconds">float indicating duration before restart.</param>
  521. public virtual void Restart(float seconds)
  522. {
  523. // notifications are done in 15 second increments
  524. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  525. // It's a 'Cancel restart' request.
  526. // RestartNow() does immediate restarting.
  527. if (seconds < 15)
  528. {
  529. m_restartTimer.Stop();
  530. m_dialogModule.SendGeneralAlert("Restart Aborted");
  531. }
  532. else
  533. {
  534. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  535. m_restartTimer.Interval = 15000;
  536. m_incrementsof15seconds = (int)seconds / 15;
  537. m_RestartTimerCounter = 0;
  538. m_restartTimer.AutoReset = true;
  539. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  540. m_log.Info("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  541. m_restartTimer.Start();
  542. m_dialogModule.SendNotificationToUsersInRegion(
  543. UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  544. }
  545. }
  546. // The Restart timer has occured.
  547. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  548. // have elapsed.
  549. // If they have elapsed, call RestartNow()
  550. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  551. {
  552. m_RestartTimerCounter++;
  553. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  554. {
  555. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  556. m_dialogModule.SendNotificationToUsersInRegion(
  557. UUID.Random(),
  558. String.Empty,
  559. RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter) * 15) + " seconds");
  560. }
  561. else
  562. {
  563. m_restartTimer.Stop();
  564. m_restartTimer.AutoReset = false;
  565. RestartNow();
  566. }
  567. }
  568. // This causes the region to restart immediatley.
  569. public void RestartNow()
  570. {
  571. if (PhysicsScene != null)
  572. {
  573. PhysicsScene.Dispose();
  574. }
  575. m_log.Error("[REGION]: Closing");
  576. Close();
  577. m_log.Error("[REGION]: Firing Region Restart Message");
  578. base.Restart(0);
  579. }
  580. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  581. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  582. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  583. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  584. // subsequently the agent will never see the region come back online.
  585. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  586. {
  587. m_restartWaitTimer.Stop();
  588. lock (m_regionRestartNotifyList)
  589. {
  590. foreach (RegionInfo region in m_regionRestartNotifyList)
  591. {
  592. try
  593. {
  594. ForEachScenePresence(delegate(ScenePresence agent)
  595. {
  596. // If agent is a root agent.
  597. if (!agent.IsChildAgent)
  598. {
  599. //agent.ControllingClient.new
  600. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  601. InformClientOfNeighbor(agent, region);
  602. }
  603. }
  604. );
  605. }
  606. catch (NullReferenceException)
  607. {
  608. // This means that we're not booted up completely yet.
  609. // This shouldn't happen too often anymore.
  610. }
  611. }
  612. // Reset list to nothing.
  613. m_regionRestartNotifyList.Clear();
  614. }
  615. }
  616. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  617. {
  618. if (m_scripts_enabled != !ScriptEngine)
  619. {
  620. // Tedd! Here's the method to disable the scripting engine!
  621. if (ScriptEngine)
  622. {
  623. m_log.Info("Stopping all Scripts in Scene");
  624. foreach (EntityBase ent in Entities)
  625. {
  626. if (ent is SceneObjectGroup)
  627. {
  628. ((SceneObjectGroup) ent).RemoveScriptInstances();
  629. }
  630. }
  631. }
  632. else
  633. {
  634. m_log.Info("Starting all Scripts in Scene");
  635. lock (Entities)
  636. {
  637. foreach (EntityBase ent in Entities)
  638. {
  639. if (ent is SceneObjectGroup)
  640. {
  641. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  642. }
  643. }
  644. }
  645. }
  646. m_scripts_enabled = !ScriptEngine;
  647. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  648. }
  649. if (m_physics_enabled != !PhysicsEngine)
  650. {
  651. m_physics_enabled = !PhysicsEngine;
  652. }
  653. }
  654. public int GetInaccurateNeighborCount()
  655. {
  656. lock (m_neighbours)
  657. {
  658. return m_neighbours.Count;
  659. }
  660. }
  661. // This is the method that shuts down the scene.
  662. public override void Close()
  663. {
  664. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  665. // Kick all ROOT agents with the message, 'The simulator is going down'
  666. ForEachScenePresence(delegate(ScenePresence avatar)
  667. {
  668. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  669. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  670. if (!avatar.IsChildAgent)
  671. avatar.ControllingClient.Kick("The simulator is going down.");
  672. avatar.ControllingClient.SendShutdownConnectionNotice();
  673. });
  674. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  675. Thread.Sleep(500);
  676. // Stop all client threads.
  677. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  678. // Stop updating the scene objects and agents.
  679. //m_heartbeatTimer.Close();
  680. shuttingdown = true;
  681. m_log.Debug("[SCENE]: Persisting changed objects");
  682. List<EntityBase> entities = GetEntities();
  683. foreach (EntityBase entity in entities)
  684. {
  685. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  686. {
  687. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore, false);
  688. }
  689. }
  690. m_sceneGraph.Close();
  691. // De-register with region communications (events cleanup)
  692. UnRegisterRegionWithComms();
  693. // call the base class Close method.
  694. base.Close();
  695. }
  696. /// <summary>
  697. /// Start the timer which triggers regular scene updates
  698. /// </summary>
  699. public void StartTimer()
  700. {
  701. //m_log.Debug("[SCENE]: Starting timer");
  702. //m_heartbeatTimer.Enabled = true;
  703. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  704. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  705. HeartbeatThread = new Thread(new ParameterizedThreadStart(Heartbeat));
  706. HeartbeatThread.SetApartmentState(ApartmentState.MTA);
  707. HeartbeatThread.Name = string.Format("Heartbeat for region {0}", RegionInfo.RegionName);
  708. HeartbeatThread.Priority = ThreadPriority.AboveNormal;
  709. ThreadTracker.Add(HeartbeatThread);
  710. HeartbeatThread.Start();
  711. }
  712. /// <summary>
  713. /// Sets up references to modules required by the scene
  714. /// </summary>
  715. public void SetModuleInterfaces()
  716. {
  717. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  718. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  719. XferManager = RequestModuleInterface<IXfer>();
  720. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  721. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  722. m_interregionCommsOut = RequestModuleInterface<IInterregionCommsOut>();
  723. m_interregionCommsIn = RequestModuleInterface<IInterregionCommsIn>();
  724. m_dialogModule = RequestModuleInterface<IDialogModule>();
  725. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  726. m_teleportModule = RequestModuleInterface<ITeleportModule>();
  727. }
  728. #endregion
  729. #region Update Methods
  730. /// <summary>
  731. /// Performs per-frame updates regularly
  732. /// </summary>
  733. /// <param name="sender"></param>
  734. /// <param name="e"></param>
  735. private void Heartbeat(object sender)
  736. {
  737. Update();
  738. m_lastUpdate = Environment.TickCount;
  739. }
  740. /// <summary>
  741. /// Performs per-frame updates on the scene, this should be the central scene loop
  742. /// </summary>
  743. public override void Update()
  744. {
  745. int maintc = 0;
  746. while (!shuttingdown)
  747. {
  748. maintc = Environment.TickCount;
  749. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  750. // Aquire a lock so only one update call happens at once
  751. //updateLock.WaitOne();
  752. float physicsFPS = 0;
  753. //m_log.Info("sadfadf" + m_neighbours.Count.ToString());
  754. int agentsInScene = m_sceneGraph.GetRootAgentCount() + m_sceneGraph.GetChildAgentCount();
  755. if (agentsInScene > 21)
  756. {
  757. if (m_update_entities == 1)
  758. {
  759. m_update_entities = 5;
  760. StatsReporter.SetUpdateMS(6000);
  761. }
  762. }
  763. else
  764. {
  765. if (m_update_entities == 5)
  766. {
  767. m_update_entities = 1;
  768. StatsReporter.SetUpdateMS(3000);
  769. }
  770. }
  771. frameMS = Environment.TickCount;
  772. try
  773. {
  774. // Increment the frame counter
  775. m_frame++;
  776. // Loop it
  777. if (m_frame == Int32.MaxValue)
  778. m_frame = 0;
  779. otherMS = Environment.TickCount;
  780. // run through all entities looking for updates (slow)
  781. if (m_frame % m_update_entities == 0)
  782. {
  783. /* // Adam Experimental
  784. if (m_updateEntitiesThread == null)
  785. {
  786. m_updateEntitiesThread = new Thread(m_sceneGraph.UpdateEntities);
  787. ThreadTracker.Add(m_updateEntitiesThread);
  788. }
  789. if (m_updateEntitiesThread.ThreadState == ThreadState.Stopped)
  790. m_updateEntitiesThread.Start();
  791. */
  792. m_sceneGraph.UpdateEntities();
  793. }
  794. // run through entities that have scheduled themselves for
  795. // updates looking for updates(faster)
  796. if (m_frame % m_update_entitiesquick == 0)
  797. m_sceneGraph.ProcessUpdates();
  798. // Run through scenepresences looking for updates
  799. if (m_frame % m_update_presences == 0)
  800. m_sceneGraph.UpdatePresences();
  801. physicsMS2 = Environment.TickCount;
  802. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  803. m_sceneGraph.UpdatePreparePhysics();
  804. physicsMS2 = Environment.TickCount - physicsMS2;
  805. if (m_frame % m_update_entitymovement == 0)
  806. m_sceneGraph.UpdateEntityMovement();
  807. physicsMS = Environment.TickCount;
  808. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  809. physicsFPS = m_sceneGraph.UpdatePhysics(
  810. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  811. );
  812. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  813. SynchronizeScene(this);
  814. physicsMS = Environment.TickCount - physicsMS;
  815. physicsMS += physicsMS2;
  816. // Delete temp-on-rez stuff
  817. if (m_frame % m_update_backup == 0)
  818. CleanTempObjects();
  819. if (RegionStatus != RegionStatus.SlaveScene)
  820. {
  821. if (m_frame % m_update_events == 0)
  822. UpdateEvents();
  823. if (m_frame % m_update_backup == 0)
  824. UpdateStorageBackup();
  825. if (m_frame % m_update_terrain == 0)
  826. UpdateTerrain();
  827. if (m_frame % m_update_land == 0)
  828. UpdateLand();
  829. otherMS = Environment.TickCount - otherMS;
  830. // if (m_frame%m_update_avatars == 0)
  831. // UpdateInWorldTime();
  832. StatsReporter.AddPhysicsFPS(physicsFPS);
  833. StatsReporter.AddTimeDilation(m_timedilation);
  834. StatsReporter.AddFPS(1);
  835. StatsReporter.AddInPackets(0);
  836. StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  837. StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  838. StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  839. StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  840. frameMS = Environment.TickCount - frameMS;
  841. StatsReporter.addFrameMS(frameMS);
  842. StatsReporter.addPhysicsMS(physicsMS);
  843. StatsReporter.addOtherMS(otherMS);
  844. StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  845. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  846. }
  847. }
  848. catch (NotImplementedException)
  849. {
  850. throw;
  851. }
  852. catch (AccessViolationException e)
  853. {
  854. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  855. }
  856. //catch (NullReferenceException e)
  857. //{
  858. // m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  859. //}
  860. catch (InvalidOperationException e)
  861. {
  862. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  863. }
  864. catch (Exception e)
  865. {
  866. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  867. }
  868. finally
  869. {
  870. //updateLock.ReleaseMutex();
  871. // Get actual time dilation
  872. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  873. // If actual time dilation is greater then one, we're catching up, so subtract
  874. // the amount that's greater then 1 from the time dilation
  875. if (tmpval > 1.0)
  876. {
  877. tmpval = tmpval - (tmpval - 1.0f);
  878. }
  879. m_timedilation = tmpval;
  880. m_lastupdate = DateTime.Now;
  881. }
  882. maintc = Environment.TickCount - maintc;
  883. maintc = (int)(m_timespan * 1000) - maintc;
  884. if ((maintc < (m_timespan * 1000)) && maintc > 0)
  885. Thread.Sleep(maintc);
  886. }
  887. }
  888. /// <summary>
  889. /// Send out simstats data to all clients
  890. /// </summary>
  891. /// <param name="stats">Stats on the Simulator's performance</param>
  892. private void SendSimStatsPackets(SimStats stats)
  893. {
  894. List<ScenePresence> StatSendAgents = GetScenePresences();
  895. foreach (ScenePresence agent in StatSendAgents)
  896. {
  897. if (!agent.IsChildAgent)
  898. {
  899. agent.ControllingClient.SendSimStats(stats);
  900. }
  901. }
  902. }
  903. /// <summary>
  904. /// Recount SceneObjectPart in parcel aabb
  905. /// </summary>
  906. private void UpdateLand()
  907. {
  908. if (LandChannel != null)
  909. {
  910. if (LandChannel.IsLandPrimCountTainted())
  911. {
  912. EventManager.TriggerParcelPrimCountUpdate();
  913. }
  914. }
  915. }
  916. /// <summary>
  917. /// Update the terrain if it needs to be updated.
  918. /// </summary>
  919. private void UpdateTerrain()
  920. {
  921. EventManager.TriggerTerrainTick();
  922. }
  923. /// <summary>
  924. /// Back up queued up changes
  925. /// </summary>
  926. private void UpdateStorageBackup()
  927. {
  928. if (!m_backingup)
  929. {
  930. m_backingup = true;
  931. Thread backupthread = new Thread(Backup);
  932. backupthread.Name = "BackupWriter";
  933. backupthread.IsBackground = true;
  934. backupthread.Start();
  935. }
  936. }
  937. /// <summary>
  938. /// Sends out the OnFrame event to the modules
  939. /// </summary>
  940. private void UpdateEvents()
  941. {
  942. m_eventManager.TriggerOnFrame();
  943. }
  944. /// <summary>
  945. /// Perform delegate action on all clients subscribing to updates from this region.
  946. /// </summary>
  947. /// <returns></returns>
  948. public void Broadcast(Action<IClientAPI> whatToDo)
  949. {
  950. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  951. }
  952. /// <summary>
  953. /// Backup the scene. This acts as the main method of the backup thread.
  954. /// </summary>
  955. /// <returns></returns>
  956. public void Backup()
  957. {
  958. lock (m_returns)
  959. {
  960. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  961. m_backingup = false;
  962. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  963. {
  964. UUID transaction = UUID.Random();
  965. GridInstantMessage msg = new GridInstantMessage();
  966. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  967. msg.toAgentID = new Guid(ret.Key.ToString());
  968. msg.imSessionID = new Guid(transaction.ToString());
  969. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  970. msg.fromAgentName = "Server";
  971. msg.dialog = (byte)19; // Object msg
  972. msg.fromGroup = false;
  973. msg.offline = (byte)1;
  974. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  975. msg.Position = Vector3.Zero;
  976. msg.RegionID = RegionInfo.RegionID.Guid;
  977. msg.binaryBucket = new byte[0];
  978. if (ret.Value.count > 1)
  979. 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);
  980. else
  981. 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);
  982. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  983. if (tr != null)
  984. tr.SendInstantMessage(msg, delegate(bool success) {});
  985. }
  986. m_returns.Clear();
  987. }
  988. }
  989. /// <summary>
  990. /// Synchronous force backup. For deletes and links/unlinks
  991. /// </summary>
  992. /// <param name="group">Object to be backed up</param>
  993. public void ForceSceneObjectBackup(SceneObjectGroup group)
  994. {
  995. if (group != null)
  996. {
  997. group.ProcessBackup(m_storageManager.DataStore, true);
  998. }
  999. }
  1000. /// <summary>
  1001. /// Return object to avatar Message
  1002. /// </summary>
  1003. /// <param name="agentID">Avatar Unique Id</param>
  1004. /// <param name="objectName">Name of object returned</param>
  1005. /// <param name="location">Location of object returned</param>
  1006. /// <param name="reason">Reasion for object return</param>
  1007. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1008. {
  1009. lock (m_returns)
  1010. {
  1011. if (m_returns.ContainsKey(agentID))
  1012. {
  1013. ReturnInfo info = m_returns[agentID];
  1014. info.count++;
  1015. m_returns[agentID] = info;
  1016. }
  1017. else
  1018. {
  1019. ReturnInfo info = new ReturnInfo();
  1020. info.count = 1;
  1021. info.objectName = objectName;
  1022. info.location = location;
  1023. info.reason = reason;
  1024. m_returns[agentID] = info;
  1025. }
  1026. }
  1027. }
  1028. #endregion
  1029. #region Load Terrain
  1030. /// <summary>
  1031. /// Store the terrain in the persistant data store
  1032. /// </summary>
  1033. public void SaveTerrain()
  1034. {
  1035. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1036. }
  1037. /// <summary>
  1038. /// Loads the World heightmap
  1039. /// </summary>
  1040. public override void LoadWorldMap()
  1041. {
  1042. try
  1043. {
  1044. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  1045. if (map == null)
  1046. {
  1047. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  1048. Heightmap = new TerrainChannel();
  1049. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1050. }
  1051. else
  1052. {
  1053. Heightmap = new TerrainChannel(map);
  1054. }
  1055. }
  1056. catch (IOException e)
  1057. {
  1058. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString() + " Regenerating");
  1059. // Non standard region size. If there's an old terrain in the database, it might read past the buffer
  1060. if ((int)Constants.RegionSize != 256)
  1061. {
  1062. Heightmap = new TerrainChannel();
  1063. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1064. }
  1065. }
  1066. catch (Exception e)
  1067. {
  1068. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  1069. }
  1070. }
  1071. /// <summary>
  1072. /// Register this region with a grid service
  1073. /// </summary>
  1074. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1075. public void RegisterRegionWithGrid()
  1076. {
  1077. RegisterCommsEvents();
  1078. // These two 'commands' *must be* next to each other or sim rebooting fails.
  1079. m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
  1080. m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
  1081. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  1082. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  1083. {
  1084. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  1085. {
  1086. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  1087. EventManager.TriggerSetAllowForcefulBan(false);
  1088. }
  1089. else
  1090. {
  1091. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  1092. EventManager.TriggerSetAllowForcefulBan(true);
  1093. }
  1094. }
  1095. }
  1096. /// <summary>
  1097. /// Create a terrain texture for this scene
  1098. /// </summary>
  1099. public void CreateTerrainTexture(bool temporary)
  1100. {
  1101. //create a texture asset of the terrain
  1102. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  1103. // Cannot create a map for a nonexistant heightmap yet.
  1104. if (Heightmap == null)
  1105. return;
  1106. if (terrain == null)
  1107. return;
  1108. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1109. if (data != null)
  1110. {
  1111. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  1112. if (mapModule != null)
  1113. mapModule.LazySaveGeneratedMaptile(data, temporary);
  1114. }
  1115. }
  1116. #endregion
  1117. #region Load Land
  1118. /// <summary>
  1119. /// Loads all Parcel data from the datastore for region identified by regionID
  1120. /// </summary>
  1121. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1122. public void loadAllLandObjectsFromStorage(UUID regionID)
  1123. {
  1124. m_log.Info("[SCENE]: Loading land objects from storage");
  1125. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1126. if (LandChannel != null)
  1127. {
  1128. if (landData.Count == 0)
  1129. {
  1130. EventManager.TriggerNoticeNoLandDataFromStorage();
  1131. }
  1132. else
  1133. {
  1134. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1135. }
  1136. }
  1137. else
  1138. {
  1139. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1140. }
  1141. }
  1142. #endregion
  1143. #region Primitives Methods
  1144. /// <summary>
  1145. /// Loads the World's objects
  1146. /// </summary>
  1147. public virtual void LoadPrimsFromStorage(UUID regionID)
  1148. {
  1149. m_log.Info("[SCENE]: Loading objects from datastore");
  1150. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1151. foreach (SceneObjectGroup group in PrimsFromDB)
  1152. {
  1153. if (group.RootPart == null)
  1154. {
  1155. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1156. group.Children == null ? 0 : group.Children.Count);
  1157. }
  1158. AddRestoredSceneObject(group, true, true);
  1159. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1160. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1161. rootPart.TrimPermissions();
  1162. group.CheckSculptAndLoad();
  1163. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1164. }
  1165. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1166. }
  1167. /// <summary>
  1168. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1169. /// </summary>
  1170. /// <param name="RayStart"></param>
  1171. /// <param name="RayEnd"></param>
  1172. /// <param name="RayTargetID"></param>
  1173. /// <param name="rot"></param>
  1174. /// <param name="bypassRayCast"></param>
  1175. /// <param name="RayEndIsIntersection"></param>
  1176. /// <param name="frontFacesOnly"></param>
  1177. /// <param name="scale"></param>
  1178. /// <param name="FaceCenter"></param>
  1179. /// <returns></returns>
  1180. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1181. {
  1182. Vector3 pos = Vector3.Zero;
  1183. if (RayEndIsIntersection == (byte)1)
  1184. {
  1185. pos = RayEnd;
  1186. return pos;
  1187. }
  1188. if (RayTargetID != UUID.Zero)
  1189. {
  1190. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1191. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1192. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1193. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1194. if (target != null)
  1195. {
  1196. pos = target.AbsolutePosition;
  1197. //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());
  1198. // TODO: Raytrace better here
  1199. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1200. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1201. // Ray Trace against target here
  1202. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1203. // Un-comment out the following line to Get Raytrace results printed to the console.
  1204. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1205. float ScaleOffset = 0.5f;
  1206. // If we hit something
  1207. if (ei.HitTF)
  1208. {
  1209. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1210. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1211. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1212. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1213. ScaleOffset = Math.Abs(ScaleOffset);
  1214. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1215. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1216. // Set the position to the intersection point
  1217. Vector3 offset = (normal * (ScaleOffset / 2f));
  1218. pos = (intersectionpoint + offset);
  1219. //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
  1220. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  1221. // Un-offset the prim (it gets offset later by the consumer method)
  1222. //pos.Z -= 0.25F;
  1223. }
  1224. return pos;
  1225. }
  1226. else
  1227. {
  1228. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1229. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1230. // Un-comment the following line to print the raytrace results to the console.
  1231. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1232. if (ei.HitTF)
  1233. {
  1234. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1235. } else
  1236. {
  1237. // fall back to our stupid functionality
  1238. pos = RayEnd;
  1239. }
  1240. return pos;
  1241. }
  1242. }
  1243. else
  1244. {
  1245. // fall back to our stupid functionality
  1246. pos = RayEnd;
  1247. //increase height so its above the ground.
  1248. //should be getting the normal of the ground at the rez point and using that?
  1249. pos.Z += scale.Z / 2f;
  1250. return pos;
  1251. }
  1252. }
  1253. /// <summary>
  1254. /// Create a New SceneObjectGroup/Part by raycasting
  1255. /// </summary>
  1256. /// <param name="ownerID"></param>
  1257. /// <param name="groupID"></param>
  1258. /// <param name="RayEnd"></param>
  1259. /// <param name="rot"></param>
  1260. /// <param name="shape"></param>
  1261. /// <param name="bypassRaycast"></param>
  1262. /// <param name="RayStart"></param>
  1263. /// <param name="RayTargetID"></param>
  1264. /// <param name="RayEndIsIntersection"></param>
  1265. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1266. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1267. byte RayEndIsIntersection)
  1268. {
  1269. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1270. if (Permissions.CanRezObject(1, ownerID, pos))
  1271. {
  1272. // rez ON the ground, not IN the ground
  1273. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  1274. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1275. }
  1276. }
  1277. public virtual SceneObjectGroup AddNewPrim(
  1278. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1279. {
  1280. //m_log.DebugFormat(
  1281. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1282. // If an entity creator has been registered for this prim type then use that
  1283. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1284. return m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1285. // Otherwise, use this default creation code;
  1286. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1287. AddNewSceneObject(sceneObject, true);
  1288. sceneObject.SetGroup(groupID, null);
  1289. return sceneObject;
  1290. }
  1291. /// <summary>
  1292. /// Add an object into the scene that has come from storage
  1293. /// </summary>
  1294. ///
  1295. /// <param name="sceneObject"></param>
  1296. /// <param name="attachToBackup">
  1297. /// If true, changes to the object will be reflected in its persisted data
  1298. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1299. /// </param>
  1300. /// <param name="alreadyPersisted">
  1301. /// If true, we won't persist this object until it changes
  1302. /// If false, we'll persist this object immediately
  1303. /// </param>
  1304. /// <returns>
  1305. /// true if the object was added, false if an object with the same uuid was already in the scene
  1306. /// </returns>
  1307. public bool AddRestoredSceneObject(
  1308. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1309. {
  1310. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted);
  1311. }
  1312. /// <summary>
  1313. /// Add a newly created object to the scene
  1314. /// </summary>
  1315. /// <param name="sceneObject"></param>
  1316. /// <param name="attachToBackup">
  1317. /// If true, the object is made persistent into the scene.
  1318. /// If false, the object will not persist over server restarts
  1319. /// </param>
  1320. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1321. {
  1322. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup);
  1323. }
  1324. /// <summary>
  1325. /// Delete every object from the scene
  1326. /// </summary>
  1327. public void DeleteAllSceneObjects()
  1328. {
  1329. lock (Entities)
  1330. {
  1331. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1332. foreach (EntityBase e in entities)
  1333. {
  1334. if (e is SceneObjectGroup)
  1335. DeleteSceneObject((SceneObjectGroup)e, false);
  1336. }
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// Synchronously delete the given object from the scene.
  1341. /// </summary>
  1342. /// <param name="group">Object Id</param>
  1343. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  1344. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1345. {
  1346. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1347. // Serialise calls to RemoveScriptInstances to avoid
  1348. // deadlocking on m_parts inside SceneObjectGroup
  1349. lock (m_deleting_scene_object)
  1350. {
  1351. group.RemoveScriptInstances();
  1352. }
  1353. foreach (SceneObjectPart part in group.Children.Values)
  1354. {
  1355. if (part.IsJoint() && ((part.ObjectFlags&(uint)PrimFlags.Physics) != 0))
  1356. {
  1357. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  1358. }
  1359. else if (part.PhysActor != null)
  1360. {
  1361. PhysicsScene.RemovePrim(part.PhysActor);
  1362. part.PhysActor = null;
  1363. }
  1364. }
  1365. // if (rootPart.PhysActor != null)
  1366. // {
  1367. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1368. // rootPart.PhysActor = null;
  1369. // }
  1370. if (UnlinkSceneObject(group.UUID, false))
  1371. {
  1372. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1373. EventManager.TriggerParcelPrimCountTainted();
  1374. }
  1375. group.DeleteGroup(silent);
  1376. }
  1377. /// <summary>
  1378. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1379. /// object itself is not destroyed.
  1380. /// </summary>
  1381. /// <param name="uuid">Id of object.</param>
  1382. /// <returns>true if the object was in the scene, false if it was not</returns>
  1383. /// <param name="softDelete">If true, only deletes from scene, but keeps object in database.</param>
  1384. public bool UnlinkSceneObject(UUID uuid, bool softDelete)
  1385. {
  1386. if (m_sceneGraph.DeleteSceneObject(uuid, softDelete))
  1387. {
  1388. if (!softDelete)
  1389. {
  1390. m_storageManager.DataStore.RemoveObject(uuid,
  1391. m_regInfo.RegionID);
  1392. }
  1393. return true;
  1394. }
  1395. return false;
  1396. }
  1397. /// <summary>
  1398. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1399. /// into.
  1400. ///
  1401. /// This method locates the new region handle and offsets the prim position for the new region
  1402. /// </summary>
  1403. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1404. /// <param name="grp">the scene object that we're crossing</param>
  1405. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1406. {
  1407. if (grp == null)
  1408. return;
  1409. if (grp.IsDeleted)
  1410. return;
  1411. if (grp.RootPart.DIE_AT_EDGE)
  1412. {
  1413. // We remove the object here
  1414. try
  1415. {
  1416. DeleteSceneObject(grp, false);
  1417. }
  1418. catch (Exception)
  1419. {
  1420. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1421. }
  1422. return;
  1423. }
  1424. int thisx = (int)RegionInfo.RegionLocX;
  1425. int thisy = (int)RegionInfo.RegionLocY;
  1426. ulong newRegionHandle = 0;
  1427. Vector3 pos = attemptedPosition;
  1428. if (attemptedPosition.X > Constants.RegionSize + 0.1f)
  1429. {
  1430. pos.X = ((pos.X - Constants.RegionSize));
  1431. newRegionHandle
  1432. = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1433. // x + 1
  1434. }
  1435. else if (attemptedPosition.X < -0.1f)
  1436. {
  1437. pos.X = ((pos.X + Constants.RegionSize));
  1438. newRegionHandle
  1439. = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1440. // x - 1
  1441. }
  1442. if (attemptedPosition.Y > Constants.RegionSize + 0.1f)
  1443. {
  1444. pos.Y = ((pos.Y - Constants.RegionSize));
  1445. newRegionHandle
  1446. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1447. // y + 1
  1448. }
  1449. else if (attemptedPosition.Y < -0.1f)
  1450. {
  1451. pos.Y = ((pos.Y + Constants.RegionSize));
  1452. newRegionHandle
  1453. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1454. // y - 1
  1455. }
  1456. // Offset the positions for the new region across the border
  1457. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1458. grp.OffsetForNewRegion(pos);
  1459. // If we fail to cross the border, then reset the position of the scene object on that border.
  1460. if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
  1461. {
  1462. grp.OffsetForNewRegion(oldGroupPosition);
  1463. grp.ScheduleGroupForFullUpdate();
  1464. }
  1465. }
  1466. /// <summary>
  1467. /// Move the given scene object into a new region
  1468. /// </summary>
  1469. /// <param name="newRegionHandle"></param>
  1470. /// <param name="grp">Scene Object Group that we're crossing</param>
  1471. /// <returns>
  1472. /// true if the crossing itself was successful, false on failure
  1473. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1474. /// </returns>
  1475. public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
  1476. {
  1477. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  1478. bool successYN = false;
  1479. grp.RootPart.UpdateFlag = 0;
  1480. //int primcrossingXMLmethod = 0;
  1481. if (newRegionHandle != 0)
  1482. {
  1483. //string objectState = grp.GetStateSnapshot();
  1484. //successYN
  1485. // = m_sceneGridService.PrimCrossToNeighboringRegion(
  1486. // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1487. //if (successYN && (objectState != "") && m_allowScriptCrossings)
  1488. //{
  1489. // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1490. // newRegionHandle, grp.UUID, objectState, 100);
  1491. //}
  1492. // And the new channel...
  1493. if (m_interregionCommsOut != null)
  1494. successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
  1495. if (successYN)
  1496. {
  1497. // We remove the object here
  1498. try
  1499. {
  1500. DeleteSceneObject(grp, silent);
  1501. }
  1502. catch (Exception e)
  1503. {
  1504. m_log.ErrorFormat(
  1505. "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1506. grp, e);
  1507. }
  1508. }
  1509. else
  1510. {
  1511. if (!grp.IsDeleted)
  1512. {
  1513. if (grp.RootPart.PhysActor != null)
  1514. {
  1515. grp.RootPart.PhysActor.CrossingFailure();
  1516. }
  1517. }
  1518. m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
  1519. }
  1520. }
  1521. else
  1522. {
  1523. m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
  1524. }
  1525. return successYN;
  1526. }
  1527. /// <summary>
  1528. /// Handle a scene object that is crossing into this region from another.
  1529. /// NOTE: Unused as of 2009-02-09. Soon to be deleted.
  1530. /// </summary>
  1531. /// <param name="regionHandle"></param>
  1532. /// <param name="primID"></param>
  1533. /// <param name="objXMLData"></param>
  1534. /// <param name="XMLMethod"></param>
  1535. /// <returns></returns>
  1536. public bool IncomingInterRegionPrimGroup(UUID primID, string objXMLData, int XMLMethod)
  1537. {
  1538. if (XMLMethod == 0)
  1539. {
  1540. m_log.DebugFormat("[INTERREGION]: A new prim {0} arrived from a neighbor", primID);
  1541. SceneObjectGroup sceneObject = m_serialiser.DeserializeGroupFromXml2(objXMLData);
  1542. if (sceneObject.IsAttachment)
  1543. sceneObject.RootPart.ObjectFlags |= (uint)PrimFlags.Phantom;
  1544. return AddSceneObject(sceneObject);
  1545. }
  1546. else if ((XMLMethod == 100) && m_allowScriptCrossings)
  1547. {
  1548. m_log.Warn("[INTERREGION]: Prim state data arrived from a neighbor");
  1549. XmlDocument doc = new XmlDocument();
  1550. doc.LoadXml(objXMLData);
  1551. XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
  1552. if (rootL.Count == 1)
  1553. {
  1554. XmlNode rootNode = rootL[0];
  1555. if (rootNode != null)
  1556. {
  1557. XmlNodeList partL = rootNode.ChildNodes;
  1558. foreach (XmlNode part in partL)
  1559. {
  1560. XmlNodeList nodeL = part.ChildNodes;
  1561. switch (part.Name)
  1562. {
  1563. case "Assemblies":
  1564. foreach (XmlNode asm in nodeL)
  1565. {
  1566. string fn = asm.Attributes.GetNamedItem("Filename").Value;
  1567. Byte[] filedata = Convert.FromBase64String(asm.InnerText);
  1568. string path = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1569. path = Path.Combine(path, fn);
  1570. if (!File.Exists(path))
  1571. {
  1572. FileStream fs = File.Create(path);
  1573. fs.Write(filedata, 0, filedata.Length);
  1574. fs.Close();
  1575. }
  1576. }
  1577. break;
  1578. case "ScriptStates":
  1579. foreach (XmlNode st in nodeL)
  1580. {
  1581. string id = st.Attributes.GetNamedItem("UUID").Value;
  1582. UUID uuid = new UUID(id);
  1583. XmlNode state = st.ChildNodes[0];
  1584. XmlDocument sdoc = new XmlDocument();
  1585. XmlNode sxmlnode = sdoc.CreateNode(
  1586. XmlNodeType.XmlDeclaration,
  1587. "", "");
  1588. sdoc.AppendChild(sxmlnode);
  1589. XmlNode newnode = sdoc.ImportNode(state, true);
  1590. sdoc.AppendChild(newnode);
  1591. string spath = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1592. spath = Path.Combine(spath, uuid.ToString());
  1593. FileStream sfs = File.Create(spath + ".state");
  1594. ASCIIEncoding enc = new ASCIIEncoding();
  1595. Byte[] buf = enc.GetBytes(sdoc.InnerXml);
  1596. sfs.Write(buf, 0, buf.Length);
  1597. sfs.Close();
  1598. }
  1599. break;
  1600. }
  1601. }
  1602. }
  1603. }
  1604. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1605. RootPrim.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1606. return true;
  1607. }
  1608. return true;
  1609. }
  1610. public bool IncomingCreateObject(ISceneObject sog)
  1611. {
  1612. //m_log.Debug(" >>> IncomingCreateObject <<< " + ((SceneObjectGroup)sog).AbsolutePosition + " deleted? " + ((SceneObjectGroup)sog).IsDeleted);
  1613. SceneObjectGroup newObject;
  1614. try
  1615. {
  1616. newObject = (SceneObjectGroup)sog;
  1617. }
  1618. catch (Exception e)
  1619. {
  1620. m_log.WarnFormat("[SCENE]: Problem casting object: {0}", e.Message);
  1621. return false;
  1622. }
  1623. if (!AddSceneObject(newObject))
  1624. {
  1625. m_log.DebugFormat("[SCENE]: Problem adding scene object {0} in {1} ", sog.UUID, RegionInfo.RegionName);
  1626. return false;
  1627. }
  1628. newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1629. return true;
  1630. }
  1631. /// <summary>
  1632. /// Attachment rezzing
  1633. /// </summary>
  1634. /// <param name="userID">Agent Unique ID</param>
  1635. /// <param name="itemID">Object ID</param>
  1636. /// <returns>False</returns>
  1637. public virtual bool IncomingCreateObject(UUID userID, UUID itemID)
  1638. {
  1639. ScenePresence sp = GetScenePresence(userID);
  1640. if (sp != null)
  1641. {
  1642. uint attPt = (uint)sp.Appearance.GetAttachpoint(itemID);
  1643. m_sceneGraph.RezSingleAttachment(sp.ControllingClient, itemID, attPt);
  1644. }
  1645. return false;
  1646. }
  1647. /// <summary>
  1648. /// Adds a Scene Object group to the Scene.
  1649. /// Verifies that the creator of the object is not banned from the simulator.
  1650. /// Checks if the item is an Attachment
  1651. /// </summary>
  1652. /// <param name="sceneObject"></param>
  1653. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  1654. public bool AddSceneObject(SceneObjectGroup sceneObject)
  1655. {
  1656. // If the user is banned, we won't let any of their objects
  1657. // enter. Period.
  1658. //
  1659. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  1660. {
  1661. m_log.Info("[INTERREGION]: Denied prim crossing for " +
  1662. "banned avatar");
  1663. return false;
  1664. }
  1665. // Force allocation of new LocalId
  1666. //
  1667. foreach (SceneObjectPart p in sceneObject.Children.Values)
  1668. p.LocalId = 0;
  1669. if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim)
  1670. {
  1671. if (sceneObject.RootPart.Shape.State != 0) // Attachment
  1672. {
  1673. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  1674. sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
  1675. AddRestoredSceneObject(sceneObject, false, false);
  1676. // Handle attachment special case
  1677. SceneObjectPart RootPrim = sceneObject.RootPart;
  1678. // Fix up attachment Parent Local ID
  1679. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  1680. //uint parentLocalID = 0;
  1681. if (sp != null)
  1682. {
  1683. //parentLocalID = sp.LocalId;
  1684. //sceneObject.RootPart.IsAttachment = true;
  1685. //sceneObject.RootPart.SetParentLocalId(parentLocalID);
  1686. SceneObjectGroup grp = sceneObject;
  1687. //RootPrim.SetParentLocalId(parentLocalID);
  1688. m_log.DebugFormat("[ATTACHMENT]: Received " +
  1689. "attachment {0}, inworld asset id {1}",
  1690. //grp.RootPart.LastOwnerID.ToString(),
  1691. grp.GetFromAssetID(),
  1692. grp.UUID.ToString());
  1693. //grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1694. m_log.DebugFormat("[ATTACHMENT]: Attach " +
  1695. "to avatar {0} at position {1}",
  1696. sp.UUID.ToString(), grp.AbsolutePosition);
  1697. AttachObject(sp.ControllingClient,
  1698. grp.LocalId, (uint)0,
  1699. grp.GroupRotation,
  1700. grp.AbsolutePosition, false);
  1701. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1702. grp.SendGroupFullUpdate();
  1703. }
  1704. else
  1705. {
  1706. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1707. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  1708. }
  1709. }
  1710. else
  1711. {
  1712. AddRestoredSceneObject(sceneObject, true, false);
  1713. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  1714. true, sceneObject.AbsolutePosition))
  1715. {
  1716. // Deny non attachments based on parcel settings
  1717. //
  1718. m_log.Info("[INTERREGION]: Denied prim crossing " +
  1719. "because of parcel settings");
  1720. DeleteSceneObject(sceneObject, false);
  1721. return false;
  1722. }
  1723. }
  1724. }
  1725. return true;
  1726. }
  1727. #endregion
  1728. #region Add/Remove Avatar Methods
  1729. /// <summary>
  1730. /// Adding a New Client and Create a Presence for it.
  1731. /// </summary>
  1732. /// <param name="client"></param>
  1733. public override void AddNewClient(IClientAPI client)
  1734. {
  1735. SubscribeToClientEvents(client);
  1736. ScenePresence presence;
  1737. if (m_restorePresences.ContainsKey(client.AgentId))
  1738. {
  1739. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  1740. presence = m_restorePresences[client.AgentId];
  1741. m_restorePresences.Remove(client.AgentId);
  1742. // This is one of two paths to create avatars that are
  1743. // used. This tends to get called more in standalone
  1744. // than grid, not really sure why, but as such needs
  1745. // an explicity appearance lookup here.
  1746. AvatarAppearance appearance = null;
  1747. GetAvatarAppearance(client, out appearance);
  1748. presence.Appearance = appearance;
  1749. presence.initializeScenePresence(client, RegionInfo, this);
  1750. m_sceneGraph.AddScenePresence(presence);
  1751. lock (m_restorePresences)
  1752. {
  1753. Monitor.PulseAll(m_restorePresences);
  1754. }
  1755. }
  1756. else
  1757. {
  1758. m_log.DebugFormat(
  1759. "[SCENE]: Adding new child agent for {0} in {1}",
  1760. client.Name, RegionInfo.RegionName);
  1761. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1762. CreateAndAddScenePresence(client);
  1763. }
  1764. m_LastLogin = Environment.TickCount;
  1765. EventManager.TriggerOnNewClient(client);
  1766. }
  1767. /// <summary>
  1768. /// Register for events from the client
  1769. /// </summary>
  1770. /// <param name="client">The IClientAPI of the connected client</param>
  1771. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1772. {
  1773. client.OnRegionHandShakeReply += SendLayerData;
  1774. client.OnAddPrim += AddNewPrim;
  1775. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  1776. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  1777. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  1778. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  1779. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  1780. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  1781. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  1782. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  1783. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  1784. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  1785. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  1786. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1787. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1788. client.OnObjectRequest += RequestPrim;
  1789. client.OnObjectSelect += SelectPrim;
  1790. client.OnObjectDeselect += DeselectPrim;
  1791. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  1792. client.OnSpinStart += m_sceneGraph.SpinStart;
  1793. client.OnSpinUpdate += m_sceneGraph.SpinObject;
  1794. client.OnDeRezObject += DeRezObject;
  1795. client.OnRezObject += RezObject;
  1796. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  1797. client.OnRezMultipleAttachmentsFromInv += RezMultipleAttachments;
  1798. client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv;
  1799. client.OnObjectAttach += m_sceneGraph.AttachObject;
  1800. client.OnObjectDetach += m_sceneGraph.DetachObject;
  1801. client.OnObjectDrop += m_sceneGraph.DropObject;
  1802. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1803. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  1804. client.OnObjectName += m_sceneGraph.PrimName;
  1805. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  1806. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  1807. client.OnLinkObjects += m_sceneGraph.LinkObjects;
  1808. client.OnDelinkObjects += m_sceneGraph.DelinkObjects;
  1809. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  1810. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  1811. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  1812. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  1813. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1814. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1815. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  1816. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  1817. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  1818. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  1819. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  1820. client.OnFetchInventory += HandleFetchInventory;
  1821. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1822. client.OnCopyInventoryItem += CopyInventoryItem;
  1823. client.OnMoveInventoryItem += MoveInventoryItem;
  1824. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1825. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1826. client.OnRezScript += RezScript;
  1827. client.OnRequestTaskInventory += RequestTaskInventory;
  1828. client.OnRemoveTaskItem += RemoveTaskInventory;
  1829. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1830. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  1831. client.OnGrabObject += ProcessObjectGrab;
  1832. client.OnDeGrabObject += ProcessObjectDeGrab;
  1833. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1834. client.OnParcelBuy += ProcessParcelBuy;
  1835. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1836. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  1837. client.OnTeleportHomeRequest += TeleportClientHome;
  1838. client.OnSetStartLocationRequest += SetHomeRezPoint;
  1839. client.OnUndo += m_sceneGraph.HandleUndo;
  1840. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  1841. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  1842. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  1843. client.OnObjectSaleInfo += ObjectSaleInfo;
  1844. client.OnScriptReset += ProcessScriptReset;
  1845. client.OnGetScriptRunning += GetScriptRunning;
  1846. client.OnSetScriptRunning += SetScriptRunning;
  1847. client.OnRegionHandleRequest += RegionHandleRequest;
  1848. client.OnUnackedTerrain += TerrainUnAcked;
  1849. client.OnObjectOwner += ObjectOwner;
  1850. IGodsModule godsModule = RequestModuleInterface<IGodsModule>();
  1851. client.OnGodKickUser += godsModule.KickUser;
  1852. client.OnRequestGodlikePowers += godsModule.RequestGodlikePowers;
  1853. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  1854. // EventManager.TriggerOnNewClient(client);
  1855. }
  1856. /// <summary>
  1857. /// Teleport an avatar to their home region
  1858. /// </summary>
  1859. /// <param name="agentId">The avatar's Unique ID</param>
  1860. /// <param name="client">The IClientAPI for the client</param>
  1861. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  1862. {
  1863. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId);
  1864. if (UserProfile != null)
  1865. {
  1866. RegionInfo regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegionID);
  1867. if (regionInfo == null)
  1868. {
  1869. regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegion);
  1870. if (regionInfo != null) // home region can be away temporarily, too
  1871. {
  1872. UserProfile.HomeRegionID = regionInfo.RegionID;
  1873. CommsManager.UserService.UpdateUserProfile(UserProfile);
  1874. }
  1875. }
  1876. if (regionInfo == null)
  1877. {
  1878. // can't find the Home region: Tell viewer and abort
  1879. client.SendTeleportFailed("Your home-region could not be found.");
  1880. return;
  1881. }
  1882. RequestTeleportLocation(
  1883. client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
  1884. (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
  1885. }
  1886. }
  1887. /// <summary>
  1888. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  1889. /// RayEnd and RayStart to determine what the angle of the ray is
  1890. /// </summary>
  1891. /// <param name="localID">ID of object to duplicate</param>
  1892. /// <param name="dupeFlags"></param>
  1893. /// <param name="AgentID">Agent doing the duplication</param>
  1894. /// <param name="GroupID">Group of new object</param>
  1895. /// <param name="RayTargetObj">The target of the Ray</param>
  1896. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  1897. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  1898. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  1899. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  1900. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  1901. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  1902. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  1903. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  1904. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  1905. {
  1906. Vector3 pos;
  1907. const bool frontFacesOnly = true;
  1908. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  1909. SceneObjectPart target = GetSceneObjectPart(localID);
  1910. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  1911. if (target != null && target2 != null)
  1912. {
  1913. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1914. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1915. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1916. if (target2.ParentGroup != null)
  1917. {
  1918. pos = target2.AbsolutePosition;
  1919. //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());
  1920. // TODO: Raytrace better here
  1921. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1922. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1923. // Ray Trace against target here
  1924. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  1925. // Un-comment out the following line to Get Raytrace results printed to the console.
  1926. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1927. float ScaleOffset = 0.5f;
  1928. // If we hit something
  1929. if (ei.HitTF)
  1930. {
  1931. Vector3 scale = target.Scale;
  1932. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1933. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1934. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1935. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1936. ScaleOffset = Math.Abs(ScaleOffset);
  1937. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1938. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1939. Vector3 offset = normal * (ScaleOffset / 2f);
  1940. pos = intersectionpoint + offset;
  1941. // stick in offset format from the original prim
  1942. pos = pos - target.ParentGroup.AbsolutePosition;
  1943. if (CopyRotates)
  1944. {
  1945. Quaternion worldRot = target2.GetWorldRotation();
  1946. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  1947. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  1948. //obj.Rotation = worldRot;
  1949. //obj.UpdateGroupRotation(worldRot);
  1950. }
  1951. else
  1952. {
  1953. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  1954. }
  1955. }
  1956. return;
  1957. }
  1958. return;
  1959. }
  1960. }
  1961. /// <summary>
  1962. /// Sets the Home Point. The GridService uses this to know where to put a user when they log-in
  1963. /// </summary>
  1964. /// <param name="remoteClient"></param>
  1965. /// <param name="regionHandle"></param>
  1966. /// <param name="position"></param>
  1967. /// <param name="lookAt"></param>
  1968. /// <param name="flags"></param>
  1969. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  1970. {
  1971. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  1972. if (UserProfile != null)
  1973. {
  1974. // I know I'm ignoring the regionHandle provided by the teleport location request.
  1975. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  1976. UserProfile.HomeRegionID = RegionInfo.RegionID;
  1977. // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
  1978. // TODO: The HomeRegion property can be removed then, too
  1979. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  1980. UserProfile.HomeLocation = position;
  1981. UserProfile.HomeLookAt = lookAt;
  1982. CommsManager.UserService.UpdateUserProfile(UserProfile);
  1983. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  1984. m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
  1985. }
  1986. else
  1987. {
  1988. m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed.");
  1989. }
  1990. }
  1991. /// <summary>
  1992. /// Create a child agent scene presence and add it to this scene.
  1993. /// </summary>
  1994. /// <param name="client"></param>
  1995. /// <returns></returns>
  1996. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  1997. {
  1998. AvatarAppearance appearance = null;
  1999. GetAvatarAppearance(client, out appearance);
  2000. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  2001. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  2002. m_eventManager.TriggerOnNewPresence(avatar);
  2003. return avatar;
  2004. }
  2005. /// <summary>
  2006. /// Get the avatar apperance for the given client.
  2007. /// </summary>
  2008. /// <param name="client"></param>
  2009. /// <param name="appearance"></param>
  2010. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2011. {
  2012. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2013. if (aCircuit == null)
  2014. {
  2015. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  2016. appearance = new AvatarAppearance(client.AgentId);
  2017. return;
  2018. }
  2019. appearance = aCircuit.Appearance;
  2020. if (appearance == null)
  2021. {
  2022. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  2023. appearance = new AvatarAppearance(client.AgentId);
  2024. }
  2025. }
  2026. /// <summary>
  2027. /// Remove the given client from the scene.
  2028. /// </summary>
  2029. /// <param name="agentID"></param>
  2030. public override void RemoveClient(UUID agentID)
  2031. {
  2032. bool childagentYN = false;
  2033. ScenePresence avatar = GetScenePresence(agentID);
  2034. if (avatar != null)
  2035. {
  2036. childagentYN = avatar.IsChildAgent;
  2037. if (avatar.ParentID != 0)
  2038. {
  2039. avatar.StandUp();
  2040. }
  2041. try
  2042. {
  2043. m_log.DebugFormat(
  2044. "[SCENE]: Removing {0} agent {1} from region {2}",
  2045. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  2046. m_sceneGraph.removeUserCount(!childagentYN);
  2047. CapsModule.RemoveCapsHandler(agentID);
  2048. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  2049. {
  2050. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  2051. }
  2052. if (!avatar.IsChildAgent)
  2053. {
  2054. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
  2055. //List<ulong> childknownRegions = new List<ulong>();
  2056. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  2057. //for (int i = 0; i < ckn.Count; i++)
  2058. //{
  2059. // childknownRegions.Add(ckn[i]);
  2060. //}
  2061. List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
  2062. regions.Remove(RegionInfo.RegionHandle);
  2063. m_sceneGridService.SendCloseChildAgentConnections(agentID, regions);
  2064. }
  2065. m_eventManager.TriggerClientClosed(agentID, this);
  2066. }
  2067. catch (NullReferenceException)
  2068. {
  2069. // We don't know which count to remove it from
  2070. // Avatar is already disposed :/
  2071. }
  2072. m_eventManager.TriggerOnRemovePresence(agentID);
  2073. Broadcast(delegate(IClientAPI client)
  2074. {
  2075. try
  2076. {
  2077. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  2078. }
  2079. catch (NullReferenceException)
  2080. {
  2081. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2082. }
  2083. });
  2084. ForEachScenePresence(
  2085. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2086. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  2087. if (agentTransactions != null)
  2088. {
  2089. agentTransactions.RemoveAgentAssetTransactions(agentID);
  2090. }
  2091. m_sceneGraph.RemoveScenePresence(agentID);
  2092. try
  2093. {
  2094. avatar.Close();
  2095. }
  2096. catch (NullReferenceException)
  2097. {
  2098. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2099. }
  2100. catch (Exception e)
  2101. {
  2102. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  2103. }
  2104. // Remove client agent from profile, so new logins will work
  2105. if (!childagentYN)
  2106. {
  2107. m_sceneGridService.ClearUserAgent(agentID);
  2108. }
  2109. m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
  2110. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2111. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2112. }
  2113. }
  2114. /// <summary>
  2115. /// 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.
  2116. ///
  2117. /// </summary>
  2118. /// <param name="avatarID"></param>
  2119. /// <param name="regionslst"></param>
  2120. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2121. {
  2122. ScenePresence av = GetScenePresence(avatarID);
  2123. if (av != null)
  2124. {
  2125. lock (av)
  2126. {
  2127. for (int i = 0; i < regionslst.Count; i++)
  2128. {
  2129. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2130. }
  2131. }
  2132. }
  2133. }
  2134. /// <summary>
  2135. /// Closes all endpoints with the circuitcode provided.
  2136. /// </summary>
  2137. /// <param name="circuitcode">Circuit Code of the endpoint to close</param>
  2138. public override void CloseAllAgents(uint circuitcode)
  2139. {
  2140. // Called by ClientView to kill all circuit codes
  2141. ClientManager.CloseAllAgents(circuitcode);
  2142. }
  2143. /// <summary>
  2144. /// Inform all other ScenePresences on this Scene that someone else has changed position on the minimap.
  2145. /// </summary>
  2146. public void NotifyMyCoarseLocationChange()
  2147. {
  2148. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2149. }
  2150. #endregion
  2151. #region Entities
  2152. public void SendKillObject(uint localID)
  2153. {
  2154. SceneObjectPart part = GetSceneObjectPart(localID);
  2155. if (part != null) // It is a prim
  2156. {
  2157. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2158. {
  2159. if (part.ParentGroup.RootPart != part) // Child part
  2160. return;
  2161. }
  2162. }
  2163. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2164. }
  2165. #endregion
  2166. #region RegionComms
  2167. /// <summary>
  2168. /// Register the methods that should be invoked when this scene receives various incoming events
  2169. /// </summary>
  2170. public void RegisterCommsEvents()
  2171. {
  2172. m_sceneGridService.OnExpectUser += HandleNewUserConnection;
  2173. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2174. m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent;
  2175. m_sceneGridService.OnRegionUp += OtherRegionUp;
  2176. //m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2177. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  2178. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2179. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2180. m_sceneGridService.KiPrimitive += SendKillObject;
  2181. m_sceneGridService.OnGetLandData += GetLandData;
  2182. if (m_interregionCommsIn != null)
  2183. {
  2184. m_log.Debug("[SCENE]: Registering with InterregionCommsIn");
  2185. m_interregionCommsIn.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2186. }
  2187. else
  2188. m_log.Debug("[SCENE]: Unable to register with InterregionCommsIn");
  2189. }
  2190. /// <summary>
  2191. /// Deregister this scene from receiving incoming region events
  2192. /// </summary>
  2193. public void UnRegisterRegionWithComms()
  2194. {
  2195. m_sceneGridService.KiPrimitive -= SendKillObject;
  2196. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2197. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2198. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  2199. //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2200. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  2201. m_sceneGridService.OnExpectUser -= HandleNewUserConnection;
  2202. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2203. m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
  2204. m_sceneGridService.OnGetLandData -= GetLandData;
  2205. if (m_interregionCommsIn != null)
  2206. m_interregionCommsIn.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2207. m_sceneGridService.Close();
  2208. }
  2209. /// <summary>
  2210. /// A handler for the SceneCommunicationService event, to match that events return type of void.
  2211. /// Use NewUserConnection() directly if possible so the return type can refuse connections.
  2212. /// At the moment nothing actually seems to use this event,
  2213. /// as everything is switching to calling the NewUserConnection method directly.
  2214. /// </summary>
  2215. /// <param name="agent"></param>
  2216. public void HandleNewUserConnection(AgentCircuitData agent)
  2217. {
  2218. string reason;
  2219. NewUserConnection(agent, out reason);
  2220. }
  2221. /// <summary>
  2222. /// Do the work necessary to initiate a new user connection for a particular scene.
  2223. /// At the moment, this consists of setting up the caps infrastructure
  2224. /// The return bool should allow for connections to be refused, but as not all calling paths
  2225. /// take proper notice of it let, we allowed banned users in still.
  2226. /// </summary>
  2227. /// <param name="agent">CircuitData of the agent who is connecting</param>
  2228. /// <param name="reason">Outputs the reason for the false response on this string</param>
  2229. /// <returns>True if the region accepts this agent. False if it does not. False will
  2230. /// also return a reason.</returns>
  2231. public bool NewUserConnection(AgentCircuitData agent, out string reason)
  2232. {
  2233. // Don't disable this log message - it's too helpful
  2234. m_log.InfoFormat(
  2235. "[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5})",
  2236. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2237. agent.AgentID, agent.circuitcode);
  2238. reason = String.Empty;
  2239. if (!AuthenticateUser(agent, out reason))
  2240. return false;
  2241. if (!AuthorizeUser(agent, out reason))
  2242. return false;
  2243. m_log.InfoFormat(
  2244. "[CONNECTION BEGIN]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  2245. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2246. agent.AgentID, agent.circuitcode);
  2247. CapsModule.NewUserConnection(agent);
  2248. ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID);
  2249. if (sp != null)
  2250. {
  2251. m_log.DebugFormat(
  2252. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  2253. agent.AgentID, RegionInfo.RegionName);
  2254. sp.AdjustKnownSeeds();
  2255. return true;
  2256. }
  2257. CapsModule.AddCapsHandler(agent.AgentID);
  2258. if (!agent.child)
  2259. {
  2260. if (agent.startpos.X > (int)Constants.RegionSize - 1)
  2261. agent.startpos.X = (int)Constants.RegionSize - 1;
  2262. if (agent.startpos.Y > (int)Constants.RegionSize - 1)
  2263. agent.startpos.Y = (int)Constants.RegionSize - 1;
  2264. // Honor parcel landing type and position.
  2265. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  2266. if (land != null)
  2267. {
  2268. if (land.landData.LandingType == (byte)1 && land.landData.UserLocation != Vector3.Zero)
  2269. {
  2270. agent.startpos = land.landData.UserLocation;
  2271. }
  2272. }
  2273. }
  2274. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  2275. // rewrite session_id
  2276. CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID);
  2277. if (userinfo != null)
  2278. {
  2279. userinfo.SessionID = agent.SessionID;
  2280. }
  2281. else
  2282. {
  2283. m_log.WarnFormat(
  2284. "[CONNECTION BEGIN]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID);
  2285. }
  2286. return true;
  2287. }
  2288. /// <summary>
  2289. /// Verifies that the user has a session on the Grid
  2290. /// </summary>
  2291. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  2292. /// <param name="reason">Outputs the reason for the false response on this string</param>
  2293. /// <returns>True if the user has a session on the grid. False if it does not. False will
  2294. /// also return a reason.</returns>
  2295. public virtual bool AuthenticateUser(AgentCircuitData agent, out string reason)
  2296. {
  2297. reason = String.Empty;
  2298. bool result = CommsManager.UserService.VerifySession(agent.AgentID, agent.SessionID);
  2299. m_log.Debug("[CONNECTION BEGIN]: User authentication returned " + result);
  2300. if (!result)
  2301. reason = String.Format("Failed to authenticate user {0} {1}, access denied.", agent.firstname, agent.lastname);
  2302. return result;
  2303. }
  2304. /// <summary>
  2305. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  2306. /// </summary>
  2307. /// <param name="agent">The circuit data for the agent</param>
  2308. /// <param name="reason">outputs the reason to this string</param>
  2309. /// <returns>True if the region accepts this agent. False if it does not. False will
  2310. /// also return a reason.</returns>
  2311. protected virtual bool AuthorizeUser(AgentCircuitData agent, out string reason)
  2312. {
  2313. reason = String.Empty;
  2314. if (!m_strictAccessControl) return true;
  2315. if (Permissions.IsGod(agent.AgentID)) return true;
  2316. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  2317. {
  2318. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  2319. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2320. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  2321. RegionInfo.RegionName);
  2322. return false;
  2323. }
  2324. if (!m_regInfo.EstateSettings.PublicAccess &&
  2325. !m_regInfo.EstateSettings.HasAccess(agent.AgentID))
  2326. {
  2327. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  2328. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2329. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  2330. RegionInfo.RegionName);
  2331. return false;
  2332. }
  2333. // TODO: estate/region settings are not properly hooked up
  2334. // to ILandObject.isRestrictedFromLand()
  2335. // if (null != LandChannel)
  2336. // {
  2337. // // region seems to have local Id of 1
  2338. // ILandObject land = LandChannel.GetLandObject(1);
  2339. // if (null != land)
  2340. // {
  2341. // if (land.isBannedFromLand(agent.AgentID))
  2342. // {
  2343. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user has been banned from land",
  2344. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2345. // reason = String.Format("Denied access to private region {0}: You are banned from that region.",
  2346. // RegionInfo.RegionName);
  2347. // return false;
  2348. // }
  2349. // if (land.isRestrictedFromLand(agent.AgentID))
  2350. // {
  2351. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  2352. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2353. // reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  2354. // RegionInfo.RegionName);
  2355. // return false;
  2356. // }
  2357. // }
  2358. // }
  2359. return true;
  2360. }
  2361. /// <summary>
  2362. /// Update an AgentCircuitData object with new information
  2363. /// </summary>
  2364. /// <param name="data">Information to update the AgentCircuitData with</param>
  2365. public void UpdateCircuitData(AgentCircuitData data)
  2366. {
  2367. m_authenticateHandler.UpdateAgentData(data);
  2368. }
  2369. /// <summary>
  2370. /// Change the Circuit Code for the user's Circuit Data
  2371. /// </summary>
  2372. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  2373. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  2374. /// <returns>True if we successfully changed it. False if we did not</returns>
  2375. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  2376. {
  2377. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  2378. }
  2379. /// <summary>
  2380. /// The Grid has requested that we log-off a user. Log them off.
  2381. /// </summary>
  2382. /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  2383. /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  2384. /// <param name="message">message to display to the user. Reason for being logged off</param>
  2385. public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  2386. {
  2387. ScenePresence loggingOffUser = null;
  2388. loggingOffUser = GetScenePresence(AvatarID);
  2389. if (loggingOffUser != null)
  2390. {
  2391. UUID localRegionSecret = UUID.Zero;
  2392. bool parsedsecret = UUID.TryParse(m_regInfo.regionSecret, out localRegionSecret);
  2393. // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  2394. // Will update the user server in a few revisions to use it.
  2395. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  2396. {
  2397. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  2398. loggingOffUser.ControllingClient.Kick(message);
  2399. // Give them a second to receive the message!
  2400. Thread.Sleep(1000);
  2401. loggingOffUser.ControllingClient.Close(true);
  2402. }
  2403. else
  2404. {
  2405. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  2406. }
  2407. }
  2408. else
  2409. {
  2410. 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());
  2411. }
  2412. }
  2413. /// <summary>
  2414. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  2415. /// </summary>
  2416. /// <param name="agentID"></param>
  2417. /// <param name="position"></param>
  2418. /// <param name="isFlying"></param>
  2419. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  2420. {
  2421. ScenePresence presence;
  2422. lock (m_scenePresences)
  2423. {
  2424. m_scenePresences.TryGetValue(agentID, out presence);
  2425. }
  2426. if (presence != null)
  2427. {
  2428. try
  2429. {
  2430. presence.MakeRootAgent(position, isFlying);
  2431. }
  2432. catch (Exception e)
  2433. {
  2434. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  2435. }
  2436. }
  2437. else
  2438. {
  2439. m_log.ErrorFormat(
  2440. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  2441. agentID, RegionInfo.RegionName);
  2442. }
  2443. }
  2444. /// <summary>
  2445. /// We've got an update about an agent that sees into this region,
  2446. /// send it to ScenePresence for processing It's the full data.
  2447. /// </summary>
  2448. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  2449. /// Appearance, animations, position, etc.</param>
  2450. /// <returns>true if we handled it.</returns>
  2451. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  2452. {
  2453. // m_log.DebugFormat(
  2454. // "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  2455. // We have to wait until the viewer contacts this region after receiving EAC.
  2456. // That calls AddNewClient, which finally creates the ScenePresence
  2457. ScenePresence childAgentUpdate = WaitGetScenePresence(cAgentData.AgentID);
  2458. if (childAgentUpdate != null)
  2459. {
  2460. childAgentUpdate.ChildAgentDataUpdate(cAgentData);
  2461. return true;
  2462. }
  2463. return false;
  2464. }
  2465. /// <summary>
  2466. /// We've got an update about an agent that sees into this region,
  2467. /// send it to ScenePresence for processing It's only positional data
  2468. /// </summary>
  2469. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  2470. /// <returns>true if we handled it.</returns>
  2471. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  2472. {
  2473. //m_log.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  2474. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  2475. if (childAgentUpdate != null)
  2476. {
  2477. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  2478. // however to avoid a race condition crossing borders..
  2479. if (childAgentUpdate.IsChildAgent)
  2480. {
  2481. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  2482. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  2483. uint tRegionX = RegionInfo.RegionLocX;
  2484. uint tRegionY = RegionInfo.RegionLocY;
  2485. //Send Data to ScenePresence
  2486. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  2487. // Not Implemented:
  2488. //TODO: Do we need to pass the message on to one of our neighbors?
  2489. }
  2490. return true;
  2491. }
  2492. return false;
  2493. }
  2494. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  2495. {
  2496. int ntimes = 10;
  2497. ScenePresence childAgentUpdate = null;
  2498. while ((childAgentUpdate = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  2499. Thread.Sleep(1000);
  2500. return childAgentUpdate;
  2501. }
  2502. public virtual bool IncomingRetrieveRootAgent(UUID id, out IAgentData agent)
  2503. {
  2504. agent = null;
  2505. ScenePresence sp = GetScenePresence(id);
  2506. if ((sp != null) && (!sp.IsChildAgent))
  2507. {
  2508. sp.IsChildAgent = true;
  2509. return sp.CopyAgent(out agent);
  2510. }
  2511. return false;
  2512. }
  2513. public virtual bool IncomingReleaseAgent(UUID id)
  2514. {
  2515. return m_sceneGridService.ReleaseAgent(id);
  2516. }
  2517. public void SendReleaseAgent(ulong regionHandle, UUID id, string uri)
  2518. {
  2519. m_interregionCommsOut.SendReleaseAgent(regionHandle, id, uri);
  2520. }
  2521. /// <summary>
  2522. /// Tell a single agent to disconnect from the region.
  2523. /// </summary>
  2524. /// <param name="regionHandle"></param>
  2525. /// <param name="agentID"></param>
  2526. public bool IncomingCloseAgent(UUID agentID)
  2527. {
  2528. //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
  2529. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  2530. if (presence != null)
  2531. {
  2532. // Nothing is removed here, so down count it as such
  2533. if (presence.IsChildAgent)
  2534. {
  2535. m_sceneGraph.removeUserCount(false);
  2536. }
  2537. else
  2538. {
  2539. m_sceneGraph.removeUserCount(true);
  2540. }
  2541. // Don't do this to root agents on logout, it's not nice for the viewer
  2542. if (presence.IsChildAgent)
  2543. {
  2544. // Tell a single agent to disconnect from the region.
  2545. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  2546. if (eq != null)
  2547. {
  2548. eq.DisableSimulator(RegionInfo.RegionHandle, agentID);
  2549. }
  2550. else
  2551. presence.ControllingClient.SendShutdownConnectionNotice();
  2552. }
  2553. presence.ControllingClient.Close(true);
  2554. return true;
  2555. }
  2556. // Agent not here
  2557. return false;
  2558. }
  2559. /// <summary>
  2560. /// Tell neighboring regions about this agent
  2561. /// When the regions respond with a true value,
  2562. /// tell the agents about the region.
  2563. ///
  2564. /// We have to tell the regions about the agents first otherwise it'll deny them access
  2565. ///
  2566. /// </summary>
  2567. /// <param name="presence"></param>
  2568. public void InformClientOfNeighbours(ScenePresence presence)
  2569. {
  2570. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2571. }
  2572. /// <summary>
  2573. /// Tell a neighboring region about this agent
  2574. /// </summary>
  2575. /// <param name="presence"></param>
  2576. /// <param name="region"></param>
  2577. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  2578. {
  2579. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2580. }
  2581. /// <summary>
  2582. /// Requests information about this region from gridcomms
  2583. /// </summary>
  2584. /// <param name="regionHandle"></param>
  2585. /// <returns></returns>
  2586. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  2587. {
  2588. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  2589. }
  2590. /// <summary>
  2591. /// Requests textures for map from minimum region to maximum region in world cordinates
  2592. /// </summary>
  2593. /// <param name="remoteClient"></param>
  2594. /// <param name="minX"></param>
  2595. /// <param name="minY"></param>
  2596. /// <param name="maxX"></param>
  2597. /// <param name="maxY"></param>
  2598. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  2599. {
  2600. m_log.DebugFormat("[MAPBLOCK]: {0}-{1}, {2}-{3}", minX, minY, maxX, maxY);
  2601. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxY);
  2602. }
  2603. /// <summary>
  2604. /// Tries to teleport agent to other region.
  2605. /// </summary>
  2606. /// <param name="remoteClient"></param>
  2607. /// <param name="regionName"></param>
  2608. /// <param name="position"></param>
  2609. /// <param name="lookAt"></param>
  2610. /// <param name="teleportFlags"></param>
  2611. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  2612. Vector3 lookat, uint teleportFlags)
  2613. {
  2614. RegionInfo regionInfo = m_sceneGridService.RequestClosestRegion(regionName);
  2615. if (regionInfo == null)
  2616. {
  2617. // can't find the region: Tell viewer and abort
  2618. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  2619. return;
  2620. }
  2621. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  2622. }
  2623. /// <summary>
  2624. /// Tries to teleport agent to other region.
  2625. /// </summary>
  2626. /// <param name="remoteClient"></param>
  2627. /// <param name="regionHandle"></param>
  2628. /// <param name="position"></param>
  2629. /// <param name="lookAt"></param>
  2630. /// <param name="teleportFlags"></param>
  2631. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  2632. Vector3 lookAt, uint teleportFlags)
  2633. {
  2634. ScenePresence sp = null;
  2635. lock (m_scenePresences)
  2636. {
  2637. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2638. sp = m_scenePresences[remoteClient.AgentId];
  2639. }
  2640. if (sp != null)
  2641. {
  2642. if (m_teleportModule != null)
  2643. {
  2644. m_teleportModule.RequestTeleportToLocation(sp, regionHandle,
  2645. position, lookAt, teleportFlags);
  2646. }
  2647. else
  2648. {
  2649. m_sceneGridService.RequestTeleportToLocation(sp, regionHandle,
  2650. position, lookAt, teleportFlags);
  2651. }
  2652. }
  2653. }
  2654. /// <summary>
  2655. /// Tries to teleport agent to landmark.
  2656. /// </summary>
  2657. /// <param name="remoteClient"></param>
  2658. /// <param name="regionHandle"></param>
  2659. /// <param name="position"></param>
  2660. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  2661. {
  2662. RegionInfo info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  2663. if (info == null)
  2664. {
  2665. // can't find the region: Tell viewer and abort
  2666. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  2667. return;
  2668. }
  2669. RequestTeleportLocation(remoteClient, info.RegionHandle, position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  2670. }
  2671. public void CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  2672. {
  2673. m_sceneGridService.CrossAgentToNewRegion(this, agent, isFlying);
  2674. }
  2675. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  2676. {
  2677. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  2678. }
  2679. #endregion
  2680. #region Other Methods
  2681. public void SetObjectCapacity(int objects)
  2682. {
  2683. // Region specific config overrides global
  2684. //
  2685. if (RegionInfo.ObjectCapacity != 0)
  2686. objects = RegionInfo.ObjectCapacity;
  2687. if (StatsReporter != null)
  2688. {
  2689. StatsReporter.SetObjectCapacity(objects);
  2690. }
  2691. objectCapacity = objects;
  2692. }
  2693. public List<FriendListItem> GetFriendList(string id)
  2694. {
  2695. UUID avatarID;
  2696. if (!UUID.TryParse(id, out avatarID))
  2697. return new List<FriendListItem>();
  2698. return CommsManager.GetUserFriendList(avatarID);
  2699. }
  2700. public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
  2701. {
  2702. return CommsManager.GetFriendRegionInfos(uuids);
  2703. }
  2704. public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
  2705. {
  2706. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2707. }
  2708. public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
  2709. {
  2710. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2711. }
  2712. public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
  2713. {
  2714. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2715. }
  2716. #endregion
  2717. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  2718. {
  2719. // Check for spoofing.. since this is permissions we're talking about here!
  2720. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  2721. {
  2722. // Tell the object to do permission update
  2723. if (localId != 0)
  2724. {
  2725. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  2726. if (chObjectGroup != null)
  2727. {
  2728. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  2729. }
  2730. }
  2731. }
  2732. }
  2733. /// <summary>
  2734. /// Causes all clients to get a full object update on all of the objects in the scene.
  2735. /// </summary>
  2736. public void ForceClientUpdate()
  2737. {
  2738. List<EntityBase> EntityList = GetEntities();
  2739. foreach (EntityBase ent in EntityList)
  2740. {
  2741. if (ent is SceneObjectGroup)
  2742. {
  2743. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  2744. }
  2745. }
  2746. }
  2747. /// <summary>
  2748. /// This is currently only used for scale (to scale to MegaPrim size)
  2749. /// There is a console command that calls this in OpenSimMain
  2750. /// </summary>
  2751. /// <param name="cmdparams"></param>
  2752. public void HandleEditCommand(string[] cmdparams)
  2753. {
  2754. m_log.Debug("Searching for Primitive: '" + cmdparams[2] + "'");
  2755. List<EntityBase> EntityList = GetEntities();
  2756. foreach (EntityBase ent in EntityList)
  2757. {
  2758. if (ent is SceneObjectGroup)
  2759. {
  2760. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  2761. if (part != null)
  2762. {
  2763. if (part.Name == cmdparams[2])
  2764. {
  2765. part.Resize(
  2766. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  2767. Convert.ToSingle(cmdparams[5])));
  2768. m_log.Debug("Edited scale of Primitive: " + part.Name);
  2769. }
  2770. }
  2771. }
  2772. }
  2773. }
  2774. public override void Show(string[] showParams)
  2775. {
  2776. base.Show(showParams);
  2777. switch (showParams[0])
  2778. {
  2779. case "users":
  2780. m_log.Error("Current Region: " + RegionInfo.RegionName);
  2781. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  2782. "Agent ID", "Session ID", "Circuit", "IP", "World");
  2783. foreach (ScenePresence scenePresence in GetAvatars())
  2784. {
  2785. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  2786. scenePresence.Firstname,
  2787. scenePresence.Lastname,
  2788. scenePresence.UUID,
  2789. scenePresence.ControllingClient.AgentId,
  2790. "Unknown",
  2791. "Unknown",
  2792. RegionInfo.RegionName);
  2793. }
  2794. break;
  2795. }
  2796. }
  2797. #region Script Handling Methods
  2798. /// <summary>
  2799. /// Console command handler to send script command to script engine.
  2800. /// </summary>
  2801. /// <param name="args"></param>
  2802. public void SendCommandToPlugins(string[] args)
  2803. {
  2804. m_eventManager.TriggerOnPluginConsole(args);
  2805. }
  2806. public LandData GetLandData(float x, float y)
  2807. {
  2808. return LandChannel.GetLandObject(x, y).landData;
  2809. }
  2810. public LandData GetLandData(uint x, uint y)
  2811. {
  2812. m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  2813. return LandChannel.GetLandObject((int)x, (int)y).landData;
  2814. }
  2815. public RegionInfo RequestClosestRegion(string name)
  2816. {
  2817. return m_sceneGridService.RequestClosestRegion(name);
  2818. }
  2819. #endregion
  2820. #region Script Engine
  2821. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  2822. public bool DumpAssetsToFile;
  2823. /// <summary>
  2824. ///
  2825. /// </summary>
  2826. /// <param name="scriptEngine"></param>
  2827. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  2828. {
  2829. ScriptEngines.Add(scriptEngine);
  2830. scriptEngine.InitializeEngine(this);
  2831. }
  2832. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  2833. {
  2834. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  2835. if (part != null)
  2836. {
  2837. if (parcel != null)
  2838. {
  2839. if ((parcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  2840. {
  2841. return true;
  2842. }
  2843. else if ((parcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  2844. {
  2845. if (part.OwnerID == parcel.landData.OwnerID
  2846. || (parcel.landData.IsGroupOwned && part.GroupID == parcel.landData.GroupID)
  2847. || Permissions.IsGod(part.OwnerID))
  2848. {
  2849. return true;
  2850. }
  2851. else
  2852. {
  2853. return false;
  2854. }
  2855. }
  2856. else
  2857. {
  2858. if (part.OwnerID == parcel.landData.OwnerID)
  2859. {
  2860. return true;
  2861. }
  2862. else
  2863. {
  2864. return false;
  2865. }
  2866. }
  2867. }
  2868. else
  2869. {
  2870. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  2871. {
  2872. // The only time parcel != null when an object is inside a region is when
  2873. // there is nothing behind the landchannel. IE, no land plugin loaded.
  2874. return true;
  2875. }
  2876. else
  2877. {
  2878. // The object is outside of this region. Stop piping events to it.
  2879. return false;
  2880. }
  2881. }
  2882. }
  2883. else
  2884. {
  2885. return false;
  2886. }
  2887. }
  2888. public bool ScriptDanger(uint localID, Vector3 pos)
  2889. {
  2890. SceneObjectPart part = GetSceneObjectPart(localID);
  2891. if (part != null)
  2892. {
  2893. return ScriptDanger(part, pos);
  2894. }
  2895. else
  2896. {
  2897. return false;
  2898. }
  2899. }
  2900. public bool PipeEventsForScript(uint localID)
  2901. {
  2902. SceneObjectPart part = GetSceneObjectPart(localID);
  2903. if (part != null)
  2904. {
  2905. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  2906. // their scripts will actually run.
  2907. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  2908. SceneObjectPart parent = part.ParentGroup.RootPart;
  2909. if (parent != null && parent.IsAttachment)
  2910. return ScriptDanger(parent, parent.GetWorldPosition());
  2911. else
  2912. return ScriptDanger(part, part.GetWorldPosition());
  2913. }
  2914. else
  2915. {
  2916. return false;
  2917. }
  2918. }
  2919. #endregion
  2920. #region SceneGraph wrapper methods
  2921. /// <summary>
  2922. ///
  2923. /// </summary>
  2924. /// <param name="localID"></param>
  2925. /// <returns></returns>
  2926. public UUID ConvertLocalIDToFullID(uint localID)
  2927. {
  2928. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  2929. }
  2930. public void SwapRootAgentCount(bool rootChildChildRootTF)
  2931. {
  2932. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  2933. }
  2934. public void AddPhysicalPrim(int num)
  2935. {
  2936. m_sceneGraph.AddPhysicalPrim(num);
  2937. }
  2938. public void RemovePhysicalPrim(int num)
  2939. {
  2940. m_sceneGraph.RemovePhysicalPrim(num);
  2941. }
  2942. //The idea is to have a group of method that return a list of avatars meeting some requirement
  2943. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  2944. /// <summary>
  2945. /// Return a list of all avatars in this region.
  2946. /// This list is a new object, so it can be iterated over without locking.
  2947. /// </summary>
  2948. /// <returns></returns>
  2949. public List<ScenePresence> GetAvatars()
  2950. {
  2951. return m_sceneGraph.GetAvatars();
  2952. }
  2953. /// <summary>
  2954. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  2955. /// This list is a new object, so it can be iterated over without locking.
  2956. /// </summary>
  2957. /// <returns></returns>
  2958. public List<ScenePresence> GetScenePresences()
  2959. {
  2960. return m_sceneGraph.GetScenePresences();
  2961. }
  2962. /// <summary>
  2963. /// Request a filtered list of ScenePresences in this region.
  2964. /// This list is a new object, so it can be iterated over without locking.
  2965. /// </summary>
  2966. /// <param name="filter"></param>
  2967. /// <returns></returns>
  2968. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  2969. {
  2970. return m_sceneGraph.GetScenePresences(filter);
  2971. }
  2972. /// <summary>
  2973. /// Request a scene presence by UUID
  2974. /// </summary>
  2975. /// <param name="avatarID"></param>
  2976. /// <returns></returns>
  2977. public ScenePresence GetScenePresence(UUID avatarID)
  2978. {
  2979. return m_sceneGraph.GetScenePresence(avatarID);
  2980. }
  2981. public override bool PresenceChildStatus(UUID avatarID)
  2982. {
  2983. ScenePresence cp = GetScenePresence(avatarID);
  2984. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  2985. // This needs to be fixed properly by cleaning up the logout code.
  2986. //if (cp != null)
  2987. // return cp.IsChildAgent;
  2988. //return false;
  2989. return cp.IsChildAgent;
  2990. }
  2991. /// <summary>
  2992. ///
  2993. /// </summary>
  2994. /// <param name="action"></param>
  2995. public void ForEachScenePresence(Action<ScenePresence> action)
  2996. {
  2997. // We don't want to try to send messages if there are no avatars.
  2998. if (m_scenePresences != null)
  2999. {
  3000. try
  3001. {
  3002. List<ScenePresence> presenceList = GetScenePresences();
  3003. foreach (ScenePresence presence in presenceList)
  3004. {
  3005. action(presence);
  3006. }
  3007. }
  3008. catch (Exception e)
  3009. {
  3010. m_log.Info("[BUG] in " + RegionInfo.RegionName + ": " + e.ToString());
  3011. m_log.Info("[BUG] Stack Trace: " + e.StackTrace);
  3012. }
  3013. }
  3014. }
  3015. /// <summary>
  3016. ///
  3017. /// </summary>
  3018. /// <param name="action"></param>
  3019. // public void ForEachObject(Action<SceneObjectGroup> action)
  3020. // {
  3021. // List<SceneObjectGroup> presenceList;
  3022. //
  3023. // lock (m_sceneObjects)
  3024. // {
  3025. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  3026. // }
  3027. //
  3028. // foreach (SceneObjectGroup presence in presenceList)
  3029. // {
  3030. // action(presence);
  3031. // }
  3032. // }
  3033. /// <summary>
  3034. /// Get a named prim contained in this scene (will return the first
  3035. /// found, if there are more than one prim with the same name)
  3036. /// </summary>
  3037. /// <param name="name"></param>
  3038. /// <returns></returns>
  3039. public SceneObjectPart GetSceneObjectPart(string name)
  3040. {
  3041. return m_sceneGraph.GetSceneObjectPart(name);
  3042. }
  3043. /// <summary>
  3044. /// Get a prim via its local id
  3045. /// </summary>
  3046. /// <param name="localID"></param>
  3047. /// <returns></returns>
  3048. public SceneObjectPart GetSceneObjectPart(uint localID)
  3049. {
  3050. return m_sceneGraph.GetSceneObjectPart(localID);
  3051. }
  3052. /// <summary>
  3053. /// Get a prim via its UUID
  3054. /// </summary>
  3055. /// <param name="fullID"></param>
  3056. /// <returns></returns>
  3057. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  3058. {
  3059. return m_sceneGraph.GetSceneObjectPart(fullID);
  3060. }
  3061. public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  3062. {
  3063. return m_sceneGraph.TryGetAvatar(avatarId, out avatar);
  3064. }
  3065. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  3066. {
  3067. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  3068. }
  3069. public void ForEachClient(Action<IClientAPI> action)
  3070. {
  3071. m_sceneGraph.ForEachClient(action);
  3072. }
  3073. /// <summary>
  3074. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  3075. /// will not affect the original list of objects in the scene.
  3076. /// </summary>
  3077. /// <returns></returns>
  3078. public List<EntityBase> GetEntities()
  3079. {
  3080. return m_sceneGraph.GetEntities();
  3081. }
  3082. #endregion
  3083. #region Avatar Appearance Default
  3084. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  3085. {
  3086. visualParams = AvatarAppearance.GetDefaultVisualParams();
  3087. wearables = AvatarWearable.DefaultWearables;
  3088. }
  3089. #endregion
  3090. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  3091. {
  3092. RegionInfo info;
  3093. if (regionID == RegionInfo.RegionID)
  3094. info = RegionInfo;
  3095. else
  3096. info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  3097. if (info != null)
  3098. client.SendRegionHandle(regionID, info.RegionHandle);
  3099. }
  3100. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  3101. {
  3102. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  3103. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  3104. }
  3105. public void SetRootAgentScene(UUID agentID)
  3106. {
  3107. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3108. if (inv == null)
  3109. return;
  3110. inv.SetRootAgentScene(agentID, this);
  3111. EventManager.TriggerSetRootAgentScene(agentID, this);
  3112. }
  3113. public bool NeedSceneCacheClear(UUID agentID)
  3114. {
  3115. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3116. if (inv == null)
  3117. return true;
  3118. return inv.NeedSceneCacheClear(agentID, this);
  3119. }
  3120. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  3121. {
  3122. SceneObjectPart part = GetSceneObjectPart(localID);
  3123. if (part == null || part.ParentGroup == null)
  3124. return;
  3125. if (part.ParentGroup.IsDeleted)
  3126. return;
  3127. part = part.ParentGroup.RootPart;
  3128. part.ObjectSaleType = saleType;
  3129. part.SalePrice = salePrice;
  3130. part.ParentGroup.HasGroupChanged = true;
  3131. part.GetProperties(client);
  3132. }
  3133. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  3134. uint localID, byte saleType)
  3135. {
  3136. SceneObjectPart part = GetSceneObjectPart(localID);
  3137. if (part == null)
  3138. return false;
  3139. if (part.ParentGroup == null)
  3140. return false;
  3141. SceneObjectGroup group = part.ParentGroup;
  3142. switch (saleType)
  3143. {
  3144. case 1: // Sell as original (in-place sale)
  3145. uint effectivePerms=group.GetEffectivePermissions();
  3146. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  3147. {
  3148. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3149. return false;
  3150. }
  3151. group.SetOwnerId(remoteClient.AgentId);
  3152. group.SetRootPartOwner(part, remoteClient.AgentId,
  3153. remoteClient.ActiveGroupId);
  3154. List<SceneObjectPart> partList =
  3155. new List<SceneObjectPart>(group.Children.Values);
  3156. if (Permissions.PropagatePermissions())
  3157. {
  3158. foreach (SceneObjectPart child in partList)
  3159. {
  3160. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  3161. child.ApplyNextOwnerPermissions();
  3162. }
  3163. }
  3164. part.ObjectSaleType = 0;
  3165. part.SalePrice = 10;
  3166. group.HasGroupChanged = true;
  3167. part.GetProperties(remoteClient);
  3168. part.ScheduleFullUpdate();
  3169. break;
  3170. case 2: // Sell a copy
  3171. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
  3172. CachedUserInfo userInfo =
  3173. CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId);
  3174. if (userInfo != null)
  3175. {
  3176. uint perms=group.GetEffectivePermissions();
  3177. if ((perms & (uint)PermissionMask.Transfer) == 0)
  3178. {
  3179. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3180. return false;
  3181. }
  3182. AssetBase asset = CreateAsset(
  3183. group.GetPartName(localID),
  3184. group.GetPartDescription(localID),
  3185. (sbyte)AssetType.Object,
  3186. Utils.StringToBytes(sceneObjectXml));
  3187. AssetService.Store(asset);
  3188. InventoryItemBase item = new InventoryItemBase();
  3189. item.CreatorId = part.CreatorID.ToString();
  3190. item.ID = UUID.Random();
  3191. item.Owner = remoteClient.AgentId;
  3192. item.AssetID = asset.FullID;
  3193. item.Description = asset.Description;
  3194. item.Name = asset.Name;
  3195. item.AssetType = asset.Type;
  3196. item.InvType = (int)InventoryType.Object;
  3197. item.Folder = categoryID;
  3198. uint nextPerms=(perms & 7) << 13;
  3199. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  3200. perms &= ~(uint)PermissionMask.Copy;
  3201. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  3202. perms &= ~(uint)PermissionMask.Transfer;
  3203. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  3204. perms &= ~(uint)PermissionMask.Modify;
  3205. item.BasePermissions = perms & part.NextOwnerMask;
  3206. item.CurrentPermissions = perms & part.NextOwnerMask;
  3207. item.NextPermissions = part.NextOwnerMask;
  3208. item.EveryOnePermissions = part.EveryoneMask &
  3209. part.NextOwnerMask;
  3210. item.GroupPermissions = part.GroupMask &
  3211. part.NextOwnerMask;
  3212. item.CurrentPermissions |= 8; // Slam!
  3213. item.CreationDate = Util.UnixTimeSinceEpoch();
  3214. userInfo.AddItem(item);
  3215. remoteClient.SendInventoryItemCreateUpdate(item, 0);
  3216. }
  3217. else
  3218. {
  3219. m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
  3220. return false;
  3221. }
  3222. break;
  3223. case 3: // Sell contents
  3224. List<UUID> invList = part.Inventory.GetInventoryList();
  3225. bool okToSell = true;
  3226. foreach (UUID invID in invList)
  3227. {
  3228. TaskInventoryItem item = part.Inventory.GetInventoryItem(invID);
  3229. if ((item.CurrentPermissions &
  3230. (uint)PermissionMask.Transfer) == 0)
  3231. {
  3232. okToSell = false;
  3233. break;
  3234. }
  3235. }
  3236. if (!okToSell)
  3237. {
  3238. m_dialogModule.SendAlertToUser(
  3239. remoteClient, "This item's inventory doesn't appear to be for sale");
  3240. return false;
  3241. }
  3242. if (invList.Count > 0)
  3243. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  3244. part, invList);
  3245. break;
  3246. }
  3247. return true;
  3248. }
  3249. public void CleanTempObjects()
  3250. {
  3251. List<EntityBase> objs = GetEntities();
  3252. foreach (EntityBase obj in objs)
  3253. {
  3254. if (obj is SceneObjectGroup)
  3255. {
  3256. SceneObjectGroup grp = (SceneObjectGroup)obj;
  3257. if (!grp.IsDeleted)
  3258. {
  3259. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  3260. {
  3261. if (grp.RootPart.Expires <= DateTime.Now)
  3262. DeleteSceneObject(grp, false);
  3263. }
  3264. }
  3265. }
  3266. }
  3267. }
  3268. public void DeleteFromStorage(UUID uuid)
  3269. {
  3270. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  3271. }
  3272. public int GetHealth()
  3273. {
  3274. // Returns:
  3275. // 1 = sim is up and accepting http requests. The heartbeat has
  3276. // stopped and the sim is probably locked up, but a remote
  3277. // admin restart may succeed
  3278. //
  3279. // 2 = Sim is up and the heartbeat is running. The sim is likely
  3280. // usable for people within and logins _may_ work
  3281. //
  3282. // 3 = We have seen a new user enter within the past 4 minutes
  3283. // which can be seen as positive confirmation of sim health
  3284. //
  3285. int health=1; // Start at 1, means we're up
  3286. if ((Environment.TickCount - m_lastUpdate) < 1000)
  3287. health+=1;
  3288. else
  3289. return health;
  3290. // A login in the last 4 mins? We can't be doing too badly
  3291. //
  3292. if ((Environment.TickCount - m_LastLogin) < 240000)
  3293. health++;
  3294. else
  3295. return health;
  3296. return health;
  3297. }
  3298. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3299. // update non-physical objects like the joint proxy objects that represent the position
  3300. // of the joints in the scene.
  3301. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3302. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3303. // from within the OdePhysicsScene.
  3304. protected internal void jointMoved(PhysicsJoint joint)
  3305. {
  3306. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  3307. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3308. if (jointProxyObject == null)
  3309. {
  3310. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  3311. return;
  3312. }
  3313. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  3314. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  3315. 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.
  3316. jointProxyObject.Velocity = trackedBody.Velocity;
  3317. jointProxyObject.RotationalVelocity = trackedBody.RotationalVelocity;
  3318. switch (joint.Type)
  3319. {
  3320. case PhysicsJointType.Ball:
  3321. {
  3322. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3323. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3324. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3325. }
  3326. break;
  3327. case PhysicsJointType.Hinge:
  3328. {
  3329. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3330. // Normally, we would just ask the physics scene to return the axis for the joint.
  3331. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  3332. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  3333. // Therefore the following call does not always work:
  3334. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  3335. // instead we compute the joint orientation by saving the original joint orientation
  3336. // relative to one of the jointed bodies, and applying this transformation
  3337. // to the current position of the jointed bodies (the tracked body) to compute the
  3338. // current joint orientation.
  3339. if (joint.TrackedBodyName == null)
  3340. {
  3341. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  3342. }
  3343. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3344. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  3345. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3346. jointProxyObject.ParentGroup.UpdateGroupRotation(q); // schedules the entire group for a terse update
  3347. }
  3348. break;
  3349. }
  3350. }
  3351. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3352. // update non-physical objects like the joint proxy objects that represent the position
  3353. // of the joints in the scene.
  3354. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3355. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3356. // from within the OdePhysicsScene.
  3357. protected internal void jointDeactivated(PhysicsJoint joint)
  3358. {
  3359. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  3360. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3361. if (jointProxyObject == null)
  3362. {
  3363. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  3364. return;
  3365. }
  3366. // turn the proxy non-physical, which also stops its client-side interpolation
  3367. bool wasUsingPhysics = ((jointProxyObject.ObjectFlags & (uint)PrimFlags.Physics) != 0);
  3368. if (wasUsingPhysics)
  3369. {
  3370. 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
  3371. }
  3372. }
  3373. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3374. // alert the user of errors by using the debug channel in the same way that scripts alert
  3375. // the user of compile errors.
  3376. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3377. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3378. // from within the OdePhysicsScene.
  3379. public void jointErrorMessage(PhysicsJoint joint, string message)
  3380. {
  3381. if (joint != null)
  3382. {
  3383. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3384. return;
  3385. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3386. if (jointProxyObject != null)
  3387. {
  3388. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  3389. ChatTypeEnum.DebugChannel,
  3390. 2147483647,
  3391. jointProxyObject.AbsolutePosition,
  3392. jointProxyObject.Name,
  3393. jointProxyObject.UUID,
  3394. false);
  3395. joint.ErrorMessageCount++;
  3396. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3397. {
  3398. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  3399. ChatTypeEnum.DebugChannel,
  3400. 2147483647,
  3401. jointProxyObject.AbsolutePosition,
  3402. jointProxyObject.Name,
  3403. jointProxyObject.UUID,
  3404. false);
  3405. }
  3406. }
  3407. else
  3408. {
  3409. // couldn't find the joint proxy object; the error message is silently suppressed
  3410. }
  3411. }
  3412. }
  3413. public Scene ConsoleScene()
  3414. {
  3415. if (MainConsole.Instance == null)
  3416. return null;
  3417. if (MainConsole.Instance.ConsoleScene is Scene)
  3418. return (Scene)MainConsole.Instance.ConsoleScene;
  3419. return null;
  3420. }
  3421. public float GetGroundHeight(float x, float y)
  3422. {
  3423. if (x < 0)
  3424. x = 0;
  3425. if (x >= Heightmap.Width)
  3426. x = Heightmap.Width - 1;
  3427. if (y < 0)
  3428. y = 0;
  3429. if (y >= Heightmap.Height)
  3430. y = Heightmap.Height - 1;
  3431. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  3432. Vector3 p1 = new Vector3(p0);
  3433. Vector3 p2 = new Vector3(p0);
  3434. p1.X += 1.0f;
  3435. if (p1.X < Heightmap.Width)
  3436. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  3437. p2.Y += 1.0f;
  3438. if (p2.Y < Heightmap.Height)
  3439. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  3440. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  3441. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  3442. v0.Normalize();
  3443. v1.Normalize();
  3444. Vector3 vsn = new Vector3();
  3445. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  3446. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  3447. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  3448. vsn.Normalize();
  3449. float xdiff = x - (float)((int)x);
  3450. float ydiff = y - (float)((int)y);
  3451. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  3452. }
  3453. }
  3454. }