PageRenderTime 94ms CodeModel.GetById 37ms RepoModel.GetById 1ms app.codeStats 1ms

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

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