PageRenderTime 95ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

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

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