AttachmentsModule.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 attachments 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. // Scripts of the originals will be removed when the Agent is successfully removed.
  219. // sog.RemoveScriptInstances(true);
  220. }
  221. }
  222. }
  223. }
  224. public void CopyAttachments(AgentData ad, IScenePresence sp)
  225. {
  226. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Copying attachment data into {0} in {1}", sp.Name, m_scene.Name);
  227. if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
  228. {
  229. lock (sp.AttachmentsSyncLock)
  230. sp.ClearAttachments();
  231. int i = 0;
  232. foreach (ISceneObject so in ad.AttachmentObjects)
  233. {
  234. ((SceneObjectGroup)so).LocalId = 0;
  235. ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
  236. // m_log.DebugFormat(
  237. // "[ATTACHMENTS MODULE]: Copying script state with {0} bytes for object {1} for {2} in {3}",
  238. // ad.AttachmentObjectStates[i].Length, so.Name, sp.Name, m_scene.Name);
  239. so.SetState(ad.AttachmentObjectStates[i++], m_scene);
  240. m_scene.IncomingCreateObject(Vector3.Zero, so);
  241. }
  242. }
  243. }
  244. public void RezAttachments(IScenePresence sp)
  245. {
  246. if (!Enabled)
  247. return;
  248. if (null == sp.Appearance)
  249. {
  250. m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
  251. return;
  252. }
  253. if (sp.GetAttachments().Count > 0)
  254. {
  255. if (DebugLevel > 0)
  256. m_log.DebugFormat(
  257. "[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments",
  258. m_scene.Name, sp.Name);
  259. return;
  260. }
  261. if (DebugLevel > 0)
  262. m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name);
  263. List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
  264. foreach (AvatarAttachment attach in attachments)
  265. {
  266. uint attachmentPt = (uint)attach.AttachPoint;
  267. // m_log.DebugFormat(
  268. // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
  269. // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
  270. // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
  271. // But they're not used anyway, the item is being looked up for now, so let's proceed.
  272. //if (UUID.Zero == assetID)
  273. //{
  274. // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
  275. // continue;
  276. //}
  277. try
  278. {
  279. // If we're an NPC then skip all the item checks and manipulations since we don't have an
  280. // inventory right now.
  281. RezSingleAttachmentFromInventoryInternal(
  282. sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true);
  283. }
  284. catch (Exception e)
  285. {
  286. UUID agentId = (sp.ControllingClient == null) ? default(UUID) : sp.ControllingClient.AgentId;
  287. m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
  288. attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace);
  289. }
  290. }
  291. }
  292. public void DeRezAttachments(IScenePresence sp)
  293. {
  294. if (!Enabled)
  295. return;
  296. List<SceneObjectGroup> attachments = sp.GetAttachments();
  297. if (DebugLevel > 0)
  298. m_log.DebugFormat(
  299. "[ATTACHMENTS MODULE]: Saving for {0} attachments for {1} in {2}",
  300. attachments.Count, sp.Name, m_scene.Name);
  301. if (attachments.Count <= 0)
  302. return;
  303. Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>();
  304. foreach (SceneObjectGroup so in attachments)
  305. {
  306. // Scripts MUST be snapshotted before the object is
  307. // removed from the scene because doing otherwise will
  308. // clobber the run flag
  309. // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
  310. // scripts performing attachment operations at the same time. Getting object states stops the scripts.
  311. scriptStates[so] = PrepareScriptInstanceForSave(so, false);
  312. // m_log.DebugFormat(
  313. // "[ATTACHMENTS MODULE]: For object {0} for {1} in {2} got saved state {3}",
  314. // so.Name, sp.Name, m_scene.Name, scriptStates[so]);
  315. }
  316. lock (sp.AttachmentsSyncLock)
  317. {
  318. foreach (SceneObjectGroup so in attachments)
  319. UpdateDetachedObject(sp, so, scriptStates[so]);
  320. sp.ClearAttachments();
  321. }
  322. }
  323. public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
  324. {
  325. if (!Enabled)
  326. return;
  327. if (DebugLevel > 0)
  328. m_log.DebugFormat(
  329. "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
  330. m_scene.RegionInfo.RegionName, sp.Name, silent);
  331. foreach (SceneObjectGroup sop in sp.GetAttachments())
  332. {
  333. sop.Scene.DeleteSceneObject(sop, silent);
  334. }
  335. sp.ClearAttachments();
  336. }
  337. public bool AttachObject(
  338. IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append)
  339. {
  340. if (!Enabled)
  341. return false;
  342. group.DetachFromBackup();
  343. bool success = AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append);
  344. if (!success)
  345. group.AttachToBackup();
  346. return success;
  347. }
  348. /// <summary>
  349. /// Internal method which actually does all the work for attaching an object.
  350. /// </summary>
  351. /// <returns>The object attached.</returns>
  352. /// <param name='sp'></param>
  353. /// <param name='group'>The object to attach.</param>
  354. /// <param name='attachmentPt'></param>
  355. /// <param name='silent'></param>
  356. /// <param name='addToInventory'>If true then add object to user inventory.</param>
  357. /// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param>
  358. /// <param name='append'>Append to attachment point rather than replace.</param>
  359. private bool AttachObjectInternal(
  360. IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append)
  361. {
  362. if (group.GetSittingAvatarsCount() != 0)
  363. {
  364. if (DebugLevel > 0)
  365. m_log.WarnFormat(
  366. "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
  367. group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
  368. return false;
  369. }
  370. Vector3 attachPos = group.AbsolutePosition;
  371. // If the attachment point isn't the same as the one previously used
  372. // set it's offset position = 0 so that it appears on the attachment point
  373. // and not in a weird location somewhere unknown.
  374. if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint)
  375. {
  376. attachPos = Vector3.Zero;
  377. }
  378. // if the attachment point is the same as previous, make sure we get the saved
  379. // position info.
  380. if (attachmentPt != 0 && attachmentPt == group.RootPart.Shape.LastAttachPoint)
  381. {
  382. attachPos = group.RootPart.AttachedPos;
  383. }
  384. // AttachmentPt 0 means the client chose to 'wear' the attachment.
  385. if (attachmentPt == (uint)AttachmentPoint.Default)
  386. {
  387. // Check object for stored attachment point
  388. attachmentPt = group.AttachmentPoint;
  389. }
  390. // if we didn't find an attach point, look for where it was last attached
  391. if (attachmentPt == 0)
  392. {
  393. attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint;
  394. attachPos = group.RootPart.AttachedPos;
  395. group.HasGroupChanged = true;
  396. }
  397. // if we still didn't find a suitable attachment point.......
  398. if (attachmentPt == 0)
  399. {
  400. // Stick it on left hand with Zero Offset from the attachment point.
  401. attachmentPt = (uint)AttachmentPoint.LeftHand;
  402. attachPos = Vector3.Zero;
  403. }
  404. group.AttachmentPoint = attachmentPt;
  405. group.AbsolutePosition = attachPos;
  406. List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
  407. if (attachments.Contains(group))
  408. {
  409. if (DebugLevel > 0)
  410. m_log.WarnFormat(
  411. "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
  412. group.Name, group.LocalId, sp.Name, attachmentPt);
  413. return false;
  414. }
  415. // If we already have 5, remove the oldest until only 4 are left. Skip over temp ones
  416. while (attachments.Count >= 5)
  417. {
  418. if (attachments[0].FromItemID != UUID.Zero)
  419. DetachSingleAttachmentToInv(sp, attachments[0]);
  420. attachments.RemoveAt(0);
  421. }
  422. // If we're not appending, remove the rest as well
  423. if (attachments.Count != 0 && !append)
  424. {
  425. foreach (SceneObjectGroup g in attachments)
  426. {
  427. if (g.FromItemID != UUID.Zero)
  428. DetachSingleAttachmentToInv(sp, g);
  429. }
  430. }
  431. lock (sp.AttachmentsSyncLock)
  432. {
  433. if (addToInventory && sp.PresenceType != PresenceType.Npc)
  434. UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append);
  435. AttachToAgent(sp, group, attachmentPt, attachPos, silent);
  436. if (resumeScripts)
  437. {
  438. // Fire after attach, so we don't get messy perms dialogs
  439. // 4 == AttachedRez
  440. group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
  441. group.ResumeScripts();
  442. }
  443. // Do this last so that event listeners have access to all the effects of the attachment
  444. m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
  445. }
  446. return true;
  447. }
  448. private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append)
  449. {
  450. // Add the new attachment to inventory if we don't already have it.
  451. UUID newAttachmentItemID = group.FromItemID;
  452. if (newAttachmentItemID == UUID.Zero)
  453. newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
  454. ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append);
  455. }
  456. public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
  457. {
  458. if (!Enabled)
  459. return null;
  460. if (DebugLevel > 0)
  461. m_log.DebugFormat(
  462. "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}",
  463. (AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name);
  464. // We check the attachments in the avatar appearance here rather than the objects attached to the
  465. // ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are
  466. // already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done
  467. // because pre-outfit folder viewers (most version 1 viewers) require it.
  468. bool alreadyOn = false;
  469. List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments();
  470. foreach (AvatarAttachment existingAttachment in existingAttachments)
  471. {
  472. if (existingAttachment.ItemID == itemID)
  473. {
  474. alreadyOn = true;
  475. break;
  476. }
  477. }
  478. if (alreadyOn)
  479. {
  480. if (DebugLevel > 0)
  481. m_log.DebugFormat(
  482. "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
  483. sp.Name, itemID, AttachmentPt);
  484. return null;
  485. }
  486. bool append = (AttachmentPt & 0x80) != 0;
  487. AttachmentPt &= 0x7f;
  488. return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append);
  489. }
  490. public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
  491. {
  492. if (!Enabled)
  493. return;
  494. if (DebugLevel > 0)
  495. m_log.DebugFormat(
  496. "[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}",
  497. rezlist.Count, sp.Name, m_scene.Name);
  498. foreach (KeyValuePair<UUID, uint> rez in rezlist)
  499. {
  500. RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
  501. }
  502. }
  503. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
  504. {
  505. DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
  506. }
  507. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
  508. {
  509. if (!Enabled)
  510. return;
  511. if (DebugLevel > 0)
  512. m_log.DebugFormat(
  513. "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
  514. sp.UUID, soLocalId);
  515. SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
  516. if (so == null)
  517. return;
  518. if (so.AttachedAvatar != sp.UUID)
  519. return;
  520. UUID inventoryID = so.FromItemID;
  521. // As per Linden spec, drop is disabled for temp attachs
  522. if (inventoryID == UUID.Zero)
  523. return;
  524. if (DebugLevel > 0)
  525. m_log.DebugFormat(
  526. "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
  527. so.Name, so.LocalId, inventoryID);
  528. lock (sp.AttachmentsSyncLock)
  529. {
  530. if (!m_scene.Permissions.CanRezObject(
  531. so.PrimCount, sp.UUID, sp.AbsolutePosition))
  532. return;
  533. bool changed = false;
  534. if (inventoryID != UUID.Zero)
  535. changed = sp.Appearance.DetachAttachment(inventoryID);
  536. if (changed && m_scene.AvatarFactory != null)
  537. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  538. sp.RemoveAttachment(so);
  539. so.FromItemID = UUID.Zero;
  540. SceneObjectPart rootPart = so.RootPart;
  541. so.AbsolutePosition = absolutePos;
  542. if (absoluteRot != Quaternion.Identity)
  543. {
  544. so.UpdateGroupRotationR(absoluteRot);
  545. }
  546. so.AttachedAvatar = UUID.Zero;
  547. rootPart.SetParentLocalId(0);
  548. so.ClearPartAttachmentData();
  549. rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
  550. so.HasGroupChanged = true;
  551. so.RootPart.Shape.LastAttachPoint = (byte)so.AttachmentPoint;
  552. rootPart.Rezzed = DateTime.Now;
  553. rootPart.RemFlag(PrimFlags.TemporaryOnRez);
  554. so.AttachToBackup();
  555. m_scene.EventManager.TriggerParcelPrimCountTainted();
  556. rootPart.ScheduleFullUpdate();
  557. rootPart.ClearUndoState();
  558. List<UUID> uuids = new List<UUID>();
  559. uuids.Add(inventoryID);
  560. m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
  561. sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
  562. }
  563. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
  564. }
  565. public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
  566. {
  567. if (so.AttachedAvatar != sp.UUID)
  568. {
  569. m_log.WarnFormat(
  570. "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
  571. so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
  572. return;
  573. }
  574. if (DebugLevel > 0)
  575. m_log.DebugFormat(
  576. "[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}",
  577. so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name);
  578. // Scripts MUST be snapshotted before the object is
  579. // removed from the scene because doing otherwise will
  580. // clobber the run flag
  581. // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
  582. // scripts performing attachment operations at the same time. Getting object states stops the scripts.
  583. string scriptedState = PrepareScriptInstanceForSave(so, true);
  584. lock (sp.AttachmentsSyncLock)
  585. {
  586. // Save avatar attachment information
  587. // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
  588. bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
  589. if (changed && m_scene.AvatarFactory != null)
  590. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  591. sp.RemoveAttachment(so);
  592. UpdateDetachedObject(sp, so, scriptedState);
  593. }
  594. }
  595. public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
  596. {
  597. if (!Enabled)
  598. return;
  599. sog.UpdateGroupPosition(pos);
  600. sog.HasGroupChanged = true;
  601. }
  602. #endregion
  603. #region AttachmentModule private methods
  604. // This is public but is not part of the IAttachmentsModule interface.
  605. // RegionCombiner module needs to poke at it to deliver client events.
  606. // This breaks the encapsulation of the module and should get fixed somehow.
  607. public void SubscribeToClientEvents(IClientAPI client)
  608. {
  609. client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
  610. client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
  611. client.OnObjectAttach += Client_OnObjectAttach;
  612. client.OnObjectDetach += Client_OnObjectDetach;
  613. client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
  614. client.OnObjectDrop += Client_OnObjectDrop;
  615. }
  616. // This is public but is not part of the IAttachmentsModule interface.
  617. // RegionCombiner module needs to poke at it to deliver client events.
  618. // This breaks the encapsulation of the module and should get fixed somehow.
  619. public void UnsubscribeFromClientEvents(IClientAPI client)
  620. {
  621. client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
  622. client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
  623. client.OnObjectAttach -= Client_OnObjectAttach;
  624. client.OnObjectDetach -= Client_OnObjectDetach;
  625. client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
  626. client.OnObjectDrop -= Client_OnObjectDrop;
  627. }
  628. /// <summary>
  629. /// Update the attachment asset for the new sog details if they have changed.
  630. /// </summary>
  631. /// <remarks>
  632. /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
  633. /// these details are not stored on the region.
  634. /// </remarks>
  635. /// <param name="sp"></param>
  636. /// <param name="grp"></param>
  637. /// <param name="saveAllScripted"></param>
  638. private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
  639. {
  640. if (grp.FromItemID == UUID.Zero)
  641. {
  642. // We can't save temp attachments
  643. grp.HasGroupChanged = false;
  644. return;
  645. }
  646. // Saving attachments for NPCs messes them up for the real owner!
  647. INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
  648. if (module != null)
  649. {
  650. if (module.IsNPC(sp.UUID, m_scene))
  651. return;
  652. }
  653. if (grp.HasGroupChanged)
  654. {
  655. m_log.DebugFormat(
  656. "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
  657. grp.UUID, grp.AttachmentPoint);
  658. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
  659. InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
  660. item = m_scene.InventoryService.GetItem(item);
  661. if (item != null)
  662. {
  663. AssetBase asset = m_scene.CreateAsset(
  664. grp.GetPartName(grp.LocalId),
  665. grp.GetPartDescription(grp.LocalId),
  666. (sbyte)AssetType.Object,
  667. Utils.StringToBytes(sceneObjectXml),
  668. sp.UUID);
  669. if (m_invAccessModule != null)
  670. m_invAccessModule.UpdateInventoryItemAsset(sp.UUID, item, asset);
  671. // If the name of the object has been changed whilst attached then we want to update the inventory
  672. // item in the viewer.
  673. if (sp.ControllingClient != null)
  674. sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
  675. }
  676. grp.HasGroupChanged = false; // Prevent it being saved over and over
  677. }
  678. else if (DebugLevel > 0)
  679. {
  680. m_log.DebugFormat(
  681. "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
  682. grp.UUID, grp.AttachmentPoint);
  683. }
  684. }
  685. /// <summary>
  686. /// Attach this scene object to the given avatar.
  687. /// </summary>
  688. /// <remarks>
  689. /// This isn't publicly available since attachments should always perform the corresponding inventory
  690. /// operation (to show the attach in user inventory and update the asset with positional information).
  691. /// </remarks>
  692. /// <param name="sp"></param>
  693. /// <param name="so"></param>
  694. /// <param name="attachmentpoint"></param>
  695. /// <param name="attachOffset"></param>
  696. /// <param name="silent"></param>
  697. private void AttachToAgent(
  698. IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
  699. {
  700. if (DebugLevel > 0)
  701. m_log.DebugFormat(
  702. "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} at pt {2} pos {3} {4} in {5}",
  703. so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos, m_scene.Name);
  704. // Remove from database and parcel prim count
  705. m_scene.DeleteFromStorage(so.UUID);
  706. m_scene.EventManager.TriggerParcelPrimCountTainted();
  707. so.AttachedAvatar = sp.UUID;
  708. if (so.RootPart.PhysActor != null)
  709. so.RootPart.RemoveFromPhysics();
  710. so.AbsolutePosition = attachOffset;
  711. so.RootPart.AttachedPos = attachOffset;
  712. so.IsAttachment = true;
  713. so.RootPart.SetParentLocalId(sp.LocalId);
  714. so.AttachmentPoint = attachmentpoint;
  715. sp.AddAttachment(so);
  716. if (!silent)
  717. {
  718. if (so.HasPrivateAttachmentPoint)
  719. {
  720. if (DebugLevel > 0)
  721. m_log.DebugFormat(
  722. "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
  723. so.Name, sp.Name, so.AttachmentPoint);
  724. // As this scene object can now only be seen by the attaching avatar, tell everybody else in the
  725. // scene that it's no longer in their awareness.
  726. m_scene.ForEachClient(
  727. client =>
  728. { if (client.AgentId != so.AttachedAvatar)
  729. client.SendKillObject(new List<uint>() { so.LocalId });
  730. });
  731. }
  732. // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update
  733. // will succeed, as that will not update if an attachment is selected.
  734. so.IsSelected = false; // fudge....
  735. so.ScheduleGroupForFullUpdate();
  736. }
  737. // In case it is later dropped again, don't let
  738. // it get cleaned up
  739. so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  740. }
  741. /// <summary>
  742. /// Add a scene object as a new attachment in the user inventory.
  743. /// </summary>
  744. /// <param name="remoteClient"></param>
  745. /// <param name="grp"></param>
  746. /// <returns>The user inventory item created that holds the attachment.</returns>
  747. private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
  748. {
  749. if (m_invAccessModule == null)
  750. return null;
  751. if (DebugLevel > 0)
  752. m_log.DebugFormat(
  753. "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
  754. grp.Name, grp.LocalId, sp.Name);
  755. InventoryItemBase newItem
  756. = m_invAccessModule.CopyToInventory(
  757. DeRezAction.TakeCopy,
  758. m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
  759. new List<SceneObjectGroup> { grp },
  760. sp.ControllingClient, true)[0];
  761. // sets itemID so client can show item as 'attached' in inventory
  762. grp.FromItemID = newItem.ID;
  763. return newItem;
  764. }
  765. /// <summary>
  766. /// Prepares the script instance for save.
  767. /// </summary>
  768. /// <remarks>
  769. /// This involves triggering the detach event and getting the script state (which also stops the script)
  770. /// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a
  771. /// running script is performing attachment operations.
  772. /// </remarks>
  773. /// <returns>
  774. /// The script state ready for persistence.
  775. /// </returns>
  776. /// <param name='grp'>
  777. /// </param>
  778. /// <param name='fireDetachEvent'>
  779. /// If true, then fire the script event before we save its state.
  780. /// </param>
  781. private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent)
  782. {
  783. if (fireDetachEvent)
  784. m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero);
  785. using (StringWriter sw = new StringWriter())
  786. {
  787. using (XmlTextWriter writer = new XmlTextWriter(sw))
  788. {
  789. grp.SaveScriptedState(writer);
  790. }
  791. return sw.ToString();
  792. }
  793. }
  794. private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState)
  795. {
  796. // Don't save attachments for HG visitors, it
  797. // messes up their inventory. When a HG visitor logs
  798. // out on a foreign grid, their attachments will be
  799. // reloaded in the state they were in when they left
  800. // the home grid. This is best anyway as the visited
  801. // grid may use an incompatible script engine.
  802. bool saveChanged
  803. = sp.PresenceType != PresenceType.Npc
  804. && (m_scene.UserManagementModule == null
  805. || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
  806. // Remove the object from the scene so no more updates
  807. // are sent. Doing this before the below changes will ensure
  808. // updates can't cause "HUD artefacts"
  809. m_scene.DeleteSceneObject(so, false, false);
  810. // Prepare sog for storage
  811. so.AttachedAvatar = UUID.Zero;
  812. so.RootPart.SetParentLocalId(0);
  813. so.IsAttachment = false;
  814. if (saveChanged)
  815. {
  816. // We cannot use AbsolutePosition here because that would
  817. // attempt to cross the prim as it is detached
  818. so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
  819. UpdateKnownItem(sp, so, scriptedState);
  820. }
  821. // Now, remove the scripts
  822. so.RemoveScriptInstances(true);
  823. }
  824. protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
  825. IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append)
  826. {
  827. if (m_invAccessModule == null)
  828. return null;
  829. SceneObjectGroup objatt;
  830. if (itemID != UUID.Zero)
  831. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  832. itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  833. false, false, sp.UUID, true);
  834. else
  835. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  836. null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  837. false, false, sp.UUID, true);
  838. if (objatt == null)
  839. {
  840. m_log.WarnFormat(
  841. "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
  842. itemID, sp.Name, attachmentPt);
  843. return null;
  844. }
  845. else if (itemID == UUID.Zero)
  846. {
  847. // We need to have a FromItemID for multiple attachments on a single attach point to appear. This is
  848. // true on Singularity 1.8.5 and quite possibly other viewers as well. As NPCs don't have an inventory
  849. // we will satisfy this requirement by inserting a random UUID.
  850. objatt.FromItemID = UUID.Random();
  851. }
  852. if (DebugLevel > 0)
  853. m_log.DebugFormat(
  854. "[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}",
  855. objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
  856. // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
  857. objatt.HasGroupChanged = false;
  858. bool tainted = false;
  859. if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
  860. tainted = true;
  861. // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
  862. // course of events. If not, then it's probably not worth trying to recover the situation
  863. // since this is more likely to trigger further exceptions and confuse later debugging. If
  864. // exceptions can be thrown in expected error conditions (not NREs) then make this consistent
  865. // since other normal error conditions will simply return false instead.
  866. // This will throw if the attachment fails
  867. try
  868. {
  869. AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append);
  870. }
  871. catch (Exception e)
  872. {
  873. m_log.ErrorFormat(
  874. "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
  875. objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
  876. // Make sure the object doesn't stick around and bail
  877. sp.RemoveAttachment(objatt);
  878. m_scene.DeleteSceneObject(objatt, false);
  879. return null;
  880. }
  881. if (tainted)
  882. objatt.HasGroupChanged = true;
  883. if (ThrottlePer100PrimsRezzed > 0)
  884. {
  885. int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed);
  886. if (DebugLevel > 0)
  887. m_log.DebugFormat(
  888. "[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}",
  889. throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
  890. Thread.Sleep(throttleMs);
  891. }
  892. return objatt;
  893. }
  894. /// <summary>
  895. /// Update the user inventory to reflect an attachment
  896. /// </summary>
  897. /// <param name="sp"></param>
  898. /// <param name="AttachmentPt"></param>
  899. /// <param name="itemID"></param>
  900. /// <param name="att"></param>
  901. private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append)
  902. {
  903. // m_log.DebugFormat(
  904. // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
  905. // att.Name, sp.Name, AttachmentPt, itemID);
  906. if (UUID.Zero == itemID)
  907. {
  908. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
  909. return;
  910. }
  911. if (0 == AttachmentPt)
  912. {
  913. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
  914. return;
  915. }
  916. InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
  917. item = m_scene.InventoryService.GetItem(item);
  918. if (item == null)
  919. return;
  920. int attFlag = append ? 0x80 : 0;
  921. bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID);
  922. if (changed && m_scene.AvatarFactory != null)
  923. {
  924. if (DebugLevel > 0)
  925. m_log.DebugFormat(
  926. "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
  927. sp.Name, att.Name, AttachmentPt);
  928. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  929. }
  930. }
  931. #endregion
  932. #region Client Event Handlers
  933. private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
  934. {
  935. if (!Enabled)
  936. return null;
  937. if (DebugLevel > 0)
  938. m_log.DebugFormat(
  939. "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
  940. (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
  941. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  942. if (sp == null)
  943. {
  944. m_log.ErrorFormat(
  945. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
  946. remoteClient.Name, remoteClient.AgentId);
  947. return null;
  948. }
  949. return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
  950. }
  951. private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
  952. {
  953. if (!Enabled)
  954. return;
  955. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  956. if (sp != null)
  957. RezMultipleAttachmentsFromInventory(sp, rezlist);
  958. else
  959. m_log.ErrorFormat(
  960. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
  961. remoteClient.Name, remoteClient.AgentId);
  962. }
  963. private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
  964. {
  965. if (DebugLevel > 0)
  966. m_log.DebugFormat(
  967. "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
  968. objectLocalID, remoteClient.Name, AttachmentPt, silent);
  969. if (!Enabled)
  970. return;
  971. try
  972. {
  973. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  974. if (sp == null)
  975. {
  976. m_log.ErrorFormat(
  977. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
  978. return;
  979. }
  980. // If we can't take it, we can't attach it!
  981. SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
  982. if (part == null)
  983. return;
  984. if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
  985. {
  986. remoteClient.SendAgentAlertMessage(
  987. "You don't have sufficient permissions to attach this object", false);
  988. return;
  989. }
  990. bool append = (AttachmentPt & 0x80) != 0;
  991. AttachmentPt &= 0x7f;
  992. // Calls attach with a Zero position
  993. if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append))
  994. {
  995. if (DebugLevel > 0)
  996. m_log.Debug(
  997. "[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
  998. + ", AttachmentPoint: " + AttachmentPt);
  999. // Save avatar attachment information
  1000. m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId);
  1001. }
  1002. }
  1003. catch (Exception e)
  1004. {
  1005. m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
  1006. }
  1007. }
  1008. private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
  1009. {
  1010. if (!Enabled)
  1011. return;
  1012. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1013. SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
  1014. if (sp != null && group != null && group.FromItemID != UUID.Zero)
  1015. DetachSingleAttachmentToInv(sp, group);
  1016. }
  1017. private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
  1018. {
  1019. if (!Enabled)
  1020. return;
  1021. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1022. if (sp != null)
  1023. {
  1024. List<SceneObjectGroup> attachments = sp.GetAttachments();
  1025. foreach (SceneObjectGroup group in attachments)
  1026. {
  1027. if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
  1028. {
  1029. DetachSingleAttachmentToInv(sp, group);
  1030. return;
  1031. }
  1032. }
  1033. }
  1034. }
  1035. private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
  1036. {
  1037. if (!Enabled)
  1038. return;
  1039. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1040. if (sp != null)
  1041. DetachSingleAttachmentToGround(sp, soLocalId);
  1042. }
  1043. #endregion
  1044. }
  1045. }