AttachmentsModule.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the 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.Reflection;
  30. using System.IO;
  31. using System.Threading;
  32. using System.Xml;
  33. using log4net;
  34. using Mono.Addins;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenSim.Region.Framework.Scenes.Serialization;
  43. namespace OpenSim.Region.CoreModules.Avatar.Attachments
  44. {
  45. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")]
  46. public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule
  47. {
  48. #region INonSharedRegionModule
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. public int DebugLevel { get; set; }
  51. /// <summary>
  52. /// Period to sleep per 100 prims in order to avoid CPU spikes when an avatar with many attachments logs in/changes
  53. /// outfit or many avatars with a medium levels of attachments login/change outfit simultaneously.
  54. /// </summary>
  55. /// <remarks>
  56. /// A value of 0 will apply no pause. The pause is specified in milliseconds.
  57. /// </remarks>
  58. public int ThrottlePer100PrimsRezzed { get; set; }
  59. private Scene m_scene;
  60. private IInventoryAccessModule m_invAccessModule;
  61. /// <summary>
  62. /// Are attachments enabled?
  63. /// </summary>
  64. public bool Enabled { get; private set; }
  65. public string Name { get { return "Attachments Module"; } }
  66. public Type ReplaceableInterface { get { return null; } }
  67. public void Initialise(IConfigSource source)
  68. {
  69. IConfig config = source.Configs["Attachments"];
  70. if (config != null)
  71. {
  72. Enabled = config.GetBoolean("Enabled", true);
  73. ThrottlePer100PrimsRezzed = config.GetInt("ThrottlePer100PrimsRezzed", 0);
  74. }
  75. else
  76. {
  77. Enabled = true;
  78. }
  79. }
  80. public void AddRegion(Scene scene)
  81. {
  82. m_scene = scene;
  83. if (Enabled)
  84. {
  85. // Only register module with scene if it is enabled. All callers check for a null attachments module.
  86. // Ideally, there should be a null attachments module for when this core attachments module has been
  87. // disabled. Registering only when enabled allows for other attachments module implementations.
  88. m_scene.RegisterModuleInterface<IAttachmentsModule>(this);
  89. m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
  90. m_scene.EventManager.OnStartScript += (localID, itemID) => HandleScriptStateChange(localID, true);
  91. m_scene.EventManager.OnStopScript += (localID, itemID) => HandleScriptStateChange(localID, false);
  92. MainConsole.Instance.Commands.AddCommand(
  93. "Debug",
  94. false,
  95. "debug attachments log",
  96. "debug attachments log [0|1]",
  97. "Turn on attachments debug logging",
  98. " <= 0 - turns off debug logging\n"
  99. + " >= 1 - turns on attachment message debug logging",
  100. HandleDebugAttachmentsLog);
  101. MainConsole.Instance.Commands.AddCommand(
  102. "Debug",
  103. false,
  104. "debug attachments throttle",
  105. "debug attachments throttle <ms>",
  106. "Turn on attachments throttling.",
  107. "This requires a millisecond value. " +
  108. " == 0 - disable throttling.\n"
  109. + " > 0 - sleeps for this number of milliseconds per 100 prims rezzed.",
  110. HandleDebugAttachmentsThrottle);
  111. MainConsole.Instance.Commands.AddCommand(
  112. "Debug",
  113. false,
  114. "debug attachments status",
  115. "debug attachments status",
  116. "Show current attachments debug status",
  117. HandleDebugAttachmentsStatus);
  118. }
  119. // TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI
  120. }
  121. private void HandleDebugAttachmentsLog(string module, string[] args)
  122. {
  123. int debugLevel;
  124. if (!(args.Length == 4 && int.TryParse(args[3], out debugLevel)))
  125. {
  126. MainConsole.Instance.OutputFormat("Usage: debug attachments log [0|1]");
  127. }
  128. else
  129. {
  130. DebugLevel = debugLevel;
  131. MainConsole.Instance.OutputFormat(
  132. "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.Name);
  133. }
  134. }
  135. private void HandleDebugAttachmentsThrottle(string module, string[] args)
  136. {
  137. int ms;
  138. if (args.Length == 4 && int.TryParse(args[3], out ms))
  139. {
  140. ThrottlePer100PrimsRezzed = ms;
  141. MainConsole.Instance.OutputFormat(
  142. "Attachments rez throttle per 100 prims is now {0} in {1}", ThrottlePer100PrimsRezzed, m_scene.Name);
  143. return;
  144. }
  145. MainConsole.Instance.OutputFormat("Usage: debug attachments throttle <ms>");
  146. }
  147. private void HandleDebugAttachmentsStatus(string module, string[] args)
  148. {
  149. MainConsole.Instance.OutputFormat("Settings for {0}", m_scene.Name);
  150. MainConsole.Instance.OutputFormat("Debug logging level: {0}", DebugLevel);
  151. MainConsole.Instance.OutputFormat("Throttle per 100 prims: {0}ms", ThrottlePer100PrimsRezzed);
  152. }
  153. /// <summary>
  154. /// Listen for client triggered running state changes so that we can persist the script's object if necessary.
  155. /// </summary>
  156. /// <param name='localID'></param>
  157. /// <param name='itemID'></param>
  158. private void HandleScriptStateChange(uint localID, bool started)
  159. {
  160. SceneObjectGroup sog = m_scene.GetGroupByPrim(localID);
  161. if (sog != null && sog.IsAttachment)
  162. {
  163. if (!started)
  164. {
  165. // FIXME: This is a convoluted way for working out whether the script state has changed to stop
  166. // because it has been manually stopped or because the stop was called in UpdateDetachedObject() below
  167. // This needs to be handled in a less tangled way.
  168. ScenePresence sp = m_scene.GetScenePresence(sog.AttachedAvatar);
  169. if (sp.ControllingClient.IsActive)
  170. sog.HasGroupChanged = true;
  171. }
  172. else
  173. {
  174. sog.HasGroupChanged = true;
  175. }
  176. }
  177. }
  178. public void RemoveRegion(Scene scene)
  179. {
  180. m_scene.UnregisterModuleInterface<IAttachmentsModule>(this);
  181. if (Enabled)
  182. m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
  183. }
  184. public void RegionLoaded(Scene scene)
  185. {
  186. m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>();
  187. }
  188. public void Close()
  189. {
  190. RemoveRegion(m_scene);
  191. }
  192. #endregion
  193. #region IAttachmentsModule
  194. public void CopyAttachments(IScenePresence sp, AgentData ad)
  195. {
  196. lock (sp.AttachmentsSyncLock)
  197. {
  198. // Attachment objects
  199. List<SceneObjectGroup> attachments = sp.GetAttachments();
  200. if (attachments.Count > 0)
  201. {
  202. ad.AttachmentObjects = new List<ISceneObject>();
  203. ad.AttachmentObjectStates = new List<string>();
  204. // IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>();
  205. sp.InTransitScriptStates.Clear();
  206. foreach (SceneObjectGroup sog in attachments)
  207. {
  208. // We need to make a copy and pass that copy
  209. // because of transfers withn the same sim
  210. ISceneObject clone = sog.CloneForNewScene();
  211. // Attachment module assumes that GroupPosition holds the offsets...!
  212. ((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos;
  213. ((SceneObjectGroup)clone).IsAttachment = false;
  214. ad.AttachmentObjects.Add(clone);
  215. string state = sog.GetStateSnapshot();
  216. ad.AttachmentObjectStates.Add(state);
  217. sp.InTransitScriptStates.Add(state);
  218. // Let's remove the scripts of the original object here
  219. sog.RemoveScriptInstances(true);
  220. }
  221. }
  222. }
  223. }
  224. public void CopyAttachments(AgentData ad, IScenePresence sp)
  225. {
  226. if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
  227. {
  228. lock (sp.AttachmentsSyncLock)
  229. sp.ClearAttachments();
  230. int i = 0;
  231. foreach (ISceneObject so in ad.AttachmentObjects)
  232. {
  233. ((SceneObjectGroup)so).LocalId = 0;
  234. ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
  235. so.SetState(ad.AttachmentObjectStates[i++], m_scene);
  236. m_scene.IncomingCreateObject(Vector3.Zero, so);
  237. }
  238. }
  239. }
  240. public void RezAttachments(IScenePresence sp)
  241. {
  242. if (!Enabled)
  243. return;
  244. if (null == sp.Appearance)
  245. {
  246. m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
  247. return;
  248. }
  249. if (sp.GetAttachments().Count > 0)
  250. {
  251. if (DebugLevel > 0)
  252. m_log.DebugFormat(
  253. "[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments",
  254. m_scene.Name, sp.Name);
  255. return;
  256. }
  257. if (DebugLevel > 0)
  258. m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name);
  259. List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
  260. foreach (AvatarAttachment attach in attachments)
  261. {
  262. uint attachmentPt = (uint)attach.AttachPoint;
  263. // m_log.DebugFormat(
  264. // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
  265. // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
  266. // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
  267. // But they're not used anyway, the item is being looked up for now, so let's proceed.
  268. //if (UUID.Zero == assetID)
  269. //{
  270. // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
  271. // continue;
  272. //}
  273. try
  274. {
  275. // If we're an NPC then skip all the item checks and manipulations since we don't have an
  276. // inventory right now.
  277. RezSingleAttachmentFromInventoryInternal(
  278. sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true);
  279. }
  280. catch (Exception e)
  281. {
  282. UUID agentId = (sp.ControllingClient == null) ? (UUID)null : sp.ControllingClient.AgentId;
  283. m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
  284. attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace);
  285. }
  286. }
  287. }
  288. public void DeRezAttachments(IScenePresence sp)
  289. {
  290. if (!Enabled)
  291. return;
  292. if (DebugLevel > 0)
  293. m_log.DebugFormat("[ATTACHMENTS MODULE]: Saving changed attachments for {0}", sp.Name);
  294. List<SceneObjectGroup> attachments = sp.GetAttachments();
  295. if (attachments.Count <= 0)
  296. return;
  297. Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>();
  298. foreach (SceneObjectGroup so in attachments)
  299. {
  300. // Scripts MUST be snapshotted before the object is
  301. // removed from the scene because doing otherwise will
  302. // clobber the run flag
  303. // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
  304. // scripts performing attachment operations at the same time. Getting object states stops the scripts.
  305. scriptStates[so] = PrepareScriptInstanceForSave(so, false);
  306. }
  307. lock (sp.AttachmentsSyncLock)
  308. {
  309. foreach (SceneObjectGroup so in attachments)
  310. UpdateDetachedObject(sp, so, scriptStates[so]);
  311. sp.ClearAttachments();
  312. }
  313. }
  314. public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
  315. {
  316. if (!Enabled)
  317. return;
  318. if (DebugLevel > 0)
  319. m_log.DebugFormat(
  320. "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
  321. m_scene.RegionInfo.RegionName, sp.Name, silent);
  322. foreach (SceneObjectGroup sop in sp.GetAttachments())
  323. {
  324. sop.Scene.DeleteSceneObject(sop, silent);
  325. }
  326. sp.ClearAttachments();
  327. }
  328. public bool AttachObject(
  329. IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append)
  330. {
  331. if (!Enabled)
  332. return false;
  333. return AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append);
  334. }
  335. /// <summary>
  336. /// Internal method which actually does all the work for attaching an object.
  337. /// </summary>
  338. /// <returns>The object attached.</returns>
  339. /// <param name='sp'></param>
  340. /// <param name='group'>The object to attach.</param>
  341. /// <param name='attachmentPt'></param>
  342. /// <param name='silent'></param>
  343. /// <param name='addToInventory'>If true then add object to user inventory.</param>
  344. /// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param>
  345. /// <param name='append'>Append to attachment point rather than replace.</param>
  346. private bool AttachObjectInternal(
  347. IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append)
  348. {
  349. if (group.GetSittingAvatarsCount() != 0)
  350. {
  351. if (DebugLevel > 0)
  352. m_log.WarnFormat(
  353. "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
  354. group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
  355. return false;
  356. }
  357. Vector3 attachPos = group.AbsolutePosition;
  358. // If the attachment point isn't the same as the one previously used
  359. // set it's offset position = 0 so that it appears on the attachment point
  360. // and not in a weird location somewhere unknown.
  361. if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint)
  362. {
  363. attachPos = Vector3.Zero;
  364. }
  365. // AttachmentPt 0 means the client chose to 'wear' the attachment.
  366. if (attachmentPt == (uint)AttachmentPoint.Default)
  367. {
  368. // Check object for stored attachment point
  369. attachmentPt = group.AttachmentPoint;
  370. }
  371. // if we still didn't find a suitable attachment point.......
  372. if (attachmentPt == 0)
  373. {
  374. // Stick it on left hand with Zero Offset from the attachment point.
  375. attachmentPt = (uint)AttachmentPoint.LeftHand;
  376. attachPos = Vector3.Zero;
  377. }
  378. group.AttachmentPoint = attachmentPt;
  379. group.AbsolutePosition = attachPos;
  380. List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
  381. if (attachments.Contains(group))
  382. {
  383. if (DebugLevel > 0)
  384. m_log.WarnFormat(
  385. "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
  386. group.Name, group.LocalId, sp.Name, attachmentPt);
  387. return false;
  388. }
  389. // If we already have 5, remove the oldest until only 4 are left. Skip over temp ones
  390. while (attachments.Count >= 5)
  391. {
  392. if (attachments[0].FromItemID != UUID.Zero)
  393. DetachSingleAttachmentToInv(sp, attachments[0]);
  394. attachments.RemoveAt(0);
  395. }
  396. // If we're not appending, remove the rest as well
  397. if (attachments.Count != 0 && !append)
  398. {
  399. foreach (SceneObjectGroup g in attachments)
  400. {
  401. if (g.FromItemID != UUID.Zero)
  402. DetachSingleAttachmentToInv(sp, g);
  403. }
  404. }
  405. lock (sp.AttachmentsSyncLock)
  406. {
  407. if (addToInventory && sp.PresenceType != PresenceType.Npc)
  408. UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append);
  409. AttachToAgent(sp, group, attachmentPt, attachPos, silent);
  410. if (resumeScripts)
  411. {
  412. // Fire after attach, so we don't get messy perms dialogs
  413. // 4 == AttachedRez
  414. group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
  415. group.ResumeScripts();
  416. }
  417. // Do this last so that event listeners have access to all the effects of the attachment
  418. m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
  419. }
  420. return true;
  421. }
  422. private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append)
  423. {
  424. // Add the new attachment to inventory if we don't already have it.
  425. UUID newAttachmentItemID = group.FromItemID;
  426. if (newAttachmentItemID == UUID.Zero)
  427. newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
  428. ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append);
  429. }
  430. public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
  431. {
  432. if (!Enabled)
  433. return null;
  434. if (DebugLevel > 0)
  435. m_log.DebugFormat(
  436. "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}",
  437. (AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name);
  438. // We check the attachments in the avatar appearance here rather than the objects attached to the
  439. // ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are
  440. // already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done
  441. // because pre-outfit folder viewers (most version 1 viewers) require it.
  442. bool alreadyOn = false;
  443. List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments();
  444. foreach (AvatarAttachment existingAttachment in existingAttachments)
  445. {
  446. if (existingAttachment.ItemID == itemID)
  447. {
  448. alreadyOn = true;
  449. break;
  450. }
  451. }
  452. if (alreadyOn)
  453. {
  454. if (DebugLevel > 0)
  455. m_log.DebugFormat(
  456. "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
  457. sp.Name, itemID, AttachmentPt);
  458. return null;
  459. }
  460. bool append = (AttachmentPt & 0x80) != 0;
  461. AttachmentPt &= 0x7f;
  462. return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append);
  463. }
  464. public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
  465. {
  466. if (!Enabled)
  467. return;
  468. if (DebugLevel > 0)
  469. m_log.DebugFormat(
  470. "[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}",
  471. rezlist.Count, sp.Name, m_scene.Name);
  472. foreach (KeyValuePair<UUID, uint> rez in rezlist)
  473. {
  474. RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
  475. }
  476. }
  477. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
  478. {
  479. DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
  480. }
  481. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
  482. {
  483. if (!Enabled)
  484. return;
  485. if (DebugLevel > 0)
  486. m_log.DebugFormat(
  487. "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
  488. sp.UUID, soLocalId);
  489. SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
  490. if (so == null)
  491. return;
  492. if (so.AttachedAvatar != sp.UUID)
  493. return;
  494. UUID inventoryID = so.FromItemID;
  495. // As per Linden spec, drop is disabled for temp attachs
  496. if (inventoryID == UUID.Zero)
  497. return;
  498. if (DebugLevel > 0)
  499. m_log.DebugFormat(
  500. "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
  501. so.Name, so.LocalId, inventoryID);
  502. lock (sp.AttachmentsSyncLock)
  503. {
  504. if (!m_scene.Permissions.CanRezObject(
  505. so.PrimCount, sp.UUID, sp.AbsolutePosition))
  506. return;
  507. bool changed = false;
  508. if (inventoryID != UUID.Zero)
  509. changed = sp.Appearance.DetachAttachment(inventoryID);
  510. if (changed && m_scene.AvatarFactory != null)
  511. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  512. sp.RemoveAttachment(so);
  513. so.FromItemID = UUID.Zero;
  514. SceneObjectPart rootPart = so.RootPart;
  515. so.AbsolutePosition = absolutePos;
  516. if (absoluteRot != Quaternion.Identity)
  517. {
  518. so.UpdateGroupRotationR(absoluteRot);
  519. }
  520. so.AttachedAvatar = UUID.Zero;
  521. rootPart.SetParentLocalId(0);
  522. so.ClearPartAttachmentData();
  523. rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
  524. so.HasGroupChanged = true;
  525. rootPart.Rezzed = DateTime.Now;
  526. rootPart.RemFlag(PrimFlags.TemporaryOnRez);
  527. so.AttachToBackup();
  528. m_scene.EventManager.TriggerParcelPrimCountTainted();
  529. rootPart.ScheduleFullUpdate();
  530. rootPart.ClearUndoState();
  531. List<UUID> uuids = new List<UUID>();
  532. uuids.Add(inventoryID);
  533. m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
  534. sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
  535. }
  536. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
  537. }
  538. public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
  539. {
  540. if (so.AttachedAvatar != sp.UUID)
  541. {
  542. m_log.WarnFormat(
  543. "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
  544. so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
  545. return;
  546. }
  547. if (DebugLevel > 0)
  548. m_log.DebugFormat(
  549. "[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}",
  550. so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name);
  551. // Scripts MUST be snapshotted before the object is
  552. // removed from the scene because doing otherwise will
  553. // clobber the run flag
  554. // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
  555. // scripts performing attachment operations at the same time. Getting object states stops the scripts.
  556. string scriptedState = PrepareScriptInstanceForSave(so, true);
  557. lock (sp.AttachmentsSyncLock)
  558. {
  559. // Save avatar attachment information
  560. // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
  561. bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
  562. if (changed && m_scene.AvatarFactory != null)
  563. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  564. sp.RemoveAttachment(so);
  565. UpdateDetachedObject(sp, so, scriptedState);
  566. }
  567. }
  568. public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
  569. {
  570. if (!Enabled)
  571. return;
  572. sog.UpdateGroupPosition(pos);
  573. sog.HasGroupChanged = true;
  574. }
  575. #endregion
  576. #region AttachmentModule private methods
  577. // This is public but is not part of the IAttachmentsModule interface.
  578. // RegionCombiner module needs to poke at it to deliver client events.
  579. // This breaks the encapsulation of the module and should get fixed somehow.
  580. public void SubscribeToClientEvents(IClientAPI client)
  581. {
  582. client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
  583. client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
  584. client.OnObjectAttach += Client_OnObjectAttach;
  585. client.OnObjectDetach += Client_OnObjectDetach;
  586. client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
  587. client.OnObjectDrop += Client_OnObjectDrop;
  588. }
  589. // This is public but is not part of the IAttachmentsModule interface.
  590. // RegionCombiner module needs to poke at it to deliver client events.
  591. // This breaks the encapsulation of the module and should get fixed somehow.
  592. public void UnsubscribeFromClientEvents(IClientAPI client)
  593. {
  594. client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
  595. client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
  596. client.OnObjectAttach -= Client_OnObjectAttach;
  597. client.OnObjectDetach -= Client_OnObjectDetach;
  598. client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
  599. client.OnObjectDrop -= Client_OnObjectDrop;
  600. }
  601. /// <summary>
  602. /// Update the attachment asset for the new sog details if they have changed.
  603. /// </summary>
  604. /// <remarks>
  605. /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
  606. /// these details are not stored on the region.
  607. /// </remarks>
  608. /// <param name="sp"></param>
  609. /// <param name="grp"></param>
  610. /// <param name="saveAllScripted"></param>
  611. private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
  612. {
  613. if (grp.FromItemID == UUID.Zero)
  614. {
  615. // We can't save temp attachments
  616. grp.HasGroupChanged = false;
  617. return;
  618. }
  619. // Saving attachments for NPCs messes them up for the real owner!
  620. INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
  621. if (module != null)
  622. {
  623. if (module.IsNPC(sp.UUID, m_scene))
  624. return;
  625. }
  626. if (grp.HasGroupChanged)
  627. {
  628. m_log.DebugFormat(
  629. "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
  630. grp.UUID, grp.AttachmentPoint);
  631. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
  632. InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
  633. item = m_scene.InventoryService.GetItem(item);
  634. if (item != null)
  635. {
  636. AssetBase asset = m_scene.CreateAsset(
  637. grp.GetPartName(grp.LocalId),
  638. grp.GetPartDescription(grp.LocalId),
  639. (sbyte)AssetType.Object,
  640. Utils.StringToBytes(sceneObjectXml),
  641. sp.UUID);
  642. m_scene.AssetService.Store(asset);
  643. item.AssetID = asset.FullID;
  644. item.Description = asset.Description;
  645. item.Name = asset.Name;
  646. item.AssetType = asset.Type;
  647. item.InvType = (int)InventoryType.Object;
  648. m_scene.InventoryService.UpdateItem(item);
  649. // If the name of the object has been changed whilst attached then we want to update the inventory
  650. // item in the viewer.
  651. if (sp.ControllingClient != null)
  652. sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
  653. }
  654. grp.HasGroupChanged = false; // Prevent it being saved over and over
  655. }
  656. else if (DebugLevel > 0)
  657. {
  658. m_log.DebugFormat(
  659. "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
  660. grp.UUID, grp.AttachmentPoint);
  661. }
  662. }
  663. /// <summary>
  664. /// Attach this scene object to the given avatar.
  665. /// </summary>
  666. /// <remarks>
  667. /// This isn't publicly available since attachments should always perform the corresponding inventory
  668. /// operation (to show the attach in user inventory and update the asset with positional information).
  669. /// </remarks>
  670. /// <param name="sp"></param>
  671. /// <param name="so"></param>
  672. /// <param name="attachmentpoint"></param>
  673. /// <param name="attachOffset"></param>
  674. /// <param name="silent"></param>
  675. private void AttachToAgent(
  676. IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
  677. {
  678. if (DebugLevel > 0)
  679. m_log.DebugFormat(
  680. "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}",
  681. so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos);
  682. so.DetachFromBackup();
  683. // Remove from database and parcel prim count
  684. m_scene.DeleteFromStorage(so.UUID);
  685. m_scene.EventManager.TriggerParcelPrimCountTainted();
  686. so.AttachedAvatar = sp.UUID;
  687. if (so.RootPart.PhysActor != null)
  688. so.RootPart.RemoveFromPhysics();
  689. so.AbsolutePosition = attachOffset;
  690. so.RootPart.AttachedPos = attachOffset;
  691. so.IsAttachment = true;
  692. so.RootPart.SetParentLocalId(sp.LocalId);
  693. so.AttachmentPoint = attachmentpoint;
  694. sp.AddAttachment(so);
  695. if (!silent)
  696. {
  697. if (so.HasPrivateAttachmentPoint)
  698. {
  699. if (DebugLevel > 0)
  700. m_log.DebugFormat(
  701. "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
  702. so.Name, sp.Name, so.AttachmentPoint);
  703. // As this scene object can now only be seen by the attaching avatar, tell everybody else in the
  704. // scene that it's no longer in their awareness.
  705. m_scene.ForEachClient(
  706. client =>
  707. { if (client.AgentId != so.AttachedAvatar)
  708. client.SendKillObject(new List<uint>() { so.LocalId });
  709. });
  710. }
  711. // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update
  712. // will succeed, as that will not update if an attachment is selected.
  713. so.IsSelected = false; // fudge....
  714. so.ScheduleGroupForFullUpdate();
  715. }
  716. // In case it is later dropped again, don't let
  717. // it get cleaned up
  718. so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  719. }
  720. /// <summary>
  721. /// Add a scene object as a new attachment in the user inventory.
  722. /// </summary>
  723. /// <param name="remoteClient"></param>
  724. /// <param name="grp"></param>
  725. /// <returns>The user inventory item created that holds the attachment.</returns>
  726. private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
  727. {
  728. if (m_invAccessModule == null)
  729. return null;
  730. if (DebugLevel > 0)
  731. m_log.DebugFormat(
  732. "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
  733. grp.Name, grp.LocalId, sp.Name);
  734. InventoryItemBase newItem
  735. = m_invAccessModule.CopyToInventory(
  736. DeRezAction.TakeCopy,
  737. m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
  738. new List<SceneObjectGroup> { grp },
  739. sp.ControllingClient, true)[0];
  740. // sets itemID so client can show item as 'attached' in inventory
  741. grp.FromItemID = newItem.ID;
  742. return newItem;
  743. }
  744. /// <summary>
  745. /// Prepares the script instance for save.
  746. /// </summary>
  747. /// <remarks>
  748. /// This involves triggering the detach event and getting the script state (which also stops the script)
  749. /// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a
  750. /// running script is performing attachment operations.
  751. /// </remarks>
  752. /// <returns>
  753. /// The script state ready for persistence.
  754. /// </returns>
  755. /// <param name='grp'>
  756. /// </param>
  757. /// <param name='fireDetachEvent'>
  758. /// If true, then fire the script event before we save its state.
  759. /// </param>
  760. private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent)
  761. {
  762. if (fireDetachEvent)
  763. m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero);
  764. using (StringWriter sw = new StringWriter())
  765. {
  766. using (XmlTextWriter writer = new XmlTextWriter(sw))
  767. {
  768. grp.SaveScriptedState(writer);
  769. }
  770. return sw.ToString();
  771. }
  772. }
  773. private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState)
  774. {
  775. // Don't save attachments for HG visitors, it
  776. // messes up their inventory. When a HG visitor logs
  777. // out on a foreign grid, their attachments will be
  778. // reloaded in the state they were in when they left
  779. // the home grid. This is best anyway as the visited
  780. // grid may use an incompatible script engine.
  781. bool saveChanged
  782. = sp.PresenceType != PresenceType.Npc
  783. && (m_scene.UserManagementModule == null
  784. || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
  785. // Remove the object from the scene so no more updates
  786. // are sent. Doing this before the below changes will ensure
  787. // updates can't cause "HUD artefacts"
  788. m_scene.DeleteSceneObject(so, false, false);
  789. // Prepare sog for storage
  790. so.AttachedAvatar = UUID.Zero;
  791. so.RootPart.SetParentLocalId(0);
  792. so.IsAttachment = false;
  793. if (saveChanged)
  794. {
  795. // We cannot use AbsolutePosition here because that would
  796. // attempt to cross the prim as it is detached
  797. so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
  798. UpdateKnownItem(sp, so, scriptedState);
  799. }
  800. // Now, remove the scripts
  801. so.RemoveScriptInstances(true);
  802. }
  803. protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
  804. IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append)
  805. {
  806. if (m_invAccessModule == null)
  807. return null;
  808. SceneObjectGroup objatt;
  809. if (itemID != UUID.Zero)
  810. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  811. itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  812. false, false, sp.UUID, true);
  813. else
  814. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  815. null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  816. false, false, sp.UUID, true);
  817. if (objatt == null)
  818. {
  819. m_log.WarnFormat(
  820. "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
  821. itemID, sp.Name, attachmentPt);
  822. return null;
  823. }
  824. if (DebugLevel > 0)
  825. m_log.DebugFormat(
  826. "[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}",
  827. objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
  828. // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
  829. objatt.HasGroupChanged = false;
  830. bool tainted = false;
  831. if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
  832. tainted = true;
  833. // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
  834. // course of events. If not, then it's probably not worth trying to recover the situation
  835. // since this is more likely to trigger further exceptions and confuse later debugging. If
  836. // exceptions can be thrown in expected error conditions (not NREs) then make this consistent
  837. // since other normal error conditions will simply return false instead.
  838. // This will throw if the attachment fails
  839. try
  840. {
  841. AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append);
  842. }
  843. catch (Exception e)
  844. {
  845. m_log.ErrorFormat(
  846. "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
  847. objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
  848. // Make sure the object doesn't stick around and bail
  849. sp.RemoveAttachment(objatt);
  850. m_scene.DeleteSceneObject(objatt, false);
  851. return null;
  852. }
  853. if (tainted)
  854. objatt.HasGroupChanged = true;
  855. if (ThrottlePer100PrimsRezzed > 0)
  856. {
  857. int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed);
  858. if (DebugLevel > 0)
  859. m_log.DebugFormat(
  860. "[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}",
  861. throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
  862. Thread.Sleep(throttleMs);
  863. }
  864. return objatt;
  865. }
  866. /// <summary>
  867. /// Update the user inventory to reflect an attachment
  868. /// </summary>
  869. /// <param name="sp"></param>
  870. /// <param name="AttachmentPt"></param>
  871. /// <param name="itemID"></param>
  872. /// <param name="att"></param>
  873. private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append)
  874. {
  875. // m_log.DebugFormat(
  876. // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
  877. // att.Name, sp.Name, AttachmentPt, itemID);
  878. if (UUID.Zero == itemID)
  879. {
  880. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
  881. return;
  882. }
  883. if (0 == AttachmentPt)
  884. {
  885. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
  886. return;
  887. }
  888. InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
  889. item = m_scene.InventoryService.GetItem(item);
  890. if (item == null)
  891. return;
  892. int attFlag = append ? 0x80 : 0;
  893. bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID);
  894. if (changed && m_scene.AvatarFactory != null)
  895. {
  896. if (DebugLevel > 0)
  897. m_log.DebugFormat(
  898. "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
  899. sp.Name, att.Name, AttachmentPt);
  900. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  901. }
  902. }
  903. #endregion
  904. #region Client Event Handlers
  905. private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
  906. {
  907. if (!Enabled)
  908. return null;
  909. if (DebugLevel > 0)
  910. m_log.DebugFormat(
  911. "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
  912. (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
  913. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  914. if (sp == null)
  915. {
  916. m_log.ErrorFormat(
  917. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
  918. remoteClient.Name, remoteClient.AgentId);
  919. return null;
  920. }
  921. return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
  922. }
  923. private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
  924. {
  925. if (!Enabled)
  926. return;
  927. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  928. if (sp != null)
  929. RezMultipleAttachmentsFromInventory(sp, rezlist);
  930. else
  931. m_log.ErrorFormat(
  932. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
  933. remoteClient.Name, remoteClient.AgentId);
  934. }
  935. private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
  936. {
  937. if (DebugLevel > 0)
  938. m_log.DebugFormat(
  939. "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
  940. objectLocalID, remoteClient.Name, AttachmentPt, silent);
  941. if (!Enabled)
  942. return;
  943. try
  944. {
  945. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  946. if (sp == null)
  947. {
  948. m_log.ErrorFormat(
  949. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
  950. return;
  951. }
  952. // If we can't take it, we can't attach it!
  953. SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
  954. if (part == null)
  955. return;
  956. if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
  957. {
  958. remoteClient.SendAgentAlertMessage(
  959. "You don't have sufficient permissions to attach this object", false);
  960. return;
  961. }
  962. bool append = (AttachmentPt & 0x80) != 0;
  963. AttachmentPt &= 0x7f;
  964. // Calls attach with a Zero position
  965. if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append))
  966. {
  967. if (DebugLevel > 0)
  968. m_log.Debug(
  969. "[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
  970. + ", AttachmentPoint: " + AttachmentPt);
  971. // Save avatar attachment information
  972. m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId);
  973. }
  974. }
  975. catch (Exception e)
  976. {
  977. m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
  978. }
  979. }
  980. private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
  981. {
  982. if (!Enabled)
  983. return;
  984. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  985. SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
  986. if (sp != null && group != null && group.FromItemID != UUID.Zero)
  987. DetachSingleAttachmentToInv(sp, group);
  988. }
  989. private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
  990. {
  991. if (!Enabled)
  992. return;
  993. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  994. if (sp != null)
  995. {
  996. List<SceneObjectGroup> attachments = sp.GetAttachments();
  997. foreach (SceneObjectGroup group in attachments)
  998. {
  999. if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
  1000. {
  1001. DetachSingleAttachmentToInv(sp, group);
  1002. return;
  1003. }
  1004. }
  1005. }
  1006. }
  1007. private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
  1008. {
  1009. if (!Enabled)
  1010. return;
  1011. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1012. if (sp != null)
  1013. DetachSingleAttachmentToGround(sp, soLocalId);
  1014. }
  1015. #endregion
  1016. }
  1017. }