PageRenderTime 141ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/Aurora/Region/SceneGraph.cs

https://bitbucket.org/VirtualReality/async-sim-testing
C# | 2252 lines | 1471 code | 225 blank | 556 comment | 263 complexity | 22755561143feb731883e7805a0c001e MD5 | raw file
  1. /*
  2. * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the Aurora-Sim 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 Aurora.Framework;
  28. using Aurora.Framework.ClientInterfaces;
  29. using Aurora.Framework.ConsoleFramework;
  30. using Aurora.Framework.Modules;
  31. using Aurora.Framework.Physics;
  32. using Aurora.Framework.PresenceInfo;
  33. using Aurora.Framework.SceneInfo;
  34. using Aurora.Framework.SceneInfo.Entities;
  35. using Aurora.Framework.Services;
  36. using Aurora.Framework.Utilities;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.Packets;
  40. using System;
  41. using System.Collections.Generic;
  42. using System.Linq;
  43. using System.Threading;
  44. namespace Aurora.Region
  45. {
  46. /// <summary>
  47. /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components
  48. /// should be migrated out over time.
  49. /// </summary>
  50. public class SceneGraph : ISceneGraph
  51. {
  52. #region Declares
  53. protected internal EntityManager Entities = new EntityManager();
  54. protected RegionInfo m_regInfo;
  55. protected IScene m_parentScene;
  56. protected bool EnableFakeRaycasting = false;
  57. protected string m_DefaultObjectName = "Primitive";
  58. /// <summary>
  59. /// The last allocated local prim id. When a new local id is requested, the next number in the sequence is
  60. /// dispensed.
  61. /// </summary>
  62. protected uint m_lastAllocatedLocalId = 720000;
  63. private readonly object _primAllocateLock = new object();
  64. protected internal object m_syncRoot = new object();
  65. protected internal PhysicsScene _PhyScene;
  66. private readonly Object m_updateLock = new Object();
  67. public PhysicsScene PhysicsScene
  68. {
  69. get { return _PhyScene; }
  70. set { _PhyScene = value; }
  71. }
  72. #endregion
  73. #region Constructor and close
  74. protected internal SceneGraph(IScene parent, RegionInfo regInfo)
  75. {
  76. Random random = new Random();
  77. m_lastAllocatedLocalId = (uint) (random.NextDouble()*(uint.MaxValue/2)) + uint.MaxValue/4;
  78. m_parentScene = parent;
  79. m_regInfo = regInfo;
  80. //Subscript to the scene events
  81. m_parentScene.EventManager.OnNewClient += SubscribeToClientEvents;
  82. m_parentScene.EventManager.OnClosingClient += UnSubscribeToClientEvents;
  83. IConfig aurorastartupConfig = parent.Config.Configs["AuroraStartup"];
  84. if (aurorastartupConfig != null)
  85. {
  86. m_DefaultObjectName = aurorastartupConfig.GetString("DefaultObjectName", m_DefaultObjectName);
  87. EnableFakeRaycasting = aurorastartupConfig.GetBoolean("EnableFakeRaycasting", false);
  88. }
  89. }
  90. protected internal void Close()
  91. {
  92. Entities.Clear();
  93. //Remove the events
  94. m_parentScene.EventManager.OnNewClient -= SubscribeToClientEvents;
  95. m_parentScene.EventManager.OnClosingClient -= UnSubscribeToClientEvents;
  96. }
  97. #endregion
  98. #region Update Methods
  99. protected internal void UpdatePreparePhysics()
  100. {
  101. // If we are using a threaded physics engine
  102. // grab the latest scene from the engine before
  103. // trying to process it.
  104. // PhysX does this (runs in the background).
  105. if (_PhyScene != null && _PhyScene.IsThreaded)
  106. {
  107. _PhyScene.GetResults();
  108. }
  109. }
  110. private readonly object m_taintedPresencesLock = new object();
  111. private readonly List<IScenePresence> m_taintedPresences = new List<IScenePresence>();
  112. public void TaintPresenceForUpdate(IScenePresence presence, PresenceTaint taint)
  113. {
  114. lock (m_taintedPresencesLock)
  115. {
  116. if (!presence.IsTainted) //We ONLY set the IsTainted under this lock, so we can trust it
  117. m_taintedPresences.Add(presence);
  118. presence.Taints |= taint;
  119. }
  120. }
  121. protected internal void UpdateEntities()
  122. {
  123. IScenePresence[] presences;
  124. lock (m_taintedPresencesLock)
  125. {
  126. presences = new IScenePresence[m_taintedPresences.Count];
  127. m_taintedPresences.CopyTo(presences);
  128. m_taintedPresences.Clear();
  129. }
  130. foreach (IScenePresence presence in presences)
  131. {
  132. presence.IsTainted = false;
  133. //We set this first so that it is cleared out, but also so that the method can re-taint us
  134. presence.Update();
  135. }
  136. }
  137. protected internal void UpdatePhysics(double elapsed)
  138. {
  139. if (_PhyScene == null)
  140. return;
  141. lock (m_syncRoot)
  142. {
  143. // Update DisableCollisions
  144. _PhyScene.DisableCollisions = m_regInfo.RegionSettings.DisableCollisions;
  145. // Here is where the Scene calls the PhysicsScene. This is a one-way
  146. // interaction; the PhysicsScene cannot access the calling Scene directly.
  147. // But with joints, we want a PhysicsActor to be able to influence a
  148. // non-physics SceneObjectPart. In particular, a PhysicsActor that is connected
  149. // with a joint should be able to move the SceneObjectPart which is the visual
  150. // representation of that joint (for editing and serialization purposes).
  151. // However the PhysicsActor normally cannot directly influence anything outside
  152. // of the PhysicsScene, and the non-physical SceneObjectPart which represents
  153. // the joint in the Scene does not exist in the PhysicsScene.
  154. //
  155. // To solve this, we have an event in the PhysicsScene that is fired when a joint
  156. // has changed position (because one of its associated PhysicsActors has changed
  157. // position).
  158. //
  159. // Therefore, JointMoved and JointDeactivated events will be fired as a result of the following Simulate().
  160. _PhyScene.Simulate((float) elapsed);
  161. }
  162. }
  163. private List<Vector3> m_oldCoarseLocations = new List<Vector3>();
  164. private List<UUID> m_oldAvatarUUIDs = new List<UUID>();
  165. public bool GetCoarseLocations(out List<Vector3> coarseLocations, out List<UUID> avatarUUIDs, uint maxLocations)
  166. {
  167. coarseLocations = new List<Vector3>();
  168. avatarUUIDs = new List<UUID>();
  169. List<IScenePresence> presences = GetScenePresences();
  170. for (int i = 0; i < Math.Min(presences.Count, maxLocations); i++)
  171. {
  172. IScenePresence sp = presences[i];
  173. // If this presence is a child agent, we don't want its coarse locations
  174. if (sp.IsChildAgent)
  175. continue;
  176. if (sp.ParentID != UUID.Zero)
  177. {
  178. // sitting avatar
  179. ISceneChildEntity sop = m_parentScene.GetSceneObjectPart(sp.ParentID);
  180. if (sop != null)
  181. {
  182. coarseLocations.Add(sop.AbsolutePosition + sp.OffsetPosition);
  183. avatarUUIDs.Add(sp.UUID);
  184. }
  185. else
  186. {
  187. // we can't find the parent.. ! arg!
  188. MainConsole.Instance.Warn("Could not find parent prim for avatar " + sp.Name);
  189. coarseLocations.Add(sp.AbsolutePosition);
  190. avatarUUIDs.Add(sp.UUID);
  191. }
  192. }
  193. else
  194. {
  195. coarseLocations.Add(sp.AbsolutePosition);
  196. avatarUUIDs.Add(sp.UUID);
  197. }
  198. }
  199. if (m_oldCoarseLocations.Count == coarseLocations.Count)
  200. {
  201. List<UUID> foundAvies = new List<UUID>(m_oldAvatarUUIDs);
  202. foreach (UUID t in avatarUUIDs)
  203. {
  204. foundAvies.Remove(t);
  205. }
  206. if (foundAvies.Count == 0)
  207. {
  208. //All avies are still the same, check their locations now
  209. for (int i = 0; i < avatarUUIDs.Count; i++)
  210. {
  211. if (m_oldCoarseLocations[i].ApproxEquals(coarseLocations[i], 5))
  212. continue;
  213. m_oldCoarseLocations = coarseLocations;
  214. m_oldAvatarUUIDs = avatarUUIDs;
  215. return true;
  216. }
  217. //Things are still close enough to the same
  218. return false;
  219. }
  220. }
  221. m_oldCoarseLocations = coarseLocations;
  222. m_oldAvatarUUIDs = avatarUUIDs;
  223. //Its changed, tell it to send new
  224. return true;
  225. }
  226. #endregion
  227. #region Entity Methods
  228. protected internal void HandleUndo(IClientAPI remoteClient, UUID primId)
  229. {
  230. if (primId != UUID.Zero)
  231. {
  232. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(primId);
  233. if (part != null)
  234. if (m_parentScene.Permissions.CanEditObject(part.UUID, remoteClient.AgentId))
  235. part.Undo();
  236. }
  237. }
  238. protected internal void HandleRedo(IClientAPI remoteClient, UUID primId)
  239. {
  240. if (primId != UUID.Zero)
  241. {
  242. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(primId);
  243. if (part != null)
  244. if (m_parentScene.Permissions.CanEditObject(part.UUID, remoteClient.AgentId))
  245. part.Redo();
  246. }
  247. }
  248. protected internal void HandleObjectGroupUpdate(
  249. IClientAPI remoteClient, UUID GroupID, uint LocalID, UUID Garbage)
  250. {
  251. IEntity entity;
  252. if (TryGetEntity(LocalID, out entity))
  253. {
  254. if (m_parentScene.Permissions.CanEditObject(entity.UUID, remoteClient.AgentId))
  255. if (((ISceneEntity) entity).OwnerID == remoteClient.AgentId)
  256. ((ISceneEntity) entity).SetGroup(GroupID, remoteClient.AgentId, true);
  257. }
  258. }
  259. /// <summary>
  260. /// Add a presence to the scene
  261. /// </summary>
  262. /// <param name="presence"></param>
  263. protected internal void AddScenePresence(IScenePresence presence)
  264. {
  265. AddEntity(presence, true);
  266. }
  267. /// <summary>
  268. /// Remove a presence from the scene
  269. /// </summary>
  270. protected internal void RemoveScenePresence(IEntity agent)
  271. {
  272. if (!Entities.Remove(agent))
  273. {
  274. MainConsole.Instance.WarnFormat(
  275. "[SCENE]: Tried to remove non-existent scene presence with agent ID {0} from scene Entities list",
  276. agent.UUID);
  277. return;
  278. }
  279. }
  280. #endregion
  281. #region Get Methods
  282. /// <summary>
  283. /// Get a reference to the scene presence list. Changes to the list will be done in a copy
  284. /// There is no guarantee that presences will remain in the scene after the list is returned.
  285. /// This list should remain private to SceneGraph. Callers wishing to iterate should instead
  286. /// pass a delegate to ForEachScenePresence.
  287. /// </summary>
  288. /// <returns></returns>
  289. public List<IScenePresence> GetScenePresences()
  290. {
  291. return Entities.GetPresences();
  292. }
  293. /// <summary>
  294. /// Request a scene presence by UUID. Fast, indexed lookup.
  295. /// </summary>
  296. /// <param name="agentID"></param>
  297. /// <returns>null if the presence was not found</returns>
  298. protected internal IScenePresence GetScenePresence(UUID agentID)
  299. {
  300. IScenePresence sp;
  301. Entities.TryGetPresenceValue(agentID, out sp);
  302. return sp;
  303. }
  304. /// <summary>
  305. /// Request the scene presence by name.
  306. /// NOTE: Depricated, use the ScenePresence GetScenePresence (string Name) instead!
  307. /// </summary>
  308. /// <param name="firstName"></param>
  309. /// <param name="lastName"></param>
  310. /// <returns>null if the presence was not found</returns>
  311. public IScenePresence GetScenePresence(string firstName, string lastName)
  312. {
  313. List<IScenePresence> presences = GetScenePresences();
  314. return presences.FirstOrDefault(presence => presence.Firstname == firstName && presence.Lastname == lastName);
  315. }
  316. /// <summary>
  317. /// Request the scene presence by localID.
  318. /// </summary>
  319. /// <param name="localID"></param>
  320. /// <returns>null if the presence was not found</returns>
  321. public IScenePresence GetScenePresence(uint localID)
  322. {
  323. List<IScenePresence> presences = GetScenePresences();
  324. return presences.FirstOrDefault(presence => presence.LocalId == localID);
  325. }
  326. protected internal bool TryGetScenePresence(UUID agentID, out IScenePresence avatar)
  327. {
  328. return Entities.TryGetPresenceValue(agentID, out avatar);
  329. }
  330. protected internal bool TryGetAvatarByName(string name, out IScenePresence avatar)
  331. {
  332. avatar =
  333. GetScenePresences()
  334. .FirstOrDefault(presence => String.Compare(name, presence.ControllingClient.Name, true) == 0);
  335. return (avatar != null);
  336. }
  337. /// <summary>
  338. /// Get a scene object group that contains the prim with the given uuid
  339. /// </summary>
  340. /// <param name="hray"></param>
  341. /// <param name="frontFacesOnly"></param>
  342. /// <param name="faceCenters"></param>
  343. /// <returns>null if no scene object group containing that prim is found</returns>
  344. protected internal EntityIntersection GetClosestIntersectingPrim(Ray hray, bool frontFacesOnly, bool faceCenters)
  345. {
  346. // Primitive Ray Tracing
  347. float closestDistance = 280f;
  348. EntityIntersection result = new EntityIntersection();
  349. ISceneEntity[] EntityList = Entities.GetEntities(hray.Origin, closestDistance);
  350. foreach (ISceneEntity ent in EntityList)
  351. {
  352. if (ent is SceneObjectGroup)
  353. {
  354. SceneObjectGroup reportingG = (SceneObjectGroup) ent;
  355. EntityIntersection inter = reportingG.TestIntersection(hray, frontFacesOnly, faceCenters);
  356. if (inter.HitTF && inter.distance < closestDistance)
  357. {
  358. closestDistance = inter.distance;
  359. result = inter;
  360. }
  361. }
  362. }
  363. return result;
  364. }
  365. /// <summary>
  366. /// Gets a list of scene object group that intersect with the given ray
  367. /// </summary>
  368. public List<EntityIntersection> GetIntersectingPrims(Ray hray, float length, int count,
  369. bool frontFacesOnly, bool faceCenters, bool getAvatars,
  370. bool getLand, bool getPrims)
  371. {
  372. // Primitive Ray Tracing
  373. List<EntityIntersection> result = new List<EntityIntersection>(count);
  374. if (getPrims)
  375. {
  376. ISceneEntity[] EntityList = Entities.GetEntities(hray.Origin, length);
  377. result.AddRange(
  378. EntityList.OfType<SceneObjectGroup>()
  379. .Select(reportingG => reportingG.TestIntersection(hray, frontFacesOnly, faceCenters))
  380. .Where(inter => inter.HitTF));
  381. }
  382. if (getAvatars)
  383. {
  384. List<IScenePresence> presenceList = Entities.GetPresences();
  385. foreach (IScenePresence ent in presenceList)
  386. {
  387. //Do rough approximation and keep the # of loops down
  388. Vector3 newPos = hray.Origin;
  389. for (int i = 0; i < 100; i++)
  390. {
  391. newPos += ((Vector3.One*(length*(i/100)))*hray.Direction);
  392. if (ent.AbsolutePosition.ApproxEquals(newPos, ent.PhysicsActor.Size.X*2))
  393. {
  394. EntityIntersection intersection = new EntityIntersection();
  395. intersection.distance = length*(i/100);
  396. intersection.face = 0;
  397. intersection.HitTF = true;
  398. intersection.obj = ent;
  399. intersection.ipoint = newPos;
  400. intersection.normal = newPos;
  401. result.Add(intersection);
  402. break;
  403. }
  404. }
  405. }
  406. }
  407. if (getLand)
  408. {
  409. //TODO
  410. }
  411. result.Sort((a, b) => a.distance.CompareTo(b.distance));
  412. if (result.Count > count)
  413. result.RemoveRange(count, result.Count - count);
  414. return result;
  415. }
  416. #endregion
  417. #region ForEach* Methods
  418. /// <summary>
  419. /// Performs action on all scene object groups.
  420. /// </summary>
  421. /// <param name="action"></param>
  422. protected internal void ForEachSceneEntity(Action<ISceneEntity> action)
  423. {
  424. ISceneEntity[] objlist = Entities.GetEntities();
  425. foreach (ISceneEntity obj in objlist)
  426. {
  427. try
  428. {
  429. action(obj);
  430. }
  431. catch (Exception e)
  432. {
  433. // Catch it and move on. This includes situations where splist has inconsistent info
  434. MainConsole.Instance.WarnFormat("[SCENE]: Problem processing action in ForEachSOG: {0}",
  435. e.ToString());
  436. }
  437. }
  438. }
  439. /// <summary>
  440. /// Performs action on all scene presences. This can ultimately run the actions in parallel but
  441. /// any delegates passed in will need to implement their own locking on data they reference and
  442. /// modify outside of the scope of the delegate.
  443. /// </summary>
  444. /// <param name="action"></param>
  445. public void ForEachScenePresence(Action<IScenePresence> action)
  446. {
  447. // Once all callers have their delegates configured for parallelism, we can unleash this
  448. /*
  449. Action<ScenePresence> protectedAction = new Action<ScenePresence>(delegate(ScenePresence sp)
  450. {
  451. try
  452. {
  453. action(sp);
  454. }
  455. catch (Exception e)
  456. {
  457. MainConsole.Instance.Info("[BUG] in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString());
  458. MainConsole.Instance.Info("[BUG] Stack Trace: " + e.StackTrace);
  459. }
  460. });
  461. Parallel.ForEach<ScenePresence>(GetScenePresences(), protectedAction);
  462. */
  463. // For now, perform actions serially
  464. List<IScenePresence> presences = new List<IScenePresence>(GetScenePresences());
  465. foreach (IScenePresence sp in presences)
  466. {
  467. try
  468. {
  469. action(sp);
  470. }
  471. catch (Exception e)
  472. {
  473. MainConsole.Instance.Info("[BUG] in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString());
  474. MainConsole.Instance.Info("[BUG] Stack Trace: " + e.StackTrace);
  475. }
  476. }
  477. }
  478. #endregion ForEach* Methods
  479. #region Client Event handlers
  480. public void SubscribeToClientEvents(IClientAPI client)
  481. {
  482. client.OnUpdatePrimGroupPosition += UpdatePrimPosition;
  483. client.OnUpdatePrimSinglePosition += UpdatePrimSinglePosition;
  484. client.OnUpdatePrimGroupRotation += UpdatePrimRotation;
  485. client.OnUpdatePrimGroupMouseRotation += UpdatePrimRotation;
  486. client.OnUpdatePrimSingleRotation += UpdatePrimSingleRotation;
  487. client.OnUpdatePrimSingleRotationPosition += UpdatePrimSingleRotationPosition;
  488. client.OnUpdatePrimScale += UpdatePrimScale;
  489. client.OnUpdatePrimGroupScale += UpdatePrimGroupScale;
  490. client.OnUpdateExtraParams += UpdateExtraParam;
  491. client.OnUpdatePrimShape += UpdatePrimShape;
  492. client.OnUpdatePrimTexture += UpdatePrimTexture;
  493. client.OnGrabUpdate += MoveObject;
  494. client.OnSpinStart += SpinStart;
  495. client.OnSpinUpdate += SpinObject;
  496. client.OnObjectName += PrimName;
  497. client.OnObjectClickAction += PrimClickAction;
  498. client.OnObjectMaterial += PrimMaterial;
  499. client.OnLinkObjects += LinkObjects;
  500. client.OnDelinkObjects += DelinkObjects;
  501. client.OnObjectDuplicate += DuplicateObject;
  502. client.OnUpdatePrimFlags += UpdatePrimFlags;
  503. client.OnRequestObjectPropertiesFamily += RequestObjectPropertiesFamily;
  504. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  505. client.OnGrabObject += ProcessObjectGrab;
  506. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  507. client.OnDeGrabObject += ProcessObjectDeGrab;
  508. client.OnUndo += HandleUndo;
  509. client.OnRedo += HandleRedo;
  510. client.OnObjectDescription += PrimDescription;
  511. client.OnObjectIncludeInSearch += MakeObjectSearchable;
  512. client.OnObjectOwner += ObjectOwner;
  513. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  514. client.OnAddPrim += AddNewPrim;
  515. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  516. }
  517. public void UnSubscribeToClientEvents(IClientAPI client)
  518. {
  519. client.OnUpdatePrimGroupPosition -= UpdatePrimPosition;
  520. client.OnUpdatePrimSinglePosition -= UpdatePrimSinglePosition;
  521. client.OnUpdatePrimGroupRotation -= UpdatePrimRotation;
  522. client.OnUpdatePrimGroupMouseRotation -= UpdatePrimRotation;
  523. client.OnUpdatePrimSingleRotation -= UpdatePrimSingleRotation;
  524. client.OnUpdatePrimSingleRotationPosition -= UpdatePrimSingleRotationPosition;
  525. client.OnUpdatePrimScale -= UpdatePrimScale;
  526. client.OnUpdatePrimGroupScale -= UpdatePrimGroupScale;
  527. client.OnUpdateExtraParams -= UpdateExtraParam;
  528. client.OnUpdatePrimShape -= UpdatePrimShape;
  529. client.OnUpdatePrimTexture -= UpdatePrimTexture;
  530. client.OnGrabUpdate -= MoveObject;
  531. client.OnSpinStart -= SpinStart;
  532. client.OnSpinUpdate -= SpinObject;
  533. client.OnObjectName -= PrimName;
  534. client.OnObjectClickAction -= PrimClickAction;
  535. client.OnObjectMaterial -= PrimMaterial;
  536. client.OnLinkObjects -= LinkObjects;
  537. client.OnDelinkObjects -= DelinkObjects;
  538. client.OnObjectDuplicate -= DuplicateObject;
  539. client.OnUpdatePrimFlags -= UpdatePrimFlags;
  540. client.OnRequestObjectPropertiesFamily -= RequestObjectPropertiesFamily;
  541. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  542. client.OnGrabObject -= ProcessObjectGrab;
  543. client.OnGrabUpdate -= ProcessObjectGrabUpdate;
  544. client.OnDeGrabObject -= ProcessObjectDeGrab;
  545. client.OnUndo -= HandleUndo;
  546. client.OnRedo -= HandleRedo;
  547. client.OnObjectDescription -= PrimDescription;
  548. client.OnObjectIncludeInSearch -= MakeObjectSearchable;
  549. client.OnObjectOwner -= ObjectOwner;
  550. client.OnObjectGroupRequest -= HandleObjectGroupUpdate;
  551. client.OnAddPrim -= AddNewPrim;
  552. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  553. }
  554. public virtual void ProcessObjectGrab(uint localID, Vector3 offsetPos, IClientAPI remoteClient,
  555. List<SurfaceTouchEventArgs> surfaceArgs)
  556. {
  557. SurfaceTouchEventArgs surfaceArg = null;
  558. if (surfaceArgs != null && surfaceArgs.Count > 0)
  559. surfaceArg = surfaceArgs[0];
  560. ISceneChildEntity childPrim;
  561. if (TryGetPart(localID, out childPrim))
  562. {
  563. SceneObjectPart part = childPrim as SceneObjectPart;
  564. if (part != null)
  565. {
  566. SceneObjectGroup obj = part.ParentGroup;
  567. if (obj.RootPart.BlockGrab || obj.RootPart.BlockGrabObject)
  568. return;
  569. // Currently only grab/touch for the single prim
  570. // the client handles rez correctly
  571. obj.ObjectGrabHandler(localID, offsetPos, remoteClient);
  572. // If the touched prim handles touches, deliver it
  573. // If not, deliver to root prim
  574. m_parentScene.EventManager.TriggerObjectGrab(part, part, part.OffsetPosition, remoteClient,
  575. surfaceArg);
  576. // Deliver to the root prim if the touched prim doesn't handle touches
  577. // or if we're meant to pass on touches anyway. Don't send to root prim
  578. // if prim touched is the root prim as we just did it
  579. if ((part.LocalId != obj.RootPart.LocalId))
  580. {
  581. const int PASS_IF_NOT_HANDLED = 0;
  582. const int PASS_ALWAYS = 1;
  583. const int PASS_NEVER = 2;
  584. if (part.PassTouch == PASS_NEVER)
  585. {
  586. }
  587. if (part.PassTouch == PASS_ALWAYS)
  588. {
  589. m_parentScene.EventManager.TriggerObjectGrab(obj.RootPart, part, part.OffsetPosition,
  590. remoteClient, surfaceArg);
  591. }
  592. else if (((part.ScriptEvents & scriptEvents.touch_start) == 0) &&
  593. part.PassTouch == PASS_IF_NOT_HANDLED) //If no event in this prim, pass to parent
  594. {
  595. m_parentScene.EventManager.TriggerObjectGrab(obj.RootPart, part, part.OffsetPosition,
  596. remoteClient, surfaceArg);
  597. }
  598. }
  599. }
  600. }
  601. }
  602. public virtual void ProcessObjectGrabUpdate(UUID objectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient,
  603. List<SurfaceTouchEventArgs> surfaceArgs)
  604. {
  605. SurfaceTouchEventArgs surfaceArg = null;
  606. if (surfaceArgs != null && surfaceArgs.Count > 0)
  607. surfaceArg = surfaceArgs[0];
  608. ISceneChildEntity childPrim;
  609. if (TryGetPart(objectID, out childPrim))
  610. {
  611. SceneObjectPart part = childPrim as SceneObjectPart;
  612. if (part != null)
  613. {
  614. SceneObjectGroup obj = part.ParentGroup;
  615. if (obj.RootPart.BlockGrab || obj.RootPart.BlockGrabObject)
  616. return;
  617. // If the touched prim handles touches, deliver it
  618. // If not, deliver to root prim
  619. m_parentScene.EventManager.TriggerObjectGrabbing(part, part, part.OffsetPosition, remoteClient,
  620. surfaceArg);
  621. // Deliver to the root prim if the touched prim doesn't handle touches
  622. // or if we're meant to pass on touches anyway. Don't send to root prim
  623. // if prim touched is the root prim as we just did it
  624. if ((part.LocalId != obj.RootPart.LocalId))
  625. {
  626. const int PASS_IF_NOT_HANDLED = 0;
  627. const int PASS_ALWAYS = 1;
  628. const int PASS_NEVER = 2;
  629. if (part.PassTouch == PASS_NEVER)
  630. {
  631. }
  632. if (part.PassTouch == PASS_ALWAYS)
  633. {
  634. m_parentScene.EventManager.TriggerObjectGrabbing(obj.RootPart, part, part.OffsetPosition,
  635. remoteClient, surfaceArg);
  636. }
  637. else if ((((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
  638. ((part.ScriptEvents & scriptEvents.touch) == 0)) &&
  639. part.PassTouch == PASS_IF_NOT_HANDLED) //If no event in this prim, pass to parent
  640. {
  641. m_parentScene.EventManager.TriggerObjectGrabbing(obj.RootPart, part, part.OffsetPosition,
  642. remoteClient, surfaceArg);
  643. }
  644. }
  645. }
  646. }
  647. }
  648. public virtual void ProcessObjectDeGrab(uint localID, IClientAPI remoteClient,
  649. List<SurfaceTouchEventArgs> surfaceArgs)
  650. {
  651. SurfaceTouchEventArgs surfaceArg = null;
  652. if (surfaceArgs != null && surfaceArgs.Count > 0)
  653. surfaceArg = surfaceArgs[0];
  654. ISceneChildEntity childPrim;
  655. if (TryGetPart(localID, out childPrim))
  656. {
  657. SceneObjectPart part = childPrim as SceneObjectPart;
  658. if (part != null)
  659. {
  660. SceneObjectGroup obj = part.ParentGroup;
  661. // If the touched prim handles touches, deliver it
  662. // If not, deliver to root prim
  663. m_parentScene.EventManager.TriggerObjectDeGrab(part, part, remoteClient, surfaceArg);
  664. if ((part.LocalId != obj.RootPart.LocalId))
  665. {
  666. const int PASS_IF_NOT_HANDLED = 0;
  667. const int PASS_ALWAYS = 1;
  668. const int PASS_NEVER = 2;
  669. if (part.PassTouch == PASS_NEVER)
  670. {
  671. }
  672. if (part.PassTouch == PASS_ALWAYS)
  673. {
  674. m_parentScene.EventManager.TriggerObjectDeGrab(obj.RootPart, part, remoteClient, surfaceArg);
  675. }
  676. else if ((((part.ScriptEvents & scriptEvents.touch_start) == 0) ||
  677. ((part.ScriptEvents & scriptEvents.touch_end) == 0)) &&
  678. part.PassTouch == PASS_IF_NOT_HANDLED) //If no event in this prim, pass to parent
  679. {
  680. m_parentScene.EventManager.TriggerObjectDeGrab(obj.RootPart, part, remoteClient,
  681. surfaceArg);
  682. }
  683. }
  684. }
  685. }
  686. }
  687. /// <summary>
  688. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  689. /// </summary>
  690. /// <param name="RayStart"></param>
  691. /// <param name="RayEnd"></param>
  692. /// <param name="RayTargetID"></param>
  693. /// <param name="rot"></param>
  694. /// <param name="bypassRayCast"></param>
  695. /// <param name="RayEndIsIntersection"></param>
  696. /// <param name="frontFacesOnly"></param>
  697. /// <param name="scale"></param>
  698. /// <param name="FaceCenter"></param>
  699. /// <returns></returns>
  700. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot,
  701. byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly,
  702. Vector3 scale, bool FaceCenter)
  703. {
  704. Vector3 pos = Vector3.Zero;
  705. if (RayEndIsIntersection == 1)
  706. {
  707. pos = RayEnd;
  708. return pos;
  709. }
  710. if (RayTargetID != UUID.Zero)
  711. {
  712. ISceneChildEntity target = m_parentScene.GetSceneObjectPart(RayTargetID);
  713. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  714. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  715. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  716. if (target != null)
  717. {
  718. pos = target.AbsolutePosition;
  719. //MainConsole.Instance.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());
  720. // TODO: Raytrace better here
  721. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  722. Ray NewRay = new Ray(AXOrigin, AXdirection);
  723. // Ray Trace against target here
  724. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly,
  725. FaceCenter);
  726. // Un-comment out the following line to Get Raytrace results printed to the console.
  727. //MainConsole.Instance.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  728. float ScaleOffset = 0.5f;
  729. // If we hit something
  730. if (ei.HitTF)
  731. {
  732. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  733. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  734. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  735. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  736. ScaleOffset = Math.Abs(ScaleOffset);
  737. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  738. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  739. // Set the position to the intersection point
  740. Vector3 offset = (normal*(ScaleOffset/2f));
  741. pos = (intersectionpoint + offset);
  742. //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
  743. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  744. // Un-offset the prim (it gets offset later by the consumer method)
  745. //pos.Z -= 0.25F;
  746. }
  747. return pos;
  748. }
  749. else
  750. {
  751. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  752. EntityIntersection ei = GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  753. // Un-comment the following line to print the raytrace results to the console.
  754. //MainConsole.Instance.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  755. pos = ei.HitTF ? new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z) : RayEnd;
  756. return pos;
  757. }
  758. }
  759. // fall back to our stupid functionality
  760. pos = RayEnd;
  761. //increase height so its above the ground.
  762. //should be getting the normal of the ground at the rez point and using that?
  763. pos.Z += scale.Z/2f;
  764. return pos;
  765. }
  766. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot,
  767. PrimitiveBaseShape shape,
  768. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  769. byte RayEndIsIntersection)
  770. {
  771. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection,
  772. true, new Vector3(0.5f, 0.5f, 0.5f), false);
  773. string reason;
  774. if (m_parentScene.Permissions.CanRezObject(1, ownerID, pos, out reason))
  775. {
  776. AddNewPrim(ownerID, groupID, pos, rot, shape);
  777. }
  778. else
  779. {
  780. GetScenePresence(ownerID)
  781. .ControllingClient.SendAlertMessage("You do not have permission to rez objects here: " + reason);
  782. }
  783. }
  784. /// <summary>
  785. /// Create a New SceneObjectGroup/Part by raycasting
  786. /// </summary>
  787. /// <param name="ownerID"></param>
  788. /// <param name="groupID"></param>
  789. /// <param name="pos"></param>
  790. /// <param name="rot"></param>
  791. /// <param name="shape"></param>
  792. public virtual ISceneEntity AddNewPrim(
  793. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  794. {
  795. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape, m_DefaultObjectName,
  796. m_parentScene);
  797. // If an entity creator has been registered for this prim type then use that
  798. if (m_entityCreators.ContainsKey((PCode) shape.PCode))
  799. {
  800. sceneObject =
  801. (SceneObjectGroup)
  802. m_entityCreators[(PCode) shape.PCode].CreateEntity(sceneObject, ownerID, groupID, pos, rot, shape);
  803. }
  804. else
  805. {
  806. // Otherwise, use this default creation code;
  807. sceneObject.SetGroup(groupID, ownerID, false);
  808. AddPrimToScene(sceneObject);
  809. sceneObject.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
  810. }
  811. return sceneObject;
  812. }
  813. /// <summary>
  814. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  815. /// RayEnd and RayStart to determine what the angle of the ray is
  816. /// </summary>
  817. /// <param name="localID">ID of object to duplicate</param>
  818. /// <param name="dupeFlags"></param>
  819. /// <param name="AgentID">Agent doing the duplication</param>
  820. /// <param name="GroupID">Group of new object</param>
  821. /// <param name="RayTargetObj">The target of the Ray</param>
  822. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  823. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  824. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  825. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  826. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  827. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  828. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  829. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  830. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters,
  831. bool CopyRotates)
  832. {
  833. const bool frontFacesOnly = true;
  834. //MainConsole.Instance.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  835. ISceneChildEntity target = m_parentScene.GetSceneObjectPart(localID);
  836. ISceneChildEntity target2 = m_parentScene.GetSceneObjectPart(RayTargetObj);
  837. IScenePresence Sp = GetScenePresence(AgentID);
  838. if (target != null && target2 != null)
  839. {
  840. Vector3 pos;
  841. if (EnableFakeRaycasting)
  842. {
  843. RayStart = Sp.CameraPosition;
  844. RayEnd = pos = target2.AbsolutePosition;
  845. }
  846. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  847. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  848. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  849. if (target2.ParentEntity != null)
  850. {
  851. pos = target2.AbsolutePosition;
  852. // TODO: Raytrace better here
  853. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), false, false);
  854. Ray NewRay = new Ray(AXOrigin, AXdirection);
  855. // Ray Trace against target here
  856. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly,
  857. CopyCenters);
  858. // Un-comment out the following line to Get Raytrace results printed to the console.
  859. //MainConsole.Instance.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  860. float ScaleOffset = 0.5f;
  861. // If we hit something
  862. if (ei.HitTF)
  863. {
  864. Vector3 scale = target.Scale;
  865. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  866. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  867. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  868. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  869. ScaleOffset = Math.Abs(ScaleOffset);
  870. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  871. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  872. Vector3 offset = normal*(ScaleOffset/2f);
  873. pos = intersectionpoint + offset;
  874. // stick in offset format from the original prim
  875. pos = pos - target.ParentEntity.AbsolutePosition;
  876. if (CopyRotates)
  877. {
  878. Quaternion worldRot = target2.GetWorldRotation();
  879. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  880. DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  881. //obj.Rotation = worldRot;
  882. //obj.UpdateGroupRotationR(worldRot);
  883. }
  884. else
  885. {
  886. DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID,
  887. Quaternion.Identity);
  888. }
  889. }
  890. return;
  891. }
  892. return;
  893. }
  894. }
  895. /// <value>
  896. /// Registered classes that are capable of creating entities.
  897. /// </value>
  898. protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
  899. public void RegisterEntityCreatorModule(IEntityCreator entityCreator)
  900. {
  901. lock (m_entityCreators)
  902. {
  903. foreach (PCode pcode in entityCreator.CreationCapabilities)
  904. {
  905. m_entityCreators[pcode] = entityCreator;
  906. }
  907. }
  908. }
  909. /// <summary>
  910. /// Unregister a module commander and all its commands
  911. /// </summary>
  912. /// <param name="entityCreator"></param>
  913. public void UnregisterEntityCreatorCommander(IEntityCreator entityCreator)
  914. {
  915. lock (m_entityCreators)
  916. {
  917. foreach (PCode pcode in entityCreator.CreationCapabilities)
  918. {
  919. m_entityCreators[pcode] = null;
  920. }
  921. }
  922. }
  923. protected internal void ObjectOwner(IClientAPI remoteClient, UUID ownerID, UUID groupID, List<uint> localIDs)
  924. {
  925. if (!m_parentScene.Permissions.IsGod(remoteClient.AgentId))
  926. {
  927. if (ownerID != UUID.Zero)
  928. return;
  929. if (!m_parentScene.Permissions.CanDeedObject(remoteClient.AgentId, groupID))
  930. return;
  931. }
  932. List<ISceneEntity> groups = new List<ISceneEntity>();
  933. foreach (uint localID in localIDs)
  934. {
  935. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(localID);
  936. if (!groups.Contains(part.ParentEntity))
  937. groups.Add(part.ParentEntity);
  938. }
  939. foreach (ISceneEntity sog in groups)
  940. {
  941. if (ownerID != UUID.Zero)
  942. {
  943. sog.SetOwnerId(ownerID);
  944. sog.SetGroup(groupID, remoteClient.AgentId, true);
  945. sog.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
  946. foreach (ISceneChildEntity child in sog.ChildrenEntities())
  947. child.Inventory.ChangeInventoryOwner(ownerID);
  948. }
  949. else
  950. {
  951. if (!m_parentScene.Permissions.CanEditObject(sog.UUID, remoteClient.AgentId))
  952. continue;
  953. if (sog.GroupID != groupID)
  954. continue;
  955. foreach (ISceneChildEntity child in sog.ChildrenEntities())
  956. {
  957. child.LastOwnerID = child.OwnerID;
  958. child.Inventory.ChangeInventoryOwner(groupID);
  959. }
  960. sog.SetOwnerId(groupID);
  961. sog.ApplyNextOwnerPermissions();
  962. }
  963. //Trigger the prim count event so that this parcel gets changed!
  964. m_parentScene.AuroraEventManager.FireGenericEventHandler("ObjectChangedOwner", sog);
  965. }
  966. foreach (uint localID in localIDs)
  967. {
  968. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(localID);
  969. part.GetProperties(remoteClient);
  970. }
  971. }
  972. /// <summary>
  973. /// </summary>
  974. /// <param name="LocalID"></param>
  975. /// <param name="scale"></param>
  976. /// <param name="remoteClient"></param>
  977. protected internal void UpdatePrimScale(uint LocalID, Vector3 scale, IClientAPI remoteClient)
  978. {
  979. IEntity entity;
  980. if (TryGetEntity(LocalID, out entity))
  981. {
  982. if (m_parentScene.Permissions.CanEditObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId))
  983. {
  984. ((SceneObjectGroup) entity).Resize(scale, LocalID);
  985. }
  986. }
  987. }
  988. protected internal void UpdatePrimGroupScale(uint LocalID, Vector3 scale, IClientAPI remoteClient)
  989. {
  990. IEntity entity;
  991. if (TryGetEntity(LocalID, out entity))
  992. {
  993. if (m_parentScene.Permissions.CanEditObject(entity.UUID, remoteClient.AgentId))
  994. {
  995. ((SceneObjectGroup) entity).GroupResize(scale, LocalID);
  996. }
  997. }
  998. }
  999. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field,
  1000. uint localId, uint mask, byte set)
  1001. {
  1002. // Check for spoofing.. since this is permissions we're talking about here!
  1003. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  1004. {
  1005. // Tell the object to do permission update
  1006. if (localId != 0)
  1007. {
  1008. ISceneEntity chObjectGroup = m_parentScene.GetGroupByPrim(localId);
  1009. if (chObjectGroup != null)
  1010. {
  1011. if (m_parentScene.Permissions.CanEditObject(chObjectGroup.UUID, controller.AgentId))
  1012. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  1013. }
  1014. }
  1015. }
  1016. }
  1017. /// <summary>
  1018. /// This handles the nifty little tool tip that you get when you drag your mouse over an object
  1019. /// Send to the Object Group to process. We don't know enough to service the request
  1020. /// </summary>
  1021. /// <param name="remoteClient"></param>
  1022. /// <param name="AgentID"></param>
  1023. /// <param name="RequestFlags"></param>
  1024. /// <param name="ObjectID"></param>
  1025. protected internal void RequestObjectPropertiesFamily(
  1026. IClientAPI remoteClient, UUID AgentID, uint RequestFlags, UUID ObjectID)
  1027. {
  1028. IEntity group;
  1029. if (TryGetEntity(ObjectID, out group))
  1030. {
  1031. if (group is SceneObjectGroup)
  1032. ((SceneObjectGroup) group).ServiceObjectPropertiesFamilyRequest(remoteClient, AgentID, RequestFlags);
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// </summary>
  1037. /// <param name="LocalID"></param>
  1038. /// <param name="rot"></param>
  1039. /// <param name="remoteClient"></param>
  1040. protected internal void UpdatePrimSingleRotation(uint LocalID, Quaternion rot, IClientAPI remoteClient)
  1041. {
  1042. IEntity entity;
  1043. if (TryGetEntity(LocalID, out entity))
  1044. {
  1045. if (m_parentScene.Permissions.CanMoveObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId))
  1046. {
  1047. ((SceneObjectGroup) entity).UpdateSingleRotation(rot, LocalID);
  1048. }
  1049. }
  1050. }
  1051. /// <summary>
  1052. /// </summary>
  1053. /// <param name="LocalID"></param>
  1054. /// <param name="rot"></param>
  1055. /// <param name="pos"></param>
  1056. /// <param name="remoteClient"></param>
  1057. protected internal void UpdatePrimSingleRotationPosition(uint LocalID, Quaternion rot, Vector3 pos,
  1058. IClientAPI remoteClient)
  1059. {
  1060. IEntity entity;
  1061. if (TryGetEntity(LocalID, out entity))
  1062. {
  1063. if (m_parentScene.Permissions.CanMoveObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId))
  1064. {
  1065. ((SceneObjectGroup) entity).UpdateSingleRotation(rot, pos, LocalID);
  1066. }
  1067. }
  1068. }
  1069. /// <summary>
  1070. /// </summary>
  1071. /// <param name="LocalID"></param>
  1072. /// <param name="rot"></param>
  1073. /// <param name="remoteClient"></param>
  1074. protected internal void UpdatePrimRotation(uint LocalID, Quaternion rot, IClientAPI remoteClient)
  1075. {
  1076. IEntity entity;
  1077. if (TryGetEntity(LocalID, out entity))
  1078. {
  1079. if (m_parentScene.Permissions.CanMoveObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId))
  1080. {
  1081. ((SceneObjectGroup) entity).UpdateGroupRotationR(rot);
  1082. }
  1083. }
  1084. }
  1085. /// <summary>
  1086. /// </summary>
  1087. /// <param name="LocalID"></param>
  1088. /// <param name="pos"></param>
  1089. /// <param name="rot"></param>
  1090. /// <param name="remoteClient"></param>
  1091. protected internal void UpdatePrimRotation(uint LocalID, Vector3 pos, Quaternion rot, IClientAPI remoteClient)
  1092. {
  1093. IEntity entity;
  1094. if (TryGetEntity(LocalID, out entity))
  1095. {
  1096. if (m_parentScene.Permissions.CanMoveObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId))
  1097. {
  1098. ((SceneObjectGroup) entity).UpdateGroupRotationPR(pos, rot);
  1099. }
  1100. }
  1101. }
  1102. /// <summary>
  1103. /// Update the position of the given part
  1104. /// </summary>
  1105. /// <param name="LocalID"></param>
  1106. /// <param name="pos"></param>
  1107. /// <param name="remoteClient"></param>
  1108. /// <param name="SaveUpdate"></param>
  1109. protected internal void UpdatePrimSinglePosition(uint LocalID, Vector3 pos, IClientAPI remoteClient,
  1110. bool SaveUpdate)
  1111. {
  1112. IEntity entity;
  1113. if (TryGetEntity(LocalID, out entity))
  1114. {
  1115. if (m_parentScene.Permissions.CanMoveObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId) ||
  1116. ((SceneObjectGroup) entity).IsAttachment)
  1117. {
  1118. ((SceneObjectGroup) entity).UpdateSinglePosition(pos, LocalID, SaveUpdate);
  1119. }
  1120. }
  1121. }
  1122. /// <summary>
  1123. /// Update the position of the given part
  1124. /// </summary>
  1125. /// <param name="LocalID"></param>
  1126. /// <param name="pos"></param>
  1127. /// <param name="remoteClient"></param>
  1128. /// <param name="SaveUpdate"></param>
  1129. protected internal void UpdatePrimPosition(uint LocalID, Vector3 pos, IClientAPI remoteClient, bool SaveUpdate)
  1130. {
  1131. IEntity entity;
  1132. if (TryGetEntity(LocalID, out entity))
  1133. {
  1134. if (((SceneObjectGroup) entity).IsAttachment ||
  1135. (((SceneObjectGroup) entity).RootPart.Shape.PCode == 9 &&
  1136. ((SceneObjectGroup) entity).RootPart.Shape.State != 0))
  1137. {
  1138. //We don't deal with attachments, they handle themselves in the IAttachmentModule
  1139. }
  1140. else
  1141. {
  1142. //Move has edit permission as well
  1143. if (
  1144. m_parentScene.Permissions.CanMoveObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId) &&
  1145. m_parentScene.Permissions.CanObjectEntry(((SceneObjectGroup) entity).UUID, false, pos,
  1146. remoteClient.AgentId))
  1147. {
  1148. ((SceneObjectGroup) entity).UpdateGroupPosition(pos, SaveUpdate);
  1149. }
  1150. else
  1151. {
  1152. IScenePresence SP = GetScenePresence(remoteClient.AgentId);
  1153. ((SceneObjectGroup) entity).ScheduleGroupUpdateToAvatar(SP, PrimUpdateFlags.FullUpdate);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /// <summary>
  1159. /// Update the texture entry of the given prim.
  1160. /// </summary>
  1161. /// A texture entry is an object that contains details of all the textures of the prim's face. In this case,
  1162. /// the texture is given in its byte serialized form.
  1163. /// <param name="LocalID"></param>
  1164. /// <param name="texture"></param>
  1165. /// <param name="remoteClient"></param>
  1166. protected internal void UpdatePrimTexture(uint LocalID, byte[] texture, IClientAPI remoteClient)
  1167. {
  1168. IEntity entity;
  1169. if (TryGetEntity(LocalID, out entity))
  1170. {
  1171. if (m_parentScene.Permissions.CanEditObject(((SceneObjectGroup) entity).UUID, remoteClient.AgentId))
  1172. {
  1173. ((SceneObjectGroup) entity).UpdateTextureEntry(LocalID, texture, true);
  1174. }
  1175. }
  1176. }
  1177. /// <summary>
  1178. /// A user has changed an object setting
  1179. /// </summary>
  1180. /// <param name="LocalID"></param>
  1181. /// <param name="blocks"></param>
  1182. /// <param name="remoteClient"></param>
  1183. /// <param name="UsePhysics"></param>
  1184. /// <param name="IsTemporary"></param>
  1185. /// <param name="IsPhantom"></param>
  1186. protected internal void UpdatePrimFlags(uint LocalID, bool UsePhysics, bool IsTemporary, bool IsPhantom,
  1187. ObjectFlagUpdatePacket.ExtraPhysicsBlock[] blocks,
  1188. IClientAPI remoteClient)
  1189. {
  1190. IEntity entity;
  1191. if (TryGetEntity(LocalID, out entity))
  1192. {
  1193. if (m_parentScene.Permissions.CanEditObject(entity.UUID, remoteClient.AgentId))
  1194. {
  1195. ((SceneObjectGroup) entity).UpdatePrimFlags(LocalID, UsePhysics, IsTemporary, IsPhantom, false,
  1196. blocks);
  1197. // VolumeDetect can't be set via UI and will always be off when a change is made there
  1198. }
  1199. }
  1200. }
  1201. /// <summary>
  1202. /// Move the given object
  1203. /// </summary>
  1204. /// <param name="ObjectID"></param>
  1205. /// <param name="offset"></param>
  1206. /// <param name="pos"></param>
  1207. /// <param name="remoteClient"></param>
  1208. /// <param name="surfaceArgs"></param>
  1209. protected internal void MoveObject(UUID ObjectID, Vector3 offset, Vector3 pos, IClientAPI remoteClient,
  1210. List<SurfaceTouchEventArgs> surfaceArgs)
  1211. {
  1212. IEntity group;
  1213. if (TryGetEntity(ObjectID, out group))
  1214. {
  1215. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId)) // && PermissionsMngr.)
  1216. {
  1217. ((SceneObjectGroup) group).GrabMovement(offset, pos, remoteClient);
  1218. }
  1219. }
  1220. }
  1221. /// <summary>
  1222. /// Start spinning the given object
  1223. /// </summary>
  1224. /// <param name="ObjectID"></param>
  1225. /// <param name="remoteClient"></param>
  1226. protected internal void SpinStart(UUID ObjectID, IClientAPI remoteClient)
  1227. {
  1228. IEntity group;
  1229. if (TryGetEntity(ObjectID, out group))
  1230. {
  1231. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId)) // && PermissionsMngr.)
  1232. {
  1233. ((SceneObjectGroup) group).SpinStart(remoteClient);
  1234. }
  1235. }
  1236. }
  1237. /// <summary>
  1238. /// Spin the given object
  1239. /// </summary>
  1240. /// <param name="ObjectID"></param>
  1241. /// <param name="rotation"></param>
  1242. /// <param name="remoteClient"></param>
  1243. protected internal void SpinObject(UUID ObjectID, Quaternion rotation, IClientAPI remoteClient)
  1244. {
  1245. IEntity group;
  1246. if (TryGetEntity(ObjectID, out group))
  1247. {
  1248. if (m_parentScene.Permissions.CanMoveObject(group.UUID, remoteClient.AgentId)) // && PermissionsMngr.)
  1249. {
  1250. ((SceneObjectGroup) group).SpinMovement(rotation, remoteClient);
  1251. }
  1252. // This is outside the above permissions condition
  1253. // so that if the object is locked the client moving the object
  1254. // get's it's position on the simulator even if it was the same as before
  1255. // This keeps the moving user's client in sync with the rest of the world.
  1256. ((SceneObjectGroup) group).ScheduleGroupTerseUpdate();
  1257. }
  1258. }
  1259. /// <summary>
  1260. /// </summary>
  1261. /// <param name="remoteClient"></param>
  1262. /// <param name="LocalID"></param>
  1263. /// <param name="name"></param>
  1264. protected internal void PrimName(IClientAPI remoteClient, uint LocalID, string name)
  1265. {
  1266. IEntity group;
  1267. if (TryGetEntity(LocalID, out group))
  1268. {
  1269. if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
  1270. {
  1271. ((SceneObjectGroup) group).SetPartName(Util.CleanString(name), LocalID);
  1272. ((SceneObjectGroup) group).ScheduleGroupUpdate(PrimUpdateFlags.FindBest);
  1273. }
  1274. }
  1275. }
  1276. /// <summary>
  1277. /// </summary>
  1278. /// <param name="LocalID"></param>
  1279. /// <param name="description"></param>
  1280. /// <param name="remoteClient"></param>
  1281. protected internal void PrimDescription(IClientAPI remoteClient, uint LocalID, string description)
  1282. {
  1283. IEntity group;
  1284. if (TryGetEntity(LocalID, out group))
  1285. {
  1286. if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
  1287. {
  1288. ((SceneObjectGroup) group).SetPartDescription(Util.CleanString(description), LocalID);
  1289. ((SceneObjectGroup) group).ScheduleGroupUpdate(PrimUpdateFlags.ClickAction);
  1290. }
  1291. }
  1292. }
  1293. protected internal void PrimClickAction(IClientAPI remoteClient, uint LocalID, string clickAction)
  1294. {
  1295. IEntity group;
  1296. if (TryGetEntity(LocalID, out group))
  1297. {
  1298. if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
  1299. {
  1300. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(LocalID);
  1301. part.ClickAction = Convert.ToByte(clickAction);
  1302. ((ISceneEntity) group).ScheduleGroupUpdate(PrimUpdateFlags.ClickAction);
  1303. }
  1304. }
  1305. }
  1306. protected internal void PrimMaterial(IClientAPI remoteClient, uint LocalID, string material)
  1307. {
  1308. IEntity group;
  1309. if (TryGetEntity(LocalID, out group))
  1310. {
  1311. if (m_parentScene.Permissions.CanEditObject(group.UUID, remoteClient.AgentId))
  1312. {
  1313. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(LocalID);
  1314. part.UpdateMaterial(Convert.ToInt32(material));
  1315. //Update the client here as well... we changed restitution and friction in the physics engine probably
  1316. IEventQueueService eqs = m_parentScene.RequestModuleInterface<IEventQueueService>();
  1317. if (eqs != null)
  1318. eqs.ObjectPhysicsProperties(new[] {part}, remoteClient.AgentId,
  1319. m_parentScene.RegionInfo.RegionID);
  1320. ((ISceneEntity) group).ScheduleGroupUpdate(PrimUpdateFlags.ClickAction);
  1321. }
  1322. }
  1323. }
  1324. protected internal void UpdateExtraParam(UUID agentID, uint LocalID, ushort type, bool inUse, byte[] data)
  1325. {
  1326. ISceneChildEntity part;
  1327. if (TryGetPart(LocalID, out part))
  1328. {
  1329. if (m_parentScene.Permissions.CanEditObject(part.UUID, agentID))
  1330. {
  1331. ((SceneObjectPart) part).UpdateExtraParam(type, inUse, data);
  1332. }
  1333. }
  1334. }
  1335. /// <summary>
  1336. /// </summary>
  1337. /// <param name="LocalID"></param>
  1338. /// <param name="shapeBlock"></param>
  1339. /// <param name="agentID"></param>
  1340. protected internal void UpdatePrimShape(UUID agentID, uint LocalID, UpdateShapeArgs shapeBlock)
  1341. {
  1342. ISceneChildEntity part;
  1343. if (TryGetPart(LocalID, out part))
  1344. {
  1345. if (m_parentScene.Permissions.CanEditObject(part.UUID, agentID))
  1346. {
  1347. ObjectShapePacket.ObjectDataBlock shapeData = new ObjectShapePacket.ObjectDataBlock
  1348. {
  1349. ObjectLocalID = shapeBlock.ObjectLocalID,
  1350. PathBegin = shapeBlock.PathBegin,
  1351. PathCurve = shapeBlock.PathCurve,
  1352. PathEnd = shapeBlock.PathEnd,
  1353. PathRadiusOffset = shapeBlock.PathRadiusOffset,
  1354. PathRevolutions = shapeBlock.PathRevolutions,
  1355. PathScaleX = shapeBlock.PathScaleX,
  1356. PathScaleY = shapeBlock.PathScaleY,
  1357. PathShearX = shapeBlock.PathShearX,
  1358. PathShearY = shapeBlock.PathShearY,
  1359. PathSkew = shapeBlock.PathSkew,
  1360. PathTaperX = shapeBlock.PathTaperX,
  1361. PathTaperY = shapeBlock.PathTaperY,
  1362. PathTwist = shapeBlock.PathTwist,
  1363. PathTwistBegin = shapeBlock.PathTwistBegin,
  1364. ProfileBegin = shapeBlock.ProfileBegin,
  1365. ProfileCurve = shapeBlock.ProfileCurve,
  1366. ProfileEnd = shapeBlock.ProfileEnd,
  1367. ProfileHollow = shapeBlock.ProfileHollow
  1368. };
  1369. ((SceneObjectPart) part).UpdateShape(shapeData);
  1370. }
  1371. }
  1372. }
  1373. /// <summary>
  1374. /// Make this object be added to search
  1375. /// </summary>
  1376. /// <param name="remoteClient"></param>
  1377. /// <param name="IncludeInSearch"></param>
  1378. /// <param name="LocalID"></param>
  1379. protected internal void MakeObjectSearchable(IClientAPI remoteClient, bool IncludeInSearch, uint LocalID)
  1380. {
  1381. UUID user = remoteClient.AgentId;
  1382. UUID objid = UUID.Zero;
  1383. IEntity entity;
  1384. if (!TryGetEntity(LocalID, out entity))
  1385. return;
  1386. SceneObjectGroup grp = (SceneObjectGroup) entity;
  1387. //Protip: In my day, we didn't call them searchable objects, we called them limited point-to-point joints
  1388. //aka ObjectFlags.JointWheel = IncludeInSearch
  1389. //Permissions model: Object can be REMOVED from search IFF:
  1390. // * User owns object
  1391. //use CanEditObject
  1392. //Object can be ADDED to search IFF:
  1393. // * User owns object
  1394. // * Asset/DRM permission bit "modify" is enabled
  1395. //use CanEditObjectPosition
  1396. // libomv will complain about PrimFlags.JointWheel being
  1397. // deprecated, so we
  1398. #pragma warning disable 0612
  1399. if (IncludeInSearch && m_parentScene.Permissions.CanEditObject(objid, user))
  1400. {
  1401. grp.RootPart.AddFlag(PrimFlags.JointWheel);
  1402. }
  1403. else if (!IncludeInSearch && m_parentScene.Permissions.CanEditObject(objid, user))
  1404. {
  1405. grp.RootPart.RemFlag(PrimFlags.JointWheel);
  1406. }
  1407. #pragma warning restore 0612
  1408. }
  1409. /// <summary>
  1410. /// Duplicate the given entity and add it to the world
  1411. /// </summary>
  1412. /// <param name="LocalID">LocalID of the object to duplicate</param>
  1413. /// <param name="offset">Duplicated objects position offset from the original entity</param>
  1414. /// <param name="flags">Flags to give the Duplicated object</param>
  1415. /// <param name="AgentID"></param>
  1416. /// <param name="GroupID"></param>
  1417. /// <param name="rot">Rotation to have the duplicated entity set to</param>
  1418. /// <returns></returns>
  1419. public bool DuplicateObject(uint LocalID, Vector3 offset, uint flags, UUID AgentID, UUID GroupID, Quaternion rot)
  1420. {
  1421. //MainConsole.Instance.DebugFormat("[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", originalPrim, offset, AgentID);
  1422. IEntity entity;
  1423. if (TryGetEntity(LocalID, out entity))
  1424. {
  1425. SceneObjectGroup original = (SceneObjectGroup) entity;
  1426. string reason = "You cannot duplicate this object.";
  1427. if (
  1428. m_parentScene.Permissions.CanDuplicateObject(original.ChildrenList.Count, original.UUID, AgentID,
  1429. original.AbsolutePosition) &&
  1430. m_parentScene.Permissions.CanRezObject(1, AgentID, original.AbsolutePosition + offset, out reason))
  1431. {
  1432. ISceneEntity duplicatedEntity = DuplicateEntity(original);
  1433. duplicatedEntity.AbsolutePosition = duplicatedEntity.AbsolutePosition + offset;
  1434. SceneObjectGroup duplicatedGroup = (SceneObjectGroup) duplicatedEntity;
  1435. if (original.OwnerID != AgentID)
  1436. {
  1437. duplicatedGroup.SetOwnerId(AgentID);
  1438. duplicatedGroup.SetRootPartOwner(duplicatedGroup.RootPart, AgentID, GroupID);
  1439. List<SceneObjectPart> partList =
  1440. new List<SceneObjectPart>(duplicatedGroup.ChildrenList);
  1441. if (m_parentScene.Permissions.PropagatePermissions())
  1442. {
  1443. foreach (SceneObjectPart child in partList)
  1444. {
  1445. child.Inventory.ChangeInventoryOwner(AgentID);
  1446. child.TriggerScriptChangedEvent(Changed.OWNER);
  1447. child.ApplyNextOwnerPermissions();
  1448. }
  1449. }
  1450. duplicatedGroup.RootPart.ObjectSaleType = 0;
  1451. duplicatedGroup.RootPart.SalePrice = 10;
  1452. }
  1453. // Since we copy from a source group that is in selected
  1454. // state, but the copy is shown deselected in the viewer,
  1455. // We need to clear the selection flag here, else that
  1456. // prim never gets persisted at all. The client doesn't
  1457. // think it's selected, so it will never send a deselect...
  1458. duplicatedGroup.IsSelected = false;
  1459. if (rot != Quaternion.Identity)
  1460. {
  1461. duplicatedGroup.UpdateGroupRotationR(rot);
  1462. }
  1463. duplicatedGroup.CreateScriptInstances(0, true, StateSource.NewRez, UUID.Zero, false);
  1464. duplicatedGroup.HasGroupChanged = true;
  1465. duplicatedGroup.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
  1466. // required for physics to update it's position
  1467. duplicatedGroup.AbsolutePosition = duplicatedGroup.AbsolutePosition;
  1468. return true;
  1469. }
  1470. else
  1471. GetScenePresence(AgentID).ControllingClient.SendAlertMessage(reason);
  1472. }
  1473. return false;
  1474. }
  1475. #region Linking and Delinking
  1476. public void DelinkObjects(List<uint> primIds, IClientAPI client)
  1477. {
  1478. List<ISceneChildEntity> parts =
  1479. primIds.Select(localID => m_parentScene.GetSceneObjectPart(localID)).Where(part => part != null).Where(
  1480. part => m_parentScene.Permissions.CanDelinkObject(client.AgentId, part.ParentEntity.UUID)).ToList();
  1481. DelinkObjects(parts);
  1482. }
  1483. public void LinkObjects(IClientAPI client, uint parentPrimId, List<uint> childPrimIds)
  1484. {
  1485. List<UUID> owners = new List<UUID>();
  1486. List<ISceneChildEntity> children = new List<ISceneChildEntity>();
  1487. ISceneChildEntity root = m_parentScene.GetSceneObjectPart(parentPrimId);
  1488. if (root == null)
  1489. {
  1490. MainConsole.Instance.DebugFormat("[LINK]: Can't find linkset root prim {0}", parentPrimId);
  1491. return;
  1492. }
  1493. if (!m_parentScene.Permissions.CanLinkObject(client.AgentId, root.ParentEntity.UUID))
  1494. {
  1495. MainConsole.Instance.DebugFormat("[LINK]: Refusing link. No permissions on root prim");
  1496. return;
  1497. }
  1498. foreach (uint localID in childPrimIds)
  1499. {
  1500. ISceneChildEntity part = m_parentScene.GetSceneObjectPart(localID);
  1501. if (part == null)
  1502. continue;
  1503. if (!owners.Contains(part.OwnerID))
  1504. owners.Add(part.OwnerID);
  1505. if (m_parentScene.Permissions.CanLinkObject(client.AgentId, part.ParentEntity.UUID))
  1506. children.Add(part);
  1507. }
  1508. // Must be all one owner
  1509. //
  1510. if (owners.Count > 1)
  1511. {
  1512. MainConsole.Instance.DebugFormat("[LINK]: Refusing link. Too many owners");
  1513. client.SendAlertMessage("Permissions: Cannot link, too many owners.");
  1514. return;
  1515. }
  1516. if (children.Count == 0)
  1517. {
  1518. MainConsole.Instance.DebugFormat("[LINK]: Refusing link. No permissions to link any of the children");
  1519. client.SendAlertMessage("Permissions: Cannot link, not enough permissions.");
  1520. return;
  1521. }
  1522. int LinkCount = children.Cast<SceneObjectPart>().Sum(part => part.ParentGroup.ChildrenList.Count);
  1523. IOpenRegionSettingsModule module = m_parentScene.RequestModuleInterface<IOpenRegionSettingsModule>();
  1524. if (module != null)
  1525. {
  1526. if (LinkCount > module.MaximumLinkCount &&
  1527. module.MaximumLinkCount != -1)
  1528. {
  1529. client.SendAlertMessage("You cannot link more than " + module.MaximumLinkCount +
  1530. " prims. Please try again with fewer prims.");
  1531. return;
  1532. }
  1533. if ((root.Flags & PrimFlags.Physics) == PrimFlags.Physics)
  1534. {
  1535. //We only check the root here because if the root is physical, it will be applied to all during the link
  1536. if (LinkCount > module.MaximumLinkCountPhys &&
  1537. module.MaximumLinkCountPhys != -1)
  1538. {
  1539. client.SendAlertMessage("You cannot link more than " + module.MaximumLinkCountPhys +
  1540. " physical prims. Please try again with fewer prims.");
  1541. return;
  1542. }
  1543. }
  1544. }
  1545. LinkObjects(root, children);
  1546. }
  1547. /// <summary>
  1548. /// Initial method invoked when we receive a link objects request from the client.
  1549. /// </summary>
  1550. /// <param name="root"></param>
  1551. /// <param name="children"></param>
  1552. protected internal void LinkObjects(ISceneChildEntity root, List<ISceneChildEntity> children)
  1553. {
  1554. Monitor.Enter(m_updateLock);
  1555. try
  1556. {
  1557. ISceneEntity parentGroup = root.ParentEntity;
  1558. List<ISceneEntity> childGroups = new List<ISceneEntity>();
  1559. if (parentGroup != null)
  1560. {
  1561. // We do this in reverse to get the link order of the prims correct
  1562. for (int i = children.Count - 1; i >= 0; i--)
  1563. {
  1564. ISceneEntity child = children[i].ParentEntity;
  1565. if (child != null)
  1566. {
  1567. // Make sure no child prim is set for sale
  1568. // So that, on delink, no prims are unwittingly
  1569. // left for sale and sold off
  1570. child.RootChild.ObjectSaleType = 0;
  1571. child.RootChild.SalePrice = 10;
  1572. childGroups.Add(child);
  1573. }
  1574. }
  1575. }
  1576. else
  1577. {
  1578. return; // parent is null so not in this region
  1579. }
  1580. foreach (ISceneEntity child in childGroups)
  1581. {
  1582. parentGroup.LinkToGroup(child);
  1583. // this is here so physics gets updated!
  1584. // Don't remove! Bad juju! Stay away! or fix physics!
  1585. child.AbsolutePosition = child.AbsolutePosition;
  1586. }
  1587. // We need to explicitly resend the newly link prim's object properties since no other actions
  1588. // occur on link to invoke this elsewhere (such as object selection)
  1589. parentGroup.RootChild.CreateSelected = true;
  1590. parentGroup.HasGroupChanged = true;
  1591. //parentGroup.RootPart.SendFullUpdateToAllClients(PrimUpdateFlags.FullUpdate);
  1592. //parentGroup.ScheduleGroupForFullUpdate(PrimUpdateFlags.FullUpdate);
  1593. parentGroup.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
  1594. parentGroup.TriggerScriptChangedEvent(Changed.LINK);
  1595. }
  1596. finally
  1597. {
  1598. Monitor.Exit(m_updateLock);
  1599. }
  1600. }
  1601. /// <summary>
  1602. /// Delink a linkset
  1603. /// </summary>
  1604. /// <param name="prims"></param>
  1605. protected internal void DelinkObjects(List<ISceneChildEntity> prims)
  1606. {
  1607. Monitor.Enter(m_updateLock);
  1608. try
  1609. {
  1610. List<ISceneChildEntity> childParts = new List<ISceneChildEntity>();
  1611. List<ISceneChildEntity> rootParts = new List<ISceneChildEntity>();
  1612. List<ISceneEntity> affectedGroups = new List<ISceneEntity>();
  1613. // Look them all up in one go, since that is comparatively expensive
  1614. //
  1615. foreach (ISceneChildEntity part in prims)
  1616. {
  1617. if (part != null)
  1618. {
  1619. if (part.ParentEntity.PrimCount != 1) // Skip single
  1620. {
  1621. if (part.LinkNum < 2) // Root
  1622. rootParts.Add(part);
  1623. else
  1624. childParts.Add(part);
  1625. ISceneEntity group = part.ParentEntity;
  1626. if (!affectedGroups.Contains(group))
  1627. affectedGroups.Add(group);
  1628. }
  1629. }
  1630. }
  1631. foreach (ISceneChildEntity child in childParts)
  1632. {
  1633. // Unlink all child parts from their groups
  1634. //
  1635. child.ParentEntity.DelinkFromGroup(child, true);
  1636. // These are not in affected groups and will not be
  1637. // handled further. Do the honors here.
  1638. child.ParentEntity.HasGroupChanged = true;
  1639. if (!affectedGroups.Contains(child.ParentEntity))
  1640. affectedGroups.Add(child.ParentEntity);
  1641. }
  1642. foreach (ISceneChildEntity root in rootParts)
  1643. {
  1644. // In most cases, this will run only one time, and the prim
  1645. // will be a solo prim
  1646. // However, editing linked parts and unlinking may be different
  1647. //
  1648. ISceneEntity group = root.ParentEntity;
  1649. List<ISceneChildEntity> newSet = new List<ISceneChildEntity>(group.ChildrenEntities());
  1650. int numChildren = group.PrimCount;
  1651. // If there are prims left in a link set, but the root is
  1652. // slated for unlink, we need to do this
  1653. //
  1654. if (numChildren != 1)
  1655. {
  1656. // Unlink the remaining set
  1657. //
  1658. bool sendEventsToRemainder = true;
  1659. if (numChildren > 1)
  1660. sendEventsToRemainder = false;
  1661. foreach (ISceneChildEntity p in newSet)
  1662. {
  1663. if (p != group.RootChild)
  1664. group.DelinkFromGroup(p, sendEventsToRemainder);
  1665. }
  1666. // If there is more than one prim remaining, we
  1667. // need to re-link
  1668. //
  1669. if (numChildren > 2)
  1670. {
  1671. // Remove old root
  1672. //
  1673. if (newSet.Contains(root))
  1674. newSet.Remove(root);
  1675. // Preserve link ordering
  1676. //
  1677. newSet.Sort(LinkSetSorter);
  1678. // Determine new root
  1679. //
  1680. ISceneChildEntity newRoot = newSet[0];
  1681. newSet.RemoveAt(0);
  1682. LinkObjects(newRoot, newSet);
  1683. if (!affectedGroups.Contains(newRoot.ParentEntity))
  1684. affectedGroups.Add(newRoot.ParentEntity);
  1685. }
  1686. }
  1687. }
  1688. // Finally, trigger events in the roots
  1689. //
  1690. foreach (ISceneEntity g in affectedGroups)
  1691. {
  1692. g.TriggerScriptChangedEvent(Changed.LINK);
  1693. g.HasGroupChanged = true; // Persist
  1694. g.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
  1695. }
  1696. //Fix undo states now that the linksets have been changed
  1697. foreach (ISceneChildEntity part in prims)
  1698. {
  1699. part.StoreUndoState();
  1700. }
  1701. }
  1702. finally
  1703. {
  1704. Monitor.Exit(m_updateLock);
  1705. }
  1706. }
  1707. /// <summary>
  1708. /// Sorts a list of Parts by Link Number so they end up in the correct order
  1709. /// </summary>
  1710. /// <param name="a"></param>
  1711. /// <param name="b"></param>
  1712. /// <returns></returns>
  1713. public int LinkSetSorter(ISceneChildEntity a, ISceneChildEntity b)
  1714. {
  1715. return a.LinkNum.CompareTo(b.LinkNum);
  1716. }
  1717. #endregion
  1718. #endregion
  1719. #region New Scene Entity Manager Code
  1720. public bool LinkPartToSOG(ISceneEntity grp, ISceneChildEntity part, int linkNum)
  1721. {
  1722. part.SetParentLocalId(grp.RootChild.LocalId);
  1723. part.SetParent(grp);
  1724. // Insert in terms of link numbers, the new links
  1725. // before the current ones (with the exception of
  1726. // the root prim. Shuffle the old ones up
  1727. foreach (ISceneChildEntity otherPart in grp.ChildrenEntities())
  1728. {
  1729. if (otherPart.LinkNum >= linkNum)
  1730. {
  1731. // Don't update root prim link number
  1732. otherPart.LinkNum += 1;
  1733. }
  1734. }
  1735. part.LinkNum = linkNum;
  1736. return LinkPartToEntity(grp, part);
  1737. }
  1738. /// <summary>
  1739. /// Dupliate the entity and add it to the Scene
  1740. /// </summary>
  1741. /// <param name="entity"></param>
  1742. /// <returns></returns>
  1743. public ISceneEntity DuplicateEntity(ISceneEntity entity)
  1744. {
  1745. //Make an exact copy of the entity
  1746. ISceneEntity copiedEntity = entity.Copy(false);
  1747. //Add the entity to the scene and back it up
  1748. //Reset the entity IDs
  1749. ResetEntityIDs(copiedEntity);
  1750. //Force the prim to backup now that it has been added
  1751. copiedEntity.ForcePersistence();
  1752. //Tell the entity that they are being added to a scene
  1753. copiedEntity.AttachToScene(m_parentScene);
  1754. //Now save the entity that we have
  1755. AddEntity(copiedEntity, false);
  1756. //Fix physics representation now
  1757. // entity.RebuildPhysicalRepresentation();
  1758. return copiedEntity;
  1759. }
  1760. /// <summary>
  1761. /// Add the new part to the group in the EntityManager
  1762. /// </summary>
  1763. /// <param name="entity"></param>
  1764. /// <param name="part"></param>
  1765. /// <returns></returns>
  1766. public bool LinkPartToEntity(ISceneEntity entity, ISceneChildEntity part)
  1767. {
  1768. //Remove the entity so that we can rebuild
  1769. RemoveEntity(entity);
  1770. bool RetVal = entity.LinkChild(part);
  1771. AddEntity(entity, false);
  1772. //Now that everything is linked, destroy the undo states because it will fry the link otherwise
  1773. entity.ClearUndoState();
  1774. return RetVal;
  1775. }
  1776. /// <summary>
  1777. /// Delinks the object from the group in the EntityManager
  1778. /// </summary>
  1779. /// <param name="entity"></param>
  1780. /// <param name="part"></param>
  1781. /// <returns></returns>
  1782. public bool DeLinkPartFromEntity(ISceneEntity entity, ISceneChildEntity part)
  1783. {
  1784. //Remove the entity so that we can rebuild
  1785. RemoveEntity(entity);
  1786. bool RetVal = entity.RemoveChild(part);
  1787. AddEntity(entity, false);
  1788. //Now that everything is linked, destroy the undo states because it will fry the object otherwise
  1789. entity.ClearUndoState();
  1790. return RetVal;
  1791. }
  1792. /// <summary>
  1793. /// THIS IS TO ONLY BE CALLED WHEN AN OBJECT UUID IS UPDATED!!!
  1794. /// This method is HIGHLY unsafe and destroys the integrity of the checks above!
  1795. /// This is NOT to be used lightly! Do NOT use this unless you have to!
  1796. /// </summary>
  1797. /// <param name="entity"></param>
  1798. /// <param name="newID">new UUID to set the root part to</param>
  1799. public void UpdateEntity(ISceneEntity entity, UUID newID)
  1800. {
  1801. RemoveEntity(entity);
  1802. //Set it to the root so that we don't create an infinite loop as the ONLY place this should be being called is from the setter in SceneObjectGroup.UUID
  1803. entity.RootChild.UUID = newID;
  1804. AddEntity(entity, false);
  1805. }
  1806. #endregion
  1807. #region Public Methods
  1808. /// <summary>
  1809. /// Try to get an EntityBase as given by its UUID
  1810. /// </summary>
  1811. /// <param name="ID"></param>
  1812. /// <param name="entity"></param>
  1813. /// <returns></returns>
  1814. public bool TryGetEntity(UUID ID, out IEntity entity)
  1815. {
  1816. return Entities.TryGetValue(ID, out entity);
  1817. }
  1818. /// <summary>
  1819. /// Try to get an EntityBase as given by it's LocalID
  1820. /// </summary>
  1821. /// <param name="LocalID"></param>
  1822. /// <param name="entity"></param>
  1823. /// <returns></returns>
  1824. public bool TryGetEntity(uint LocalID, out IEntity entity)
  1825. {
  1826. return Entities.TryGetValue(LocalID, out entity);
  1827. }
  1828. /// <summary>
  1829. /// Get a part (SceneObjectPart) from the EntityManager by LocalID
  1830. /// </summary>
  1831. /// <param name="LocalID"></param>
  1832. /// <param name="entity"></param>
  1833. /// <returns></returns>
  1834. public bool TryGetPart(uint LocalID, out ISceneChildEntity entity)
  1835. {
  1836. return Entities.TryGetChildPrim(LocalID, out entity);
  1837. }
  1838. /// <summary>
  1839. /// Get a part (SceneObjectPart) from the EntityManager by UUID
  1840. /// </summary>
  1841. /// <param name="ID"></param>
  1842. /// <param name="entity"></param>
  1843. /// <returns></returns>
  1844. public bool TryGetPart(UUID ID, out ISceneChildEntity entity)
  1845. {
  1846. IEntity ent;
  1847. if (Entities.TryGetValue(ID, out ent))
  1848. {
  1849. if (ent is ISceneEntity)
  1850. {
  1851. ISceneEntity parent = (ISceneEntity) ent;
  1852. return parent.GetChildPrim(ID, out entity);
  1853. }
  1854. }
  1855. entity = null;
  1856. return false;
  1857. }
  1858. /// <summary>
  1859. /// Get this prim ready to add to the scene
  1860. /// </summary>
  1861. /// <param name="entity"></param>
  1862. public void PrepPrimForAdditionToScene(ISceneEntity entity)
  1863. {
  1864. ResetEntityIDs(entity);
  1865. }
  1866. /// <summary>
  1867. /// Add the Entity to the Scene and back it up
  1868. /// </summary>
  1869. /// <param name="entity"></param>
  1870. /// <returns></returns>
  1871. public bool AddPrimToScene(ISceneEntity entity)
  1872. {
  1873. //Reset the entity IDs
  1874. ResetEntityIDs(entity);
  1875. //Force the prim to backup now that it has been added
  1876. entity.ForcePersistence();
  1877. //Tell the entity that they are being added to a scene
  1878. entity.AttachToScene(m_parentScene);
  1879. //Now save the entity that we have
  1880. return AddEntity(entity, false);
  1881. }
  1882. /// <summary>
  1883. /// Add the Entity to the Scene and back it up, but do NOT reset its ID's
  1884. /// </summary>
  1885. /// <param name="entity"></param>
  1886. /// <param name="force"></param>
  1887. /// <returns></returns>
  1888. public bool RestorePrimToScene(ISceneEntity entity, bool force)
  1889. {
  1890. List<ISceneChildEntity> children = entity.ChildrenEntities();
  1891. //Sort so that we rebuild in the same order and the root being first
  1892. children.Sort(LinkSetSorter);
  1893. entity.ClearChildren();
  1894. foreach (ISceneChildEntity child in children)
  1895. {
  1896. if (child.LocalId == 0)
  1897. child.LocalId = AllocateLocalId();
  1898. if (((SceneObjectPart) child).PhysActor != null)
  1899. {
  1900. ((SceneObjectPart) child).PhysActor.LocalID = child.LocalId;
  1901. ((SceneObjectPart) child).PhysActor.UUID = child.UUID;
  1902. }
  1903. child.Flags &= ~PrimFlags.Scripted;
  1904. child.TrimPermissions();
  1905. entity.AddChild(child, child.LinkNum);
  1906. }
  1907. //Tell the entity that they are being added to a scene
  1908. entity.AttachToScene(m_parentScene);
  1909. //Now save the entity that we have
  1910. bool success = AddEntity(entity, false);
  1911. if (force && !success)
  1912. {
  1913. IBackupModule backup = m_parentScene.RequestModuleInterface<IBackupModule>();
  1914. backup.DeleteSceneObjects(new ISceneEntity[1] {entity}, false, true);
  1915. return RestorePrimToScene(entity, false);
  1916. }
  1917. return success;
  1918. }
  1919. /// <summary>
  1920. /// Move this group from inside of another group into the Scene as a full member
  1921. /// This does not reset IDs so that it is updated correctly in the client
  1922. /// </summary>
  1923. /// <param name="entity"></param>
  1924. public void DelinkPartToScene(ISceneEntity entity)
  1925. {
  1926. //Force the prim to backup now that it has been added
  1927. entity.ForcePersistence();
  1928. //Tell the entity that they are being added to a scene
  1929. entity.RebuildPhysicalRepresentation(true);
  1930. //Now save the entity that we have
  1931. AddEntity(entity, false);
  1932. }
  1933. /// <summary>
  1934. /// Destroy the entity and remove it from the scene
  1935. /// </summary>
  1936. /// <param name="entity"></param>
  1937. /// <returns></returns>
  1938. public bool DeleteEntity(IEntity entity)
  1939. {
  1940. return RemoveEntity(entity);
  1941. }
  1942. #endregion
  1943. #region Private Methods
  1944. /// These methods are UNSAFE to be accessed from outside this manager, if they are, BAD things WILL happen.
  1945. /// If these are changed so that they can be accessed from the outside, ghost prims and other nasty things will occur unless you are EXTREMELY careful.
  1946. /// If more changes need to occur in this area, you must use public methods to safely add/update/remove objects from the EntityManager
  1947. /// <summary>
  1948. /// Remove this entity fully from the EntityManager
  1949. /// </summary>
  1950. /// <param name="entity"></param>
  1951. /// <returns></returns>
  1952. private bool RemoveEntity(IEntity entity)
  1953. {
  1954. return Entities.Remove(entity);
  1955. }
  1956. /// <summary>
  1957. /// Add this entity to the EntityManager
  1958. /// </summary>
  1959. /// <param name="entity"></param>
  1960. /// <param name="AllowUpdate"></param>
  1961. /// <returns></returns>
  1962. private bool AddEntity(IEntity entity, bool AllowUpdate)
  1963. {
  1964. return Entities.Add(entity);
  1965. }
  1966. /// <summary>
  1967. /// Reset all of the UUID's, localID's, etc in this group (includes children)
  1968. /// </summary>
  1969. /// <param name="entity"></param>
  1970. private void ResetEntityIDs(ISceneEntity entity)
  1971. {
  1972. List<ISceneChildEntity> children = entity.ChildrenEntities();
  1973. //Sort so that we rebuild in the same order and the root being first
  1974. children.Sort(LinkSetSorter);
  1975. entity.ClearChildren();
  1976. foreach (ISceneChildEntity child in children)
  1977. {
  1978. UUID oldID = child.UUID;
  1979. child.ResetEntityIDs();
  1980. entity.AddChild(child, child.LinkNum);
  1981. }
  1982. //This clears the xml file, which will need rebuilt now that we have changed the UUIDs
  1983. entity.HasGroupChanged = true;
  1984. foreach (ISceneChildEntity child in children)
  1985. {
  1986. if (!child.IsRoot)
  1987. {
  1988. child.SetParentLocalId(entity.RootChild.LocalId);
  1989. }
  1990. }
  1991. }
  1992. /// <summary>
  1993. /// Returns a new unallocated local ID
  1994. /// </summary>
  1995. /// <returns>A brand new local ID</returns>
  1996. public uint AllocateLocalId()
  1997. {
  1998. lock (_primAllocateLock)
  1999. return ++m_lastAllocatedLocalId;
  2000. }
  2001. /// <summary>
  2002. /// Check all the localIDs in this group to make sure that they have not been used previously
  2003. /// </summary>
  2004. /// <param name="group"></param>
  2005. public void CheckAllocationOfLocalIds(ISceneEntity group)
  2006. {
  2007. foreach (ISceneChildEntity part in group.ChildrenEntities())
  2008. {
  2009. if (part.LocalId != 0)
  2010. CheckAllocationOfLocalId(part.LocalId);
  2011. }
  2012. }
  2013. /// <summary>
  2014. /// Make sure that this localID has not been used earlier in the Scene Startup
  2015. /// </summary>
  2016. /// <param name="LocalID"></param>
  2017. private void CheckAllocationOfLocalId(uint LocalID)
  2018. {
  2019. lock (_primAllocateLock)
  2020. {
  2021. if (LocalID > m_lastAllocatedLocalId)
  2022. m_lastAllocatedLocalId = LocalID + 1;
  2023. }
  2024. }
  2025. #endregion
  2026. }
  2027. }