PageRenderTime 78ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/OpenSim/Region/Framework/Scenes/Scene.cs

https://bitbucket.org/VirtualReality/taiga
C# | 4980 lines | 3384 code | 694 blank | 902 comment | 506 complexity | cb7c8e4c8650ce7af238a32b7e33a597 MD5 | raw file
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyrightD
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Text;
  33. using System.Threading;
  34. using System.Timers;
  35. using System.Xml;
  36. using Nini.Config;
  37. using OpenMetaverse;
  38. using OpenMetaverse.Packets;
  39. using OpenMetaverse.Imaging;
  40. using OpenSim.Framework;
  41. using OpenSim.Services.Interfaces;
  42. using OpenSim.Framework.Communications;
  43. using OpenSim.Framework.Communications.Cache;
  44. using OpenSim.Framework.Communications.Clients;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.Framework.Scenes.Scripting;
  48. using OpenSim.Region.Framework.Scenes.Serialization;
  49. using OpenSim.Region.Physics.Manager;
  50. using Timer=System.Timers.Timer;
  51. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  52. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  53. namespace OpenSim.Region.Framework.Scenes
  54. {
  55. public delegate bool FilterAvatarList(ScenePresence avatar);
  56. public partial class Scene : SceneBase
  57. {
  58. public enum UpdatePrioritizationSchemes {
  59. Time = 0,
  60. Distance = 1,
  61. SimpleAngularDistance = 2,
  62. FrontBack = 3,
  63. }
  64. public delegate void SynchronizeSceneHandler(Scene scene);
  65. public SynchronizeSceneHandler SynchronizeScene = null;
  66. /* Used by the loadbalancer plugin on GForge */
  67. protected int m_splitRegionID = 0;
  68. public int SplitRegionID
  69. {
  70. get { return m_splitRegionID; }
  71. set { m_splitRegionID = value; }
  72. }
  73. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  74. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  75. #region Fields
  76. protected Timer m_restartWaitTimer = new Timer();
  77. public SimStatsReporter StatsReporter;
  78. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  79. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  80. private volatile int m_bordersLocked = 0;
  81. public bool BordersLocked
  82. {
  83. get { return m_bordersLocked == 1; }
  84. set
  85. {
  86. if (value == true)
  87. m_bordersLocked = 1;
  88. else
  89. m_bordersLocked = 0;
  90. }
  91. }
  92. public List<Border> NorthBorders = new List<Border>();
  93. public List<Border> EastBorders = new List<Border>();
  94. public List<Border> SouthBorders = new List<Border>();
  95. public List<Border> WestBorders = new List<Border>();
  96. /// <value>
  97. /// The scene graph for this scene
  98. /// </value>
  99. /// TODO: Possibly stop other classes being able to manipulate this directly.
  100. private SceneGraph m_sceneGraph;
  101. /// <summary>
  102. /// Are we applying physics to any of the prims in this scene?
  103. /// </summary>
  104. public bool m_physicalPrim;
  105. public float m_maxNonphys = 256;
  106. public float m_maxPhys = 10;
  107. public bool m_clampPrimSize;
  108. public bool m_trustBinaries;
  109. public bool m_allowScriptCrossings;
  110. public bool m_useFlySlow;
  111. public bool m_usePreJump;
  112. public bool m_seeIntoRegionFromNeighbor;
  113. // TODO: need to figure out how allow client agents but deny
  114. // root agents when ACL denies access to root agent
  115. public bool m_strictAccessControl = true;
  116. public int MaxUndoCount = 5;
  117. private int m_RestartTimerCounter;
  118. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  119. private int m_incrementsof15seconds;
  120. private volatile bool m_backingup;
  121. private bool m_useAsyncWhenPossible;
  122. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  123. private Dictionary<UUID, SceneObjectGroup> m_groupsWithTargets = new Dictionary<UUID, SceneObjectGroup>();
  124. protected string m_simulatorVersion = "OpenSimulator Server";
  125. protected ModuleLoader m_moduleLoader;
  126. protected StorageManager m_storageManager;
  127. protected AgentCircuitManager m_authenticateHandler;
  128. public CommunicationsManager CommsManager;
  129. protected SceneCommunicationService m_sceneGridService;
  130. public bool LoginsDisabled = true;
  131. public new float TimeDilation
  132. {
  133. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  134. }
  135. public SceneCommunicationService SceneGridService
  136. {
  137. get { return m_sceneGridService; }
  138. }
  139. public IXfer XferManager;
  140. protected IAssetService m_AssetService;
  141. protected IAuthorizationService m_AuthorizationService;
  142. private Object m_heartbeatLock = new Object();
  143. public IAssetService AssetService
  144. {
  145. get
  146. {
  147. if (m_AssetService == null)
  148. {
  149. m_AssetService = RequestModuleInterface<IAssetService>();
  150. if (m_AssetService == null)
  151. {
  152. throw new Exception("No IAssetService available.");
  153. }
  154. }
  155. return m_AssetService;
  156. }
  157. }
  158. public IAuthorizationService AuthorizationService
  159. {
  160. get
  161. {
  162. if (m_AuthorizationService == null)
  163. {
  164. m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
  165. if (m_AuthorizationService == null)
  166. {
  167. // don't throw an exception if no authorization service is set for the time being
  168. m_log.InfoFormat("[SCENE]: No Authorization service is configured");
  169. }
  170. }
  171. return m_AuthorizationService;
  172. }
  173. }
  174. protected IInventoryService m_InventoryService;
  175. public IInventoryService InventoryService
  176. {
  177. get
  178. {
  179. if (m_InventoryService == null)
  180. {
  181. m_InventoryService = RequestModuleInterface<IInventoryService>();
  182. if (m_InventoryService == null)
  183. {
  184. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  185. }
  186. }
  187. return m_InventoryService;
  188. }
  189. }
  190. protected IGridService m_GridService;
  191. public IGridService GridService
  192. {
  193. get
  194. {
  195. if (m_GridService == null)
  196. {
  197. m_GridService = RequestModuleInterface<IGridService>();
  198. if (m_GridService == null)
  199. {
  200. throw new Exception("No IGridService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  201. }
  202. }
  203. return m_GridService;
  204. }
  205. }
  206. protected IXMLRPC m_xmlrpcModule;
  207. protected IWorldComm m_worldCommModule;
  208. protected IAvatarFactory m_AvatarFactory;
  209. public IAvatarFactory AvatarFactory
  210. {
  211. get { return m_AvatarFactory; }
  212. }
  213. protected IConfigSource m_config;
  214. protected IRegionSerialiserModule m_serialiser;
  215. protected IInterregionCommsOut m_interregionCommsOut;
  216. protected IInterregionCommsIn m_interregionCommsIn;
  217. protected IDialogModule m_dialogModule;
  218. protected ITeleportModule m_teleportModule;
  219. protected ICapabilitiesModule m_capsModule;
  220. public ICapabilitiesModule CapsModule
  221. {
  222. get { return m_capsModule; }
  223. }
  224. protected override IConfigSource GetConfig()
  225. {
  226. return m_config;
  227. }
  228. // Central Update Loop
  229. protected int m_fps = 10;
  230. protected uint m_frame;
  231. protected float m_timespan = 0.089f;
  232. protected DateTime m_lastupdate = DateTime.UtcNow;
  233. private int m_update_physics = 1;
  234. private int m_update_entitymovement = 1;
  235. private int m_update_objects = 1; // Update objects which have scheduled themselves for updates
  236. private int m_update_presences = 1; // Update scene presence movements
  237. private int m_update_events = 1;
  238. private int m_update_backup = 200;
  239. private int m_update_terrain = 50;
  240. private int m_update_land = 1;
  241. private int frameMS;
  242. private int physicsMS2;
  243. private int physicsMS;
  244. private int otherMS;
  245. private int tempOnRezMS;
  246. private int eventMS;
  247. private int backupMS;
  248. private int terrainMS;
  249. private int landMS;
  250. private int lastCompletedFrame;
  251. public int MonitorFrameTime { get { return frameMS; } }
  252. public int MonitorPhysicsUpdateTime { get { return physicsMS; } }
  253. public int MonitorPhysicsSyncTime { get { return physicsMS2; } }
  254. public int MonitorOtherTime { get { return otherMS; } }
  255. public int MonitorTempOnRezTime { get { return tempOnRezMS; } }
  256. public int MonitorEventTime { get { return eventMS; } } // This may need to be divided into each event?
  257. public int MonitorBackupTime { get { return backupMS; } }
  258. public int MonitorTerrainTime { get { return terrainMS; } }
  259. public int MonitorLandTime { get { return landMS; } }
  260. public int MonitorLastFrameTick { get { return lastCompletedFrame; } }
  261. private bool m_physics_enabled = true;
  262. private bool m_scripts_enabled = true;
  263. private string m_defaultScriptEngine;
  264. private int m_LastLogin;
  265. private Thread HeartbeatThread;
  266. private volatile bool shuttingdown;
  267. private int m_lastUpdate;
  268. private bool m_firstHeartbeat = true;
  269. private UpdatePrioritizationSchemes m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time;
  270. private bool m_reprioritization_enabled = true;
  271. private double m_reprioritization_interval = 5000.0;
  272. private double m_root_reprioritization_distance = 10.0;
  273. private double m_child_reprioritization_distance = 20.0;
  274. private object m_deleting_scene_object = new object();
  275. // the minimum time that must elapse before a changed object will be considered for persisted
  276. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  277. // the maximum time that must elapse before a changed object will be considered for persisted
  278. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  279. #endregion
  280. #region Properties
  281. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get { return this.m_update_prioritization_scheme; } }
  282. public bool IsReprioritizationEnabled { get { return m_reprioritization_enabled; } }
  283. public double ReprioritizationInterval { get { return m_reprioritization_interval; } }
  284. public double RootReprioritizationDistance { get { return m_root_reprioritization_distance; } }
  285. public double ChildReprioritizationDistance { get { return m_child_reprioritization_distance; } }
  286. public AgentCircuitManager AuthenticateHandler
  287. {
  288. get { return m_authenticateHandler; }
  289. }
  290. public SceneGraph SceneContents
  291. {
  292. get { return m_sceneGraph; }
  293. }
  294. // an instance to the physics plugin's Scene object.
  295. public PhysicsScene PhysicsScene
  296. {
  297. get { return m_sceneGraph.PhysicsScene; }
  298. set
  299. {
  300. // If we're not doing the initial set
  301. // Then we've got to remove the previous
  302. // event handler
  303. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  304. {
  305. PhysicsScene.OnJointMoved -= jointMoved;
  306. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  307. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  308. }
  309. m_sceneGraph.PhysicsScene = value;
  310. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  311. {
  312. // register event handlers to respond to joint movement/deactivation
  313. PhysicsScene.OnJointMoved += jointMoved;
  314. PhysicsScene.OnJointDeactivated += jointDeactivated;
  315. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  316. }
  317. }
  318. }
  319. // This gets locked so things stay thread safe.
  320. public object SyncRoot
  321. {
  322. get { return m_sceneGraph.m_syncRoot; }
  323. }
  324. /// <summary>
  325. /// This is for llGetRegionFPS
  326. /// </summary>
  327. public float SimulatorFPS
  328. {
  329. get { return StatsReporter.getLastReportedSimFPS(); }
  330. }
  331. public float[] SimulatorStats
  332. {
  333. get { return StatsReporter.getLastReportedSimStats(); }
  334. }
  335. public string DefaultScriptEngine
  336. {
  337. get { return m_defaultScriptEngine; }
  338. }
  339. public EntityManager Entities
  340. {
  341. get { return m_sceneGraph.Entities; }
  342. }
  343. public Dictionary<UUID, ScenePresence> m_restorePresences
  344. {
  345. get { return m_sceneGraph.RestorePresences; }
  346. set { m_sceneGraph.RestorePresences = value; }
  347. }
  348. public int objectCapacity = 45000;
  349. #endregion
  350. #region BinaryStats
  351. public class StatLogger
  352. {
  353. public DateTime StartTime;
  354. public string Path;
  355. public System.IO.BinaryWriter Log;
  356. }
  357. static StatLogger m_statLog = null;
  358. static TimeSpan m_statLogPeriod = TimeSpan.FromSeconds(300);
  359. static string m_statsDir = String.Empty;
  360. static Object m_statLockObject = new Object();
  361. private void LogSimStats(SimStats stats)
  362. {
  363. SimStatsPacket pack = new SimStatsPacket();
  364. pack.Region = new SimStatsPacket.RegionBlock();
  365. pack.Region.RegionX = stats.RegionX;
  366. pack.Region.RegionY = stats.RegionY;
  367. pack.Region.RegionFlags = stats.RegionFlags;
  368. pack.Region.ObjectCapacity = stats.ObjectCapacity;
  369. //pack.Region = //stats.RegionBlock;
  370. pack.Stat = stats.StatsBlock;
  371. pack.Header.Reliable = false;
  372. // note that we are inside the reporter lock when called
  373. DateTime now = DateTime.Now;
  374. // hide some time information into the packet
  375. pack.Header.Sequence = (uint)now.Ticks;
  376. lock (m_statLockObject) // m_statLog is shared so make sure there is only executer here
  377. {
  378. try
  379. {
  380. if (m_statLog == null || now > m_statLog.StartTime + m_statLogPeriod)
  381. {
  382. // First log file or time has expired, start writing to a new log file
  383. if (m_statLog != null && m_statLog.Log != null)
  384. {
  385. m_statLog.Log.Close();
  386. }
  387. m_statLog = new StatLogger();
  388. m_statLog.StartTime = now;
  389. m_statLog.Path = (m_statsDir.Length > 0 ? m_statsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  390. + String.Format("stats-{0}.log", now.ToString("yyyyMMddHHmmss"));
  391. m_statLog.Log = new BinaryWriter(File.Open(m_statLog.Path, FileMode.Append, FileAccess.Write));
  392. }
  393. // Write the serialized data to disk
  394. if (m_statLog != null && m_statLog.Log != null)
  395. m_statLog.Log.Write(pack.ToBytes());
  396. }
  397. catch (Exception ex)
  398. {
  399. m_log.Error("statistics gathering failed: " + ex.Message, ex);
  400. if (m_statLog != null && m_statLog.Log != null)
  401. {
  402. m_statLog.Log.Close();
  403. }
  404. m_statLog = null;
  405. }
  406. }
  407. return;
  408. }
  409. #endregion
  410. #region Constructors
  411. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  412. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  413. StorageManager storeManager,
  414. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  415. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  416. {
  417. m_config = config;
  418. Random random = new Random();
  419. BordersLocked = true;
  420. Border northBorder = new Border();
  421. northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  422. northBorder.CrossDirection = Cardinals.N;
  423. NorthBorders.Add(northBorder);
  424. Border southBorder = new Border();
  425. southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0); //--->
  426. southBorder.CrossDirection = Cardinals.S;
  427. SouthBorders.Add(southBorder);
  428. Border eastBorder = new Border();
  429. eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  430. eastBorder.CrossDirection = Cardinals.E;
  431. EastBorders.Add(eastBorder);
  432. Border westBorder = new Border();
  433. westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0); //--->
  434. westBorder.CrossDirection = Cardinals.W;
  435. WestBorders.Add(westBorder);
  436. BordersLocked = false;
  437. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  438. m_moduleLoader = moduleLoader;
  439. m_authenticateHandler = authen;
  440. CommsManager = commsMan;
  441. m_sceneGridService = sceneGridService;
  442. m_storageManager = storeManager;
  443. m_regInfo = regInfo;
  444. m_regionHandle = m_regInfo.RegionHandle;
  445. m_regionName = m_regInfo.RegionName;
  446. m_datastore = m_regInfo.DataStore;
  447. m_lastUpdate = Util.EnvironmentTickCount();
  448. m_physicalPrim = physicalPrim;
  449. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  450. m_eventManager = new EventManager();
  451. m_permissions = new ScenePermissions(this);
  452. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  453. m_asyncSceneObjectDeleter.Enabled = true;
  454. // Load region settings
  455. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  456. if (m_storageManager.EstateDataStore != null)
  457. {
  458. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
  459. }
  460. //Bind Storage Manager functions to some land manager functions for this scene
  461. EventManager.OnLandObjectAdded +=
  462. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  463. EventManager.OnLandObjectRemoved +=
  464. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  465. m_sceneGraph = new SceneGraph(this, m_regInfo);
  466. // If the scene graph has an Unrecoverable error, restart this sim.
  467. // Currently the only thing that causes it to happen is two kinds of specific
  468. // Physics based crashes.
  469. //
  470. // Out of memory
  471. // Operating system has killed the plugin
  472. m_sceneGraph.UnRecoverableError += RestartNow;
  473. RegisterDefaultSceneEvents();
  474. DumpAssetsToFile = dumpAssetsToFile;
  475. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  476. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  477. StatsReporter = new SimStatsReporter(this);
  478. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  479. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  480. StatsReporter.SetObjectCapacity(objectCapacity);
  481. // Old
  482. /*
  483. m_simulatorVersion = simulatorVersion
  484. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  485. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  486. + " PhysPrim:" + m_physicalPrim.ToString();
  487. */
  488. m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";
  489. try
  490. {
  491. // Region config overrides global config
  492. //
  493. IConfig startupConfig = m_config.Configs["Startup"];
  494. // Should we try to run loops synchronously or asynchronously?
  495. m_useAsyncWhenPossible = startupConfig.GetBoolean("use_async_when_possible", false);
  496. //Animation states
  497. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  498. // TODO: Change default to true once the feature is supported
  499. m_usePreJump = startupConfig.GetBoolean("enableprejump", false);
  500. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  501. if (RegionInfo.NonphysPrimMax > 0)
  502. {
  503. m_maxNonphys = RegionInfo.NonphysPrimMax;
  504. }
  505. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  506. if (RegionInfo.PhysPrimMax > 0)
  507. {
  508. m_maxPhys = RegionInfo.PhysPrimMax;
  509. }
  510. // Here, if clamping is requested in either global or
  511. // local config, it will be used
  512. //
  513. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  514. if (RegionInfo.ClampPrimSize)
  515. {
  516. m_clampPrimSize = true;
  517. }
  518. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  519. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  520. m_dontPersistBefore =
  521. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  522. m_dontPersistBefore *= 10000000;
  523. m_persistAfter =
  524. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  525. m_persistAfter *= 10000000;
  526. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
  527. IConfig packetConfig = m_config.Configs["PacketPool"];
  528. if (packetConfig != null)
  529. {
  530. PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
  531. PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
  532. }
  533. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  534. IConfig interest_management_config = m_config.Configs["InterestManagement"];
  535. if (interest_management_config != null)
  536. {
  537. string update_prioritization_scheme = interest_management_config.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  538. switch (update_prioritization_scheme)
  539. {
  540. case "time":
  541. m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time;
  542. break;
  543. case "distance":
  544. m_update_prioritization_scheme = UpdatePrioritizationSchemes.Distance;
  545. break;
  546. case "simpleangulardistance":
  547. m_update_prioritization_scheme = UpdatePrioritizationSchemes.SimpleAngularDistance;
  548. break;
  549. case "frontback":
  550. m_update_prioritization_scheme = UpdatePrioritizationSchemes.FrontBack;
  551. break;
  552. default:
  553. m_log.Warn("[SCENE]: UpdatePrioritizationScheme was not recognized, setting to default settomg of Time");
  554. m_update_prioritization_scheme = UpdatePrioritizationSchemes.Time;
  555. break;
  556. }
  557. m_reprioritization_enabled = interest_management_config.GetBoolean("ReprioritizationEnabled", true);
  558. m_reprioritization_interval = interest_management_config.GetDouble("ReprioritizationInterval", 5000.0);
  559. m_root_reprioritization_distance = interest_management_config.GetDouble("RootReprioritizationDistance", 10.0);
  560. m_child_reprioritization_distance = interest_management_config.GetDouble("ChildReprioritizationDistance", 20.0);
  561. }
  562. m_log.Info("[SCENE]: Using the " + m_update_prioritization_scheme + " prioritization scheme");
  563. #region BinaryStats
  564. try
  565. {
  566. IConfig statConfig = m_config.Configs["Statistics.Binary"];
  567. if (statConfig.Contains("enabled") && statConfig.GetBoolean("enabled"))
  568. {
  569. if (statConfig.Contains("collect_region_stats"))
  570. {
  571. if (statConfig.GetBoolean("collect_region_stats"))
  572. {
  573. // if enabled, add us to the event. If not enabled, I won't get called
  574. StatsReporter.OnSendStatsResult += LogSimStats;
  575. }
  576. }
  577. if (statConfig.Contains("region_stats_period_seconds"))
  578. {
  579. m_statLogPeriod = TimeSpan.FromSeconds(statConfig.GetInt("region_stats_period_seconds"));
  580. }
  581. if (statConfig.Contains("stats_dir"))
  582. {
  583. m_statsDir = statConfig.GetString("stats_dir");
  584. }
  585. }
  586. }
  587. catch
  588. {
  589. // if it doesn't work, we don't collect anything
  590. }
  591. #endregion BinaryStats
  592. }
  593. catch
  594. {
  595. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  596. }
  597. }
  598. /// <summary>
  599. /// Mock constructor for scene group persistency unit tests.
  600. /// SceneObjectGroup RegionId property is delegated to Scene.
  601. /// </summary>
  602. /// <param name="regInfo"></param>
  603. public Scene(RegionInfo regInfo)
  604. {
  605. BordersLocked = true;
  606. Border northBorder = new Border();
  607. northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  608. northBorder.CrossDirection = Cardinals.N;
  609. NorthBorders.Add(northBorder);
  610. Border southBorder = new Border();
  611. southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue,0); //--->
  612. southBorder.CrossDirection = Cardinals.S;
  613. SouthBorders.Add(southBorder);
  614. Border eastBorder = new Border();
  615. eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  616. eastBorder.CrossDirection = Cardinals.E;
  617. EastBorders.Add(eastBorder);
  618. Border westBorder = new Border();
  619. westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue,0); //--->
  620. westBorder.CrossDirection = Cardinals.W;
  621. WestBorders.Add(westBorder);
  622. BordersLocked = false;
  623. m_regInfo = regInfo;
  624. m_eventManager = new EventManager();
  625. m_lastUpdate = Util.EnvironmentTickCount();
  626. }
  627. #endregion
  628. #region Startup / Close Methods
  629. public bool ShuttingDown
  630. {
  631. get { return shuttingdown; }
  632. }
  633. /// <value>
  634. /// The scene graph for this scene
  635. /// </value>
  636. /// TODO: Possibly stop other classes being able to manipulate this directly.
  637. public SceneGraph SceneGraph
  638. {
  639. get { return m_sceneGraph; }
  640. }
  641. protected virtual void RegisterDefaultSceneEvents()
  642. {
  643. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  644. if (dm != null)
  645. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  646. }
  647. public override string GetSimulatorVersion()
  648. {
  649. return m_simulatorVersion;
  650. }
  651. /// <summary>
  652. /// Another region is up.
  653. ///
  654. /// We only add it to the neighbor list if it's within 1 region from here.
  655. /// Agents may have draw distance values that cross two regions though, so
  656. /// we add it to the notify list regardless of distance. We'll check
  657. /// the agent's draw distance before notifying them though.
  658. /// </summary>
  659. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  660. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  661. public override void OtherRegionUp(GridRegion otherRegion)
  662. {
  663. uint xcell = (uint)((int)otherRegion.RegionLocX / (int)Constants.RegionSize);
  664. uint ycell = (uint)((int)otherRegion.RegionLocY / (int)Constants.RegionSize);
  665. m_log.InfoFormat("[SCENE]: (on region {0}): Region {1} up in coords {2}-{3}",
  666. RegionInfo.RegionName, otherRegion.RegionName, xcell, ycell);
  667. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  668. {
  669. // If these are cast to INT because long + negative values + abs returns invalid data
  670. int resultX = Math.Abs((int)xcell - (int)RegionInfo.RegionLocX);
  671. int resultY = Math.Abs((int)ycell - (int)RegionInfo.RegionLocY);
  672. if (resultX <= 1 && resultY <= 1)
  673. {
  674. // Let the grid service module know, so this can be cached
  675. m_eventManager.TriggerOnRegionUp(otherRegion);
  676. RegionInfo regInfo = new RegionInfo(xcell, ycell, otherRegion.InternalEndPoint, otherRegion.ExternalHostName);
  677. regInfo.RegionID = otherRegion.RegionID;
  678. regInfo.RegionName = otherRegion.RegionName;
  679. regInfo.ScopeID = otherRegion.ScopeID;
  680. regInfo.ExternalHostName = otherRegion.ExternalHostName;
  681. try
  682. {
  683. ForEachScenePresence(delegate(ScenePresence agent)
  684. {
  685. // If agent is a root agent.
  686. if (!agent.IsChildAgent)
  687. {
  688. //agent.ControllingClient.new
  689. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  690. List<ulong> old = new List<ulong>();
  691. old.Add(otherRegion.RegionHandle);
  692. agent.DropOldNeighbours(old);
  693. InformClientOfNeighbor(agent, regInfo);
  694. }
  695. }
  696. );
  697. }
  698. catch (NullReferenceException)
  699. {
  700. // This means that we're not booted up completely yet.
  701. // This shouldn't happen too often anymore.
  702. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  703. }
  704. }
  705. else
  706. {
  707. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  708. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  709. otherRegion.RegionLocY.ToString() + ")");
  710. }
  711. }
  712. }
  713. public void AddNeighborRegion(RegionInfo region)
  714. {
  715. lock (m_neighbours)
  716. {
  717. if (!CheckNeighborRegion(region))
  718. {
  719. m_neighbours.Add(region);
  720. }
  721. }
  722. }
  723. public bool CheckNeighborRegion(RegionInfo region)
  724. {
  725. bool found = false;
  726. lock (m_neighbours)
  727. {
  728. foreach (RegionInfo reg in m_neighbours)
  729. {
  730. if (reg.RegionHandle == region.RegionHandle)
  731. {
  732. found = true;
  733. break;
  734. }
  735. }
  736. }
  737. return found;
  738. }
  739. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  740. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  741. {
  742. OtherRegionUp(new GridRegion(neighbour));
  743. return new GridRegion(RegionInfo);
  744. }
  745. /// <summary>
  746. /// Given float seconds, this will restart the region.
  747. /// </summary>
  748. /// <param name="seconds">float indicating duration before restart.</param>
  749. public virtual void Restart(float seconds)
  750. {
  751. // notifications are done in 15 second increments
  752. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  753. // It's a 'Cancel restart' request.
  754. // RestartNow() does immediate restarting.
  755. if (seconds < 15)
  756. {
  757. m_restartTimer.Stop();
  758. m_dialogModule.SendGeneralAlert("Restart Aborted");
  759. }
  760. else
  761. {
  762. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  763. m_restartTimer.Interval = 15000;
  764. m_incrementsof15seconds = (int)seconds / 15;
  765. m_RestartTimerCounter = 0;
  766. m_restartTimer.AutoReset = true;
  767. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  768. m_log.Info("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  769. m_restartTimer.Start();
  770. m_dialogModule.SendNotificationToUsersInRegion(
  771. UUID.Random(), String.Empty, RegionInfo.RegionName + String.Format(": Restarting in {0} Minutes", (int)(seconds / 60.0)));
  772. }
  773. }
  774. // The Restart timer has occured.
  775. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  776. // have elapsed.
  777. // If they have elapsed, call RestartNow()
  778. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  779. {
  780. m_RestartTimerCounter++;
  781. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  782. {
  783. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  784. m_dialogModule.SendNotificationToUsersInRegion(
  785. UUID.Random(),
  786. String.Empty,
  787. RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter) * 15) + " seconds");
  788. }
  789. else
  790. {
  791. m_restartTimer.Stop();
  792. m_restartTimer.AutoReset = false;
  793. RestartNow();
  794. }
  795. }
  796. // This causes the region to restart immediatley.
  797. public void RestartNow()
  798. {
  799. IConfig startupConfig = m_config.Configs["Startup"];
  800. if (startupConfig != null)
  801. {
  802. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  803. {
  804. MainConsole.Instance.RunCommand("shutdown");
  805. return;
  806. }
  807. }
  808. if (PhysicsScene != null)
  809. {
  810. PhysicsScene.Dispose();
  811. }
  812. m_log.Error("[REGION]: Closing");
  813. Close();
  814. m_log.Error("[REGION]: Firing Region Restart Message");
  815. base.Restart(0);
  816. }
  817. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  818. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  819. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  820. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  821. // subsequently the agent will never see the region come back online.
  822. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  823. {
  824. m_restartWaitTimer.Stop();
  825. lock (m_regionRestartNotifyList)
  826. {
  827. foreach (RegionInfo region in m_regionRestartNotifyList)
  828. {
  829. try
  830. {
  831. ForEachScenePresence(delegate(ScenePresence agent)
  832. {
  833. // If agent is a root agent.
  834. if (!agent.IsChildAgent)
  835. {
  836. //agent.ControllingClient.new
  837. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  838. InformClientOfNeighbor(agent, region);
  839. }
  840. }
  841. );
  842. }
  843. catch (NullReferenceException)
  844. {
  845. // This means that we're not booted up completely yet.
  846. // This shouldn't happen too often anymore.
  847. }
  848. }
  849. // Reset list to nothing.
  850. m_regionRestartNotifyList.Clear();
  851. }
  852. }
  853. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  854. {
  855. if (m_scripts_enabled != !ScriptEngine)
  856. {
  857. // Tedd! Here's the method to disable the scripting engine!
  858. if (ScriptEngine)
  859. {
  860. m_log.Info("Stopping all Scripts in Scene");
  861. foreach (EntityBase ent in Entities)
  862. {
  863. if (ent is SceneObjectGroup)
  864. {
  865. ((SceneObjectGroup) ent).RemoveScriptInstances(false);
  866. }
  867. }
  868. }
  869. else
  870. {
  871. m_log.Info("Starting all Scripts in Scene");
  872. lock (Entities)
  873. {
  874. foreach (EntityBase ent in Entities)
  875. {
  876. if (ent is SceneObjectGroup)
  877. {
  878. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  879. }
  880. }
  881. }
  882. }
  883. m_scripts_enabled = !ScriptEngine;
  884. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  885. }
  886. if (m_physics_enabled != !PhysicsEngine)
  887. {
  888. m_physics_enabled = !PhysicsEngine;
  889. }
  890. }
  891. public int GetInaccurateNeighborCount()
  892. {
  893. return m_neighbours.Count;
  894. }
  895. // This is the method that shuts down the scene.
  896. public override void Close()
  897. {
  898. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  899. m_restartTimer.Stop();
  900. m_restartTimer.Close();
  901. // Kick all ROOT agents with the message, 'The simulator is going down'
  902. ForEachScenePresence(delegate(ScenePresence avatar)
  903. {
  904. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  905. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  906. if (!avatar.IsChildAgent)
  907. avatar.ControllingClient.Kick("The simulator is going down.");
  908. avatar.ControllingClient.SendShutdownConnectionNotice();
  909. });
  910. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  911. Thread.Sleep(500);
  912. // Stop all client threads.
  913. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(); });
  914. // Stop updating the scene objects and agents.
  915. //m_heartbeatTimer.Close();
  916. shuttingdown = true;
  917. m_log.Debug("[SCENE]: Persisting changed objects");
  918. List<EntityBase> entities = GetEntities();
  919. foreach (EntityBase entity in entities)
  920. {
  921. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  922. {
  923. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore, false);
  924. }
  925. }
  926. m_sceneGraph.Close();
  927. // De-register with region communications (events cleanup)
  928. UnRegisterRegionWithComms();
  929. // call the base class Close method.
  930. base.Close();
  931. }
  932. /// <summary>
  933. /// Start the timer which triggers regular scene updates
  934. /// </summary>
  935. public void StartTimer()
  936. {
  937. //m_log.Debug("[SCENE]: Starting timer");
  938. //m_heartbeatTimer.Enabled = true;
  939. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  940. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  941. if (HeartbeatThread != null)
  942. {
  943. HeartbeatThread.Abort();
  944. HeartbeatThread = null;
  945. }
  946. m_lastUpdate = Util.EnvironmentTickCount();
  947. HeartbeatThread = Watchdog.StartThread(Heartbeat, "Heartbeat for region " + RegionInfo.RegionName, ThreadPriority.Normal, false);
  948. }
  949. /// <summary>
  950. /// Sets up references to modules required by the scene
  951. /// </summary>
  952. public void SetModuleInterfaces()
  953. {
  954. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  955. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  956. XferManager = RequestModuleInterface<IXfer>();
  957. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  958. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  959. m_interregionCommsOut = RequestModuleInterface<IInterregionCommsOut>();
  960. m_interregionCommsIn = RequestModuleInterface<IInterregionCommsIn>();
  961. m_dialogModule = RequestModuleInterface<IDialogModule>();
  962. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  963. m_teleportModule = RequestModuleInterface<ITeleportModule>();
  964. }
  965. #endregion
  966. #region Update Methods
  967. /// <summary>
  968. /// Performs per-frame updates regularly
  969. /// </summary>
  970. private void Heartbeat()
  971. {
  972. if (!Monitor.TryEnter(m_heartbeatLock))
  973. {
  974. Watchdog.RemoveThread();
  975. return;
  976. }
  977. try
  978. {
  979. Update();
  980. m_lastUpdate = Util.EnvironmentTickCount();
  981. m_firstHeartbeat = false;
  982. }
  983. catch (ThreadAbortException)
  984. {
  985. }
  986. finally
  987. {
  988. Monitor.Pulse(m_heartbeatLock);
  989. Monitor.Exit(m_heartbeatLock);
  990. }
  991. Watchdog.RemoveThread();
  992. }
  993. /// <summary>
  994. /// Performs per-frame updates on the scene, this should be the central scene loop
  995. /// </summary>
  996. public override void Update()
  997. {
  998. float physicsFPS;
  999. int maintc;
  1000. while (!shuttingdown)
  1001. {
  1002. TimeSpan SinceLastFrame = DateTime.UtcNow - m_lastupdate;
  1003. physicsFPS = 0f;
  1004. maintc = Util.EnvironmentTickCount();
  1005. int tmpFrameMS = maintc;
  1006. tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0;
  1007. // Increment the frame counter
  1008. ++m_frame;
  1009. try
  1010. {
  1011. // Check if any objects have reached their targets
  1012. CheckAtTargets();
  1013. // Update SceneObjectGroups that have scheduled themselves for updates
  1014. // Objects queue their updates onto all scene presences
  1015. if (m_frame % m_update_objects == 0)
  1016. m_sceneGraph.UpdateObjectGroups();
  1017. // Run through all ScenePresences looking for updates
  1018. // Presence updates and queued object updates for each presence are sent to clients
  1019. if (m_frame % m_update_presences == 0)
  1020. m_sceneGraph.UpdatePresences();
  1021. int tmpPhysicsMS2 = Util.EnvironmentTickCount();
  1022. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  1023. m_sceneGraph.UpdatePreparePhysics();
  1024. physicsMS2 = Util.EnvironmentTickCountSubtract(tmpPhysicsMS2);
  1025. if (m_frame % m_update_entitymovement == 0)
  1026. m_sceneGraph.UpdateScenePresenceMovement();
  1027. int tmpPhysicsMS = Util.EnvironmentTickCount();
  1028. if (m_frame % m_update_physics == 0)
  1029. {
  1030. if (m_physics_enabled)
  1031. physicsFPS = m_sceneGraph.UpdatePhysics(Math.Max(SinceLastFrame.TotalSeconds, m_timespan));
  1032. if (SynchronizeScene != null)
  1033. SynchronizeScene(this);
  1034. }
  1035. physicsMS = Util.EnvironmentTickCountSubtract(tmpPhysicsMS);
  1036. // Delete temp-on-rez stuff
  1037. if (m_frame % m_update_backup == 0)
  1038. {
  1039. int tmpTempOnRezMS = Util.EnvironmentTickCount();
  1040. CleanTempObjects();
  1041. tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpTempOnRezMS);
  1042. }
  1043. if (RegionStatus != RegionStatus.SlaveScene)
  1044. {
  1045. if (m_frame % m_update_events == 0)
  1046. {
  1047. int evMS = Util.EnvironmentTickCount();
  1048. UpdateEvents();
  1049. eventMS = Util.EnvironmentTickCountSubtract(evMS); ;
  1050. }
  1051. if (m_frame % m_update_backup == 0)
  1052. {
  1053. int backMS = Util.EnvironmentTickCount();
  1054. UpdateStorageBackup();
  1055. backupMS = Util.EnvironmentTickCountSubtract(backMS);
  1056. }
  1057. if (m_frame % m_update_terrain == 0)
  1058. {
  1059. int terMS = Util.EnvironmentTickCount();
  1060. UpdateTerrain();
  1061. terrainMS = Util.EnvironmentTickCountSubtract(terMS);
  1062. }
  1063. if (m_frame % m_update_land == 0)
  1064. {
  1065. int ldMS = Util.EnvironmentTickCount();
  1066. UpdateLand();
  1067. landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1068. }
  1069. frameMS = Util.EnvironmentTickCountSubtract(tmpFrameMS);
  1070. otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1071. lastCompletedFrame = Util.EnvironmentTickCount();
  1072. // if (m_frame%m_update_avatars == 0)
  1073. // UpdateInWorldTime();
  1074. StatsReporter.AddPhysicsFPS(physicsFPS);
  1075. StatsReporter.AddTimeDilation(TimeDilation);
  1076. StatsReporter.AddFPS(1);
  1077. StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  1078. StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  1079. StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  1080. StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  1081. StatsReporter.addFrameMS(frameMS);
  1082. StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
  1083. StatsReporter.addOtherMS(otherMS);
  1084. StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  1085. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  1086. }
  1087. if (LoginsDisabled && m_frame == 20)
  1088. {
  1089. // In 99.9% of cases it is a bad idea to manually force garbage collection. However,
  1090. // this is a rare case where we know we have just went through a long cycle of heap
  1091. // allocations, and there is no more work to be done until someone logs in
  1092. GC.Collect();
  1093. IConfig startupConfig = m_config.Configs["Startup"];
  1094. if (startupConfig == null || !startupConfig.GetBoolean("StartDisabled", false))
  1095. {
  1096. m_log.DebugFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
  1097. LoginsDisabled = false;
  1098. }
  1099. }
  1100. }
  1101. catch (NotImplementedException)
  1102. {
  1103. throw;
  1104. }
  1105. catch (AccessViolationException e)
  1106. {
  1107. m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1108. }
  1109. //catch (NullReferenceException e)
  1110. //{
  1111. // m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1112. //}
  1113. catch (InvalidOperationException e)
  1114. {
  1115. m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1116. }
  1117. catch (Exception e)
  1118. {
  1119. m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1120. }
  1121. finally
  1122. {
  1123. m_lastupdate = DateTime.UtcNow;
  1124. }
  1125. maintc = Util.EnvironmentTickCountSubtract(maintc);
  1126. maintc = (int)(m_timespan * 1000) - maintc;
  1127. if (maintc > 0)
  1128. Thread.Sleep(maintc);
  1129. // Tell the watchdog that this thread is still alive
  1130. Watchdog.UpdateThread();
  1131. }
  1132. }
  1133. public void AddGroupTarget(SceneObjectGroup grp)
  1134. {
  1135. lock (m_groupsWithTargets)
  1136. m_groupsWithTargets[grp.UUID] = grp;
  1137. }
  1138. public void RemoveGroupTarget(SceneObjectGroup grp)
  1139. {
  1140. lock (m_groupsWithTargets)
  1141. m_groupsWithTargets.Remove(grp.UUID);
  1142. }
  1143. private void CheckAtTargets()
  1144. {
  1145. lock (m_groupsWithTargets)
  1146. {
  1147. foreach (SceneObjectGroup entry in m_groupsWithTargets.Values)
  1148. {
  1149. entry.checkAtTargets();
  1150. }
  1151. }
  1152. }
  1153. /// <summary>
  1154. /// Send out simstats data to all clients
  1155. /// </summary>
  1156. /// <param name="stats">Stats on the Simulator's performance</param>
  1157. private void SendSimStatsPackets(SimStats stats)
  1158. {
  1159. ForEachScenePresence(
  1160. delegate(ScenePresence agent)
  1161. {
  1162. if (!agent.IsChildAgent)
  1163. agent.ControllingClient.SendSimStats(stats);
  1164. }
  1165. );
  1166. }
  1167. /// <summary>
  1168. /// Recount SceneObjectPart in parcel aabb
  1169. /// </summary>
  1170. private void UpdateLand()
  1171. {
  1172. if (LandChannel != null)
  1173. {
  1174. if (LandChannel.IsLandPrimCountTainted())
  1175. {
  1176. EventManager.TriggerParcelPrimCountUpdate();
  1177. }
  1178. }
  1179. }
  1180. /// <summary>
  1181. /// Update the terrain if it needs to be updated.
  1182. /// </summary>
  1183. private void UpdateTerrain()
  1184. {
  1185. EventManager.TriggerTerrainTick();
  1186. }
  1187. /// <summary>
  1188. /// Back up queued up changes
  1189. /// </summary>
  1190. private void UpdateStorageBackup()
  1191. {
  1192. if (!m_backingup)
  1193. {
  1194. m_backingup = true;
  1195. Util.FireAndForget(BackupWaitCallback);
  1196. }
  1197. }
  1198. /// <summary>
  1199. /// Sends out the OnFrame event to the modules
  1200. /// </summary>
  1201. private void UpdateEvents()
  1202. {
  1203. m_eventManager.TriggerOnFrame();
  1204. }
  1205. /// <summary>
  1206. /// Wrapper for Backup() that can be called with Util.FireAndForget()
  1207. /// </summary>
  1208. private void BackupWaitCallback(object o)
  1209. {
  1210. Backup();
  1211. }
  1212. /// <summary>
  1213. /// Backup the scene. This acts as the main method of the backup thread.
  1214. /// </summary>
  1215. /// <returns></returns>
  1216. public void Backup()
  1217. {
  1218. lock (m_returns)
  1219. {
  1220. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  1221. m_backingup = false;
  1222. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1223. {
  1224. UUID transaction = UUID.Random();
  1225. GridInstantMessage msg = new GridInstantMessage();
  1226. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  1227. msg.toAgentID = new Guid(ret.Key.ToString());
  1228. msg.imSessionID = new Guid(transaction.ToString());
  1229. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  1230. msg.fromAgentName = "Server";
  1231. msg.dialog = (byte)19; // Object msg
  1232. msg.fromGroup = false;
  1233. msg.offline = (byte)1;
  1234. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  1235. msg.Position = Vector3.Zero;
  1236. msg.RegionID = RegionInfo.RegionID.Guid;
  1237. msg.binaryBucket = new byte[0];
  1238. if (ret.Value.count > 1)
  1239. msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1240. else
  1241. msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1242. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1243. if (tr != null)
  1244. tr.SendInstantMessage(msg, delegate(bool success) {});
  1245. }
  1246. m_returns.Clear();
  1247. }
  1248. }
  1249. /// <summary>
  1250. /// Synchronous force backup. For deletes and links/unlinks
  1251. /// </summary>
  1252. /// <param name="group">Object to be backed up</param>
  1253. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1254. {
  1255. if (group != null)
  1256. {
  1257. group.ProcessBackup(m_storageManager.DataStore, true);
  1258. }
  1259. }
  1260. /// <summary>
  1261. /// Return object to avatar Message
  1262. /// </summary>
  1263. /// <param name="agentID">Avatar Unique Id</param>
  1264. /// <param name="objectName">Name of object returned</param>
  1265. /// <param name="location">Location of object returned</param>
  1266. /// <param name="reason">Reasion for object return</param>
  1267. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1268. {
  1269. lock (m_returns)
  1270. {
  1271. if (m_returns.ContainsKey(agentID))
  1272. {
  1273. ReturnInfo info = m_returns[agentID];
  1274. info.count++;
  1275. m_returns[agentID] = info;
  1276. }
  1277. else
  1278. {
  1279. ReturnInfo info = new ReturnInfo();
  1280. info.count = 1;
  1281. info.objectName = objectName;
  1282. info.location = location;
  1283. info.reason = reason;
  1284. m_returns[agentID] = info;
  1285. }
  1286. }
  1287. }
  1288. #endregion
  1289. #region Load Terrain
  1290. /// <summary>
  1291. /// Store the terrain in the persistant data store
  1292. /// </summary>
  1293. public void SaveTerrain()
  1294. {
  1295. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1296. }
  1297. /// <summary>
  1298. /// Loads the World heightmap
  1299. /// </summary>
  1300. public override void LoadWorldMap()
  1301. {
  1302. try
  1303. {
  1304. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  1305. if (map == null)
  1306. {
  1307. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  1308. Heightmap = new TerrainChannel();
  1309. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1310. }
  1311. else
  1312. {
  1313. Heightmap = new TerrainChannel(map);
  1314. }
  1315. }
  1316. catch (IOException e)
  1317. {
  1318. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString() + " Regenerating");
  1319. // Non standard region size. If there's an old terrain in the database, it might read past the buffer
  1320. #pragma warning disable 0162
  1321. if ((int)Constants.RegionSize != 256)
  1322. {
  1323. Heightmap = new TerrainChannel();
  1324. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1325. }
  1326. }
  1327. catch (Exception e)
  1328. {
  1329. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  1330. }
  1331. }
  1332. /// <summary>
  1333. /// Register this region with a grid service
  1334. /// </summary>
  1335. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1336. public void RegisterRegionWithGrid()
  1337. {
  1338. RegisterCommsEvents();
  1339. // These two 'commands' *must be* next to each other or sim rebooting fails.
  1340. //m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
  1341. GridRegion region = new GridRegion(RegionInfo);
  1342. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1343. if (error != String.Empty)
  1344. throw new Exception(error);
  1345. m_sceneGridService.SetScene(this);
  1346. m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
  1347. //Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  1348. //if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  1349. //{
  1350. // if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  1351. // {
  1352. // m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  1353. // EventManager.TriggerSetAllowForcefulBan(false);
  1354. // }
  1355. // else
  1356. // {
  1357. // m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  1358. // EventManager.TriggerSetAllowForcefulBan(true);
  1359. // }
  1360. //}
  1361. }
  1362. /// <summary>
  1363. /// Create a terrain texture for this scene
  1364. /// </summary>
  1365. public void CreateTerrainTexture(bool temporary)
  1366. {
  1367. //create a texture asset of the terrain
  1368. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  1369. // Cannot create a map for a nonexistant heightmap yet.
  1370. if (Heightmap == null)
  1371. return;
  1372. if (terrain == null)
  1373. return;
  1374. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1375. if (data != null)
  1376. {
  1377. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  1378. if (mapModule != null)
  1379. mapModule.LazySaveGeneratedMaptile(data, temporary);
  1380. }
  1381. }
  1382. #endregion
  1383. #region Load Land
  1384. /// <summary>
  1385. /// Loads all Parcel data from the datastore for region identified by regionID
  1386. /// </summary>
  1387. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1388. public void loadAllLandObjectsFromStorage(UUID regionID)
  1389. {
  1390. m_log.Info("[SCENE]: Loading land objects from storage");
  1391. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1392. if (LandChannel != null)
  1393. {
  1394. if (landData.Count == 0)
  1395. {
  1396. EventManager.TriggerNoticeNoLandDataFromStorage();
  1397. }
  1398. else
  1399. {
  1400. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1401. }
  1402. }
  1403. else
  1404. {
  1405. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1406. }
  1407. }
  1408. #endregion
  1409. #region Primitives Methods
  1410. /// <summary>
  1411. /// Loads the World's objects
  1412. /// </summary>
  1413. public virtual void LoadPrimsFromStorage(UUID regionID)
  1414. {
  1415. m_log.Info("[SCENE]: Loading objects from datastore");
  1416. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1417. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count + " objects from the datastore");
  1418. foreach (SceneObjectGroup group in PrimsFromDB)
  1419. {
  1420. if (group.RootPart == null)
  1421. {
  1422. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1423. group.Children == null ? 0 : group.Children.Count);
  1424. }
  1425. AddRestoredSceneObject(group, true, true);
  1426. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1427. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1428. rootPart.TrimPermissions();
  1429. group.CheckSculptAndLoad();
  1430. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1431. }
  1432. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1433. }
  1434. /// <summary>
  1435. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1436. /// </summary>
  1437. /// <param name="RayStart"></param>
  1438. /// <param name="RayEnd"></param>
  1439. /// <param name="RayTargetID"></param>
  1440. /// <param name="rot"></param>
  1441. /// <param name="bypassRayCast"></param>
  1442. /// <param name="RayEndIsIntersection"></param>
  1443. /// <param name="frontFacesOnly"></param>
  1444. /// <param name="scale"></param>
  1445. /// <param name="FaceCenter"></param>
  1446. /// <returns></returns>
  1447. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1448. {
  1449. Vector3 pos = Vector3.Zero;
  1450. if (RayEndIsIntersection == (byte)1)
  1451. {
  1452. pos = RayEnd;
  1453. return pos;
  1454. }
  1455. if (RayTargetID != UUID.Zero)
  1456. {
  1457. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1458. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1459. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1460. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1461. if (target != null)
  1462. {
  1463. pos = target.AbsolutePosition;
  1464. //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());
  1465. // TODO: Raytrace better here
  1466. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1467. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1468. // Ray Trace against target here
  1469. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1470. // Un-comment out the following line to Get Raytrace results printed to the console.
  1471. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1472. float ScaleOffset = 0.5f;
  1473. // If we hit something
  1474. if (ei.HitTF)
  1475. {
  1476. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1477. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1478. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1479. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1480. ScaleOffset = Math.Abs(ScaleOffset);
  1481. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1482. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1483. // Set the position to the intersection point
  1484. Vector3 offset = (normal * (ScaleOffset / 2f));
  1485. pos = (intersectionpoint + offset);
  1486. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  1487. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  1488. // Un-offset the prim (it gets offset later by the consumer method)
  1489. //pos.Z -= 0.25F;
  1490. }
  1491. return pos;
  1492. }
  1493. else
  1494. {
  1495. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1496. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1497. // Un-comment the following line to print the raytrace results to the console.
  1498. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1499. if (ei.HitTF)
  1500. {
  1501. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1502. } else
  1503. {
  1504. // fall back to our stupid functionality
  1505. pos = RayEnd;
  1506. }
  1507. return pos;
  1508. }
  1509. }
  1510. else
  1511. {
  1512. // fall back to our stupid functionality
  1513. pos = RayEnd;
  1514. //increase height so its above the ground.
  1515. //should be getting the normal of the ground at the rez point and using that?
  1516. pos.Z += scale.Z / 2f;
  1517. return pos;
  1518. }
  1519. }
  1520. /// <summary>
  1521. /// Create a New SceneObjectGroup/Part by raycasting
  1522. /// </summary>
  1523. /// <param name="ownerID"></param>
  1524. /// <param name="groupID"></param>
  1525. /// <param name="RayEnd"></param>
  1526. /// <param name="rot"></param>
  1527. /// <param name="shape"></param>
  1528. /// <param name="bypassRaycast"></param>
  1529. /// <param name="RayStart"></param>
  1530. /// <param name="RayTargetID"></param>
  1531. /// <param name="RayEndIsIntersection"></param>
  1532. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1533. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1534. byte RayEndIsIntersection)
  1535. {
  1536. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1537. if (Permissions.CanRezObject(1, ownerID, pos))
  1538. {
  1539. // rez ON the ground, not IN the ground
  1540. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  1541. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1542. }
  1543. }
  1544. public virtual SceneObjectGroup AddNewPrim(
  1545. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1546. {
  1547. //m_log.DebugFormat(
  1548. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1549. SceneObjectGroup sceneObject = null;
  1550. // If an entity creator has been registered for this prim type then use that
  1551. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1552. {
  1553. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1554. }
  1555. else
  1556. {
  1557. // Otherwise, use this default creation code;
  1558. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1559. AddNewSceneObject(sceneObject, true);
  1560. sceneObject.SetGroup(groupID, null);
  1561. }
  1562. sceneObject.ScheduleGroupForFullUpdate();
  1563. return sceneObject;
  1564. }
  1565. /// <summary>
  1566. /// Add an object into the scene that has come from storage
  1567. /// </summary>
  1568. ///
  1569. /// <param name="sceneObject"></param>
  1570. /// <param name="attachToBackup">
  1571. /// If true, changes to the object will be reflected in its persisted data
  1572. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1573. /// </param>
  1574. /// <param name="alreadyPersisted">
  1575. /// If true, we won't persist this object until it changes
  1576. /// If false, we'll persist this object immediately
  1577. /// </param>
  1578. /// <returns>
  1579. /// true if the object was added, false if an object with the same uuid was already in the scene
  1580. /// </returns>
  1581. public bool AddRestoredSceneObject(
  1582. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1583. {
  1584. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted);
  1585. }
  1586. /// <summary>
  1587. /// Add a newly created object to the scene. Updates are also sent to viewers.
  1588. /// </summary>
  1589. /// <param name="sceneObject"></param>
  1590. /// <param name="attachToBackup">
  1591. /// If true, the object is made persistent into the scene.
  1592. /// If false, the object will not persist over server restarts
  1593. /// </param>
  1594. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1595. {
  1596. return AddNewSceneObject(sceneObject, attachToBackup, true);
  1597. }
  1598. /// <summary>
  1599. /// Add a newly created object to the scene
  1600. /// </summary>
  1601. /// <param name="sceneObject"></param>
  1602. /// <param name="attachToBackup">
  1603. /// If true, the object is made persistent into the scene.
  1604. /// If false, the object will not persist over server restarts
  1605. /// </param>
  1606. /// <param name="sendClientUpdates">
  1607. /// If true, updates for the new scene object are sent to all viewers in range.
  1608. /// If false, it is left to the caller to schedule the update
  1609. /// </param>
  1610. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  1611. {
  1612. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates);
  1613. }
  1614. /// <summary>
  1615. /// Delete every object from the scene
  1616. /// </summary>
  1617. public void DeleteAllSceneObjects()
  1618. {
  1619. lock (Entities)
  1620. {
  1621. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1622. foreach (EntityBase e in entities)
  1623. {
  1624. if (e is SceneObjectGroup)
  1625. DeleteSceneObject((SceneObjectGroup)e, false);
  1626. }
  1627. }
  1628. }
  1629. /// <summary>
  1630. /// Synchronously delete the given object from the scene.
  1631. /// </summary>
  1632. /// <param name="group">Object Id</param>
  1633. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  1634. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1635. {
  1636. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  1637. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1638. // Serialise calls to RemoveScriptInstances to avoid
  1639. // deadlocking on m_parts inside SceneObjectGroup
  1640. lock (m_deleting_scene_object)
  1641. {
  1642. group.RemoveScriptInstances(true);
  1643. }
  1644. foreach (SceneObjectPart part in group.Children.Values)
  1645. {
  1646. if (part.IsJoint() && ((part.ObjectFlags&(uint)PrimFlags.Physics) != 0))
  1647. {
  1648. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  1649. }
  1650. else if (part.PhysActor != null)
  1651. {
  1652. PhysicsScene.RemovePrim(part.PhysActor);
  1653. part.PhysActor = null;
  1654. }
  1655. }
  1656. // if (rootPart.PhysActor != null)
  1657. // {
  1658. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1659. // rootPart.PhysActor = null;
  1660. // }
  1661. if (UnlinkSceneObject(group.UUID, false))
  1662. {
  1663. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1664. EventManager.TriggerParcelPrimCountTainted();
  1665. }
  1666. group.DeleteGroup(silent);
  1667. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  1668. }
  1669. /// <summary>
  1670. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1671. /// object itself is not destroyed.
  1672. /// </summary>
  1673. /// <param name="uuid">Id of object.</param>
  1674. /// <returns>true if the object was in the scene, false if it was not</returns>
  1675. /// <param name="softDelete">If true, only deletes from scene, but keeps object in database.</param>
  1676. public bool UnlinkSceneObject(UUID uuid, bool softDelete)
  1677. {
  1678. if (m_sceneGraph.DeleteSceneObject(uuid, softDelete))
  1679. {
  1680. if (!softDelete)
  1681. {
  1682. m_storageManager.DataStore.RemoveObject(uuid,
  1683. m_regInfo.RegionID);
  1684. }
  1685. return true;
  1686. }
  1687. return false;
  1688. }
  1689. /// <summary>
  1690. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1691. /// into.
  1692. ///
  1693. /// This method locates the new region handle and offsets the prim position for the new region
  1694. /// </summary>
  1695. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1696. /// <param name="grp">the scene object that we're crossing</param>
  1697. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1698. {
  1699. if (grp == null)
  1700. return;
  1701. if (grp.IsDeleted)
  1702. return;
  1703. if (grp.RootPart.DIE_AT_EDGE)
  1704. {
  1705. // We remove the object here
  1706. try
  1707. {
  1708. DeleteSceneObject(grp, false);
  1709. }
  1710. catch (Exception)
  1711. {
  1712. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1713. }
  1714. return;
  1715. }
  1716. if (grp.RootPart.RETURN_AT_EDGE)
  1717. {
  1718. // We remove the object here
  1719. try
  1720. {
  1721. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  1722. objects.Add(grp);
  1723. SceneObjectGroup[] objectsArray = objects.ToArray();
  1724. returnObjects(objectsArray, UUID.Zero);
  1725. }
  1726. catch (Exception)
  1727. {
  1728. m_log.Warn("[DATABASE]: exception when trying to return the prim that crossed the border.");
  1729. }
  1730. return;
  1731. }
  1732. int thisx = (int)RegionInfo.RegionLocX;
  1733. int thisy = (int)RegionInfo.RegionLocY;
  1734. Vector3 EastCross = new Vector3(0.1f,0,0);
  1735. Vector3 WestCross = new Vector3(-0.1f, 0, 0);
  1736. Vector3 NorthCross = new Vector3(0, 0.1f, 0);
  1737. Vector3 SouthCross = new Vector3(0, -0.1f, 0);
  1738. // use this if no borders were crossed!
  1739. ulong newRegionHandle
  1740. = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
  1741. (uint)((thisy) * Constants.RegionSize));
  1742. Vector3 pos = attemptedPosition;
  1743. int changeX = 1;
  1744. int changeY = 1;
  1745. if (TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
  1746. {
  1747. if (TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1748. {
  1749. Border crossedBorderx = GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1750. if (crossedBorderx.BorderLine.Z > 0)
  1751. {
  1752. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1753. changeX = (int)(crossedBorderx.BorderLine.Z /(int) Constants.RegionSize);
  1754. }
  1755. else
  1756. pos.X = ((pos.X + Constants.RegionSize));
  1757. Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1758. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1759. if (crossedBordery.BorderLine.Z > 0)
  1760. {
  1761. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1762. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1763. }
  1764. else
  1765. pos.Y = ((pos.Y + Constants.RegionSize));
  1766. newRegionHandle
  1767. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1768. (uint)((thisy - changeY) * Constants.RegionSize));
  1769. // x - 1
  1770. // y - 1
  1771. }
  1772. else if (TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1773. {
  1774. Border crossedBorderx = GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1775. if (crossedBorderx.BorderLine.Z > 0)
  1776. {
  1777. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1778. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1779. }
  1780. else
  1781. pos.X = ((pos.X + Constants.RegionSize));
  1782. Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1783. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1784. try
  1785. {
  1786. if (crossedBordery.BorderLine.Z > 0)
  1787. {
  1788. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1789. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1790. }
  1791. else
  1792. pos.Y = ((pos.Y + Constants.RegionSize));
  1793. newRegionHandle
  1794. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1795. (uint)((thisy + changeY) * Constants.RegionSize));
  1796. // x - 1
  1797. // y + 1
  1798. }
  1799. catch (Exception ex)
  1800. {
  1801. }
  1802. }
  1803. else
  1804. {
  1805. Border crossedBorderx = GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1806. if (crossedBorderx.BorderLine.Z > 0)
  1807. {
  1808. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1809. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1810. }
  1811. else
  1812. pos.X = ((pos.X + Constants.RegionSize));
  1813. newRegionHandle
  1814. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1815. (uint) (thisy*Constants.RegionSize));
  1816. // x - 1
  1817. }
  1818. }
  1819. else if (TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
  1820. {
  1821. if (TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1822. {
  1823. pos.X = ((pos.X - Constants.RegionSize));
  1824. Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1825. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1826. if (crossedBordery.BorderLine.Z > 0)
  1827. {
  1828. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1829. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1830. }
  1831. else
  1832. pos.Y = ((pos.Y + Constants.RegionSize));
  1833. newRegionHandle
  1834. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1835. (uint)((thisy - changeY) * Constants.RegionSize));
  1836. // x + 1
  1837. // y - 1
  1838. }
  1839. else if (TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1840. {
  1841. pos.X = ((pos.X - Constants.RegionSize));
  1842. pos.Y = ((pos.Y - Constants.RegionSize));
  1843. newRegionHandle
  1844. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1845. (uint)((thisy + changeY) * Constants.RegionSize));
  1846. // x + 1
  1847. // y + 1
  1848. }
  1849. else
  1850. {
  1851. pos.X = ((pos.X - Constants.RegionSize));
  1852. newRegionHandle
  1853. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1854. (uint) (thisy*Constants.RegionSize));
  1855. // x + 1
  1856. }
  1857. }
  1858. else if (TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1859. {
  1860. Border crossedBordery = GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1861. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1862. if (crossedBordery.BorderLine.Z > 0)
  1863. {
  1864. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1865. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1866. }
  1867. else
  1868. pos.Y = ((pos.Y + Constants.RegionSize));
  1869. newRegionHandle
  1870. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
  1871. // y - 1
  1872. }
  1873. else if (TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1874. {
  1875. pos.Y = ((pos.Y - Constants.RegionSize));
  1876. newRegionHandle
  1877. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
  1878. // y + 1
  1879. }
  1880. // Offset the positions for the new region across the border
  1881. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1882. grp.OffsetForNewRegion(pos);
  1883. // If we fail to cross the border, then reset the position of the scene object on that border.
  1884. if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
  1885. {
  1886. grp.OffsetForNewRegion(oldGroupPosition);
  1887. grp.ScheduleGroupForFullUpdate();
  1888. }
  1889. }
  1890. public Border GetCrossedBorder(Vector3 position, Cardinals gridline)
  1891. {
  1892. if (BordersLocked)
  1893. {
  1894. switch (gridline)
  1895. {
  1896. case Cardinals.N:
  1897. lock (NorthBorders)
  1898. {
  1899. foreach (Border b in NorthBorders)
  1900. {
  1901. if (b.TestCross(position))
  1902. return b;
  1903. }
  1904. }
  1905. break;
  1906. case Cardinals.S:
  1907. lock (SouthBorders)
  1908. {
  1909. foreach (Border b in SouthBorders)
  1910. {
  1911. if (b.TestCross(position))
  1912. return b;
  1913. }
  1914. }
  1915. break;
  1916. case Cardinals.E:
  1917. lock (EastBorders)
  1918. {
  1919. foreach (Border b in EastBorders)
  1920. {
  1921. if (b.TestCross(position))
  1922. return b;
  1923. }
  1924. }
  1925. break;
  1926. case Cardinals.W:
  1927. lock (WestBorders)
  1928. {
  1929. foreach (Border b in WestBorders)
  1930. {
  1931. if (b.TestCross(position))
  1932. return b;
  1933. }
  1934. }
  1935. break;
  1936. }
  1937. }
  1938. else
  1939. {
  1940. switch (gridline)
  1941. {
  1942. case Cardinals.N:
  1943. foreach (Border b in NorthBorders)
  1944. {
  1945. if (b.TestCross(position))
  1946. return b;
  1947. }
  1948. break;
  1949. case Cardinals.S:
  1950. foreach (Border b in SouthBorders)
  1951. {
  1952. if (b.TestCross(position))
  1953. return b;
  1954. }
  1955. break;
  1956. case Cardinals.E:
  1957. foreach (Border b in EastBorders)
  1958. {
  1959. if (b.TestCross(position))
  1960. return b;
  1961. }
  1962. break;
  1963. case Cardinals.W:
  1964. foreach (Border b in WestBorders)
  1965. {
  1966. if (b.TestCross(position))
  1967. return b;
  1968. }
  1969. break;
  1970. }
  1971. }
  1972. return null;
  1973. }
  1974. public bool TestBorderCross(Vector3 position, Cardinals border)
  1975. {
  1976. if (BordersLocked)
  1977. {
  1978. switch (border)
  1979. {
  1980. case Cardinals.N:
  1981. lock (NorthBorders)
  1982. {
  1983. foreach (Border b in NorthBorders)
  1984. {
  1985. if (b.TestCross(position))
  1986. return true;
  1987. }
  1988. }
  1989. break;
  1990. case Cardinals.E:
  1991. lock (EastBorders)
  1992. {
  1993. foreach (Border b in EastBorders)
  1994. {
  1995. if (b.TestCross(position))
  1996. return true;
  1997. }
  1998. }
  1999. break;
  2000. case Cardinals.S:
  2001. lock (SouthBorders)
  2002. {
  2003. foreach (Border b in SouthBorders)
  2004. {
  2005. if (b.TestCross(position))
  2006. return true;
  2007. }
  2008. }
  2009. break;
  2010. case Cardinals.W:
  2011. lock (WestBorders)
  2012. {
  2013. foreach (Border b in WestBorders)
  2014. {
  2015. if (b.TestCross(position))
  2016. return true;
  2017. }
  2018. }
  2019. break;
  2020. }
  2021. }
  2022. else
  2023. {
  2024. switch (border)
  2025. {
  2026. case Cardinals.N:
  2027. foreach (Border b in NorthBorders)
  2028. {
  2029. if (b.TestCross(position))
  2030. return true;
  2031. }
  2032. break;
  2033. case Cardinals.E:
  2034. foreach (Border b in EastBorders)
  2035. {
  2036. if (b.TestCross(position))
  2037. return true;
  2038. }
  2039. break;
  2040. case Cardinals.S:
  2041. foreach (Border b in SouthBorders)
  2042. {
  2043. if (b.TestCross(position))
  2044. return true;
  2045. }
  2046. break;
  2047. case Cardinals.W:
  2048. foreach (Border b in WestBorders)
  2049. {
  2050. if (b.TestCross(position))
  2051. return true;
  2052. }
  2053. break;
  2054. }
  2055. }
  2056. return false;
  2057. }
  2058. /// <summary>
  2059. /// Move the given scene object into a new region
  2060. /// </summary>
  2061. /// <param name="newRegionHandle"></param>
  2062. /// <param name="grp">Scene Object Group that we're crossing</param>
  2063. /// <returns>
  2064. /// true if the crossing itself was successful, false on failure
  2065. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  2066. /// </returns>
  2067. public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
  2068. {
  2069. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  2070. bool successYN = false;
  2071. grp.RootPart.UpdateFlag = 0;
  2072. //int primcrossingXMLmethod = 0;
  2073. if (newRegionHandle != 0)
  2074. {
  2075. //string objectState = grp.GetStateSnapshot();
  2076. //successYN
  2077. // = m_sceneGridService.PrimCrossToNeighboringRegion(
  2078. // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  2079. //if (successYN && (objectState != "") && m_allowScriptCrossings)
  2080. //{
  2081. // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  2082. // newRegionHandle, grp.UUID, objectState, 100);
  2083. //}
  2084. // And the new channel...
  2085. if (m_interregionCommsOut != null)
  2086. successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
  2087. if (successYN)
  2088. {
  2089. // We remove the object here
  2090. try
  2091. {
  2092. DeleteSceneObject(grp, silent);
  2093. }
  2094. catch (Exception e)
  2095. {
  2096. m_log.ErrorFormat(
  2097. "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  2098. grp, e);
  2099. }
  2100. }
  2101. else
  2102. {
  2103. if (!grp.IsDeleted)
  2104. {
  2105. if (grp.RootPart.PhysActor != null)
  2106. {
  2107. grp.RootPart.PhysActor.CrossingFailure();
  2108. }
  2109. }
  2110. m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
  2111. }
  2112. }
  2113. else
  2114. {
  2115. m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
  2116. }
  2117. return successYN;
  2118. }
  2119. /// <summary>
  2120. /// Called when objects or attachments cross the border between regions.
  2121. /// </summary>
  2122. /// <param name="sog"></param>
  2123. /// <returns></returns>
  2124. public bool IncomingCreateObject(ISceneObject sog)
  2125. {
  2126. //m_log.Debug(" >>> IncomingCreateObject(sog) <<< " + ((SceneObjectGroup)sog).AbsolutePosition + " deleted? " + ((SceneObjectGroup)sog).IsDeleted);
  2127. SceneObjectGroup newObject;
  2128. try
  2129. {
  2130. newObject = (SceneObjectGroup)sog;
  2131. }
  2132. catch (Exception e)
  2133. {
  2134. m_log.WarnFormat("[SCENE]: Problem casting object: {0}", e.Message);
  2135. return false;
  2136. }
  2137. if (!AddSceneObject(newObject))
  2138. {
  2139. m_log.DebugFormat("[SCENE]: Problem adding scene object {0} in {1} ", sog.UUID, RegionInfo.RegionName);
  2140. return false;
  2141. }
  2142. newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  2143. // Do this as late as possible so that listeners have full access to the incoming object
  2144. EventManager.TriggerOnIncomingSceneObject(newObject);
  2145. return true;
  2146. }
  2147. /// <summary>
  2148. /// Attachment rezzing
  2149. /// </summary>
  2150. /// <param name="userID">Agent Unique ID</param>
  2151. /// <param name="itemID">Object ID</param>
  2152. /// <returns>False</returns>
  2153. public virtual bool IncomingCreateObject(UUID userID, UUID itemID)
  2154. {
  2155. //m_log.DebugFormat(" >>> IncomingCreateObject(userID, itemID) <<< {0} {1}", userID, itemID);
  2156. ScenePresence sp = GetScenePresence(userID);
  2157. if (sp != null)
  2158. {
  2159. uint attPt = (uint)sp.Appearance.GetAttachpoint(itemID);
  2160. m_sceneGraph.RezSingleAttachment(sp.ControllingClient, itemID, attPt);
  2161. }
  2162. return false;
  2163. }
  2164. /// <summary>
  2165. /// Adds a Scene Object group to the Scene.
  2166. /// Verifies that the creator of the object is not banned from the simulator.
  2167. /// Checks if the item is an Attachment
  2168. /// </summary>
  2169. /// <param name="sceneObject"></param>
  2170. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2171. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2172. {
  2173. // If the user is banned, we won't let any of their objects
  2174. // enter. Period.
  2175. //
  2176. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  2177. {
  2178. m_log.Info("[INTERREGION]: Denied prim crossing for " +
  2179. "banned avatar");
  2180. return false;
  2181. }
  2182. // Force allocation of new LocalId
  2183. //
  2184. foreach (SceneObjectPart p in sceneObject.Children.Values)
  2185. p.LocalId = 0;
  2186. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2187. {
  2188. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2189. sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
  2190. AddRestoredSceneObject(sceneObject, false, false);
  2191. // Handle attachment special case
  2192. SceneObjectPart RootPrim = sceneObject.RootPart;
  2193. // Fix up attachment Parent Local ID
  2194. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2195. //uint parentLocalID = 0;
  2196. if (sp != null)
  2197. {
  2198. //parentLocalID = sp.LocalId;
  2199. //sceneObject.RootPart.IsAttachment = true;
  2200. //sceneObject.RootPart.SetParentLocalId(parentLocalID);
  2201. SceneObjectGroup grp = sceneObject;
  2202. //RootPrim.SetParentLocalId(parentLocalID);
  2203. m_log.DebugFormat(
  2204. "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.GetFromItemID(), grp.UUID);
  2205. //grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  2206. m_log.DebugFormat(
  2207. "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2208. AttachObject(
  2209. sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition, false);
  2210. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2211. grp.SendGroupFullUpdate();
  2212. }
  2213. else
  2214. {
  2215. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2216. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2217. }
  2218. }
  2219. else
  2220. {
  2221. AddRestoredSceneObject(sceneObject, true, false);
  2222. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  2223. true, sceneObject.AbsolutePosition))
  2224. {
  2225. // Deny non attachments based on parcel settings
  2226. //
  2227. m_log.Info("[INTERREGION]: Denied prim crossing " +
  2228. "because of parcel settings");
  2229. DeleteSceneObject(sceneObject, false);
  2230. return false;
  2231. }
  2232. }
  2233. return true;
  2234. }
  2235. #endregion
  2236. #region Add/Remove Avatar Methods
  2237. /// <summary>
  2238. /// Adding a New Client and Create a Presence for it.
  2239. /// </summary>
  2240. /// <param name="client"></param>
  2241. public override void AddNewClient(IClientAPI client)
  2242. {
  2243. m_clientManager.Add(client);
  2244. CheckHeartbeat();
  2245. SubscribeToClientEvents(client);
  2246. ScenePresence presence;
  2247. if (m_restorePresences.ContainsKey(client.AgentId))
  2248. {
  2249. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  2250. presence = m_restorePresences[client.AgentId];
  2251. m_restorePresences.Remove(client.AgentId);
  2252. // This is one of two paths to create avatars that are
  2253. // used. This tends to get called more in standalone
  2254. // than grid, not really sure why, but as such needs
  2255. // an explicity appearance lookup here.
  2256. AvatarAppearance appearance = null;
  2257. GetAvatarAppearance(client, out appearance);
  2258. presence.Appearance = appearance;
  2259. presence.initializeScenePresence(client, RegionInfo, this);
  2260. m_sceneGraph.AddScenePresence(presence);
  2261. lock (m_restorePresences)
  2262. {
  2263. Monitor.PulseAll(m_restorePresences);
  2264. }
  2265. }
  2266. else
  2267. {
  2268. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2269. m_log.Debug("[Scene] Adding new agent " + client.Name + " to scene " + RegionInfo.RegionName);
  2270. /*
  2271. string logMsg = string.Format("[SCENE]: Adding new {0} agent for {1} in {2}",
  2272. ((aCircuit.child == true) ? "child" : "root"), client.Name,
  2273. RegionInfo.RegionName);
  2274. m_log.Debug(logMsg);
  2275. */
  2276. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  2277. ScenePresence sp = CreateAndAddScenePresence(client);
  2278. // HERE!!! Do the initial attachments right here
  2279. // first agent upon login is a root agent by design.
  2280. // All other AddNewClient calls find aCircuit.child to be true
  2281. if (aCircuit == null || aCircuit.child == false)
  2282. {
  2283. sp.IsChildAgent = false;
  2284. Util.FireAndForget(delegate(object o) { sp.RezAttachments(); });
  2285. }
  2286. }
  2287. m_LastLogin = Util.EnvironmentTickCount();
  2288. EventManager.TriggerOnNewClient(client);
  2289. }
  2290. /// <summary>
  2291. /// Register for events from the client
  2292. /// </summary>
  2293. /// <param name="client">The IClientAPI of the connected client</param>
  2294. public virtual void SubscribeToClientEvents(IClientAPI client)
  2295. {
  2296. SubscribeToClientTerrainEvents(client);
  2297. SubscribeToClientPrimEvents(client);
  2298. SubscribeToClientPrimRezEvents(client);
  2299. SubscribeToClientInventoryEvents(client);
  2300. SubscribeToClientAttachmentEvents(client);
  2301. SubscribeToClientTeleportEvents(client);
  2302. SubscribeToClientScriptEvents(client);
  2303. SubscribeToClientParcelEvents(client);
  2304. SubscribeToClientGridEvents(client);
  2305. SubscribeToClientGodEvents(client);
  2306. SubscribeToClientNetworkEvents(client);
  2307. // EventManager.TriggerOnNewClient(client);
  2308. }
  2309. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2310. {
  2311. client.OnRegionHandShakeReply += SendLayerData;
  2312. client.OnUnackedTerrain += TerrainUnAcked;
  2313. }
  2314. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2315. {
  2316. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  2317. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2318. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  2319. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  2320. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2321. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2322. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2323. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2324. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2325. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2326. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2327. client.OnObjectRequest += RequestPrim;
  2328. client.OnObjectSelect += SelectPrim;
  2329. client.OnObjectDeselect += DeselectPrim;
  2330. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  2331. client.OnSpinStart += m_sceneGraph.SpinStart;
  2332. client.OnSpinUpdate += m_sceneGraph.SpinObject;
  2333. client.OnDeRezObject += DeRezObject;
  2334. client.OnObjectName += m_sceneGraph.PrimName;
  2335. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2336. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2337. client.OnLinkObjects += m_sceneGraph.LinkObjects;
  2338. client.OnDelinkObjects += m_sceneGraph.DelinkObjects;
  2339. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  2340. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2341. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2342. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2343. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2344. client.OnGrabObject += ProcessObjectGrab;
  2345. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2346. client.OnDeGrabObject += ProcessObjectDeGrab;
  2347. client.OnUndo += m_sceneGraph.HandleUndo;
  2348. client.OnRedo += m_sceneGraph.HandleRedo;
  2349. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2350. client.OnObjectDrop += m_sceneGraph.DropObject;
  2351. client.OnObjectSaleInfo += ObjectSaleInfo;
  2352. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2353. client.OnObjectOwner += ObjectOwner;
  2354. }
  2355. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2356. {
  2357. client.OnAddPrim += AddNewPrim;
  2358. client.OnRezObject += RezObject;
  2359. }
  2360. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2361. {
  2362. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  2363. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2364. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2365. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2366. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2367. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2368. client.OnFetchInventory += HandleFetchInventory;
  2369. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2370. client.OnCopyInventoryItem += CopyInventoryItem;
  2371. client.OnMoveInventoryItem += MoveInventoryItem;
  2372. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2373. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2374. client.OnRezScript += RezScript;
  2375. client.OnRequestTaskInventory += RequestTaskInventory;
  2376. client.OnRemoveTaskItem += RemoveTaskInventory;
  2377. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2378. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2379. }
  2380. public virtual void SubscribeToClientAttachmentEvents(IClientAPI client)
  2381. {
  2382. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  2383. client.OnRezMultipleAttachmentsFromInv += RezMultipleAttachments;
  2384. client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv;
  2385. client.OnObjectAttach += m_sceneGraph.AttachObject;
  2386. client.OnObjectDetach += m_sceneGraph.DetachObject;
  2387. }
  2388. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2389. {
  2390. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2391. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  2392. client.OnTeleportHomeRequest += TeleportClientHome;
  2393. }
  2394. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2395. {
  2396. client.OnScriptReset += ProcessScriptReset;
  2397. client.OnGetScriptRunning += GetScriptRunning;
  2398. client.OnSetScriptRunning += SetScriptRunning;
  2399. }
  2400. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2401. {
  2402. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  2403. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2404. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2405. client.OnParcelBuy += ProcessParcelBuy;
  2406. }
  2407. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2408. {
  2409. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  2410. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2411. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  2412. client.OnSetStartLocationRequest += SetHomeRezPoint;
  2413. client.OnRegionHandleRequest += RegionHandleRequest;
  2414. }
  2415. public virtual void SubscribeToClientGodEvents(IClientAPI client)
  2416. {
  2417. IGodsModule godsModule = RequestModuleInterface<IGodsModule>();
  2418. client.OnGodKickUser += godsModule.KickUser;
  2419. client.OnRequestGodlikePowers += godsModule.RequestGodlikePowers;
  2420. }
  2421. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2422. {
  2423. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2424. client.OnViewerEffect += ProcessViewerEffect;
  2425. }
  2426. protected virtual void UnsubscribeToClientEvents(IClientAPI client)
  2427. {
  2428. }
  2429. /// <summary>
  2430. /// Register for events from the client
  2431. /// </summary>
  2432. /// <param name="client">The IClientAPI of the connected client</param>
  2433. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2434. {
  2435. UnSubscribeToClientTerrainEvents(client);
  2436. UnSubscribeToClientPrimEvents(client);
  2437. UnSubscribeToClientPrimRezEvents(client);
  2438. UnSubscribeToClientInventoryEvents(client);
  2439. UnSubscribeToClientAttachmentEvents(client);
  2440. UnSubscribeToClientTeleportEvents(client);
  2441. UnSubscribeToClientScriptEvents(client);
  2442. UnSubscribeToClientParcelEvents(client);
  2443. UnSubscribeToClientGridEvents(client);
  2444. UnSubscribeToClientGodEvents(client);
  2445. UnSubscribeToClientNetworkEvents(client);
  2446. // EventManager.TriggerOnNewClient(client);
  2447. }
  2448. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2449. {
  2450. client.OnRegionHandShakeReply -= SendLayerData;
  2451. client.OnUnackedTerrain -= TerrainUnAcked;
  2452. }
  2453. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2454. {
  2455. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimPosition;
  2456. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2457. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimRotation;
  2458. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimRotation;
  2459. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2460. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2461. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2462. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2463. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2464. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2465. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2466. client.OnObjectRequest -= RequestPrim;
  2467. client.OnObjectSelect -= SelectPrim;
  2468. client.OnObjectDeselect -= DeselectPrim;
  2469. client.OnGrabUpdate -= m_sceneGraph.MoveObject;
  2470. client.OnSpinStart -= m_sceneGraph.SpinStart;
  2471. client.OnSpinUpdate -= m_sceneGraph.SpinObject;
  2472. client.OnDeRezObject -= DeRezObject;
  2473. client.OnObjectName -= m_sceneGraph.PrimName;
  2474. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2475. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2476. client.OnLinkObjects -= m_sceneGraph.LinkObjects;
  2477. client.OnDelinkObjects -= m_sceneGraph.DelinkObjects;
  2478. client.OnObjectDuplicate -= m_sceneGraph.DuplicateObject;
  2479. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2480. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2481. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2482. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2483. client.OnGrabObject -= ProcessObjectGrab;
  2484. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2485. client.OnUndo -= m_sceneGraph.HandleUndo;
  2486. client.OnRedo -= m_sceneGraph.HandleRedo;
  2487. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2488. client.OnObjectDrop -= m_sceneGraph.DropObject;
  2489. client.OnObjectSaleInfo -= ObjectSaleInfo;
  2490. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2491. client.OnObjectOwner -= ObjectOwner;
  2492. }
  2493. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2494. {
  2495. client.OnAddPrim -= AddNewPrim;
  2496. client.OnRezObject -= RezObject;
  2497. }
  2498. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2499. {
  2500. client.OnCreateNewInventoryItem -= CreateNewInventoryItem;
  2501. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2502. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  2503. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  2504. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  2505. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  2506. client.OnFetchInventory -= HandleFetchInventory;
  2507. client.OnUpdateInventoryItem -= UpdateInventoryItemAsset;
  2508. client.OnCopyInventoryItem -= CopyInventoryItem;
  2509. client.OnMoveInventoryItem -= MoveInventoryItem;
  2510. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  2511. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  2512. client.OnRezScript -= RezScript;
  2513. client.OnRequestTaskInventory -= RequestTaskInventory;
  2514. client.OnRemoveTaskItem -= RemoveTaskInventory;
  2515. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  2516. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  2517. }
  2518. public virtual void UnSubscribeToClientAttachmentEvents(IClientAPI client)
  2519. {
  2520. client.OnRezSingleAttachmentFromInv -= RezSingleAttachment;
  2521. client.OnRezMultipleAttachmentsFromInv -= RezMultipleAttachments;
  2522. client.OnDetachAttachmentIntoInv -= DetachSingleAttachmentToInv;
  2523. client.OnObjectAttach -= m_sceneGraph.AttachObject;
  2524. client.OnObjectDetach -= m_sceneGraph.DetachObject;
  2525. }
  2526. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  2527. {
  2528. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  2529. client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  2530. client.OnTeleportHomeRequest -= TeleportClientHome;
  2531. }
  2532. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  2533. {
  2534. client.OnScriptReset -= ProcessScriptReset;
  2535. client.OnGetScriptRunning -= GetScriptRunning;
  2536. client.OnSetScriptRunning -= SetScriptRunning;
  2537. }
  2538. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  2539. {
  2540. client.OnObjectGroupRequest -= m_sceneGraph.HandleObjectGroupUpdate;
  2541. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  2542. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  2543. client.OnParcelBuy -= ProcessParcelBuy;
  2544. }
  2545. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  2546. {
  2547. client.OnNameFromUUIDRequest -= CommsManager.HandleUUIDNameRequest;
  2548. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  2549. client.OnAvatarPickerRequest -= ProcessAvatarPickerRequest;
  2550. client.OnSetStartLocationRequest -= SetHomeRezPoint;
  2551. client.OnRegionHandleRequest -= RegionHandleRequest;
  2552. }
  2553. public virtual void UnSubscribeToClientGodEvents(IClientAPI client)
  2554. {
  2555. IGodsModule godsModule = RequestModuleInterface<IGodsModule>();
  2556. client.OnGodKickUser -= godsModule.KickUser;
  2557. client.OnRequestGodlikePowers -= godsModule.RequestGodlikePowers;
  2558. }
  2559. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  2560. {
  2561. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  2562. client.OnViewerEffect -= ProcessViewerEffect;
  2563. }
  2564. /// <summary>
  2565. /// Teleport an avatar to their home region
  2566. /// </summary>
  2567. /// <param name="agentId">The avatar's Unique ID</param>
  2568. /// <param name="client">The IClientAPI for the client</param>
  2569. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  2570. {
  2571. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId);
  2572. if (UserProfile != null)
  2573. {
  2574. GridRegion regionInfo = GridService.GetRegionByUUID(UUID.Zero, UserProfile.HomeRegionID);
  2575. if (regionInfo == null)
  2576. {
  2577. uint x = 0, y = 0;
  2578. Utils.LongToUInts(UserProfile.HomeRegion, out x, out y);
  2579. regionInfo = GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
  2580. if (regionInfo != null) // home region can be away temporarily, too
  2581. {
  2582. UserProfile.HomeRegionID = regionInfo.RegionID;
  2583. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2584. }
  2585. }
  2586. if (regionInfo == null)
  2587. {
  2588. // can't find the Home region: Tell viewer and abort
  2589. client.SendTeleportFailed("Your home-region could not be found.");
  2590. return;
  2591. }
  2592. RequestTeleportLocation(
  2593. client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
  2594. (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
  2595. }
  2596. }
  2597. /// <summary>
  2598. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  2599. /// RayEnd and RayStart to determine what the angle of the ray is
  2600. /// </summary>
  2601. /// <param name="localID">ID of object to duplicate</param>
  2602. /// <param name="dupeFlags"></param>
  2603. /// <param name="AgentID">Agent doing the duplication</param>
  2604. /// <param name="GroupID">Group of new object</param>
  2605. /// <param name="RayTargetObj">The target of the Ray</param>
  2606. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  2607. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  2608. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  2609. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  2610. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  2611. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  2612. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  2613. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  2614. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  2615. {
  2616. Vector3 pos;
  2617. const bool frontFacesOnly = true;
  2618. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  2619. SceneObjectPart target = GetSceneObjectPart(localID);
  2620. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  2621. if (target != null && target2 != null)
  2622. {
  2623. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  2624. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  2625. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  2626. if (target2.ParentGroup != null)
  2627. {
  2628. pos = target2.AbsolutePosition;
  2629. //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());
  2630. // TODO: Raytrace better here
  2631. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  2632. Ray NewRay = new Ray(AXOrigin, AXdirection);
  2633. // Ray Trace against target here
  2634. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  2635. // Un-comment out the following line to Get Raytrace results printed to the console.
  2636. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2637. float ScaleOffset = 0.5f;
  2638. // If we hit something
  2639. if (ei.HitTF)
  2640. {
  2641. Vector3 scale = target.Scale;
  2642. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  2643. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2644. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2645. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2646. ScaleOffset = Math.Abs(ScaleOffset);
  2647. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2648. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  2649. Vector3 offset = normal * (ScaleOffset / 2f);
  2650. pos = intersectionpoint + offset;
  2651. // stick in offset format from the original prim
  2652. pos = pos - target.ParentGroup.AbsolutePosition;
  2653. if (CopyRotates)
  2654. {
  2655. Quaternion worldRot = target2.GetWorldRotation();
  2656. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2657. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2658. //obj.Rotation = worldRot;
  2659. //obj.UpdateGroupRotationR(worldRot);
  2660. }
  2661. else
  2662. {
  2663. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  2664. }
  2665. }
  2666. return;
  2667. }
  2668. return;
  2669. }
  2670. }
  2671. /// <summary>
  2672. /// Sets the Home Point. The GridService uses this to know where to put a user when they log-in
  2673. /// </summary>
  2674. /// <param name="remoteClient"></param>
  2675. /// <param name="regionHandle"></param>
  2676. /// <param name="position"></param>
  2677. /// <param name="lookAt"></param>
  2678. /// <param name="flags"></param>
  2679. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  2680. {
  2681. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  2682. if (UserProfile != null)
  2683. {
  2684. // I know I'm ignoring the regionHandle provided by the teleport location request.
  2685. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  2686. UserProfile.HomeRegionID = RegionInfo.RegionID;
  2687. // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
  2688. // TODO: The HomeRegion property can be removed then, too
  2689. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  2690. UserProfile.HomeLocation = position;
  2691. UserProfile.HomeLookAt = lookAt;
  2692. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2693. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  2694. m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
  2695. }
  2696. else
  2697. {
  2698. m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed.");
  2699. }
  2700. }
  2701. /// <summary>
  2702. /// Create a child agent scene presence and add it to this scene.
  2703. /// </summary>
  2704. /// <param name="client"></param>
  2705. /// <returns></returns>
  2706. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  2707. {
  2708. CheckHeartbeat();
  2709. AvatarAppearance appearance = null;
  2710. GetAvatarAppearance(client, out appearance);
  2711. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  2712. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  2713. m_eventManager.TriggerOnNewPresence(avatar);
  2714. return avatar;
  2715. }
  2716. /// <summary>
  2717. /// Get the avatar apperance for the given client.
  2718. /// </summary>
  2719. /// <param name="client"></param>
  2720. /// <param name="appearance"></param>
  2721. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2722. {
  2723. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2724. if (aCircuit == null)
  2725. {
  2726. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  2727. appearance = new AvatarAppearance(client.AgentId);
  2728. return;
  2729. }
  2730. appearance = aCircuit.Appearance;
  2731. if (appearance == null)
  2732. {
  2733. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  2734. appearance = new AvatarAppearance(client.AgentId);
  2735. }
  2736. }
  2737. /// <summary>
  2738. /// Remove the given client from the scene.
  2739. /// </summary>
  2740. /// <param name="agentID"></param>
  2741. public override void RemoveClient(UUID agentID)
  2742. {
  2743. CheckHeartbeat();
  2744. bool childagentYN = false;
  2745. ScenePresence avatar = GetScenePresence(agentID);
  2746. if (avatar != null)
  2747. {
  2748. childagentYN = avatar.IsChildAgent;
  2749. if (avatar.ParentID != 0)
  2750. {
  2751. avatar.StandUp();
  2752. }
  2753. try
  2754. {
  2755. m_log.DebugFormat(
  2756. "[SCENE]: Removing {0} agent {1} from region {2}",
  2757. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  2758. m_sceneGraph.removeUserCount(!childagentYN);
  2759. CapsModule.RemoveCapsHandler(agentID);
  2760. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  2761. {
  2762. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  2763. }
  2764. if (!avatar.IsChildAgent)
  2765. {
  2766. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
  2767. //List<ulong> childknownRegions = new List<ulong>();
  2768. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  2769. //for (int i = 0; i < ckn.Count; i++)
  2770. //{
  2771. // childknownRegions.Add(ckn[i]);
  2772. //}
  2773. List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
  2774. regions.Remove(RegionInfo.RegionHandle);
  2775. m_sceneGridService.SendCloseChildAgentConnections(agentID, regions);
  2776. }
  2777. m_eventManager.TriggerClientClosed(agentID, this);
  2778. }
  2779. catch (NullReferenceException)
  2780. {
  2781. // We don't know which count to remove it from
  2782. // Avatar is already disposed :/
  2783. }
  2784. m_eventManager.TriggerOnRemovePresence(agentID);
  2785. ForEachClient(
  2786. delegate(IClientAPI client)
  2787. {
  2788. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  2789. try { client.SendKillObject(avatar.RegionHandle, avatar.LocalId); }
  2790. catch (NullReferenceException) { }
  2791. });
  2792. ForEachScenePresence(
  2793. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2794. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  2795. if (agentTransactions != null)
  2796. {
  2797. agentTransactions.RemoveAgentAssetTransactions(agentID);
  2798. }
  2799. // Remove the avatar from the scene
  2800. m_sceneGraph.RemoveScenePresence(agentID);
  2801. m_clientManager.Remove(agentID);
  2802. try
  2803. {
  2804. avatar.Close();
  2805. }
  2806. catch (NullReferenceException)
  2807. {
  2808. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2809. }
  2810. catch (Exception e)
  2811. {
  2812. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  2813. }
  2814. // Remove client agent from profile, so new logins will work
  2815. if (!childagentYN)
  2816. {
  2817. m_sceneGridService.ClearUserAgent(agentID);
  2818. }
  2819. m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
  2820. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2821. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2822. }
  2823. }
  2824. /// <summary>
  2825. /// Removes region from an avatar's known region list. This coincides with child agents. For each child agent, there will be a known region entry.
  2826. ///
  2827. /// </summary>
  2828. /// <param name="avatarID"></param>
  2829. /// <param name="regionslst"></param>
  2830. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2831. {
  2832. ScenePresence av = GetScenePresence(avatarID);
  2833. if (av != null)
  2834. {
  2835. lock (av)
  2836. {
  2837. for (int i = 0; i < regionslst.Count; i++)
  2838. {
  2839. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2840. }
  2841. }
  2842. }
  2843. }
  2844. /// <summary>
  2845. /// Inform all other ScenePresences on this Scene that someone else has changed position on the minimap.
  2846. /// </summary>
  2847. public void NotifyMyCoarseLocationChange()
  2848. {
  2849. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2850. }
  2851. #endregion
  2852. #region Entities
  2853. public void SendKillObject(uint localID)
  2854. {
  2855. SceneObjectPart part = GetSceneObjectPart(localID);
  2856. if (part != null) // It is a prim
  2857. {
  2858. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2859. {
  2860. if (part.ParentGroup.RootPart != part) // Child part
  2861. return;
  2862. }
  2863. }
  2864. ForEachClient(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2865. }
  2866. #endregion
  2867. #region RegionComms
  2868. /// <summary>
  2869. /// Register the methods that should be invoked when this scene receives various incoming events
  2870. /// </summary>
  2871. public void RegisterCommsEvents()
  2872. {
  2873. m_sceneGridService.OnExpectUser += HandleNewUserConnection;
  2874. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2875. m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent;
  2876. //m_eventManager.OnRegionUp += OtherRegionUp;
  2877. //m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2878. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2879. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2880. m_sceneGridService.KiPrimitive += SendKillObject;
  2881. m_sceneGridService.OnGetLandData += GetLandData;
  2882. if (m_interregionCommsIn != null)
  2883. {
  2884. m_log.Debug("[SCENE]: Registering with InterregionCommsIn");
  2885. m_interregionCommsIn.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2886. }
  2887. else
  2888. m_log.Debug("[SCENE]: Unable to register with InterregionCommsIn");
  2889. }
  2890. /// <summary>
  2891. /// Deregister this scene from receiving incoming region events
  2892. /// </summary>
  2893. public void UnRegisterRegionWithComms()
  2894. {
  2895. m_sceneGridService.KiPrimitive -= SendKillObject;
  2896. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2897. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2898. //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2899. //m_eventManager.OnRegionUp -= OtherRegionUp;
  2900. m_sceneGridService.OnExpectUser -= HandleNewUserConnection;
  2901. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2902. m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
  2903. m_sceneGridService.OnGetLandData -= GetLandData;
  2904. if (m_interregionCommsIn != null)
  2905. m_interregionCommsIn.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2906. // this does nothing; should be removed
  2907. m_sceneGridService.Close();
  2908. if (!GridService.DeregisterRegion(m_regInfo.RegionID))
  2909. m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", m_regInfo.RegionName);
  2910. }
  2911. /// <summary>
  2912. /// A handler for the SceneCommunicationService event, to match that events return type of void.
  2913. /// Use NewUserConnection() directly if possible so the return type can refuse connections.
  2914. /// At the moment nothing actually seems to use this event,
  2915. /// as everything is switching to calling the NewUserConnection method directly.
  2916. ///
  2917. /// Now obsoleting this because it doesn't handle teleportFlags propertly
  2918. ///
  2919. /// </summary>
  2920. /// <param name="agent"></param>
  2921. [Obsolete("Please call NewUserConnection directly.")]
  2922. public void HandleNewUserConnection(AgentCircuitData agent)
  2923. {
  2924. string reason;
  2925. NewUserConnection(agent, 0, out reason);
  2926. }
  2927. /// <summary>
  2928. /// Do the work necessary to initiate a new user connection for a particular scene.
  2929. /// At the moment, this consists of setting up the caps infrastructure
  2930. /// The return bool should allow for connections to be refused, but as not all calling paths
  2931. /// take proper notice of it let, we allowed banned users in still.
  2932. /// </summary>
  2933. /// <param name="agent">CircuitData of the agent who is connecting</param>
  2934. /// <param name="reason">Outputs the reason for the false response on this string</param>
  2935. /// <returns>True if the region accepts this agent. False if it does not. False will
  2936. /// also return a reason.</returns>
  2937. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason)
  2938. {
  2939. //Teleport flags:
  2940. //
  2941. // TeleportFlags.ViaGodlikeLure - Border Crossing
  2942. // TeleportFlags.ViaLogin - Login
  2943. // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
  2944. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  2945. if (LoginsDisabled)
  2946. {
  2947. reason = "Logins Disabled";
  2948. return false;
  2949. }
  2950. // Don't disable this log message - it's too helpful
  2951. m_log.InfoFormat(
  2952. "[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, teleportflags {6})",
  2953. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2954. agent.AgentID, agent.circuitcode, teleportFlags);
  2955. reason = String.Empty;
  2956. if (!AuthenticateUser(agent, out reason))
  2957. return false;
  2958. if (!AuthorizeUser(agent, out reason))
  2959. return false;
  2960. m_log.InfoFormat(
  2961. "[CONNECTION BEGIN]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  2962. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2963. agent.AgentID, agent.circuitcode);
  2964. CapsModule.NewUserConnection(agent);
  2965. ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID);
  2966. if (sp != null)
  2967. {
  2968. m_log.DebugFormat(
  2969. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  2970. agent.AgentID, RegionInfo.RegionName);
  2971. sp.AdjustKnownSeeds();
  2972. return true;
  2973. }
  2974. CapsModule.AddCapsHandler(agent.AgentID);
  2975. if (!agent.child)
  2976. {
  2977. if (TestBorderCross(agent.startpos,Cardinals.E))
  2978. {
  2979. Border crossedBorder = GetCrossedBorder(agent.startpos, Cardinals.E);
  2980. agent.startpos.X = crossedBorder.BorderLine.Z - 1;
  2981. }
  2982. if (TestBorderCross(agent.startpos, Cardinals.N))
  2983. {
  2984. Border crossedBorder = GetCrossedBorder(agent.startpos, Cardinals.N);
  2985. agent.startpos.Y = crossedBorder.BorderLine.Z - 1;
  2986. }
  2987. //Mitigate http://opensimulator.org/mantis/view.php?id=3522
  2988. // Check if start position is outside of region
  2989. // If it is, check the Z start position also.. if not, leave it alone.
  2990. if (BordersLocked)
  2991. {
  2992. lock (EastBorders)
  2993. {
  2994. if (agent.startpos.X > EastBorders[0].BorderLine.Z)
  2995. {
  2996. m_log.Warn("FIX AGENT POSITION");
  2997. agent.startpos.X = EastBorders[0].BorderLine.Z * 0.5f;
  2998. if (agent.startpos.Z > 720)
  2999. agent.startpos.Z = 720;
  3000. }
  3001. }
  3002. lock (NorthBorders)
  3003. {
  3004. if (agent.startpos.Y > NorthBorders[0].BorderLine.Z)
  3005. {
  3006. m_log.Warn("FIX Agent POSITION");
  3007. agent.startpos.Y = NorthBorders[0].BorderLine.Z * 0.5f;
  3008. if (agent.startpos.Z > 720)
  3009. agent.startpos.Z = 720;
  3010. }
  3011. }
  3012. }
  3013. else
  3014. {
  3015. if (agent.startpos.X > EastBorders[0].BorderLine.Z)
  3016. {
  3017. m_log.Warn("FIX AGENT POSITION");
  3018. agent.startpos.X = EastBorders[0].BorderLine.Z * 0.5f;
  3019. if (agent.startpos.Z > 720)
  3020. agent.startpos.Z = 720;
  3021. }
  3022. if (agent.startpos.Y > NorthBorders[0].BorderLine.Z)
  3023. {
  3024. m_log.Warn("FIX Agent POSITION");
  3025. agent.startpos.Y = NorthBorders[0].BorderLine.Z * 0.5f;
  3026. if (agent.startpos.Z > 720)
  3027. agent.startpos.Z = 720;
  3028. }
  3029. }
  3030. // Honor parcel landing type and position.
  3031. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  3032. if (land != null)
  3033. {
  3034. if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
  3035. {
  3036. agent.startpos = land.LandData.UserLocation;
  3037. }
  3038. }
  3039. }
  3040. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  3041. // rewrite session_id
  3042. CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID);
  3043. if (userinfo != null)
  3044. {
  3045. userinfo.SessionID = agent.SessionID;
  3046. }
  3047. else
  3048. {
  3049. m_log.WarnFormat(
  3050. "[CONNECTION BEGIN]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID);
  3051. }
  3052. return true;
  3053. }
  3054. /// <summary>
  3055. /// Verifies that the user has a session on the Grid
  3056. /// </summary>
  3057. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3058. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3059. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3060. /// also return a reason.</returns>
  3061. public virtual bool AuthenticateUser(AgentCircuitData agent, out string reason)
  3062. {
  3063. reason = String.Empty;
  3064. bool result = CommsManager.UserService.VerifySession(agent.AgentID, agent.SessionID);
  3065. m_log.Debug("[CONNECTION BEGIN]: User authentication returned " + result);
  3066. if (!result)
  3067. reason = String.Format("Failed to authenticate user {0} {1}, access denied.", agent.firstname, agent.lastname);
  3068. return result;
  3069. }
  3070. /// <summary>
  3071. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3072. /// </summary>
  3073. /// <param name="agent">The circuit data for the agent</param>
  3074. /// <param name="reason">outputs the reason to this string</param>
  3075. /// <returns>True if the region accepts this agent. False if it does not. False will
  3076. /// also return a reason.</returns>
  3077. protected virtual bool AuthorizeUser(AgentCircuitData agent, out string reason)
  3078. {
  3079. reason = String.Empty;
  3080. if (!m_strictAccessControl) return true;
  3081. if (Permissions.IsGod(agent.AgentID)) return true;
  3082. if (AuthorizationService != null)
  3083. {
  3084. if (!AuthorizationService.IsAuthorizedForRegion(agent.AgentID.ToString(), RegionInfo.RegionID.ToString(),out reason))
  3085. {
  3086. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  3087. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3088. //reason = String.Format("You are not currently on the access list for {0}",RegionInfo.RegionName);
  3089. return false;
  3090. }
  3091. }
  3092. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  3093. {
  3094. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3095. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3096. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  3097. RegionInfo.RegionName);
  3098. return false;
  3099. }
  3100. IGroupsModule groupsModule =
  3101. RequestModuleInterface<IGroupsModule>();
  3102. List<UUID> agentGroups = new List<UUID>();
  3103. if (groupsModule != null)
  3104. {
  3105. GroupMembershipData[] GroupMembership =
  3106. groupsModule.GetMembershipData(agent.AgentID);
  3107. for (int i = 0; i < GroupMembership.Length; i++)
  3108. agentGroups.Add(GroupMembership[i].GroupID);
  3109. }
  3110. bool groupAccess = false;
  3111. UUID[] estateGroups = m_regInfo.EstateSettings.EstateGroups;
  3112. foreach (UUID group in estateGroups)
  3113. {
  3114. if (agentGroups.Contains(group))
  3115. {
  3116. groupAccess = true;
  3117. break;
  3118. }
  3119. }
  3120. if (!m_regInfo.EstateSettings.PublicAccess &&
  3121. !m_regInfo.EstateSettings.HasAccess(agent.AgentID) &&
  3122. !groupAccess)
  3123. {
  3124. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3125. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3126. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3127. RegionInfo.RegionName);
  3128. return false;
  3129. }
  3130. // TODO: estate/region settings are not properly hooked up
  3131. // to ILandObject.isRestrictedFromLand()
  3132. // if (null != LandChannel)
  3133. // {
  3134. // // region seems to have local Id of 1
  3135. // ILandObject land = LandChannel.GetLandObject(1);
  3136. // if (null != land)
  3137. // {
  3138. // if (land.isBannedFromLand(agent.AgentID))
  3139. // {
  3140. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user has been banned from land",
  3141. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3142. // reason = String.Format("Denied access to private region {0}: You are banned from that region.",
  3143. // RegionInfo.RegionName);
  3144. // return false;
  3145. // }
  3146. // if (land.isRestrictedFromLand(agent.AgentID))
  3147. // {
  3148. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  3149. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3150. // reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3151. // RegionInfo.RegionName);
  3152. // return false;
  3153. // }
  3154. // }
  3155. // }
  3156. return true;
  3157. }
  3158. /// <summary>
  3159. /// Update an AgentCircuitData object with new information
  3160. /// </summary>
  3161. /// <param name="data">Information to update the AgentCircuitData with</param>
  3162. public void UpdateCircuitData(AgentCircuitData data)
  3163. {
  3164. m_authenticateHandler.UpdateAgentData(data);
  3165. }
  3166. /// <summary>
  3167. /// Change the Circuit Code for the user's Circuit Data
  3168. /// </summary>
  3169. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3170. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3171. /// <returns>True if we successfully changed it. False if we did not</returns>
  3172. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3173. {
  3174. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  3175. }
  3176. /// <summary>
  3177. /// The Grid has requested that we log-off a user. Log them off.
  3178. /// </summary>
  3179. /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3180. /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3181. /// <param name="message">message to display to the user. Reason for being logged off</param>
  3182. public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3183. {
  3184. ScenePresence loggingOffUser = null;
  3185. loggingOffUser = GetScenePresence(AvatarID);
  3186. if (loggingOffUser != null)
  3187. {
  3188. UUID localRegionSecret = UUID.Zero;
  3189. bool parsedsecret = UUID.TryParse(m_regInfo.regionSecret, out localRegionSecret);
  3190. // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3191. // Will update the user server in a few revisions to use it.
  3192. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3193. {
  3194. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  3195. loggingOffUser.ControllingClient.Kick(message);
  3196. // Give them a second to receive the message!
  3197. Thread.Sleep(1000);
  3198. loggingOffUser.ControllingClient.Close();
  3199. }
  3200. else
  3201. {
  3202. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3203. }
  3204. }
  3205. else
  3206. {
  3207. m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  3208. }
  3209. }
  3210. /// <summary>
  3211. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3212. /// </summary>
  3213. /// <param name="agentID"></param>
  3214. /// <param name="position"></param>
  3215. /// <param name="isFlying"></param>
  3216. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3217. {
  3218. ScenePresence presence;
  3219. m_sceneGraph.TryGetAvatar(agentID, out presence);
  3220. if (presence != null)
  3221. {
  3222. try
  3223. {
  3224. presence.MakeRootAgent(position, isFlying);
  3225. }
  3226. catch (Exception e)
  3227. {
  3228. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  3229. }
  3230. }
  3231. else
  3232. {
  3233. m_log.ErrorFormat(
  3234. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3235. agentID, RegionInfo.RegionName);
  3236. }
  3237. }
  3238. /// <summary>
  3239. /// We've got an update about an agent that sees into this region,
  3240. /// send it to ScenePresence for processing It's the full data.
  3241. /// </summary>
  3242. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3243. /// Appearance, animations, position, etc.</param>
  3244. /// <returns>true if we handled it.</returns>
  3245. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  3246. {
  3247. // m_log.DebugFormat(
  3248. // "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3249. // We have to wait until the viewer contacts this region after receiving EAC.
  3250. // That calls AddNewClient, which finally creates the ScenePresence
  3251. ScenePresence childAgentUpdate = WaitGetScenePresence(cAgentData.AgentID);
  3252. if (childAgentUpdate != null)
  3253. {
  3254. childAgentUpdate.ChildAgentDataUpdate(cAgentData);
  3255. return true;
  3256. }
  3257. return false;
  3258. }
  3259. /// <summary>
  3260. /// We've got an update about an agent that sees into this region,
  3261. /// send it to ScenePresence for processing It's only positional data
  3262. /// </summary>
  3263. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3264. /// <returns>true if we handled it.</returns>
  3265. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  3266. {
  3267. //m_log.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  3268. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  3269. if (childAgentUpdate != null)
  3270. {
  3271. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  3272. // however to avoid a race condition crossing borders..
  3273. if (childAgentUpdate.IsChildAgent)
  3274. {
  3275. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  3276. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  3277. uint tRegionX = RegionInfo.RegionLocX;
  3278. uint tRegionY = RegionInfo.RegionLocY;
  3279. //Send Data to ScenePresence
  3280. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  3281. // Not Implemented:
  3282. //TODO: Do we need to pass the message on to one of our neighbors?
  3283. }
  3284. return true;
  3285. }
  3286. return false;
  3287. }
  3288. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  3289. {
  3290. int ntimes = 10;
  3291. ScenePresence childAgentUpdate = null;
  3292. while ((childAgentUpdate = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  3293. Thread.Sleep(1000);
  3294. return childAgentUpdate;
  3295. }
  3296. public virtual bool IncomingRetrieveRootAgent(UUID id, out IAgentData agent)
  3297. {
  3298. agent = null;
  3299. ScenePresence sp = GetScenePresence(id);
  3300. if ((sp != null) && (!sp.IsChildAgent))
  3301. {
  3302. sp.IsChildAgent = true;
  3303. return sp.CopyAgent(out agent);
  3304. }
  3305. return false;
  3306. }
  3307. public virtual bool IncomingReleaseAgent(UUID id)
  3308. {
  3309. return m_sceneGridService.ReleaseAgent(id);
  3310. }
  3311. public void SendReleaseAgent(ulong regionHandle, UUID id, string uri)
  3312. {
  3313. m_interregionCommsOut.SendReleaseAgent(regionHandle, id, uri);
  3314. }
  3315. /// <summary>
  3316. /// Tell a single agent to disconnect from the region.
  3317. /// </summary>
  3318. /// <param name="regionHandle"></param>
  3319. /// <param name="agentID"></param>
  3320. public bool IncomingCloseAgent(UUID agentID)
  3321. {
  3322. //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
  3323. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  3324. if (presence != null)
  3325. {
  3326. // Nothing is removed here, so down count it as such
  3327. if (presence.IsChildAgent)
  3328. {
  3329. m_sceneGraph.removeUserCount(false);
  3330. }
  3331. else
  3332. {
  3333. m_sceneGraph.removeUserCount(true);
  3334. }
  3335. // Don't do this to root agents on logout, it's not nice for the viewer
  3336. if (presence.IsChildAgent)
  3337. {
  3338. // Tell a single agent to disconnect from the region.
  3339. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  3340. if (eq != null)
  3341. {
  3342. eq.DisableSimulator(RegionInfo.RegionHandle, agentID);
  3343. }
  3344. else
  3345. presence.ControllingClient.SendShutdownConnectionNotice();
  3346. }
  3347. presence.ControllingClient.Close();
  3348. return true;
  3349. }
  3350. // Agent not here
  3351. return false;
  3352. }
  3353. /// <summary>
  3354. /// Tell neighboring regions about this agent
  3355. /// When the regions respond with a true value,
  3356. /// tell the agents about the region.
  3357. ///
  3358. /// We have to tell the regions about the agents first otherwise it'll deny them access
  3359. ///
  3360. /// </summary>
  3361. /// <param name="presence"></param>
  3362. public void InformClientOfNeighbours(ScenePresence presence)
  3363. {
  3364. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  3365. }
  3366. /// <summary>
  3367. /// Tell a neighboring region about this agent
  3368. /// </summary>
  3369. /// <param name="presence"></param>
  3370. /// <param name="region"></param>
  3371. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  3372. {
  3373. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  3374. }
  3375. /// <summary>
  3376. /// Tries to teleport agent to other region.
  3377. /// </summary>
  3378. /// <param name="remoteClient"></param>
  3379. /// <param name="regionName"></param>
  3380. /// <param name="position"></param>
  3381. /// <param name="lookAt"></param>
  3382. /// <param name="teleportFlags"></param>
  3383. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  3384. Vector3 lookat, uint teleportFlags)
  3385. {
  3386. GridRegion regionInfo = GridService.GetRegionByName(UUID.Zero, regionName);
  3387. if (regionInfo == null)
  3388. {
  3389. // can't find the region: Tell viewer and abort
  3390. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  3391. return;
  3392. }
  3393. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  3394. }
  3395. /// <summary>
  3396. /// Tries to teleport agent to other region.
  3397. /// </summary>
  3398. /// <param name="remoteClient"></param>
  3399. /// <param name="regionHandle"></param>
  3400. /// <param name="position"></param>
  3401. /// <param name="lookAt"></param>
  3402. /// <param name="teleportFlags"></param>
  3403. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  3404. Vector3 lookAt, uint teleportFlags)
  3405. {
  3406. ScenePresence sp;
  3407. m_sceneGraph.TryGetAvatar(remoteClient.AgentId, out sp);
  3408. if (sp != null)
  3409. {
  3410. uint regionX = m_regInfo.RegionLocX;
  3411. uint regionY = m_regInfo.RegionLocY;
  3412. Utils.LongToUInts(regionHandle, out regionX, out regionY);
  3413. int shiftx = (int) regionX - (int) m_regInfo.RegionLocX * (int)Constants.RegionSize;
  3414. int shifty = (int) regionY - (int) m_regInfo.RegionLocY * (int)Constants.RegionSize;
  3415. position.X += shiftx;
  3416. position.Y += shifty;
  3417. bool result = false;
  3418. if (TestBorderCross(position,Cardinals.N))
  3419. result = true;
  3420. if (TestBorderCross(position, Cardinals.S))
  3421. result = true;
  3422. if (TestBorderCross(position, Cardinals.E))
  3423. result = true;
  3424. if (TestBorderCross(position, Cardinals.W))
  3425. result = true;
  3426. // bordercross if position is outside of region
  3427. if (!result)
  3428. regionHandle = m_regInfo.RegionHandle;
  3429. else
  3430. {
  3431. // not in this region, undo the shift!
  3432. position.X -= shiftx;
  3433. position.Y -= shifty;
  3434. }
  3435. if (m_teleportModule != null)
  3436. {
  3437. m_teleportModule.RequestTeleportToLocation(sp, regionHandle,
  3438. position, lookAt, teleportFlags);
  3439. }
  3440. else
  3441. {
  3442. m_sceneGridService.RequestTeleportToLocation(sp, regionHandle,
  3443. position, lookAt, teleportFlags);
  3444. }
  3445. }
  3446. }
  3447. /// <summary>
  3448. /// Tries to teleport agent to landmark.
  3449. /// </summary>
  3450. /// <param name="remoteClient"></param>
  3451. /// <param name="regionHandle"></param>
  3452. /// <param name="position"></param>
  3453. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  3454. {
  3455. GridRegion info = GridService.GetRegionByUUID(UUID.Zero, regionID);
  3456. if (info == null)
  3457. {
  3458. // can't find the region: Tell viewer and abort
  3459. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  3460. return;
  3461. }
  3462. RequestTeleportLocation(remoteClient, info.RegionHandle, position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  3463. }
  3464. public void CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  3465. {
  3466. m_sceneGridService.CrossAgentToNewRegion(this, agent, isFlying);
  3467. }
  3468. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  3469. {
  3470. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  3471. }
  3472. #endregion
  3473. #region Other Methods
  3474. public void SetObjectCapacity(int objects)
  3475. {
  3476. // Region specific config overrides global
  3477. //
  3478. if (RegionInfo.ObjectCapacity != 0)
  3479. objects = RegionInfo.ObjectCapacity;
  3480. if (StatsReporter != null)
  3481. {
  3482. StatsReporter.SetObjectCapacity(objects);
  3483. }
  3484. objectCapacity = objects;
  3485. }
  3486. public List<FriendListItem> GetFriendList(string id)
  3487. {
  3488. UUID avatarID;
  3489. if (!UUID.TryParse(id, out avatarID))
  3490. return new List<FriendListItem>();
  3491. return CommsManager.GetUserFriendList(avatarID);
  3492. }
  3493. public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
  3494. {
  3495. return CommsManager.GetFriendRegionInfos(uuids);
  3496. }
  3497. public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
  3498. {
  3499. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  3500. }
  3501. public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
  3502. {
  3503. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  3504. }
  3505. public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
  3506. {
  3507. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  3508. }
  3509. #endregion
  3510. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  3511. {
  3512. // Check for spoofing.. since this is permissions we're talking about here!
  3513. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  3514. {
  3515. // Tell the object to do permission update
  3516. if (localId != 0)
  3517. {
  3518. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  3519. if (chObjectGroup != null)
  3520. {
  3521. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  3522. }
  3523. }
  3524. }
  3525. }
  3526. /// <summary>
  3527. /// Causes all clients to get a full object update on all of the objects in the scene.
  3528. /// </summary>
  3529. public void ForceClientUpdate()
  3530. {
  3531. List<EntityBase> EntityList = GetEntities();
  3532. foreach (EntityBase ent in EntityList)
  3533. {
  3534. if (ent is SceneObjectGroup)
  3535. {
  3536. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  3537. }
  3538. }
  3539. }
  3540. /// <summary>
  3541. /// This is currently only used for scale (to scale to MegaPrim size)
  3542. /// There is a console command that calls this in OpenSimMain
  3543. /// </summary>
  3544. /// <param name="cmdparams"></param>
  3545. public void HandleEditCommand(string[] cmdparams)
  3546. {
  3547. m_log.Debug("Searching for Primitive: '" + cmdparams[2] + "'");
  3548. List<EntityBase> EntityList = GetEntities();
  3549. foreach (EntityBase ent in EntityList)
  3550. {
  3551. if (ent is SceneObjectGroup)
  3552. {
  3553. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  3554. if (part != null)
  3555. {
  3556. if (part.Name == cmdparams[2])
  3557. {
  3558. part.Resize(
  3559. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  3560. Convert.ToSingle(cmdparams[5])));
  3561. m_log.Debug("Edited scale of Primitive: " + part.Name);
  3562. }
  3563. }
  3564. }
  3565. }
  3566. }
  3567. public override void Show(string[] showParams)
  3568. {
  3569. base.Show(showParams);
  3570. switch (showParams[0])
  3571. {
  3572. case "users":
  3573. m_log.Error("Current Region: " + RegionInfo.RegionName);
  3574. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  3575. "Agent ID", "Session ID", "Circuit", "IP", "World");
  3576. foreach (ScenePresence scenePresence in GetAvatars())
  3577. {
  3578. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  3579. scenePresence.Firstname,
  3580. scenePresence.Lastname,
  3581. scenePresence.UUID,
  3582. scenePresence.ControllingClient.AgentId,
  3583. "Unknown",
  3584. "Unknown",
  3585. RegionInfo.RegionName);
  3586. }
  3587. break;
  3588. }
  3589. }
  3590. #region Script Handling Methods
  3591. /// <summary>
  3592. /// Console command handler to send script command to script engine.
  3593. /// </summary>
  3594. /// <param name="args"></param>
  3595. public void SendCommandToPlugins(string[] args)
  3596. {
  3597. m_eventManager.TriggerOnPluginConsole(args);
  3598. }
  3599. public LandData GetLandData(float x, float y)
  3600. {
  3601. return LandChannel.GetLandObject(x, y).LandData;
  3602. }
  3603. public LandData GetLandData(uint x, uint y)
  3604. {
  3605. m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  3606. return LandChannel.GetLandObject((int)x, (int)y).LandData;
  3607. }
  3608. #endregion
  3609. #region Script Engine
  3610. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  3611. public bool DumpAssetsToFile;
  3612. /// <summary>
  3613. ///
  3614. /// </summary>
  3615. /// <param name="scriptEngine"></param>
  3616. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  3617. {
  3618. ScriptEngines.Add(scriptEngine);
  3619. scriptEngine.InitializeEngine(this);
  3620. }
  3621. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  3622. {
  3623. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  3624. if (part != null)
  3625. {
  3626. if (parcel != null)
  3627. {
  3628. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  3629. {
  3630. return true;
  3631. }
  3632. else if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  3633. {
  3634. if (part.OwnerID == parcel.LandData.OwnerID
  3635. || (parcel.LandData.IsGroupOwned && part.GroupID == parcel.LandData.GroupID)
  3636. || Permissions.IsGod(part.OwnerID))
  3637. {
  3638. return true;
  3639. }
  3640. else
  3641. {
  3642. return false;
  3643. }
  3644. }
  3645. else
  3646. {
  3647. if (part.OwnerID == parcel.LandData.OwnerID)
  3648. {
  3649. return true;
  3650. }
  3651. else
  3652. {
  3653. return false;
  3654. }
  3655. }
  3656. }
  3657. else
  3658. {
  3659. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  3660. {
  3661. // The only time parcel != null when an object is inside a region is when
  3662. // there is nothing behind the landchannel. IE, no land plugin loaded.
  3663. return true;
  3664. }
  3665. else
  3666. {
  3667. // The object is outside of this region. Stop piping events to it.
  3668. return false;
  3669. }
  3670. }
  3671. }
  3672. else
  3673. {
  3674. return false;
  3675. }
  3676. }
  3677. public bool ScriptDanger(uint localID, Vector3 pos)
  3678. {
  3679. SceneObjectPart part = GetSceneObjectPart(localID);
  3680. if (part != null)
  3681. {
  3682. return ScriptDanger(part, pos);
  3683. }
  3684. else
  3685. {
  3686. return false;
  3687. }
  3688. }
  3689. public bool PipeEventsForScript(uint localID)
  3690. {
  3691. SceneObjectPart part = GetSceneObjectPart(localID);
  3692. if (part != null)
  3693. {
  3694. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  3695. // their scripts will actually run.
  3696. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  3697. SceneObjectPart parent = part.ParentGroup.RootPart;
  3698. if (parent != null && parent.IsAttachment)
  3699. return ScriptDanger(parent, parent.GetWorldPosition());
  3700. else
  3701. return ScriptDanger(part, part.GetWorldPosition());
  3702. }
  3703. else
  3704. {
  3705. return false;
  3706. }
  3707. }
  3708. #endregion
  3709. #region SceneGraph wrapper methods
  3710. /// <summary>
  3711. ///
  3712. /// </summary>
  3713. /// <param name="localID"></param>
  3714. /// <returns></returns>
  3715. public UUID ConvertLocalIDToFullID(uint localID)
  3716. {
  3717. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  3718. }
  3719. public void SwapRootAgentCount(bool rootChildChildRootTF)
  3720. {
  3721. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  3722. }
  3723. public void AddPhysicalPrim(int num)
  3724. {
  3725. m_sceneGraph.AddPhysicalPrim(num);
  3726. }
  3727. public void RemovePhysicalPrim(int num)
  3728. {
  3729. m_sceneGraph.RemovePhysicalPrim(num);
  3730. }
  3731. //The idea is to have a group of method that return a list of avatars meeting some requirement
  3732. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  3733. /// <summary>
  3734. /// Return a list of all avatars in this region.
  3735. /// This list is a new object, so it can be iterated over without locking.
  3736. /// </summary>
  3737. /// <returns></returns>
  3738. public List<ScenePresence> GetAvatars()
  3739. {
  3740. return m_sceneGraph.GetAvatars();
  3741. }
  3742. /// <summary>
  3743. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  3744. /// This list is a new object, so it can be iterated over without locking.
  3745. /// </summary>
  3746. /// <returns></returns>
  3747. public ScenePresence[] GetScenePresences()
  3748. {
  3749. return m_sceneGraph.GetScenePresences();
  3750. }
  3751. /// <summary>
  3752. /// Request a filtered list of ScenePresences in this region.
  3753. /// This list is a new object, so it can be iterated over without locking.
  3754. /// </summary>
  3755. /// <param name="filter"></param>
  3756. /// <returns></returns>
  3757. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  3758. {
  3759. return m_sceneGraph.GetScenePresences(filter);
  3760. }
  3761. /// <summary>
  3762. /// Request a scene presence by UUID
  3763. /// </summary>
  3764. /// <param name="avatarID"></param>
  3765. /// <returns></returns>
  3766. public ScenePresence GetScenePresence(UUID avatarID)
  3767. {
  3768. return m_sceneGraph.GetScenePresence(avatarID);
  3769. }
  3770. public override bool PresenceChildStatus(UUID avatarID)
  3771. {
  3772. ScenePresence cp = GetScenePresence(avatarID);
  3773. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  3774. // This needs to be fixed properly by cleaning up the logout code.
  3775. //if (cp != null)
  3776. // return cp.IsChildAgent;
  3777. //return false;
  3778. return cp.IsChildAgent;
  3779. }
  3780. /// <summary>
  3781. ///
  3782. /// </summary>
  3783. /// <param name="action"></param>
  3784. public void ForEachScenePresence(Action<ScenePresence> action)
  3785. {
  3786. // We don't want to try to send messages if there are no avatars.
  3787. if (m_sceneGraph != null)
  3788. {
  3789. try
  3790. {
  3791. ScenePresence[] presences = GetScenePresences();
  3792. for (int i = 0; i < presences.Length; i++)
  3793. action(presences[i]);
  3794. }
  3795. catch (Exception e)
  3796. {
  3797. m_log.Info("[BUG] in " + RegionInfo.RegionName + ": " + e.ToString());
  3798. m_log.Info("[BUG] Stack Trace: " + e.StackTrace);
  3799. }
  3800. }
  3801. }
  3802. /// <summary>
  3803. ///
  3804. /// </summary>
  3805. /// <param name="action"></param>
  3806. // public void ForEachObject(Action<SceneObjectGroup> action)
  3807. // {
  3808. // List<SceneObjectGroup> presenceList;
  3809. //
  3810. // lock (m_sceneObjects)
  3811. // {
  3812. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  3813. // }
  3814. //
  3815. // foreach (SceneObjectGroup presence in presenceList)
  3816. // {
  3817. // action(presence);
  3818. // }
  3819. // }
  3820. /// <summary>
  3821. /// Get a named prim contained in this scene (will return the first
  3822. /// found, if there are more than one prim with the same name)
  3823. /// </summary>
  3824. /// <param name="name"></param>
  3825. /// <returns></returns>
  3826. public SceneObjectPart GetSceneObjectPart(string name)
  3827. {
  3828. return m_sceneGraph.GetSceneObjectPart(name);
  3829. }
  3830. /// <summary>
  3831. /// Get a prim via its local id
  3832. /// </summary>
  3833. /// <param name="localID"></param>
  3834. /// <returns></returns>
  3835. public SceneObjectPart GetSceneObjectPart(uint localID)
  3836. {
  3837. return m_sceneGraph.GetSceneObjectPart(localID);
  3838. }
  3839. /// <summary>
  3840. /// Get a prim via its UUID
  3841. /// </summary>
  3842. /// <param name="fullID"></param>
  3843. /// <returns></returns>
  3844. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  3845. {
  3846. return m_sceneGraph.GetSceneObjectPart(fullID);
  3847. }
  3848. /// <summary>
  3849. /// Get a scene object group that contains the prim with the given local id
  3850. /// </summary>
  3851. /// <param name="localID"></param>
  3852. /// <returns>null if no scene object group containing that prim is found</returns>
  3853. public SceneObjectGroup GetGroupByPrim(uint localID)
  3854. {
  3855. return m_sceneGraph.GetGroupByPrim(localID);
  3856. }
  3857. public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  3858. {
  3859. return m_sceneGraph.TryGetAvatar(avatarId, out avatar);
  3860. }
  3861. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  3862. {
  3863. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  3864. }
  3865. public void ForEachClient(Action<IClientAPI> action)
  3866. {
  3867. ForEachClient(action, m_useAsyncWhenPossible);
  3868. }
  3869. public void ForEachClient(Action<IClientAPI> action, bool doAsynchronous)
  3870. {
  3871. // FIXME: Asynchronous iteration is disabled until we have a threading model that
  3872. // can support calling this function from an async packet handler without
  3873. // potentially deadlocking
  3874. m_clientManager.ForEachSync(action);
  3875. //if (doAsynchronous)
  3876. // m_clientManager.ForEach(action);
  3877. //else
  3878. // m_clientManager.ForEachSync(action);
  3879. }
  3880. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  3881. {
  3882. return m_clientManager.TryGetValue(avatarID, out client);
  3883. }
  3884. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  3885. {
  3886. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  3887. }
  3888. public void ForEachSOG(Action<SceneObjectGroup> action)
  3889. {
  3890. m_sceneGraph.ForEachSOG(action);
  3891. }
  3892. /// <summary>
  3893. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  3894. /// will not affect the original list of objects in the scene.
  3895. /// </summary>
  3896. /// <returns></returns>
  3897. public List<EntityBase> GetEntities()
  3898. {
  3899. return m_sceneGraph.GetEntities();
  3900. }
  3901. #endregion
  3902. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  3903. {
  3904. ulong handle = 0;
  3905. if (regionID == RegionInfo.RegionID)
  3906. handle = RegionInfo.RegionHandle;
  3907. else
  3908. {
  3909. GridRegion r = GridService.GetRegionByUUID(UUID.Zero, regionID);
  3910. if (r != null)
  3911. handle = r.RegionHandle;
  3912. }
  3913. if (handle != 0)
  3914. client.SendRegionHandle(regionID, handle);
  3915. }
  3916. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  3917. {
  3918. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  3919. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  3920. }
  3921. public void SetRootAgentScene(UUID agentID)
  3922. {
  3923. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3924. if (inv == null)
  3925. return;
  3926. inv.SetRootAgentScene(agentID, this);
  3927. EventManager.TriggerSetRootAgentScene(agentID, this);
  3928. }
  3929. public bool NeedSceneCacheClear(UUID agentID)
  3930. {
  3931. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3932. if (inv == null)
  3933. return true;
  3934. return inv.NeedSceneCacheClear(agentID, this);
  3935. }
  3936. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  3937. {
  3938. SceneObjectPart part = GetSceneObjectPart(localID);
  3939. if (part == null || part.ParentGroup == null)
  3940. return;
  3941. if (part.ParentGroup.IsDeleted)
  3942. return;
  3943. part = part.ParentGroup.RootPart;
  3944. part.ObjectSaleType = saleType;
  3945. part.SalePrice = salePrice;
  3946. part.ParentGroup.HasGroupChanged = true;
  3947. part.GetProperties(client);
  3948. }
  3949. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  3950. uint localID, byte saleType)
  3951. {
  3952. SceneObjectPart part = GetSceneObjectPart(localID);
  3953. if (part == null)
  3954. return false;
  3955. if (part.ParentGroup == null)
  3956. return false;
  3957. SceneObjectGroup group = part.ParentGroup;
  3958. switch (saleType)
  3959. {
  3960. case 1: // Sell as original (in-place sale)
  3961. uint effectivePerms=group.GetEffectivePermissions();
  3962. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  3963. {
  3964. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3965. return false;
  3966. }
  3967. group.SetOwnerId(remoteClient.AgentId);
  3968. group.SetRootPartOwner(part, remoteClient.AgentId,
  3969. remoteClient.ActiveGroupId);
  3970. List<SceneObjectPart> partList =
  3971. new List<SceneObjectPart>(group.Children.Values);
  3972. if (Permissions.PropagatePermissions())
  3973. {
  3974. foreach (SceneObjectPart child in partList)
  3975. {
  3976. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  3977. child.ApplyNextOwnerPermissions();
  3978. }
  3979. }
  3980. part.ObjectSaleType = 0;
  3981. part.SalePrice = 10;
  3982. group.HasGroupChanged = true;
  3983. part.GetProperties(remoteClient);
  3984. part.ScheduleFullUpdate();
  3985. break;
  3986. case 2: // Sell a copy
  3987. Vector3 inventoryStoredPosition = new Vector3
  3988. (((group.AbsolutePosition.X > (int)Constants.RegionSize)
  3989. ? 250
  3990. : group.AbsolutePosition.X)
  3991. ,
  3992. (group.AbsolutePosition.X > (int)Constants.RegionSize)
  3993. ? 250
  3994. : group.AbsolutePosition.X,
  3995. group.AbsolutePosition.Z);
  3996. Vector3 originalPosition = group.AbsolutePosition;
  3997. group.AbsolutePosition = inventoryStoredPosition;
  3998. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
  3999. group.AbsolutePosition = originalPosition;
  4000. uint perms=group.GetEffectivePermissions();
  4001. if ((perms & (uint)PermissionMask.Transfer) == 0)
  4002. {
  4003. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  4004. return false;
  4005. }
  4006. AssetBase asset = CreateAsset(
  4007. group.GetPartName(localID),
  4008. group.GetPartDescription(localID),
  4009. (sbyte)AssetType.Object,
  4010. Utils.StringToBytes(sceneObjectXml));
  4011. AssetService.Store(asset);
  4012. InventoryItemBase item = new InventoryItemBase();
  4013. item.CreatorId = part.CreatorID.ToString();
  4014. item.ID = UUID.Random();
  4015. item.Owner = remoteClient.AgentId;
  4016. item.AssetID = asset.FullID;
  4017. item.Description = asset.Description;
  4018. item.Name = asset.Name;
  4019. item.AssetType = asset.Type;
  4020. item.InvType = (int)InventoryType.Object;
  4021. item.Folder = categoryID;
  4022. uint nextPerms=(perms & 7) << 13;
  4023. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  4024. perms &= ~(uint)PermissionMask.Copy;
  4025. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  4026. perms &= ~(uint)PermissionMask.Transfer;
  4027. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  4028. perms &= ~(uint)PermissionMask.Modify;
  4029. item.BasePermissions = perms & part.NextOwnerMask;
  4030. item.CurrentPermissions = perms & part.NextOwnerMask;
  4031. item.NextPermissions = part.NextOwnerMask;
  4032. item.EveryOnePermissions = part.EveryoneMask &
  4033. part.NextOwnerMask;
  4034. item.GroupPermissions = part.GroupMask &
  4035. part.NextOwnerMask;
  4036. item.CurrentPermissions |= 8; // Slam!
  4037. item.CreationDate = Util.UnixTimeSinceEpoch();
  4038. if (InventoryService.AddItem(item))
  4039. remoteClient.SendInventoryItemCreateUpdate(item, 0);
  4040. else
  4041. {
  4042. m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
  4043. return false;
  4044. }
  4045. break;
  4046. case 3: // Sell contents
  4047. List<UUID> invList = part.Inventory.GetInventoryList();
  4048. bool okToSell = true;
  4049. foreach (UUID invID in invList)
  4050. {
  4051. TaskInventoryItem item1 = part.Inventory.GetInventoryItem(invID);
  4052. if ((item1.CurrentPermissions &
  4053. (uint)PermissionMask.Transfer) == 0)
  4054. {
  4055. okToSell = false;
  4056. break;
  4057. }
  4058. }
  4059. if (!okToSell)
  4060. {
  4061. m_dialogModule.SendAlertToUser(
  4062. remoteClient, "This item's inventory doesn't appear to be for sale");
  4063. return false;
  4064. }
  4065. if (invList.Count > 0)
  4066. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  4067. part, invList);
  4068. break;
  4069. }
  4070. return true;
  4071. }
  4072. public void CleanTempObjects()
  4073. {
  4074. List<EntityBase> objs = GetEntities();
  4075. foreach (EntityBase obj in objs)
  4076. {
  4077. if (obj is SceneObjectGroup)
  4078. {
  4079. SceneObjectGroup grp = (SceneObjectGroup)obj;
  4080. if (!grp.IsDeleted)
  4081. {
  4082. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4083. {
  4084. if (grp.RootPart.Expires <= DateTime.Now)
  4085. DeleteSceneObject(grp, false);
  4086. }
  4087. }
  4088. }
  4089. }
  4090. }
  4091. public void DeleteFromStorage(UUID uuid)
  4092. {
  4093. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  4094. }
  4095. public int GetHealth()
  4096. {
  4097. // Returns:
  4098. // 1 = sim is up and accepting http requests. The heartbeat has
  4099. // stopped and the sim is probably locked up, but a remote
  4100. // admin restart may succeed
  4101. //
  4102. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4103. // usable for people within and logins _may_ work
  4104. //
  4105. // 3 = We have seen a new user enter within the past 4 minutes
  4106. // which can be seen as positive confirmation of sim health
  4107. //
  4108. int health=1; // Start at 1, means we're up
  4109. if ((Util.EnvironmentTickCountSubtract(m_lastUpdate)) < 1000)
  4110. health+=1;
  4111. else
  4112. return health;
  4113. // A login in the last 4 mins? We can't be doing too badly
  4114. //
  4115. if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000)
  4116. health++;
  4117. else
  4118. return health;
  4119. CheckHeartbeat();
  4120. return health;
  4121. }
  4122. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4123. // update non-physical objects like the joint proxy objects that represent the position
  4124. // of the joints in the scene.
  4125. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4126. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4127. // from within the OdePhysicsScene.
  4128. protected internal void jointMoved(PhysicsJoint joint)
  4129. {
  4130. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  4131. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4132. if (jointProxyObject == null)
  4133. {
  4134. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  4135. return;
  4136. }
  4137. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  4138. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  4139. if (trackedBody == null) return; // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
  4140. jointProxyObject.Velocity = trackedBody.Velocity;
  4141. jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
  4142. switch (joint.Type)
  4143. {
  4144. case PhysicsJointType.Ball:
  4145. {
  4146. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4147. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  4148. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4149. }
  4150. break;
  4151. case PhysicsJointType.Hinge:
  4152. {
  4153. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4154. // Normally, we would just ask the physics scene to return the axis for the joint.
  4155. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  4156. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  4157. // Therefore the following call does not always work:
  4158. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  4159. // instead we compute the joint orientation by saving the original joint orientation
  4160. // relative to one of the jointed bodies, and applying this transformation
  4161. // to the current position of the jointed bodies (the tracked body) to compute the
  4162. // current joint orientation.
  4163. if (joint.TrackedBodyName == null)
  4164. {
  4165. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  4166. }
  4167. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  4168. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  4169. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4170. jointProxyObject.ParentGroup.UpdateGroupRotationR(q); // schedules the entire group for a terse update
  4171. }
  4172. break;
  4173. }
  4174. }
  4175. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4176. // update non-physical objects like the joint proxy objects that represent the position
  4177. // of the joints in the scene.
  4178. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4179. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4180. // from within the OdePhysicsScene.
  4181. protected internal void jointDeactivated(PhysicsJoint joint)
  4182. {
  4183. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  4184. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4185. if (jointProxyObject == null)
  4186. {
  4187. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  4188. return;
  4189. }
  4190. // turn the proxy non-physical, which also stops its client-side interpolation
  4191. bool wasUsingPhysics = ((jointProxyObject.ObjectFlags & (uint)PrimFlags.Physics) != 0);
  4192. if (wasUsingPhysics)
  4193. {
  4194. jointProxyObject.UpdatePrimFlags(false, false, true, false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
  4195. }
  4196. }
  4197. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4198. // alert the user of errors by using the debug channel in the same way that scripts alert
  4199. // the user of compile errors.
  4200. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4201. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4202. // from within the OdePhysicsScene.
  4203. public void jointErrorMessage(PhysicsJoint joint, string message)
  4204. {
  4205. if (joint != null)
  4206. {
  4207. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4208. return;
  4209. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4210. if (jointProxyObject != null)
  4211. {
  4212. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  4213. ChatTypeEnum.DebugChannel,
  4214. 2147483647,
  4215. jointProxyObject.AbsolutePosition,
  4216. jointProxyObject.Name,
  4217. jointProxyObject.UUID,
  4218. false);
  4219. joint.ErrorMessageCount++;
  4220. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4221. {
  4222. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  4223. ChatTypeEnum.DebugChannel,
  4224. 2147483647,
  4225. jointProxyObject.AbsolutePosition,
  4226. jointProxyObject.Name,
  4227. jointProxyObject.UUID,
  4228. false);
  4229. }
  4230. }
  4231. else
  4232. {
  4233. // couldn't find the joint proxy object; the error message is silently suppressed
  4234. }
  4235. }
  4236. }
  4237. public Scene ConsoleScene()
  4238. {
  4239. if (MainConsole.Instance == null)
  4240. return null;
  4241. if (MainConsole.Instance.ConsoleScene is Scene)
  4242. return (Scene)MainConsole.Instance.ConsoleScene;
  4243. return null;
  4244. }
  4245. public float GetGroundHeight(float x, float y)
  4246. {
  4247. if (x < 0)
  4248. x = 0;
  4249. if (x >= Heightmap.Width)
  4250. x = Heightmap.Width - 1;
  4251. if (y < 0)
  4252. y = 0;
  4253. if (y >= Heightmap.Height)
  4254. y = Heightmap.Height - 1;
  4255. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  4256. Vector3 p1 = new Vector3(p0);
  4257. Vector3 p2 = new Vector3(p0);
  4258. p1.X += 1.0f;
  4259. if (p1.X < Heightmap.Width)
  4260. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  4261. p2.Y += 1.0f;
  4262. if (p2.Y < Heightmap.Height)
  4263. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  4264. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  4265. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  4266. v0.Normalize();
  4267. v1.Normalize();
  4268. Vector3 vsn = new Vector3();
  4269. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  4270. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  4271. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  4272. vsn.Normalize();
  4273. float xdiff = x - (float)((int)x);
  4274. float ydiff = y - (float)((int)y);
  4275. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  4276. }
  4277. private void CheckHeartbeat()
  4278. {
  4279. if (m_firstHeartbeat)
  4280. return;
  4281. if (Util.EnvironmentTickCountSubtract(m_lastUpdate) > 2000)
  4282. StartTimer();
  4283. }
  4284. }
  4285. }