1
0

Scene.cs 106 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim 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.Threading;
  32. using System.Timers;
  33. using Axiom.Math;
  34. using libsecondlife;
  35. using libsecondlife.Packets;
  36. using OpenJPEGNet;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Communications;
  39. using OpenSim.Framework.Communications.Cache;
  40. using OpenSim.Framework.Servers;
  41. using OpenSim.Region.Environment.Interfaces;
  42. using OpenSim.Region.Environment.Scenes.Scripting;
  43. using OpenSim.Region.Physics.Manager;
  44. using Caps = OpenSim.Region.Capabilities.Caps;
  45. using Image = System.Drawing.Image;
  46. using Timer = System.Timers.Timer;
  47. namespace OpenSim.Region.Environment.Scenes
  48. {
  49. public delegate bool FilterAvatarList(ScenePresence avatar);
  50. public partial class Scene : SceneBase
  51. {
  52. public delegate void SynchronizeSceneHandler(Scene scene);
  53. public SynchronizeSceneHandler SynchronizeScene = null;
  54. public int splitID = 0;
  55. #region Fields
  56. protected Timer m_heartbeatTimer = new Timer();
  57. protected Timer m_restartWaitTimer = new Timer();
  58. protected SimStatsReporter m_statsReporter;
  59. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  60. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  61. public InnerScene m_innerScene;
  62. private Random Rand = new Random();
  63. private uint _primCount = 720000;
  64. private readonly Mutex _primAllocateMutex = new Mutex(false);
  65. private int m_timePhase = 24;
  66. private readonly Mutex updateLock;
  67. public bool m_physicalPrim;
  68. public bool m_seeIntoRegionFromNeighbor;
  69. private int m_RestartTimerCounter;
  70. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  71. private int m_incrementsof15seconds = 0;
  72. public string m_simulatorVersion = "OpenSimulator 0.5";
  73. protected ModuleLoader m_moduleLoader;
  74. protected StorageManager m_storageManager;
  75. protected AgentCircuitManager m_authenticateHandler;
  76. public CommunicationsManager CommsManager;
  77. // protected XferManager xferManager;
  78. protected SceneCommunicationService m_sceneGridService;
  79. protected SceneXmlLoader m_sceneXmlLoader;
  80. /// <summary>
  81. /// Each agent has its own capabilities handler.
  82. /// </summary>
  83. protected Dictionary<LLUUID, Caps> m_capsHandlers = new Dictionary<LLUUID, Caps>();
  84. protected BaseHttpServer m_httpListener;
  85. protected Dictionary<string, IRegionModule> Modules = new Dictionary<string, IRegionModule>();
  86. public Dictionary<Type, object> ModuleInterfaces = new Dictionary<Type, object>();
  87. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  88. public Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
  89. //API module interfaces
  90. public IXfer XferManager;
  91. protected IHttpRequests m_httpRequestModule;
  92. protected ISimChat m_simChatModule;
  93. protected IXMLRPC m_xmlrpcModule;
  94. protected IWorldComm m_worldCommModule;
  95. protected IAvatarFactory m_AvatarFactory;
  96. // Central Update Loop
  97. protected int m_fps = 10;
  98. protected int m_frame = 0;
  99. protected float m_timespan = 0.089f;
  100. protected DateTime m_lastupdate = DateTime.Now;
  101. protected float m_timedilation = 1.0f;
  102. private int m_update_physics = 1;
  103. private int m_update_entitymovement = 1;
  104. private int m_update_entities = 1; // Run through all objects checking for updates
  105. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  106. private int m_update_presences = 1; // Update scene presence movements
  107. private int m_update_events = 1;
  108. private int m_update_backup = 200;
  109. private int m_update_terrain = 50;
  110. private int m_update_land = 1;
  111. private int frameMS = 0;
  112. private int physicsMS2 = 0;
  113. private int physicsMS = 0;
  114. private int otherMS = 0;
  115. private bool m_physics_enabled = true;
  116. private bool m_scripts_enabled = true;
  117. #endregion
  118. #region Properties
  119. public AgentCircuitManager AuthenticateHandler
  120. {
  121. get { return m_authenticateHandler; }
  122. }
  123. protected readonly EstateManager m_estateManager;
  124. // an instance to the physics plugin's Scene object.
  125. public PhysicsScene PhysicsScene
  126. {
  127. set { m_innerScene.PhysicsScene = value; }
  128. get { return (m_innerScene.PhysicsScene); }
  129. }
  130. // This gets locked so things stay thread safe.
  131. public object SyncRoot
  132. {
  133. get { return m_innerScene.m_syncRoot; }
  134. }
  135. public EstateManager EstateManager
  136. {
  137. get { return m_estateManager; }
  138. }
  139. public float TimeDilation
  140. {
  141. get { return m_timedilation; }
  142. }
  143. protected readonly PermissionManager m_permissionManager;
  144. // This is the instance to the permissions manager.
  145. // This manages permissions to clients on in world objects
  146. public PermissionManager PermissionsMngr
  147. {
  148. get { return m_permissionManager; }
  149. }
  150. public int TimePhase
  151. {
  152. get { return m_timePhase; }
  153. }
  154. // Local reference to the objects in the scene (which are held in innerScene)
  155. // public Dictionary<LLUUID, SceneObjectGroup> Objects
  156. // {
  157. // get { return m_innerScene.SceneObjects; }
  158. // }
  159. // Reference to all of the agents in the scene (root and child)
  160. protected Dictionary<LLUUID, ScenePresence> m_scenePresences
  161. {
  162. get { return m_innerScene.ScenePresences; }
  163. set { m_innerScene.ScenePresences = value; }
  164. }
  165. // protected Dictionary<LLUUID, SceneObjectGroup> m_sceneObjects
  166. // {
  167. // get { return m_innerScene.SceneObjects; }
  168. // set { m_innerScene.SceneObjects = value; }
  169. // }
  170. public Dictionary<LLUUID, EntityBase> Entities
  171. {
  172. get { return m_innerScene.Entities; }
  173. set { m_innerScene.Entities = value; }
  174. }
  175. public Dictionary<LLUUID, ScenePresence> m_restorePresences
  176. {
  177. get { return m_innerScene.RestorePresences; }
  178. set { m_innerScene.RestorePresences = value; }
  179. }
  180. #endregion
  181. #region Constructors
  182. public Scene(RegionInfo regInfo, AgentCircuitManager authen, PermissionManager permissionManager,
  183. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  184. AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
  185. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim, bool SeeIntoRegionFromNeighbor)
  186. {
  187. updateLock = new Mutex(false);
  188. m_moduleLoader = moduleLoader;
  189. m_authenticateHandler = authen;
  190. CommsManager = commsMan;
  191. m_sceneGridService = sceneGridService;
  192. m_sceneGridService.debugRegionName = regInfo.RegionName;
  193. m_storageManager = storeManager;
  194. AssetCache = assetCach;
  195. m_regInfo = regInfo;
  196. m_regionHandle = m_regInfo.RegionHandle;
  197. m_regionName = m_regInfo.RegionName;
  198. m_datastore = m_regInfo.DataStore;
  199. m_physicalPrim = physicalPrim;
  200. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  201. m_eventManager = new EventManager();
  202. //Bind Storage Manager functions to some land manager functions for this scene
  203. EventManager.OnLandObjectAdded +=
  204. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  205. EventManager.OnLandObjectRemoved +=
  206. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  207. m_estateManager = new EstateManager(this, m_regInfo);
  208. m_permissionManager = permissionManager;
  209. m_permissionManager.Initialise(this);
  210. m_innerScene = new InnerScene(this, m_regInfo, m_permissionManager);
  211. // If the Inner scene has an Unrecoverable error, restart this sim.
  212. // Currently the only thing that causes it to happen is two kinds of specific
  213. // Physics based crashes.
  214. //
  215. // Out of memory
  216. // Operating system has killed the plugin
  217. m_innerScene.UnRecoverableError += RestartNow;
  218. m_sceneXmlLoader = new SceneXmlLoader(this, m_innerScene, m_regInfo);
  219. RegisterDefaultSceneEvents();
  220. m_log.Info("[SCENE]: Creating new entitities instance");
  221. Entities = new Dictionary<LLUUID, EntityBase>();
  222. m_scenePresences = new Dictionary<LLUUID, ScenePresence>();
  223. //m_sceneObjects = new Dictionary<LLUUID, SceneObjectGroup>();
  224. m_restorePresences = new Dictionary<LLUUID, ScenePresence>();
  225. m_httpListener = httpServer;
  226. m_dumpAssetsToFile = dumpAssetsToFile;
  227. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipScripts) == Simulator.RegionFlags.SkipScripts)
  228. {
  229. m_scripts_enabled = false;
  230. }
  231. else
  232. {
  233. m_scripts_enabled = true;
  234. }
  235. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipPhysics) == Simulator.RegionFlags.SkipPhysics)
  236. {
  237. m_physics_enabled = false;
  238. }
  239. else
  240. {
  241. m_physics_enabled = true;
  242. }
  243. m_statsReporter = new SimStatsReporter(regInfo);
  244. m_statsReporter.OnSendStatsResult += SendSimStatsPackets;
  245. string OSString = "";
  246. if (System.Environment.OSVersion.Platform != PlatformID.Unix)
  247. {
  248. OSString = System.Environment.OSVersion.ToString();
  249. }
  250. else
  251. {
  252. OSString = Util.ReadEtcIssue();
  253. }
  254. if (OSString.Length > 45)
  255. {
  256. OSString = OSString.Substring(0, 45);
  257. }
  258. m_simulatorVersion = "OpenSimulator v0.5-SVN on " + OSString + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString() + " PhysPrim:" + m_physicalPrim.ToString();
  259. }
  260. #endregion
  261. #region Startup / Close Methods
  262. protected virtual void RegisterDefaultSceneEvents()
  263. {
  264. m_eventManager.OnPermissionError += SendPermissionAlert;
  265. }
  266. public override string GetSimulatorVersion()
  267. {
  268. return m_simulatorVersion;
  269. }
  270. public override bool OtherRegionUp(RegionInfo otherRegion)
  271. {
  272. // Another region is up.
  273. // Gets called from Grid Comms (SceneCommunicationService<---RegionListener<----LocalBackEnd<----OGS1)
  274. // We have to tell all our ScenePresences about it..
  275. // and add it to the neighbor list.
  276. // We only add it to the neighbor list if it's within 1 region from here.
  277. // Agents may have draw distance values that cross two regions though, so
  278. // we add it to the notify list regardless of distance.
  279. // We'll check the agent's draw distance before notifying them though.
  280. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  281. {
  282. for (int i = 0; i < m_neighbours.Count; i++)
  283. {
  284. // The purpose of this loop is to re-update the known neighbors
  285. // when another region comes up on top of another one.
  286. // The latest region in that location ends up in the
  287. // 'known neighbors list'
  288. // Additionally, the commFailTF property gets reset to false.
  289. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  290. {
  291. lock (m_neighbours)
  292. {
  293. m_neighbours[i] = otherRegion;
  294. }
  295. }
  296. }
  297. // If the value isn't in the neighbours, add it.
  298. // If the RegionInfo isn't exact but is for the same XY World location,
  299. // then the above loop will fix that.
  300. if (!(m_neighbours.Contains(otherRegion)))
  301. {
  302. lock (m_neighbours)
  303. {
  304. m_neighbours.Add(otherRegion);
  305. }
  306. }
  307. // If these are cast to INT because long + negative values + abs returns invalid data
  308. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  309. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  310. if ((resultX <= 1) &&
  311. (resultY <= 1))
  312. {
  313. try
  314. {
  315. ForEachScenePresence(delegate(ScenePresence agent)
  316. {
  317. // If agent is a root agent.
  318. if (!agent.IsChildAgent)
  319. {
  320. //agent.ControllingClient.new
  321. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  322. InformClientOfNeighbor(agent, otherRegion);
  323. }
  324. }
  325. );
  326. }
  327. catch (NullReferenceException)
  328. {
  329. // This means that we're not booted up completely yet.
  330. // This shouldn't happen too often anymore.
  331. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  332. }
  333. }
  334. else
  335. {
  336. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  337. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  338. otherRegion.RegionLocY.ToString() + ")");
  339. }
  340. }
  341. return true;
  342. }
  343. // Given float seconds, this will restart the region.
  344. public virtual void Restart(float seconds)
  345. {
  346. // notifications are done in 15 second increments
  347. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  348. // It's a 'Cancel restart' request.
  349. // RestartNow() does immediate restarting.
  350. if (seconds < 15)
  351. {
  352. m_restartTimer.Stop();
  353. SendGeneralAlert("Restart Aborted");
  354. }
  355. else
  356. {
  357. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  358. m_restartTimer.Interval = 15000;
  359. m_incrementsof15seconds = (int)seconds / 15;
  360. m_RestartTimerCounter = 0;
  361. m_restartTimer.AutoReset = true;
  362. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  363. m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  364. m_restartTimer.Start();
  365. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  366. //SendGeneralAlert(RegionInfo.RegionName + ": Restarting in 2 Minutes");
  367. }
  368. }
  369. // The Restart timer has occured.
  370. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  371. // have elapsed.
  372. // If they have elapsed, call RestartNow()
  373. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  374. {
  375. m_RestartTimerCounter++;
  376. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  377. {
  378. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  379. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " +
  380. ((8 - m_RestartTimerCounter) * 15) + " seconds");
  381. // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) +
  382. //" seconds");
  383. }
  384. else
  385. {
  386. m_restartTimer.Stop();
  387. m_restartTimer.AutoReset = false;
  388. RestartNow();
  389. }
  390. }
  391. // This causes the region to restart immediatley.
  392. public void RestartNow()
  393. {
  394. if (PhysicsScene != null)
  395. {
  396. PhysicsScene.Dispose();
  397. }
  398. m_log.Error("[REGION]: Closing");
  399. Close();
  400. m_log.Error("[REGION]: Firing Region Restart Message");
  401. base.Restart(0);
  402. }
  403. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  404. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  405. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  406. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  407. // subsequently the agent will never see the region come back online.
  408. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  409. {
  410. m_restartWaitTimer.Stop();
  411. lock (m_regionRestartNotifyList)
  412. {
  413. foreach (RegionInfo region in m_regionRestartNotifyList)
  414. {
  415. try
  416. {
  417. ForEachScenePresence(delegate(ScenePresence agent)
  418. {
  419. // If agent is a root agent.
  420. if (!agent.IsChildAgent)
  421. {
  422. //agent.ControllingClient.new
  423. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  424. InformClientOfNeighbor(agent, region);
  425. }
  426. }
  427. );
  428. }
  429. catch (NullReferenceException)
  430. {
  431. // This means that we're not booted up completely yet.
  432. // This shouldn't happen too often anymore.
  433. }
  434. }
  435. // Reset list to nothing.
  436. m_regionRestartNotifyList.Clear();
  437. }
  438. }
  439. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  440. {
  441. if (m_scripts_enabled != !ScriptEngine)
  442. {
  443. // Tedd! Here's the method to disable the scripting engine!
  444. if (ScriptEngine)
  445. {
  446. m_log.Info("Stopping all Scripts in Scene");
  447. lock (Entities)
  448. {
  449. foreach (EntityBase ent in Entities.Values)
  450. {
  451. if (ent is SceneObjectGroup)
  452. {
  453. ((SceneObjectGroup)ent).StopScripts();
  454. }
  455. }
  456. }
  457. }
  458. else
  459. {
  460. m_log.Info("Starting all Scripts in Scene");
  461. lock (Entities)
  462. {
  463. foreach (EntityBase ent in Entities.Values)
  464. {
  465. if (ent is SceneObjectGroup)
  466. {
  467. ((SceneObjectGroup)ent).StartScripts();
  468. }
  469. }
  470. }
  471. }
  472. m_scripts_enabled = !ScriptEngine;
  473. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  474. }
  475. if (m_physics_enabled != !PhysicsEngine)
  476. {
  477. m_physics_enabled = !PhysicsEngine;
  478. }
  479. }
  480. // This is the method that shuts down the scene.
  481. public override void Close()
  482. {
  483. m_log.Warn("[SCENE]: Closing down the single simulator: " + RegionInfo.RegionName);
  484. // Kick all ROOT agents with the message, 'The simulator is going down'
  485. ForEachScenePresence(delegate(ScenePresence avatar)
  486. {
  487. if (avatar.KnownChildRegions.Contains(RegionInfo.RegionHandle))
  488. avatar.KnownChildRegions.Remove(RegionInfo.RegionHandle);
  489. if (!avatar.IsChildAgent)
  490. avatar.ControllingClient.Kick("The simulator is going down.");
  491. avatar.ControllingClient.OutPacket(PacketPool.Instance.GetPacket(libsecondlife.Packets.PacketType.DisableSimulator),
  492. ThrottleOutPacketType.Task);
  493. });
  494. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  495. Thread.Sleep(500);
  496. // Stop all client threads.
  497. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  498. // Stop updating the scene objects and agents.
  499. m_heartbeatTimer.Close();
  500. // close the inner scene
  501. m_innerScene.Close();
  502. // De-register with region communications (events cleanup)
  503. UnRegisterReginWithComms();
  504. // Shut down all non shared modules.
  505. foreach (IRegionModule module in Modules.Values)
  506. {
  507. if (!module.IsSharedModule)
  508. {
  509. module.Close();
  510. }
  511. }
  512. Modules.Clear();
  513. // call the base class Close method.
  514. base.Close();
  515. }
  516. /// <summary>
  517. /// Start the timer which triggers regular scene updates
  518. /// </summary>
  519. public void StartTimer()
  520. {
  521. m_log.Debug("[SCENE]: Starting timer");
  522. m_heartbeatTimer.Enabled = true;
  523. m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  524. m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  525. }
  526. public void SetModuleInterfaces()
  527. {
  528. m_simChatModule = RequestModuleInterface<ISimChat>();
  529. m_httpRequestModule = RequestModuleInterface<IHttpRequests>();
  530. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  531. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  532. XferManager = RequestModuleInterface<IXfer>();
  533. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  534. }
  535. #endregion
  536. #region Update Methods
  537. /// <summary>
  538. /// Performs per-frame updates regularly
  539. /// </summary>
  540. /// <param name="sender"></param>
  541. /// <param name="e"></param>
  542. private void Heartbeat(object sender, EventArgs e)
  543. {
  544. Update();
  545. }
  546. /// <summary>
  547. /// Performs per-frame updates on the scene, this should be the central scene loop
  548. /// </summary>
  549. public override void Update()
  550. {
  551. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  552. // Aquire a lock so only one update call happens at once
  553. updateLock.WaitOne();
  554. float physicsFPS = 0;
  555. int agentsInScene = m_innerScene.GetRootAgentCount() + m_innerScene.GetChildAgentCount();
  556. if (agentsInScene > 21)
  557. {
  558. if (m_update_entities == 1)
  559. {
  560. m_update_entities = 5;
  561. m_statsReporter.SetUpdateMS(6000);
  562. }
  563. }
  564. else
  565. {
  566. if (m_update_entities == 5)
  567. {
  568. m_update_entities = 1;
  569. m_statsReporter.SetUpdateMS(3000);
  570. }
  571. }
  572. frameMS = System.Environment.TickCount;
  573. try
  574. {
  575. // Increment the frame counter
  576. m_frame++;
  577. // Loop it
  578. if (m_frame == Int32.MaxValue)
  579. m_frame = 0;
  580. physicsMS2 = System.Environment.TickCount;
  581. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  582. m_innerScene.UpdatePreparePhysics();
  583. physicsMS2 = System.Environment.TickCount - physicsMS2;
  584. if (m_frame % m_update_entitymovement == 0)
  585. m_innerScene.UpdateEntityMovement();
  586. physicsMS = System.Environment.TickCount;
  587. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  588. physicsFPS = m_innerScene.UpdatePhysics(
  589. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  590. );
  591. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  592. SynchronizeScene(this);
  593. physicsMS = System.Environment.TickCount - physicsMS;
  594. physicsMS += physicsMS2;
  595. otherMS = System.Environment.TickCount;
  596. // run through all entities looking for updates (slow)
  597. if (m_frame % m_update_entities == 0)
  598. m_innerScene.UpdateEntities();
  599. // run through entities that have scheduled themselves for
  600. // updates looking for updates(faster)
  601. if (m_frame % m_update_entitiesquick == 0)
  602. m_innerScene.ProcessUpdates();
  603. // Run through scenepresences looking for updates
  604. if (m_frame % m_update_presences == 0)
  605. m_innerScene.UpdatePresences();
  606. if (Region_Status != RegionStatus.SlaveScene)
  607. {
  608. if (m_frame % m_update_events == 0)
  609. UpdateEvents();
  610. if (m_frame % m_update_backup == 0)
  611. UpdateStorageBackup();
  612. if (m_frame % m_update_terrain == 0)
  613. UpdateTerrain();
  614. if (m_frame % m_update_land == 0)
  615. UpdateLand();
  616. otherMS = System.Environment.TickCount - otherMS;
  617. // if (m_frame%m_update_avatars == 0)
  618. // UpdateInWorldTime();
  619. m_statsReporter.AddPhysicsFPS(physicsFPS);
  620. m_statsReporter.AddTimeDilation(m_timedilation);
  621. m_statsReporter.AddFPS(1);
  622. m_statsReporter.AddInPackets(0);
  623. m_statsReporter.SetRootAgents(m_innerScene.GetRootAgentCount());
  624. m_statsReporter.SetChildAgents(m_innerScene.GetChildAgentCount());
  625. m_statsReporter.SetObjects(m_innerScene.GetTotalObjects());
  626. m_statsReporter.SetActiveObjects(m_innerScene.GetActiveObjects());
  627. frameMS = System.Environment.TickCount - frameMS;
  628. m_statsReporter.addFrameMS(frameMS);
  629. m_statsReporter.addPhysicsMS(physicsMS);
  630. m_statsReporter.addOtherMS(otherMS);
  631. m_statsReporter.SetActiveScripts(m_innerScene.GetActiveScripts());
  632. m_statsReporter.addScriptLines(m_innerScene.GetScriptLPS());
  633. }
  634. }
  635. catch (NotImplementedException)
  636. {
  637. throw;
  638. }
  639. catch (System.AccessViolationException e)
  640. {
  641. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  642. }
  643. catch (System.NullReferenceException e)
  644. {
  645. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  646. }
  647. catch (System.InvalidOperationException e)
  648. {
  649. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  650. }
  651. catch (Exception e)
  652. {
  653. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  654. }
  655. finally
  656. {
  657. updateLock.ReleaseMutex();
  658. // Get actual time dilation
  659. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  660. // If actual time dilation is greater then one, we're catching up, so subtract
  661. // the amount that's greater then 1 from the time dilation
  662. if (tmpval > 1.0)
  663. {
  664. tmpval = tmpval - (tmpval - 1.0f);
  665. }
  666. m_timedilation = tmpval;
  667. m_lastupdate = DateTime.Now;
  668. }
  669. }
  670. //Updates the time in the viewer.
  671. // TODO: unused
  672. // private void UpdateInWorldTime()
  673. // {
  674. // m_timeUpdateCount++;
  675. // if (m_timeUpdateCount > 600)
  676. // {
  677. // List<ScenePresence> avatars = GetAvatars();
  678. // foreach (ScenePresence avatar in avatars)
  679. // {
  680. // avatar.ControllingClient.SendViewerTime(m_timePhase);
  681. // }
  682. // m_timeUpdateCount = 0;
  683. // m_timePhase++;
  684. // if (m_timePhase > 94)
  685. // {
  686. // m_timePhase = 0;
  687. // }
  688. // }
  689. // }
  690. private void SendSimStatsPackets(SimStatsPacket pack)
  691. {
  692. List<ScenePresence> StatSendAgents = GetScenePresences();
  693. foreach (ScenePresence agent in StatSendAgents)
  694. {
  695. if (!agent.IsChildAgent)
  696. {
  697. pack.Header.Reliable = false;
  698. agent.ControllingClient.OutPacket(pack, ThrottleOutPacketType.Task);
  699. }
  700. }
  701. }
  702. private void UpdateLand()
  703. {
  704. if (LandChannel != null)
  705. {
  706. if (LandChannel.isLandPrimCountTainted())
  707. {
  708. LandChannel.performParcelPrimCountUpdate();
  709. }
  710. }
  711. }
  712. private void UpdateTerrain()
  713. {
  714. EventManager.TriggerTerrainTick();
  715. }
  716. private void UpdateStorageBackup()
  717. {
  718. Backup();
  719. }
  720. private void UpdateEvents()
  721. {
  722. m_eventManager.TriggerOnFrame();
  723. }
  724. /// <summary>
  725. /// Perform delegate action on all clients subscribing to updates from this region.
  726. /// </summary>
  727. /// <returns></returns>
  728. internal void Broadcast(Action<IClientAPI> whatToDo)
  729. {
  730. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  731. }
  732. /// <summary>
  733. ///
  734. /// </summary>
  735. /// <returns></returns>
  736. public bool Backup()
  737. {
  738. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  739. return true;
  740. }
  741. #endregion
  742. #region Load Terrain
  743. public void ExportWorldMap(string fileName)
  744. {
  745. List<MapBlockData> mapBlocks =
  746. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  747. (int)(RegionInfo.RegionLocY - 9),
  748. (int)(RegionInfo.RegionLocX + 9),
  749. (int)(RegionInfo.RegionLocY + 9));
  750. List<AssetBase> textures = new List<AssetBase>();
  751. List<Image> bitImages = new List<Image>();
  752. foreach (MapBlockData mapBlock in mapBlocks)
  753. {
  754. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  755. if (texAsset != null)
  756. {
  757. textures.Add(texAsset);
  758. }
  759. else
  760. {
  761. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  762. if (texAsset != null)
  763. {
  764. textures.Add(texAsset);
  765. }
  766. }
  767. }
  768. foreach (AssetBase asset in textures)
  769. {
  770. Image image = OpenJPEG.DecodeToImage(asset.Data);
  771. bitImages.Add(image);
  772. }
  773. Bitmap mapTexture = new Bitmap(2560, 2560);
  774. Graphics g = Graphics.FromImage(mapTexture);
  775. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  776. g.FillRectangle(sea, 0, 0, 2560, 2560);
  777. for (int i = 0; i < mapBlocks.Count; i++)
  778. {
  779. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  780. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  781. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  782. }
  783. mapTexture.Save(fileName, ImageFormat.Jpeg);
  784. }
  785. public void SaveTerrain()
  786. {
  787. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  788. }
  789. /// <summary>
  790. /// Loads the World heightmap
  791. /// </summary>
  792. ///
  793. public override void LoadWorldMap()
  794. {
  795. try
  796. {
  797. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  798. if (map == null)
  799. {
  800. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  801. Heightmap = new Modules.Terrain.TerrainChannel();
  802. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  803. }
  804. else
  805. {
  806. Heightmap = new Modules.Terrain.TerrainChannel(map);
  807. }
  808. }
  809. catch (Exception e)
  810. {
  811. m_log.Warn("[terrain]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  812. }
  813. }
  814. public void RegisterRegionWithGrid()
  815. {
  816. RegisterCommsEvents();
  817. // These two 'commands' *must be* next to each other or sim rebooting fails.
  818. m_sceneGridService.RegisterRegion(RegionInfo);
  819. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  820. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  821. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  822. {
  823. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  824. {
  825. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  826. LandChannel.allowedForcefulBans = false;
  827. }
  828. else
  829. {
  830. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  831. LandChannel.allowedForcefulBans = true;
  832. }
  833. }
  834. }
  835. /// <summary>
  836. ///
  837. /// </summary>
  838. public void CreateTerrainTexture(bool temporary)
  839. {
  840. //TODOADAM: Move this to TerrainModule
  841. //create a texture asset of the terrain
  842. ITerrainTemp terrain = RequestModuleInterface<ITerrainTemp>();
  843. if (terrain != null)
  844. {
  845. byte[] data = terrain.WriteJpegImage("defaultstripe.png");
  846. m_regInfo.EstateSettings.terrainImageID = LLUUID.Random();
  847. AssetBase asset = new AssetBase();
  848. asset.FullID = m_regInfo.EstateSettings.terrainImageID;
  849. asset.Data = data;
  850. asset.Name = "terrainImage";
  851. asset.Description = RegionInfo.RegionName;
  852. asset.Type = 0;
  853. asset.Temporary = temporary;
  854. AssetCache.AddAsset(asset);
  855. }
  856. }
  857. #endregion
  858. #region Load Land
  859. public void loadAllLandObjectsFromStorage(LLUUID regionID)
  860. {
  861. m_log.Info("[SCENE]: Loading land objects from storage");
  862. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  863. if (landData.Count == 0)
  864. {
  865. LandChannel.NoLandDataFromStorage();
  866. }
  867. else
  868. {
  869. LandChannel.IncomingLandObjectsFromStorage(landData);
  870. }
  871. }
  872. #endregion
  873. #region Primitives Methods
  874. /// <summary>
  875. /// Loads the World's objects
  876. /// </summary>
  877. public virtual void LoadPrimsFromStorage(bool m_permissions, LLUUID regionID)
  878. {
  879. m_log.Info("[SCENE]: Loading objects from datastore");
  880. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  881. foreach (SceneObjectGroup group in PrimsFromDB)
  882. {
  883. AddEntityFromStorage(group);
  884. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  885. rootPart.ObjectFlags &= ~(uint)LLObject.ObjectFlags.Scripted;
  886. rootPart.TrimPermissions();
  887. group.ApplyPhysics(m_physicalPrim);
  888. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  889. }
  890. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  891. }
  892. /// <summary>
  893. /// Returns a new unallocated primitive ID
  894. /// </summary>
  895. /// <returns>A brand new primitive ID</returns>
  896. public uint PrimIDAllocate()
  897. {
  898. uint myID;
  899. _primAllocateMutex.WaitOne();
  900. ++_primCount;
  901. myID = _primCount;
  902. _primAllocateMutex.ReleaseMutex();
  903. return myID;
  904. }
  905. public LLVector3 GetNewRezLocation(LLVector3 RayStart, LLVector3 RayEnd, LLUUID RayTargetID, LLQuaternion rot, byte bypassRayCast, byte RayEndIsIntersection)
  906. {
  907. LLVector3 pos = LLVector3.Zero;
  908. if (RayEndIsIntersection == (byte)1)
  909. {
  910. pos = RayEnd;
  911. return pos;
  912. }
  913. if (RayTargetID != LLUUID.Zero)
  914. {
  915. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  916. LLVector3 direction = LLVector3.Norm(RayEnd - RayStart);
  917. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  918. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  919. if (target != null)
  920. {
  921. pos = target.AbsolutePosition;
  922. //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());
  923. // TODO: Raytrace better here
  924. //EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  925. Ray NewRay = new Ray(AXOrigin, AXdirection);
  926. // Ray Trace against target here
  927. EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1,0,0,0));
  928. // Un-comment out the following line to Get Raytrace results printed to the console.
  929. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  930. // If we hit something
  931. if (ei.HitTF)
  932. {
  933. // Set the position to the intersection point
  934. pos = (new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z) + (new LLVector3(ei.normal.x,ei.normal.x,ei.normal.z) * (0.5f/2f)));
  935. // Un-offset the prim (it gets offset later by the consumer method)
  936. pos.Z -= 0.25F;
  937. }
  938. return pos;
  939. }
  940. else
  941. {
  942. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  943. EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  944. // Un-comment the following line to print the raytrace results to the console.
  945. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  946. if (ei.HitTF)
  947. {
  948. pos = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  949. }
  950. return pos;
  951. }
  952. }
  953. else
  954. {
  955. // fall back to our stupid functionality
  956. pos = RayEnd;
  957. return pos;
  958. }
  959. }
  960. public virtual void AddNewPrim(LLUUID ownerID, LLVector3 RayEnd, LLQuaternion rot, PrimitiveBaseShape shape,
  961. byte bypassRaycast, LLVector3 RayStart, LLUUID RayTargetID,
  962. byte RayEndIsIntersection)
  963. {
  964. LLVector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection);
  965. if (PermissionsMngr.CanRezObject(ownerID, pos))
  966. {
  967. // rez ON the ground, not IN the ground
  968. pos.Z += 0.25F;
  969. AddNewPrim(ownerID, pos, rot, shape);
  970. }
  971. }
  972. public virtual SceneObjectGroup AddNewPrim(LLUUID ownerID, LLVector3 pos, LLQuaternion rot, PrimitiveBaseShape shape)
  973. {
  974. SceneObjectGroup sceneOb =
  975. new SceneObjectGroup(this, m_regionHandle, ownerID, PrimIDAllocate(), pos, rot, shape);
  976. AddEntity(sceneOb);
  977. SceneObjectPart rootPart = sceneOb.GetChildPart(sceneOb.UUID);
  978. // if grass or tree, make phantom
  979. //rootPart.TrimPermissions();
  980. if ((rootPart.Shape.PCode == (byte)PCode.Grass) || (rootPart.Shape.PCode == (byte)PCode.Tree) || (rootPart.Shape.PCode == (byte)PCode.NewTree))
  981. {
  982. rootPart.AddFlag(LLObject.ObjectFlags.Phantom);
  983. //rootPart.ObjectFlags += (uint)LLObject.ObjectFlags.Phantom;
  984. }
  985. // if not phantom, add to physics
  986. sceneOb.ApplyPhysics(m_physicalPrim);
  987. m_innerScene.AddToUpdateList(sceneOb);
  988. return sceneOb;
  989. }
  990. public SceneObjectGroup AddTree(LLVector3 scale, LLQuaternion rotation, LLVector3 position,
  991. Tree treeType, bool newTree)
  992. {
  993. LLUUID uuid = this.RegionInfo.MasterAvatarAssignedUUID;
  994. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  995. treeShape.PathCurve = 16;
  996. treeShape.PathEnd = 49900;
  997. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  998. treeShape.Scale = scale;
  999. treeShape.State = (byte)treeType;
  1000. return AddNewPrim(uuid, position, rotation, treeShape);
  1001. }
  1002. public void RemovePrim(uint localID, LLUUID avatar_deleter)
  1003. {
  1004. m_innerScene.RemovePrim(localID, avatar_deleter);
  1005. }
  1006. public void AddEntityFromStorage(SceneObjectGroup sceneObject)
  1007. {
  1008. m_innerScene.AddEntityFromStorage(sceneObject);
  1009. }
  1010. public void AddEntity(SceneObjectGroup sceneObject)
  1011. {
  1012. m_innerScene.AddEntity(sceneObject);
  1013. }
  1014. public void RemoveEntity(SceneObjectGroup sceneObject)
  1015. {
  1016. if (Entities.ContainsKey(sceneObject.UUID))
  1017. {
  1018. LandChannel.removePrimFromLandPrimCounts(sceneObject);
  1019. Entities.Remove(sceneObject.UUID);
  1020. LandChannel.setPrimsTainted();
  1021. m_innerScene.RemoveAPrimCount();
  1022. }
  1023. }
  1024. /// <summary>
  1025. /// Called by a prim when it has been created/cloned, so that its events can be subscribed to
  1026. /// </summary>
  1027. /// <param name="prim"></param>
  1028. public void AcknowledgeNewPrim(SceneObjectGroup prim)
  1029. {
  1030. prim.OnPrimCountTainted += LandChannel.setPrimsTainted;
  1031. }
  1032. public void LoadPrimsFromXml(string fileName, bool newIdsFlag, LLVector3 loadOffset)
  1033. {
  1034. m_sceneXmlLoader.LoadPrimsFromXml(fileName, newIdsFlag, loadOffset);
  1035. }
  1036. public void SavePrimsToXml(string fileName)
  1037. {
  1038. m_sceneXmlLoader.SavePrimsToXml(fileName);
  1039. }
  1040. public void LoadPrimsFromXml2(string fileName)
  1041. {
  1042. m_sceneXmlLoader.LoadPrimsFromXml2(fileName);
  1043. }
  1044. public void SavePrimsToXml2(string fileName)
  1045. {
  1046. m_sceneXmlLoader.SavePrimsToXml2(fileName);
  1047. }
  1048. public void CrossPrimGroupIntoNewRegion(LLVector3 position, SceneObjectGroup grp)
  1049. {
  1050. m_log.Warn("Prim crossing: " + grp.UUID.ToString());
  1051. int thisx = (int)RegionInfo.RegionLocX;
  1052. int thisy = (int)RegionInfo.RegionLocY;
  1053. int primcrossingXMLmethod = 0;
  1054. ulong newRegionHandle = 0;
  1055. LLVector3 pos = position;
  1056. if (position.X > Constants.RegionSize + 0.1f)
  1057. {
  1058. pos.X = ((pos.X - Constants.RegionSize));
  1059. newRegionHandle = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1060. // x + 1
  1061. }
  1062. else if (position.X < -0.1f)
  1063. {
  1064. pos.X = ((pos.X + Constants.RegionSize));
  1065. newRegionHandle = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1066. // x - 1
  1067. }
  1068. if (position.Y > Constants.RegionSize + 0.1f)
  1069. {
  1070. pos.Y = ((pos.Y - Constants.RegionSize));
  1071. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1072. // y + 1
  1073. }
  1074. else if (position.Y < -1f)
  1075. {
  1076. pos.Y = ((pos.Y + Constants.RegionSize));
  1077. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1078. // y - 1
  1079. }
  1080. // Offset the positions for the new region across the border
  1081. grp.OffsetForNewRegion(pos);
  1082. if (newRegionHandle != 0)
  1083. {
  1084. bool successYN = false;
  1085. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(newRegionHandle, grp.UUID, m_sceneXmlLoader.SavePrimGroupToXML2String(grp), primcrossingXMLmethod);
  1086. if (successYN)
  1087. {
  1088. // We remove the object here
  1089. try
  1090. {
  1091. DeleteSceneObjectGroup(grp);
  1092. }
  1093. catch (System.Exception)
  1094. {
  1095. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1096. }
  1097. }
  1098. else
  1099. {
  1100. m_log.Warn("[INTERREGION]: Prim Crossing Failed!");
  1101. if (grp.RootPart != null)
  1102. {
  1103. if (grp.RootPart.PhysActor != null)
  1104. {
  1105. grp.RootPart.PhysActor.CrossingFailure();
  1106. }
  1107. }
  1108. }
  1109. }
  1110. }
  1111. public bool IncomingInterRegionPrimGroup(ulong regionHandle, LLUUID primID, string objXMLData, int XMLMethod)
  1112. {
  1113. m_log.Warn("{[INTERREGION]: A new prim arrived from a neighbor");
  1114. if (XMLMethod == 0)
  1115. {
  1116. m_sceneXmlLoader.LoadGroupFromXml2String(objXMLData);
  1117. return true;
  1118. }
  1119. else
  1120. {
  1121. return false;
  1122. }
  1123. }
  1124. #endregion
  1125. #region Add/Remove Avatar Methods
  1126. /// <summary>
  1127. ///
  1128. /// </summary>
  1129. /// <param name="client"></param
  1130. /// <param name="child"></param>
  1131. public override void AddNewClient(IClientAPI client, bool child)
  1132. {
  1133. m_log.DebugFormat(
  1134. "[CONNECTION DEBUGGING]: Creating new client for {0} at {1}",
  1135. client.AgentId, RegionInfo.RegionName);
  1136. SubscribeToClientEvents(client);
  1137. ScenePresence presence = null;
  1138. if (m_restorePresences.ContainsKey(client.AgentId))
  1139. {
  1140. m_log.Info("[REGION]: Restore Scene Presence");
  1141. presence = m_restorePresences[client.AgentId];
  1142. m_restorePresences.Remove(client.AgentId);
  1143. presence.initializeScenePresence(client, RegionInfo, this);
  1144. m_innerScene.AddScenePresence(presence);
  1145. lock (m_restorePresences)
  1146. {
  1147. Monitor.PulseAll(m_restorePresences);
  1148. }
  1149. }
  1150. else
  1151. {
  1152. m_log.Info("[REGION]: Add New Scene Presence");
  1153. m_estateManager.sendRegionHandshake(client);
  1154. CreateAndAddScenePresence(client, child);
  1155. LandChannel.sendParcelOverlay(client);
  1156. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1157. }
  1158. }
  1159. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1160. {
  1161. client.OnRegionHandShakeReply += SendLayerData;
  1162. //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims);
  1163. // client.OnRequestWearables += InformClientOfNeighbours;
  1164. client.OnAddPrim += AddNewPrim;
  1165. client.OnUpdatePrimGroupPosition += m_innerScene.UpdatePrimPosition;
  1166. client.OnUpdatePrimSinglePosition += m_innerScene.UpdatePrimSinglePosition;
  1167. client.OnUpdatePrimGroupRotation += m_innerScene.UpdatePrimRotation;
  1168. client.OnUpdatePrimGroupMouseRotation += m_innerScene.UpdatePrimRotation;
  1169. client.OnUpdatePrimSingleRotation += m_innerScene.UpdatePrimSingleRotation;
  1170. client.OnUpdatePrimScale += m_innerScene.UpdatePrimScale;
  1171. client.OnUpdateExtraParams += m_innerScene.UpdateExtraParam;
  1172. client.OnUpdatePrimShape += m_innerScene.UpdatePrimShape;
  1173. client.OnRequestMapBlocks += RequestMapBlocks;
  1174. client.OnUpdatePrimTexture += m_innerScene.UpdatePrimTexture;
  1175. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1176. client.OnObjectSelect += SelectPrim;
  1177. client.OnObjectDeselect += DeselectPrim;
  1178. client.OnGrabUpdate += m_innerScene.MoveObject;
  1179. client.OnDeRezObject += DeRezObject;
  1180. client.OnRezObject += RezObject;
  1181. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  1182. client.OnObjectAttach += m_innerScene.AttachObject;
  1183. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1184. client.OnObjectDescription += m_innerScene.PrimDescription;
  1185. client.OnObjectName += m_innerScene.PrimName;
  1186. client.OnLinkObjects += m_innerScene.LinkObjects;
  1187. client.OnDelinkObjects += m_innerScene.DelinkObjects;
  1188. client.OnObjectDuplicate += m_innerScene.DuplicateObject;
  1189. client.OnUpdatePrimFlags += m_innerScene.UpdatePrimFlags;
  1190. client.OnRequestObjectPropertiesFamily += m_innerScene.RequestObjectPropertiesFamily;
  1191. client.OnParcelPropertiesRequest += new ParcelPropertiesRequest(LandChannel.handleParcelPropertiesRequest);
  1192. client.OnParcelDivideRequest += new ParcelDivideRequest(LandChannel.handleParcelDivideRequest);
  1193. client.OnParcelJoinRequest += new ParcelJoinRequest(LandChannel.handleParcelJoinRequest);
  1194. client.OnParcelPropertiesUpdateRequest +=
  1195. new ParcelPropertiesUpdateRequest(LandChannel.handleParcelPropertiesUpdateRequest);
  1196. client.OnParcelSelectObjects += new ParcelSelectObjects(LandChannel.handleParcelSelectObjectsRequest);
  1197. client.OnParcelObjectOwnerRequest +=
  1198. new ParcelObjectOwnerRequest(LandChannel.handleParcelObjectOwnersRequest);
  1199. client.OnParcelAccessListRequest += new ParcelAccessListRequest(LandChannel.handleParcelAccessRequest);
  1200. client.OnParcelAccessListUpdateRequest +=
  1201. new ParcelAccessListUpdateRequest(LandChannel.handleParcelAccessUpdateRequest);
  1202. client.OnEstateOwnerMessage += new EstateOwnerMessageRequest(m_estateManager.handleEstateOwnerMessage);
  1203. client.OnRegionInfoRequest += m_estateManager.HandleRegionInfoRequest;
  1204. client.OnEstateCovenantRequest += m_estateManager.HandleEstateCovenantRequest;
  1205. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  1206. client.OnGodKickUser += HandleGodlikeKickUser;
  1207. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1208. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1209. client.OnCreateNewInventoryFolder += CommsManager.UserProfileCacheService.HandleCreateInventoryFolder;
  1210. client.OnUpdateInventoryFolder += CommsManager.UserProfileCacheService.HandleUpdateInventoryFolder;
  1211. client.OnMoveInventoryFolder += CommsManager.UserProfileCacheService.HandleMoveInventoryFolder;
  1212. client.OnFetchInventoryDescendents += CommsManager.UserProfileCacheService.HandleFetchInventoryDescendents;
  1213. client.OnPurgeInventoryDescendents += CommsManager.UserProfileCacheService.HandlePurgeInventoryDescendents;
  1214. client.OnFetchInventory += CommsManager.UserProfileCacheService.HandleFetchInventory;
  1215. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1216. client.OnCopyInventoryItem += CopyInventoryItem;
  1217. client.OnMoveInventoryItem += MoveInventoryItem;
  1218. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1219. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1220. // client.OnAssetUploadRequest += CommsManager.TransactionsManager.HandleUDPUploadRequest;
  1221. // client.OnXferReceive += CommsManager.TransactionsManager.HandleXfer;
  1222. client.OnRezScript += RezScript;
  1223. client.OnRequestTaskInventory += RequestTaskInventory;
  1224. client.OnRemoveTaskItem += RemoveTaskInventory;
  1225. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1226. client.OnGrabObject += ProcessObjectGrab;
  1227. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1228. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1229. client.OnPacketStats += AddPacketStats;
  1230. EventManager.TriggerOnNewClient(client);
  1231. }
  1232. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client, bool child)
  1233. {
  1234. ScenePresence avatar = null;
  1235. AvatarAppearance appearance;
  1236. GetAvatarAppearance(client, out appearance);
  1237. avatar = m_innerScene.CreateAndAddScenePresence(client, child, appearance);
  1238. if (avatar.IsChildAgent)
  1239. {
  1240. avatar.OnSignificantClientMovement += LandChannel.handleSignificantClientMovement;
  1241. }
  1242. return avatar;
  1243. }
  1244. protected void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  1245. {
  1246. if (m_AvatarFactory == null ||
  1247. !m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  1248. {
  1249. //not found Appearance
  1250. m_log.Warn("[AVATAR DEBUGGING]: Couldn't fetch avatar appearance from factory, please report this to the opensim mantis");
  1251. byte[] visualParams;
  1252. AvatarWearable[] wearables;
  1253. GetDefaultAvatarAppearance(out wearables, out visualParams);
  1254. appearance = new AvatarAppearance(client.AgentId, wearables, visualParams);
  1255. }
  1256. }
  1257. /// <summary>
  1258. /// Remove the given client from the scene.
  1259. /// </summary>
  1260. /// <param name="agentID"></param>
  1261. public override void RemoveClient(LLUUID agentID)
  1262. {
  1263. bool childagentYN = false;
  1264. ScenePresence avatar = GetScenePresence(agentID);
  1265. if (avatar != null)
  1266. {
  1267. childagentYN = avatar.IsChildAgent;
  1268. }
  1269. try
  1270. {
  1271. if (avatar.IsChildAgent)
  1272. {
  1273. m_innerScene.removeUserCount(false);
  1274. }
  1275. else
  1276. {
  1277. m_innerScene.removeUserCount(true);
  1278. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle,
  1279. avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y,
  1280. avatar.AbsolutePosition.Z);
  1281. List<ulong> childknownRegions = new List<ulong>();
  1282. List<ulong> ckn = avatar.GetKnownRegionList();
  1283. for (int i = 0; i < ckn.Count; i++)
  1284. {
  1285. childknownRegions.Add(ckn[i]);
  1286. }
  1287. m_sceneGridService.SendCloseChildAgentConnections(agentID, childknownRegions);
  1288. RemoveCapsHandler(agentID);
  1289. }
  1290. m_eventManager.TriggerClientClosed(agentID);
  1291. }
  1292. catch (NullReferenceException)
  1293. {
  1294. // We don't know which count to remove it from
  1295. // Avatar is already disposed :/
  1296. }
  1297. m_eventManager.TriggerOnRemovePresence(agentID);
  1298. Broadcast(delegate(IClientAPI client)
  1299. {
  1300. try
  1301. {
  1302. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  1303. }
  1304. catch (System.NullReferenceException)
  1305. {
  1306. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1307. }
  1308. });
  1309. ForEachScenePresence(
  1310. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1311. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  1312. if (agentTransactions != null)
  1313. {
  1314. agentTransactions.RemoveAgentAssetTransactions(agentID);
  1315. }
  1316. lock (m_scenePresences)
  1317. {
  1318. if (m_scenePresences.Remove(agentID))
  1319. {
  1320. //m_log.InfoFormat("[SCENE] Removed scene presence {0}", agentID);
  1321. }
  1322. else
  1323. {
  1324. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID);
  1325. }
  1326. }
  1327. lock (Entities)
  1328. {
  1329. if (Entities.Remove(agentID))
  1330. {
  1331. //m_log.InfoFormat("[SCENE] Removed scene presence {0} from entities list", agentID);
  1332. }
  1333. else
  1334. {
  1335. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene presence with agent ID {0} from scene Entities list", agentID);
  1336. }
  1337. }
  1338. try
  1339. {
  1340. avatar.Close();
  1341. }
  1342. catch (NullReferenceException)
  1343. {
  1344. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1345. }
  1346. catch (Exception e)
  1347. {
  1348. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  1349. }
  1350. // Remove client agent from profile, so new logins will work
  1351. if (!childagentYN)
  1352. {
  1353. m_sceneGridService.ClearUserAgent(agentID);
  1354. }
  1355. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  1356. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  1357. }
  1358. public void HandleRemoveKnownRegionsFromAvatar(LLUUID avatarID, List<ulong> regionslst)
  1359. {
  1360. ScenePresence av = GetScenePresence(avatarID);
  1361. if (av != null)
  1362. {
  1363. lock (av)
  1364. {
  1365. for (int i = 0; i < regionslst.Count; i++)
  1366. {
  1367. av.KnownChildRegions.Remove(regionslst[i]);
  1368. }
  1369. }
  1370. }
  1371. }
  1372. public override void CloseAllAgents(uint circuitcode)
  1373. {
  1374. // Called by ClientView to kill all circuit codes
  1375. ClientManager.CloseAllAgents(circuitcode);
  1376. }
  1377. public void NotifyMyCoarseLocationChange()
  1378. {
  1379. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1380. }
  1381. #endregion
  1382. #region Entities
  1383. /// <summary>
  1384. ///
  1385. /// </summary>
  1386. /// <param name="entID"></param>
  1387. /// <returns></returns>
  1388. public bool DeleteEntity(LLUUID entID)
  1389. {
  1390. if (Entities.ContainsKey(entID))
  1391. {
  1392. Entities.Remove(entID);
  1393. m_storageManager.DataStore.RemoveObject(entID, m_regInfo.RegionID);
  1394. m_innerScene.RemoveAPrimCount();
  1395. return true;
  1396. }
  1397. return false;
  1398. }
  1399. public void SendKillObject(uint localID)
  1400. {
  1401. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  1402. }
  1403. #endregion
  1404. #region RegionComms
  1405. /// <summary>
  1406. ///
  1407. /// </summary>
  1408. public void RegisterCommsEvents()
  1409. {
  1410. m_sceneGridService.OnExpectUser += NewUserConnection;
  1411. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  1412. m_sceneGridService.OnCloseAgentConnection += CloseConnection;
  1413. m_sceneGridService.OnRegionUp += OtherRegionUp;
  1414. m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  1415. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  1416. m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  1417. m_sceneGridService.KillObject = SendKillObject;
  1418. }
  1419. /// <summary>
  1420. ///
  1421. /// </summary>
  1422. public void UnRegisterReginWithComms()
  1423. {
  1424. m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  1425. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  1426. m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  1427. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  1428. m_sceneGridService.OnExpectUser -= NewUserConnection;
  1429. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  1430. m_sceneGridService.OnCloseAgentConnection -= CloseConnection;
  1431. m_sceneGridService.Close();
  1432. }
  1433. /// <summary>
  1434. /// Do the work necessary to initiate a new user connection.
  1435. /// At the moment, this consists of setting up the caps infrastructure
  1436. /// </summary>
  1437. /// <param name="regionHandle"></param>
  1438. /// <param name="agent"></param>
  1439. public void NewUserConnection(ulong regionHandle, AgentCircuitData agent)
  1440. {
  1441. if (regionHandle == m_regInfo.RegionHandle)
  1442. {
  1443. capsPaths[agent.AgentID] = agent.CapsPath;
  1444. if (!agent.child)
  1445. {
  1446. AddCapsHandler(agent.AgentID);
  1447. }
  1448. m_log.DebugFormat(
  1449. "[CONNECTION DEBUGGING]: Creating new circuit code ({0}) for avatar {1} at {2}",
  1450. agent.circuitcode, agent.AgentID, RegionInfo.RegionName);
  1451. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  1452. }
  1453. else
  1454. {
  1455. m_log.WarnFormat(
  1456. "[CONNECTION DEBUGGING]: Skipping this region for welcoming avatar {0} [{1}] at {2}",
  1457. agent.AgentID, regionHandle, RegionInfo.RegionName);
  1458. }
  1459. }
  1460. /// <summary>
  1461. /// Add a caps handler for the given agent. If the CAPS handler already exists for this agent,
  1462. /// then it is replaced by a new CAPS handler.
  1463. ///
  1464. /// FIXME: On login this is called twice, once for the login and once when the connection is made.
  1465. /// This is somewhat innefficient and should be fixed. The initial login creation is necessary
  1466. /// since the client asks for capabilities immediately after being informed of the seed.
  1467. /// </summary>
  1468. /// <param name="agentId"></param>
  1469. /// <param name="capsObjectPath"></param>
  1470. public void AddCapsHandler(LLUUID agentId)
  1471. {
  1472. String capsObjectPath = GetCapsPath(agentId);
  1473. m_log.DebugFormat(
  1474. "[CAPS]: Setting up CAPS handler for root agent {0} in {1}",
  1475. agentId, RegionInfo.RegionName);
  1476. Caps cap =
  1477. new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port,
  1478. capsObjectPath, agentId, m_dumpAssetsToFile);
  1479. cap.RegisterHandlers();
  1480. cap.AddNewInventoryItem = AddInventoryItem;
  1481. cap.ItemUpdatedCall = CapsUpdateInventoryItemAsset;
  1482. cap.TaskScriptUpdatedCall = CapsUpdateTaskInventoryScriptAsset;
  1483. cap.CAPSFetchInventoryDescendents = CommsManager.UserProfileCacheService.HandleFetchInventoryDescendentsCAPS;
  1484. m_capsHandlers[agentId] = cap;
  1485. }
  1486. /// <summary>
  1487. /// Remove the caps handler for a given agent.
  1488. /// </summary>
  1489. /// <param name="agentId"></param>
  1490. public void RemoveCapsHandler(LLUUID agentId)
  1491. {
  1492. if (m_capsHandlers.ContainsKey(agentId))
  1493. {
  1494. m_log.DebugFormat(
  1495. "[CAPS]: Removing CAPS handler for root agent {0} in {1}",
  1496. agentId, RegionInfo.RegionName);
  1497. m_capsHandlers[agentId].DeregisterHandlers();
  1498. m_capsHandlers.Remove(agentId);
  1499. }
  1500. else
  1501. {
  1502. m_log.WarnFormat(
  1503. "[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
  1504. agentId, RegionInfo.RegionName);
  1505. }
  1506. }
  1507. /// <summary>
  1508. ///
  1509. /// </summary>
  1510. /// <param name="regionHandle"></param>
  1511. /// <param name="agentID"></param>
  1512. /// <param name="position"></param>
  1513. /// <param name="isFlying"></param>
  1514. public virtual void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1515. {
  1516. if (regionHandle == m_regInfo.RegionHandle)
  1517. {
  1518. if (m_scenePresences.ContainsKey(agentID))
  1519. {
  1520. try
  1521. {
  1522. m_scenePresences[agentID].MakeRootAgent(position, isFlying);
  1523. }
  1524. catch (Exception e)
  1525. {
  1526. m_log.Info("[SCENE]: Unable to do Agent Crossing.");
  1527. m_log.Debug("[SCENE]: " + e.ToString());
  1528. }
  1529. //m_innerScene.SwapRootChildAgent(false);
  1530. }
  1531. }
  1532. }
  1533. public virtual bool IncomingChildAgentDataUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData)
  1534. {
  1535. ScenePresence childAgentUpdate = GetScenePresence(new LLUUID(cAgentData.AgentID));
  1536. if (childAgentUpdate != null)
  1537. {
  1538. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  1539. // however to avoid a race condition crossing borders..
  1540. if (childAgentUpdate.IsChildAgent)
  1541. {
  1542. uint rRegionX = (uint)(cAgentData.regionHandle >> 40);
  1543. uint rRegionY = (((uint)(cAgentData.regionHandle)) >> 8);
  1544. uint tRegionX = RegionInfo.RegionLocX;
  1545. uint tRegionY = RegionInfo.RegionLocY;
  1546. //Send Data to ScenePresence
  1547. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  1548. // Not Implemented:
  1549. //TODO: Do we need to pass the message on to one of our neighbors?
  1550. }
  1551. return true;
  1552. }
  1553. return false;
  1554. }
  1555. /// <summary>
  1556. /// Tell a single agent to disconnect from the region.
  1557. /// </summary>
  1558. /// <param name="regionHandle"></param>
  1559. /// <param name="agentID"></param>
  1560. public bool CloseConnection(ulong regionHandle, LLUUID agentID)
  1561. {
  1562. if (regionHandle == m_regionHandle)
  1563. {
  1564. ScenePresence presence = m_innerScene.GetScenePresence(agentID);
  1565. if (presence != null)
  1566. {
  1567. if (presence.IsChildAgent)
  1568. {
  1569. m_innerScene.removeUserCount(false);
  1570. }
  1571. else
  1572. {
  1573. m_innerScene.removeUserCount(true);
  1574. }
  1575. // Tell a single agent to disconnect from the region.
  1576. libsecondlife.Packets.DisableSimulatorPacket disable = (libsecondlife.Packets.DisableSimulatorPacket)PacketPool.Instance.GetPacket(libsecondlife.Packets.PacketType.DisableSimulator);
  1577. presence.ControllingClient.OutPacket(disable, ThrottleOutPacketType.Unknown);
  1578. presence.ControllingClient.Close(true);
  1579. }
  1580. }
  1581. return true;
  1582. }
  1583. /// <summary>
  1584. /// Tell neighboring regions about this agent
  1585. /// When the regions respond with a true value,
  1586. /// tell the agents about the region.
  1587. ///
  1588. /// We have to tell the regions about the agents first otherwise it'll deny them access
  1589. ///
  1590. /// </summary>
  1591. /// <param name="presence"></param>
  1592. public void InformClientOfNeighbours(ScenePresence presence)
  1593. {
  1594. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  1595. }
  1596. /// <summary>
  1597. /// Tell a neighboring region about this agent
  1598. /// </summary>
  1599. /// <param name="presence"></param>
  1600. /// <param name="region"></param>
  1601. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  1602. {
  1603. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  1604. }
  1605. /// <summary>
  1606. /// Requests information about this region from gridcomms
  1607. /// </summary>
  1608. /// <param name="regionHandle"></param>
  1609. /// <returns></returns>
  1610. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  1611. {
  1612. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  1613. }
  1614. /// <summary>
  1615. /// Requests textures for map from minimum region to maximum region in world cordinates
  1616. /// </summary>
  1617. /// <param name="remoteClient"></param>
  1618. /// <param name="minX"></param>
  1619. /// <param name="minY"></param>
  1620. /// <param name="maxX"></param>
  1621. /// <param name="maxY"></param>
  1622. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  1623. {
  1624. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxX);
  1625. }
  1626. /// <summary>
  1627. /// Tries to teleport agent to other region.
  1628. /// </summary>
  1629. /// <param name="remoteClient"></param>
  1630. /// <param name="regionHandle"></param>
  1631. /// <param name="position"></param>
  1632. /// <param name="lookAt"></param>
  1633. /// <param name="flags"></param>
  1634. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, LLVector3 position,
  1635. LLVector3 lookAt, uint flags)
  1636. {
  1637. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  1638. {
  1639. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  1640. position, lookAt, flags);
  1641. }
  1642. }
  1643. /// <summary>
  1644. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  1645. /// </summary>
  1646. /// <param name="regionHandle"></param>
  1647. /// <param name="agentID"></param>
  1648. /// <param name="position"></param>
  1649. /// <param name="isFlying"></param>
  1650. /// <returns></returns>
  1651. public bool InformNeighbourOfCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1652. {
  1653. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  1654. }
  1655. public void SendOutChildAgentUpdates(ChildAgentDataUpdate cadu, ScenePresence presence)
  1656. {
  1657. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  1658. }
  1659. #endregion
  1660. #region Module Methods
  1661. /// <summary>
  1662. ///
  1663. /// </summary>
  1664. /// <param name="name"></param>
  1665. /// <param name="module"></param>
  1666. public void AddModule(string name, IRegionModule module)
  1667. {
  1668. if (!Modules.ContainsKey(name))
  1669. {
  1670. Modules.Add(name, module);
  1671. }
  1672. }
  1673. public void RegisterModuleCommander(string name, ICommander commander)
  1674. {
  1675. lock (m_moduleCommanders)
  1676. {
  1677. m_moduleCommanders.Add(name, commander);
  1678. }
  1679. }
  1680. public ICommander GetCommander(string name)
  1681. {
  1682. lock (m_moduleCommanders)
  1683. {
  1684. return m_moduleCommanders[name];
  1685. }
  1686. }
  1687. public Dictionary<string, ICommander> GetCommanders()
  1688. {
  1689. return m_moduleCommanders;
  1690. }
  1691. /// <summary>
  1692. ///
  1693. /// </summary>
  1694. /// <param name="mod"></param>
  1695. public void RegisterModuleInterface<M>(M mod)
  1696. {
  1697. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  1698. {
  1699. ModuleInterfaces.Add(typeof(M), mod);
  1700. }
  1701. }
  1702. /// <summary>
  1703. ///
  1704. /// </summary>
  1705. /// <returns></returns>
  1706. public T RequestModuleInterface<T>()
  1707. {
  1708. if (ModuleInterfaces.ContainsKey(typeof(T)))
  1709. {
  1710. return (T)ModuleInterfaces[typeof(T)];
  1711. }
  1712. else
  1713. {
  1714. return default(T);
  1715. }
  1716. }
  1717. #endregion
  1718. #region Other Methods
  1719. /// <summary>
  1720. ///
  1721. /// </summary>
  1722. /// <param name="phase"></param>
  1723. public void SetTimePhase(int phase)
  1724. {
  1725. m_timePhase = phase;
  1726. }
  1727. /// <summary>
  1728. ///
  1729. /// </summary>
  1730. /// <param name="avatarID"></param>
  1731. /// <param name="objectName"></param>
  1732. /// <param name="objectID"></param>
  1733. /// <param name="ownerID"></param>
  1734. /// <param name="groupOwned"></param>
  1735. /// <param name="message"></param>
  1736. /// <param name="url"></param>
  1737. public void SendUrlToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, bool groupOwned,
  1738. string message, string url)
  1739. {
  1740. if (m_scenePresences.ContainsKey(avatarID))
  1741. {
  1742. m_scenePresences[avatarID].ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned,
  1743. message, url);
  1744. }
  1745. }
  1746. public void SendDialogToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, string message, LLUUID TextureID, int ch, string[] buttonlabels)
  1747. {
  1748. if (m_scenePresences.ContainsKey(avatarID))
  1749. {
  1750. m_scenePresences[avatarID].ControllingClient.SendDialog(objectName, objectID, ownerID, message, TextureID, ch, buttonlabels);
  1751. }
  1752. }
  1753. /// <summary>
  1754. ///
  1755. /// </summary>
  1756. /// <param name="url"></param>
  1757. /// <param name="type"></param>
  1758. /// <param name="body"></param>
  1759. /// <returns></returns>
  1760. public LLUUID MakeHttpRequest(string url, string type, string body)
  1761. {
  1762. if (m_httpRequestModule != null)
  1763. {
  1764. return m_httpRequestModule.MakeHttpRequest(url, type, body);
  1765. }
  1766. return LLUUID.Zero;
  1767. }
  1768. /// <summary>
  1769. /// This method is a way for the Friends Module to create an instant
  1770. /// message to the avatar and for Instant Messages that travel across
  1771. /// gridcomms to make it to the Instant Message Module.
  1772. ///
  1773. /// Friendship establishment and groups are unfortunately tied with instant messaging and
  1774. /// there's no way to separate them completely.
  1775. /// </summary>
  1776. /// <param name="message">object containing the instant message data</param>
  1777. /// <returns>void</returns>
  1778. public void TriggerGridInstantMessage(GridInstantMessage message, InstantMessageReceiver options)
  1779. {
  1780. m_eventManager.TriggerGridInstantMessage(message, options);
  1781. }
  1782. public virtual void StoreAddFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  1783. {
  1784. // TODO: m_sceneGridService.DoStuff;
  1785. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  1786. }
  1787. public virtual void StoreUpdateFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  1788. {
  1789. // TODO: m_sceneGridService.DoStuff;
  1790. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  1791. }
  1792. public virtual void StoreRemoveFriendship(LLUUID ownerID, LLUUID ExfriendID)
  1793. {
  1794. // TODO: m_sceneGridService.DoStuff;
  1795. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  1796. }
  1797. public virtual List<FriendListItem> StoreGetFriendsForUser(LLUUID ownerID)
  1798. {
  1799. // TODO: m_sceneGridService.DoStuff;
  1800. return m_sceneGridService.GetUserFriendList(ownerID);
  1801. }
  1802. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  1803. {
  1804. m_statsReporter.AddInPackets(inPackets);
  1805. m_statsReporter.AddOutPackets(outPackets);
  1806. m_statsReporter.AddunAckedBytes(unAckedBytes);
  1807. }
  1808. public void AddAgentTime(int ms)
  1809. {
  1810. m_statsReporter.addFrameMS(ms);
  1811. m_statsReporter.addAgentMS(ms);
  1812. }
  1813. public void AddAgentUpdates(int count)
  1814. {
  1815. m_statsReporter.AddAgentUpdates(count);
  1816. }
  1817. public void AddPendingDownloads(int count)
  1818. {
  1819. m_statsReporter.addPendingDownload(count);
  1820. }
  1821. #endregion
  1822. #region Console Commands
  1823. #region Alert Methods
  1824. private void SendPermissionAlert(LLUUID user, string reason)
  1825. {
  1826. SendAlertToUser(user, reason, false);
  1827. }
  1828. /// <summary>
  1829. ///
  1830. /// </summary>
  1831. /// <param name="message"></param>
  1832. public void SendGeneralAlert(string message)
  1833. {
  1834. List<ScenePresence> presenceList = GetScenePresences();
  1835. foreach (ScenePresence presence in presenceList)
  1836. {
  1837. presence.ControllingClient.SendAlertMessage(message);
  1838. }
  1839. }
  1840. /// <summary>
  1841. ///
  1842. /// </summary>
  1843. /// <param name="agentID"></param>
  1844. /// <param name="message"></param>
  1845. /// <param name="modal"></param>
  1846. public void SendAlertToUser(LLUUID agentID, string message, bool modal)
  1847. {
  1848. if (m_scenePresences.ContainsKey(agentID))
  1849. {
  1850. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage(message, modal);
  1851. }
  1852. }
  1853. /// <summary>
  1854. ///
  1855. /// </summary>
  1856. /// <param name="agentID"></param>
  1857. /// <param name="sessionID"></param>
  1858. /// <param name="token"></param>
  1859. /// <param name="controllingClient"></param>
  1860. public void handleRequestGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token, bool godLike,
  1861. IClientAPI controllingClient)
  1862. {
  1863. // First check that this is the sim owner
  1864. if (m_permissionManager.GenericEstatePermission(agentID))
  1865. {
  1866. // User needs to be logged into this sim
  1867. if (m_scenePresences.ContainsKey(agentID))
  1868. {
  1869. // Next we check for spoofing.....
  1870. LLUUID testSessionID = m_scenePresences[agentID].ControllingClient.SessionId;
  1871. if (sessionID == testSessionID)
  1872. {
  1873. if (sessionID == controllingClient.SessionId)
  1874. {
  1875. //m_log.Info("godlike: " + godLike.ToString());
  1876. m_scenePresences[agentID].GrantGodlikePowers(agentID, testSessionID, token, godLike);
  1877. }
  1878. }
  1879. }
  1880. }
  1881. else
  1882. {
  1883. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage("Request for god powers denied", false);
  1884. }
  1885. }
  1886. /// <summary>
  1887. /// Sends a Big Blue Box message on the upper right of the screen to the client
  1888. /// for all agents in the region
  1889. /// </summary>
  1890. /// <param name="FromAvatarID">The person sending the message</param>
  1891. /// <param name="fromSessionID">The session of the person sending the message</param>
  1892. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  1893. /// <param name="Message">The Message being sent to the user</param>
  1894. public void SendRegionMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  1895. {
  1896. List<ScenePresence> presenceList = GetScenePresences();
  1897. foreach (ScenePresence presence in presenceList)
  1898. {
  1899. if (!presence.IsChildAgent)
  1900. presence.ControllingClient.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  1901. }
  1902. }
  1903. /// <summary>
  1904. /// Sends a Big Blue Box message on the upper right of the screen to the client
  1905. /// for all agents in the estate
  1906. /// </summary>
  1907. /// <param name="FromAvatarID">The person sending the message</param>
  1908. /// <param name="fromSessionID">The session of the person sending the message</param>
  1909. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  1910. /// <param name="Message">The Message being sent to the user</param>
  1911. public void SendEstateMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  1912. {
  1913. ClientManager.ForEachClient(delegate(IClientAPI controller)
  1914. {
  1915. controller.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  1916. }
  1917. );
  1918. }
  1919. /// <summary>
  1920. /// Kicks User specified from the simulator. This logs them off of the grid
  1921. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  1922. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  1923. /// agent is assigned
  1924. /// </summary>
  1925. /// <param name="godID">The person doing the kicking</param>
  1926. /// <param name="sessionID">The session of the person doing the kicking</param>
  1927. /// <param name="agentID">the person that is being kicked</param>
  1928. /// <param name="kickflags">This isn't used apparently</param>
  1929. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  1930. public void HandleGodlikeKickUser(LLUUID godID, LLUUID sessionID, LLUUID agentID, uint kickflags, byte[] reason)
  1931. {
  1932. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  1933. LLUUID kickUserID = new LLUUID("44e87126e7944ded05b37c42da3d5cdb");
  1934. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  1935. {
  1936. if (m_permissionManager.GenericEstatePermission(godID))
  1937. {
  1938. if (agentID == kickUserID)
  1939. {
  1940. ClientManager.ForEachClient(delegate(IClientAPI controller)
  1941. {
  1942. if (controller.AgentId != godID)
  1943. controller.Kick(Helpers.FieldToUTF8String(reason));
  1944. }
  1945. );
  1946. // This is a bit crude. It seems the client will be null before it actually stops the thread
  1947. // The thread will kill itself eventually :/
  1948. // Is there another way to make sure *all* clients get this 'inter region' message?
  1949. ClientManager.ForEachClient(delegate(IClientAPI controller)
  1950. {
  1951. ScenePresence p = GetScenePresence(controller.AgentId);
  1952. bool childagent = !p.Equals(null) && p.IsChildAgent;
  1953. if (controller.AgentId != godID && !childagent)
  1954. // Do we really want to kick the initiator of this madness?
  1955. {
  1956. controller.Close(true);
  1957. }
  1958. }
  1959. );
  1960. }
  1961. else
  1962. {
  1963. if (m_scenePresences[agentID].IsChildAgent)
  1964. {
  1965. m_innerScene.removeUserCount(false);
  1966. }
  1967. else
  1968. {
  1969. m_innerScene.removeUserCount(true);
  1970. }
  1971. m_scenePresences[agentID].ControllingClient.Kick(Helpers.FieldToUTF8String(reason));
  1972. m_scenePresences[agentID].ControllingClient.Close(true);
  1973. }
  1974. }
  1975. else
  1976. {
  1977. if (m_scenePresences.ContainsKey(godID))
  1978. m_scenePresences[godID].ControllingClient.SendAgentAlertMessage("Kick request denied", false);
  1979. }
  1980. }
  1981. }
  1982. public void HandleObjectPermissionsUpdate(IClientAPI controller, LLUUID agentID, LLUUID sessionID, byte field, uint localId, uint mask, byte set)
  1983. {
  1984. // Check for spoofing.. since this is permissions we're talking about here!
  1985. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  1986. {
  1987. // Tell the object to do permission update
  1988. if (localId != 0)
  1989. {
  1990. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  1991. if (chObjectGroup != null)
  1992. {
  1993. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  1994. }
  1995. }
  1996. }
  1997. }
  1998. /// <summary>
  1999. ///
  2000. /// </summary>
  2001. /// <param name="firstName"></param>
  2002. /// <param name="lastName"></param>
  2003. /// <param name="message"></param>
  2004. /// <param name="modal"></param>
  2005. public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
  2006. {
  2007. List<ScenePresence> presenceList = GetScenePresences();
  2008. foreach (ScenePresence presence in presenceList)
  2009. {
  2010. if ((presence.Firstname == firstName) && (presence.Lastname == lastName))
  2011. {
  2012. presence.ControllingClient.SendAgentAlertMessage(message, modal);
  2013. break;
  2014. }
  2015. }
  2016. }
  2017. /// <summary>
  2018. ///
  2019. /// </summary>
  2020. /// <param name="commandParams"></param>
  2021. public void HandleAlertCommand(string[] commandParams)
  2022. {
  2023. if (commandParams[0] == "general")
  2024. {
  2025. string message = CombineParams(commandParams, 1);
  2026. SendGeneralAlert(message);
  2027. }
  2028. else
  2029. {
  2030. string message = CombineParams(commandParams, 2);
  2031. SendAlertToUser(commandParams[0], commandParams[1], message, false);
  2032. }
  2033. }
  2034. private string CombineParams(string[] commandParams, int pos)
  2035. {
  2036. string result = String.Empty;
  2037. for (int i = pos; i < commandParams.Length; i++)
  2038. {
  2039. result += commandParams[i] + " ";
  2040. }
  2041. return result;
  2042. }
  2043. #endregion
  2044. /// <summary>
  2045. /// Causes all clients to get a full object update on all of the objects in the scene.
  2046. /// </summary>
  2047. public void ForceClientUpdate()
  2048. {
  2049. List<EntityBase> EntitieList = GetEntities();
  2050. foreach (EntityBase ent in EntitieList)
  2051. {
  2052. if (ent is SceneObjectGroup)
  2053. {
  2054. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  2055. }
  2056. }
  2057. }
  2058. /// <summary>
  2059. /// This is currently only used for scale (to scale to MegaPrim size)
  2060. /// There is a console command that calls this in OpenSimMain
  2061. /// </summary>
  2062. /// <param name="cmdparams"></param>
  2063. public void HandleEditCommand(string[] cmdparams)
  2064. {
  2065. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  2066. List<EntityBase> EntitieList = GetEntities();
  2067. foreach (EntityBase ent in EntitieList)
  2068. {
  2069. if (ent is SceneObjectGroup)
  2070. {
  2071. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  2072. if (part != null)
  2073. {
  2074. if (part.Name == cmdparams[0])
  2075. {
  2076. part.Resize(
  2077. new LLVector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  2078. Convert.ToSingle(cmdparams[3])));
  2079. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  2080. }
  2081. }
  2082. }
  2083. }
  2084. }
  2085. /// <summary>
  2086. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  2087. /// </summary>
  2088. /// <param name="showWhat"></param>
  2089. public void Show(string showWhat)
  2090. {
  2091. switch (showWhat)
  2092. {
  2093. case "users":
  2094. m_log.Error("Current Region: " + RegionInfo.RegionName);
  2095. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  2096. "Agent ID", "Session ID", "Circuit", "IP", "World");
  2097. foreach (ScenePresence scenePresence in GetAvatars())
  2098. {
  2099. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  2100. scenePresence.Firstname,
  2101. scenePresence.Lastname,
  2102. scenePresence.UUID,
  2103. scenePresence.ControllingClient.AgentId,
  2104. "Unknown",
  2105. "Unknown",
  2106. RegionInfo.RegionName);
  2107. }
  2108. break;
  2109. case "modules":
  2110. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  2111. foreach (IRegionModule module in Modules.Values)
  2112. {
  2113. if (!module.IsSharedModule)
  2114. {
  2115. m_log.Error("Region Module: " + module.Name);
  2116. }
  2117. }
  2118. break;
  2119. }
  2120. }
  2121. #endregion
  2122. #region Script Handling Methods
  2123. /// <summary>
  2124. /// Console command handler to send script command to script engine.
  2125. /// </summary>
  2126. /// <param name="args"></param>
  2127. public void SendCommandToPlugins(string[] args)
  2128. {
  2129. m_eventManager.TriggerOnPluginConsole(args);
  2130. }
  2131. public double GetLandHeight(int x, int y)
  2132. {
  2133. return Heightmap[x, y];
  2134. }
  2135. public LLUUID GetLandOwner(float x, float y)
  2136. {
  2137. ILandObject land = LandChannel.getLandObject(x, y);
  2138. if (land == null)
  2139. {
  2140. return LLUUID.Zero;
  2141. }
  2142. else
  2143. {
  2144. return land.landData.ownerID;
  2145. }
  2146. }
  2147. public LandData GetLandData(float x, float y)
  2148. {
  2149. return LandChannel.getLandObject(x, y).landData;
  2150. }
  2151. public void SetLandMusicURL(float x, float y, string url)
  2152. {
  2153. ILandObject land = LandChannel.getLandObject(x, y);
  2154. if (land == null)
  2155. {
  2156. return;
  2157. }
  2158. else
  2159. {
  2160. land.landData.musicURL = url;
  2161. return;
  2162. }
  2163. }
  2164. public void SetLandMediaURL(float x, float y, string url)
  2165. {
  2166. ILandObject land = LandChannel.getLandObject(x, y);
  2167. if (land == null)
  2168. {
  2169. return;
  2170. }
  2171. else
  2172. {
  2173. land.landData.mediaURL = url;
  2174. return;
  2175. }
  2176. }
  2177. #endregion
  2178. #region Script Engine
  2179. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  2180. private bool m_dumpAssetsToFile;
  2181. /// <summary>
  2182. ///
  2183. /// </summary>
  2184. /// <param name="scriptEngine"></param>
  2185. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  2186. {
  2187. ScriptEngines.Add(scriptEngine);
  2188. scriptEngine.InitializeEngine(this);
  2189. }
  2190. public void TriggerObjectChanged(uint localID, uint change)
  2191. {
  2192. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  2193. }
  2194. #endregion
  2195. #region InnerScene wrapper methods
  2196. /// <summary>
  2197. ///
  2198. /// </summary>
  2199. /// <param name="localID"></param>
  2200. /// <returns></returns>
  2201. public LLUUID ConvertLocalIDToFullID(uint localID)
  2202. {
  2203. return m_innerScene.ConvertLocalIDToFullID(localID);
  2204. }
  2205. public void SwapRootAgentCount(bool rootChildChildRootTF)
  2206. {
  2207. m_innerScene.SwapRootChildAgent(rootChildChildRootTF);
  2208. }
  2209. public void AddPhysicalPrim(int num)
  2210. {
  2211. m_innerScene.AddPhysicalPrim(num);
  2212. }
  2213. public void RemovePhysicalPrim(int num)
  2214. {
  2215. m_innerScene.RemovePhysicalPrim(num);
  2216. }
  2217. /// <summary>
  2218. ///
  2219. /// </summary>
  2220. /// <param name="presence"></param>
  2221. public void SendAllSceneObjectsToClient(ScenePresence presence)
  2222. {
  2223. m_innerScene.SendAllSceneObjectsToClient(presence);
  2224. }
  2225. //The idea is to have a group of method that return a list of avatars meeting some requirement
  2226. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  2227. /// <summary>
  2228. ///
  2229. /// </summary>
  2230. /// <returns></returns>
  2231. public List<ScenePresence> GetAvatars()
  2232. {
  2233. return m_innerScene.GetAvatars();
  2234. }
  2235. /// <summary>
  2236. /// Request a List of all m_scenePresences in this World
  2237. /// </summary>
  2238. /// <returns></returns>
  2239. public List<ScenePresence> GetScenePresences()
  2240. {
  2241. return m_innerScene.GetScenePresences();
  2242. }
  2243. /// <summary>
  2244. /// Request a filtered list of m_scenePresences in this World
  2245. /// </summary>
  2246. /// <param name="filter"></param>
  2247. /// <returns></returns>
  2248. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  2249. {
  2250. return m_innerScene.GetScenePresences(filter);
  2251. }
  2252. /// <summary>
  2253. /// Request a Avatar by UUID
  2254. /// </summary>
  2255. /// <param name="avatarID"></param>
  2256. /// <returns></returns>
  2257. public ScenePresence GetScenePresence(LLUUID avatarID)
  2258. {
  2259. return m_innerScene.GetScenePresence(avatarID);
  2260. }
  2261. /// <summary>
  2262. /// Request an Avatar's Child Status - used by ClientView when a 'kick everyone' or 'estate message' occurs
  2263. /// </summary>
  2264. /// <param name="avatarID">AvatarID to lookup</param>
  2265. /// <returns></returns>
  2266. public override bool PresenceChildStatus(LLUUID avatarID)
  2267. {
  2268. ScenePresence cp = GetScenePresence(avatarID);
  2269. return cp.IsChildAgent;
  2270. }
  2271. /// <summary>
  2272. ///
  2273. /// </summary>
  2274. /// <param name="action"></param>
  2275. public void ForEachScenePresence(Action<ScenePresence> action)
  2276. {
  2277. // We don't want to try to send messages if there are no avatar.
  2278. if (!(m_scenePresences.Equals(null)))
  2279. {
  2280. try
  2281. {
  2282. List<ScenePresence> presenceList = GetScenePresences();
  2283. foreach (ScenePresence presence in presenceList)
  2284. {
  2285. action(presence);
  2286. }
  2287. }
  2288. catch (Exception e)
  2289. {
  2290. m_log.Info("[BUG]: " + e.ToString());
  2291. }
  2292. }
  2293. }
  2294. /// <summary>
  2295. /// Delete this object from the scene.
  2296. /// </summary>
  2297. /// <param name="group"></param>
  2298. public void DeleteSceneObjectGroup(SceneObjectGroup group)
  2299. {
  2300. SceneObjectPart rootPart = (group).GetChildPart(group.UUID);
  2301. if (rootPart.PhysActor != null)
  2302. {
  2303. PhysicsScene.RemovePrim(rootPart.PhysActor);
  2304. rootPart.PhysActor = null;
  2305. }
  2306. m_storageManager.DataStore.RemoveObject(group.UUID, m_regInfo.RegionID);
  2307. group.DeleteGroup();
  2308. lock (Entities)
  2309. {
  2310. Entities.Remove(group.UUID);
  2311. m_innerScene.RemoveAPrimCount();
  2312. }
  2313. group.DeleteParts();
  2314. }
  2315. /// <summary>
  2316. ///
  2317. /// </summary>
  2318. /// <param name="action"></param>
  2319. // public void ForEachObject(Action<SceneObjectGroup> action)
  2320. // {
  2321. // List<SceneObjectGroup> presenceList;
  2322. //
  2323. // lock (m_sceneObjects)
  2324. // {
  2325. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  2326. // }
  2327. //
  2328. // foreach (SceneObjectGroup presence in presenceList)
  2329. // {
  2330. // action(presence);
  2331. // }
  2332. // }
  2333. /// <summary>
  2334. ///
  2335. /// </summary>
  2336. /// <param name="localID"></param>
  2337. /// <returns></returns>
  2338. public SceneObjectPart GetSceneObjectPart(uint localID)
  2339. {
  2340. return m_innerScene.GetSceneObjectPart(localID);
  2341. }
  2342. /// <summary>
  2343. ///
  2344. /// </summary>
  2345. /// <param name="fullID"></param>
  2346. /// <returns></returns>
  2347. public SceneObjectPart GetSceneObjectPart(LLUUID fullID)
  2348. {
  2349. return m_innerScene.GetSceneObjectPart(fullID);
  2350. }
  2351. internal bool TryGetAvatar(LLUUID avatarId, out ScenePresence avatar)
  2352. {
  2353. return m_innerScene.TryGetAvatar(avatarId, out avatar);
  2354. }
  2355. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  2356. {
  2357. return m_innerScene.TryGetAvatarByName(avatarName, out avatar);
  2358. }
  2359. internal void ForEachClient(Action<IClientAPI> action)
  2360. {
  2361. m_innerScene.ForEachClient(action);
  2362. }
  2363. public List<EntityBase> GetEntities()
  2364. {
  2365. return m_innerScene.GetEntities();
  2366. }
  2367. #endregion
  2368. #region BaseHTTPServer wrapper methods
  2369. public bool AddHTTPHandler(string method, GenericHTTPMethod handler)
  2370. {
  2371. return m_httpListener.AddHTTPHandler(method, handler);
  2372. }
  2373. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  2374. {
  2375. return m_httpListener.AddXmlRPCHandler(method, handler);
  2376. }
  2377. public void AddStreamHandler(IRequestHandler handler)
  2378. {
  2379. m_httpListener.AddStreamHandler(handler);
  2380. }
  2381. public void RemoveStreamHandler(string httpMethod, string path)
  2382. {
  2383. m_httpListener.RemoveStreamHandler(httpMethod, path);
  2384. }
  2385. public void RemoveHTTPHandler(string httpMethod, string path)
  2386. {
  2387. m_httpListener.RemoveHTTPHandler(httpMethod, path);
  2388. }
  2389. #endregion
  2390. #region Avatar Appearance Default
  2391. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  2392. {
  2393. visualParams = GetDefaultVisualParams();
  2394. wearables = AvatarWearable.DefaultWearables;
  2395. }
  2396. private static byte[] GetDefaultVisualParams()
  2397. {
  2398. byte[] visualParams;
  2399. visualParams = new byte[218];
  2400. for (int i = 0; i < 218; i++)
  2401. {
  2402. visualParams[i] = 100;
  2403. }
  2404. return visualParams;
  2405. }
  2406. #endregion
  2407. }
  2408. }