AttachmentsModule.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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.Xml;
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Packets;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Region.Framework.Scenes.Serialization;
  42. namespace OpenSim.Region.CoreModules.Avatar.Attachments
  43. {
  44. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")]
  45. public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule
  46. {
  47. #region INonSharedRegionModule
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private Scene m_scene;
  50. private IInventoryAccessModule m_invAccessModule;
  51. /// <summary>
  52. /// Are attachments enabled?
  53. /// </summary>
  54. public bool Enabled { get; private set; }
  55. public string Name { get { return "Attachments Module"; } }
  56. public Type ReplaceableInterface { get { return null; } }
  57. public void Initialise(IConfigSource source)
  58. {
  59. IConfig config = source.Configs["Attachments"];
  60. if (config != null)
  61. Enabled = config.GetBoolean("Enabled", true);
  62. else
  63. Enabled = true;
  64. }
  65. public void AddRegion(Scene scene)
  66. {
  67. m_scene = scene;
  68. m_scene.RegisterModuleInterface<IAttachmentsModule>(this);
  69. if (Enabled)
  70. m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
  71. // TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI
  72. }
  73. public void RemoveRegion(Scene scene)
  74. {
  75. m_scene.UnregisterModuleInterface<IAttachmentsModule>(this);
  76. if (Enabled)
  77. m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
  78. }
  79. public void RegionLoaded(Scene scene)
  80. {
  81. m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>();
  82. }
  83. public void Close()
  84. {
  85. RemoveRegion(m_scene);
  86. }
  87. #endregion
  88. #region IAttachmentsModule
  89. public void CopyAttachments(IScenePresence sp, AgentData ad)
  90. {
  91. lock (sp.AttachmentsSyncLock)
  92. {
  93. // Attachment objects
  94. List<SceneObjectGroup> attachments = sp.GetAttachments();
  95. if (attachments.Count > 0)
  96. {
  97. ad.AttachmentObjects = new List<ISceneObject>();
  98. ad.AttachmentObjectStates = new List<string>();
  99. // IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>();
  100. sp.InTransitScriptStates.Clear();
  101. foreach (SceneObjectGroup sog in attachments)
  102. {
  103. // We need to make a copy and pass that copy
  104. // because of transfers withn the same sim
  105. ISceneObject clone = sog.CloneForNewScene();
  106. // Attachment module assumes that GroupPosition holds the offsets...!
  107. ((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos;
  108. ((SceneObjectGroup)clone).IsAttachment = false;
  109. ad.AttachmentObjects.Add(clone);
  110. string state = sog.GetStateSnapshot();
  111. ad.AttachmentObjectStates.Add(state);
  112. sp.InTransitScriptStates.Add(state);
  113. // Let's remove the scripts of the original object here
  114. sog.RemoveScriptInstances(true);
  115. }
  116. }
  117. }
  118. }
  119. public void CopyAttachments(AgentData ad, IScenePresence sp)
  120. {
  121. if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
  122. {
  123. lock (sp.AttachmentsSyncLock)
  124. sp.ClearAttachments();
  125. int i = 0;
  126. foreach (ISceneObject so in ad.AttachmentObjects)
  127. {
  128. ((SceneObjectGroup)so).LocalId = 0;
  129. ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
  130. so.SetState(ad.AttachmentObjectStates[i++], m_scene);
  131. m_scene.IncomingCreateObject(Vector3.Zero, so);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// RezAttachments. This should only be called upon login on the first region.
  137. /// Attachment rezzings on crossings and TPs are done in a different way.
  138. /// </summary>
  139. public void RezAttachments(IScenePresence sp)
  140. {
  141. if (!Enabled)
  142. return;
  143. if (null == sp.Appearance)
  144. {
  145. m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
  146. return;
  147. }
  148. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0}", sp.Name);
  149. List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
  150. foreach (AvatarAttachment attach in attachments)
  151. {
  152. uint p = (uint)attach.AttachPoint;
  153. // m_log.DebugFormat(
  154. // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
  155. // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
  156. // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
  157. // But they're not used anyway, the item is being looked up for now, so let's proceed.
  158. //if (UUID.Zero == assetID)
  159. //{
  160. // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
  161. // continue;
  162. //}
  163. try
  164. {
  165. // If we're an NPC then skip all the item checks and manipulations since we don't have an
  166. // inventory right now.
  167. if (sp.PresenceType == PresenceType.Npc)
  168. RezSingleAttachmentFromInventoryInternal(sp, UUID.Zero, attach.AssetID, p);
  169. else
  170. RezSingleAttachmentFromInventory(sp, attach.ItemID, p);
  171. }
  172. catch (Exception e)
  173. {
  174. UUID agentId = (sp.ControllingClient == null) ? (UUID)null : sp.ControllingClient.AgentId;
  175. m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
  176. attach.ItemID, attach.AssetID, p, agentId, e.Message, e.StackTrace);
  177. }
  178. }
  179. }
  180. public void DeRezAttachments(IScenePresence sp)
  181. {
  182. if (!Enabled)
  183. return;
  184. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Saving changed attachments for {0}", sp.Name);
  185. lock (sp.AttachmentsSyncLock)
  186. {
  187. foreach (SceneObjectGroup so in sp.GetAttachments())
  188. {
  189. UpdateDetachedObject(sp, so);
  190. }
  191. sp.ClearAttachments();
  192. }
  193. }
  194. public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
  195. {
  196. if (!Enabled)
  197. return;
  198. // m_log.DebugFormat(
  199. // "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
  200. // m_scene.RegionInfo.RegionName, sp.Name, silent);
  201. foreach (SceneObjectGroup sop in sp.GetAttachments())
  202. {
  203. sop.Scene.DeleteSceneObject(sop, silent);
  204. }
  205. sp.ClearAttachments();
  206. }
  207. public bool AttachObject(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool temp)
  208. {
  209. if (!Enabled)
  210. return false;
  211. if (AttachObjectInternal(sp, group, attachmentPt, silent, temp))
  212. {
  213. m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
  214. return true;
  215. }
  216. return false;
  217. }
  218. private bool AttachObjectInternal(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool temp)
  219. {
  220. lock (sp.AttachmentsSyncLock)
  221. {
  222. // m_log.DebugFormat(
  223. // "[ATTACHMENTS MODULE]: Attaching object {0} {1} to {2} point {3} from ground (silent = {4})",
  224. // group.Name, group.LocalId, sp.Name, attachmentPt, silent);
  225. if (group.GetSittingAvatarsCount() != 0)
  226. {
  227. // m_log.WarnFormat(
  228. // "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
  229. // group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
  230. return false;
  231. }
  232. if (sp.GetAttachments(attachmentPt).Contains(group))
  233. {
  234. // m_log.WarnFormat(
  235. // "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
  236. // group.Name, group.LocalId, sp.Name, AttachmentPt);
  237. return false;
  238. }
  239. Vector3 attachPos = group.AbsolutePosition;
  240. // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
  241. // be removed when that functionality is implemented in opensim
  242. attachmentPt &= 0x7f;
  243. // If the attachment point isn't the same as the one previously used
  244. // set it's offset position = 0 so that it appears on the attachment point
  245. // and not in a weird location somewhere unknown.
  246. if (attachmentPt != 0 && attachmentPt != group.AttachmentPoint)
  247. {
  248. attachPos = Vector3.Zero;
  249. }
  250. // AttachmentPt 0 means the client chose to 'wear' the attachment.
  251. if (attachmentPt == 0)
  252. {
  253. // Check object for stored attachment point
  254. attachmentPt = group.AttachmentPoint;
  255. }
  256. // if we still didn't find a suitable attachment point.......
  257. if (attachmentPt == 0)
  258. {
  259. // Stick it on left hand with Zero Offset from the attachment point.
  260. attachmentPt = (uint)AttachmentPoint.LeftHand;
  261. attachPos = Vector3.Zero;
  262. }
  263. group.AttachmentPoint = attachmentPt;
  264. group.AbsolutePosition = attachPos;
  265. if (sp.PresenceType != PresenceType.Npc)
  266. UpdateUserInventoryWithAttachment(sp, group, attachmentPt, temp);
  267. AttachToAgent(sp, group, attachmentPt, attachPos, silent);
  268. }
  269. return true;
  270. }
  271. private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool temp)
  272. {
  273. // Remove any previous attachments
  274. List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
  275. // At the moment we can only deal with a single attachment
  276. if (attachments.Count != 0)
  277. {
  278. if (attachments[0].FromItemID != UUID.Zero)
  279. DetachSingleAttachmentToInvInternal(sp, attachments[0]);
  280. // Error logging commented because UUID.Zero now means temp attachment
  281. // else
  282. // m_log.WarnFormat(
  283. // "[ATTACHMENTS MODULE]: When detaching existing attachment {0} {1} at point {2} to make way for {3} {4} for {5}, couldn't find the associated item ID to adjust inventory attachment record!",
  284. // attachments[0].Name, attachments[0].LocalId, attachmentPt, group.Name, group.LocalId, sp.Name);
  285. }
  286. // Add the new attachment to inventory if we don't already have it.
  287. if (!temp)
  288. {
  289. UUID newAttachmentItemID = group.FromItemID;
  290. if (newAttachmentItemID == UUID.Zero)
  291. newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
  292. ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group);
  293. }
  294. }
  295. public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
  296. {
  297. if (!Enabled)
  298. return null;
  299. // m_log.DebugFormat(
  300. // "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2}",
  301. // (AttachmentPoint)AttachmentPt, itemID, sp.Name);
  302. // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
  303. // be removed when that functionality is implemented in opensim
  304. AttachmentPt &= 0x7f;
  305. // Viewer 2/3 sometimes asks to re-wear items that are already worn (and show up in it's inventory as such).
  306. // This often happens during login - not sure the exact reason.
  307. // For now, we will ignore the request. Unfortunately, this means that we need to dig through all the
  308. // ScenePresence attachments. We can't use the data in AvatarAppearance because that's present at login
  309. // before anything has actually been attached.
  310. bool alreadyOn = false;
  311. List<SceneObjectGroup> existingAttachments = sp.GetAttachments();
  312. foreach (SceneObjectGroup so in existingAttachments)
  313. {
  314. if (so.FromItemID == itemID)
  315. {
  316. alreadyOn = true;
  317. break;
  318. }
  319. }
  320. // if (sp.Appearance.GetAttachmentForItem(itemID) != null)
  321. if (alreadyOn)
  322. {
  323. // m_log.WarnFormat(
  324. // "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
  325. // sp.Name, itemID, AttachmentPt);
  326. return null;
  327. }
  328. return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt);
  329. }
  330. public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
  331. {
  332. if (!Enabled)
  333. return;
  334. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing multiple attachments from inventory for {0}", sp.Name);
  335. lock (sp.AttachmentsSyncLock)
  336. {
  337. foreach (KeyValuePair<UUID, uint> rez in rezlist)
  338. {
  339. RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
  340. }
  341. }
  342. }
  343. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
  344. {
  345. DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
  346. }
  347. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
  348. {
  349. if (!Enabled)
  350. return;
  351. // m_log.DebugFormat(
  352. // "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
  353. // sp.UUID, soLocalId);
  354. SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
  355. if (so == null)
  356. return;
  357. if (so.AttachedAvatar != sp.UUID)
  358. return;
  359. UUID inventoryID = so.FromItemID;
  360. // As per Linden spec, drop is disabled for temp attachs
  361. if (inventoryID == UUID.Zero)
  362. return;
  363. // m_log.DebugFormat(
  364. // "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
  365. // so.Name, so.LocalId, inventoryID);
  366. lock (sp.AttachmentsSyncLock)
  367. {
  368. if (!m_scene.Permissions.CanRezObject(
  369. so.PrimCount, sp.UUID, sp.AbsolutePosition))
  370. return;
  371. bool changed = false;
  372. if (inventoryID != UUID.Zero)
  373. changed = sp.Appearance.DetachAttachment(inventoryID);
  374. if (changed && m_scene.AvatarFactory != null)
  375. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  376. sp.RemoveAttachment(so);
  377. so.FromItemID = UUID.Zero;
  378. SceneObjectPart rootPart = so.RootPart;
  379. so.AbsolutePosition = absolutePos;
  380. if (absoluteRot != Quaternion.Identity)
  381. {
  382. so.UpdateGroupRotationR(absoluteRot);
  383. }
  384. so.AttachedAvatar = UUID.Zero;
  385. rootPart.SetParentLocalId(0);
  386. so.ClearPartAttachmentData();
  387. rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
  388. so.HasGroupChanged = true;
  389. rootPart.Rezzed = DateTime.Now;
  390. rootPart.RemFlag(PrimFlags.TemporaryOnRez);
  391. so.AttachToBackup();
  392. m_scene.EventManager.TriggerParcelPrimCountTainted();
  393. rootPart.ScheduleFullUpdate();
  394. rootPart.ClearUndoState();
  395. List<UUID> uuids = new List<UUID>();
  396. uuids.Add(inventoryID);
  397. m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
  398. sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
  399. }
  400. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
  401. }
  402. public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
  403. {
  404. lock (sp.AttachmentsSyncLock)
  405. {
  406. // Save avatar attachment information
  407. // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
  408. if (so.AttachedAvatar != sp.UUID)
  409. {
  410. m_log.WarnFormat(
  411. "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
  412. so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
  413. return;
  414. }
  415. bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
  416. if (changed && m_scene.AvatarFactory != null)
  417. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  418. DetachSingleAttachmentToInvInternal(sp, so);
  419. }
  420. }
  421. public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
  422. {
  423. if (!Enabled)
  424. return;
  425. sog.UpdateGroupPosition(pos);
  426. sog.HasGroupChanged = true;
  427. }
  428. #endregion
  429. #region AttachmentModule private methods
  430. // This is public but is not part of the IAttachmentsModule interface.
  431. // RegionCombiner module needs to poke at it to deliver client events.
  432. // This breaks the encapsulation of the module and should get fixed somehow.
  433. public void SubscribeToClientEvents(IClientAPI client)
  434. {
  435. client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
  436. client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
  437. client.OnObjectAttach += Client_OnObjectAttach;
  438. client.OnObjectDetach += Client_OnObjectDetach;
  439. client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
  440. client.OnObjectDrop += Client_OnObjectDrop;
  441. }
  442. // This is public but is not part of the IAttachmentsModule interface.
  443. // RegionCombiner module needs to poke at it to deliver client events.
  444. // This breaks the encapsulation of the module and should get fixed somehow.
  445. public void UnsubscribeFromClientEvents(IClientAPI client)
  446. {
  447. client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
  448. client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
  449. client.OnObjectAttach -= Client_OnObjectAttach;
  450. client.OnObjectDetach -= Client_OnObjectDetach;
  451. client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
  452. client.OnObjectDrop -= Client_OnObjectDrop;
  453. }
  454. /// <summary>
  455. /// Update the attachment asset for the new sog details if they have changed.
  456. /// </summary>
  457. /// <remarks>
  458. /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
  459. /// these details are not stored on the region.
  460. /// </remarks>
  461. /// <param name="sp"></param>
  462. /// <param name="grp"></param>
  463. /// <param name="saveAllScripted"></param>
  464. private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
  465. {
  466. if (grp.FromItemID == UUID.Zero)
  467. {
  468. // We can't save temp attachments
  469. grp.HasGroupChanged = false;
  470. return;
  471. }
  472. // Saving attachments for NPCs messes them up for the real owner!
  473. INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
  474. if (module != null)
  475. {
  476. if (module.IsNPC(sp.UUID, m_scene))
  477. return;
  478. }
  479. if (grp.HasGroupChanged)
  480. {
  481. m_log.DebugFormat(
  482. "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
  483. grp.UUID, grp.AttachmentPoint);
  484. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
  485. InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
  486. item = m_scene.InventoryService.GetItem(item);
  487. if (item != null)
  488. {
  489. AssetBase asset = m_scene.CreateAsset(
  490. grp.GetPartName(grp.LocalId),
  491. grp.GetPartDescription(grp.LocalId),
  492. (sbyte)AssetType.Object,
  493. Utils.StringToBytes(sceneObjectXml),
  494. sp.UUID);
  495. m_scene.AssetService.Store(asset);
  496. item.AssetID = asset.FullID;
  497. item.Description = asset.Description;
  498. item.Name = asset.Name;
  499. item.AssetType = asset.Type;
  500. item.InvType = (int)InventoryType.Object;
  501. m_scene.InventoryService.UpdateItem(item);
  502. // If the name of the object has been changed whilst attached then we want to update the inventory
  503. // item in the viewer.
  504. if (sp.ControllingClient != null)
  505. sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
  506. }
  507. grp.HasGroupChanged = false; // Prevent it being saved over and over
  508. }
  509. // else
  510. // {
  511. // m_log.DebugFormat(
  512. // "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
  513. // grp.UUID, grp.AttachmentPoint);
  514. // }
  515. }
  516. /// <summary>
  517. /// Attach this scene object to the given avatar.
  518. /// </summary>
  519. /// <remarks>
  520. /// This isn't publicly available since attachments should always perform the corresponding inventory
  521. /// operation (to show the attach in user inventory and update the asset with positional information).
  522. /// </remarks>
  523. /// <param name="sp"></param>
  524. /// <param name="so"></param>
  525. /// <param name="attachmentpoint"></param>
  526. /// <param name="attachOffset"></param>
  527. /// <param name="silent"></param>
  528. private void AttachToAgent(
  529. IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
  530. {
  531. // m_log.DebugFormat(
  532. // "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}",
  533. // so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos);
  534. so.DetachFromBackup();
  535. // Remove from database and parcel prim count
  536. m_scene.DeleteFromStorage(so.UUID);
  537. m_scene.EventManager.TriggerParcelPrimCountTainted();
  538. so.AttachedAvatar = sp.UUID;
  539. if (so.RootPart.PhysActor != null)
  540. so.RootPart.RemoveFromPhysics();
  541. so.AbsolutePosition = attachOffset;
  542. so.RootPart.AttachedPos = attachOffset;
  543. so.IsAttachment = true;
  544. so.RootPart.SetParentLocalId(sp.LocalId);
  545. so.AttachmentPoint = attachmentpoint;
  546. sp.AddAttachment(so);
  547. if (!silent)
  548. {
  549. if (so.HasPrivateAttachmentPoint)
  550. {
  551. // m_log.DebugFormat(
  552. // "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
  553. // so.Name, sp.Name, so.AttachmentPoint);
  554. // As this scene object can now only be seen by the attaching avatar, tell everybody else in the
  555. // scene that it's no longer in their awareness.
  556. m_scene.ForEachClient(
  557. client =>
  558. { if (client.AgentId != so.AttachedAvatar)
  559. client.SendKillObject(m_scene.RegionInfo.RegionHandle, new List<uint>() { so.LocalId });
  560. });
  561. }
  562. // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update
  563. // will succeed, as that will not update if an attachment is selected.
  564. so.IsSelected = false; // fudge....
  565. so.ScheduleGroupForFullUpdate();
  566. }
  567. // In case it is later dropped again, don't let
  568. // it get cleaned up
  569. so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  570. }
  571. /// <summary>
  572. /// Add a scene object as a new attachment in the user inventory.
  573. /// </summary>
  574. /// <param name="remoteClient"></param>
  575. /// <param name="grp"></param>
  576. /// <returns>The user inventory item created that holds the attachment.</returns>
  577. private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
  578. {
  579. if (m_invAccessModule == null)
  580. return null;
  581. // m_log.DebugFormat(
  582. // "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
  583. // grp.Name, grp.LocalId, remoteClient.Name);
  584. InventoryItemBase newItem
  585. = m_invAccessModule.CopyToInventory(
  586. DeRezAction.TakeCopy,
  587. m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
  588. new List<SceneObjectGroup> { grp },
  589. sp.ControllingClient, true)[0];
  590. // sets itemID so client can show item as 'attached' in inventory
  591. grp.FromItemID = newItem.ID;
  592. return newItem;
  593. }
  594. private string GetObjectScriptStates(SceneObjectGroup grp)
  595. {
  596. using (StringWriter sw = new StringWriter())
  597. {
  598. using (XmlTextWriter writer = new XmlTextWriter(sw))
  599. {
  600. grp.SaveScriptedState(writer);
  601. }
  602. return sw.ToString();
  603. }
  604. }
  605. private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so)
  606. {
  607. // Don't save attachments for HG visitors, it
  608. // messes up their inventory. When a HG visitor logs
  609. // out on a foreign grid, their attachments will be
  610. // reloaded in the state they were in when they left
  611. // the home grid. This is best anyway as the visited
  612. // grid may use an incompatible script engine.
  613. bool saveChanged
  614. = sp.PresenceType != PresenceType.Npc
  615. && (m_scene.UserManagementModule == null
  616. || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
  617. // Scripts MUST be snapshotted before the object is
  618. // removed from the scene because doing otherwise will
  619. // clobber the run flag
  620. string scriptedState = GetObjectScriptStates(so);
  621. // Remove the object from the scene so no more updates
  622. // are sent. Doing this before the below changes will ensure
  623. // updates can't cause "HUD artefacts"
  624. m_scene.DeleteSceneObject(so, false, false);
  625. // Prepare sog for storage
  626. so.AttachedAvatar = UUID.Zero;
  627. so.RootPart.SetParentLocalId(0);
  628. so.IsAttachment = false;
  629. if (saveChanged)
  630. {
  631. // We cannot use AbsolutePosition here because that would
  632. // attempt to cross the prim as it is detached
  633. so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
  634. UpdateKnownItem(sp, so, scriptedState);
  635. }
  636. // Now, remove the scripts
  637. so.RemoveScriptInstances(true);
  638. }
  639. private void DetachSingleAttachmentToInvInternal(IScenePresence sp, SceneObjectGroup so)
  640. {
  641. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Detaching item {0} to inventory for {1}", itemID, sp.Name);
  642. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.FromItemID, UUID.Zero);
  643. sp.RemoveAttachment(so);
  644. UpdateDetachedObject(sp, so);
  645. }
  646. private SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
  647. IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt)
  648. {
  649. if (m_invAccessModule == null)
  650. return null;
  651. lock (sp.AttachmentsSyncLock)
  652. {
  653. SceneObjectGroup objatt;
  654. if (itemID != UUID.Zero)
  655. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  656. itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  657. false, false, sp.UUID, true);
  658. else
  659. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  660. null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  661. false, false, sp.UUID, true);
  662. if (objatt != null)
  663. {
  664. // m_log.DebugFormat(
  665. // "[ATTACHMENTS MODULE]: Rezzed single object {0} for attachment to {1} on point {2} in {3}",
  666. // objatt.Name, sp.Name, attachmentPt, m_scene.Name);
  667. // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
  668. objatt.HasGroupChanged = false;
  669. bool tainted = false;
  670. if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
  671. tainted = true;
  672. // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
  673. // course of events. If not, then it's probably not worth trying to recover the situation
  674. // since this is more likely to trigger further exceptions and confuse later debugging. If
  675. // exceptions can be thrown in expected error conditions (not NREs) then make this consistent
  676. // since other normal error conditions will simply return false instead.
  677. // This will throw if the attachment fails
  678. try
  679. {
  680. AttachObjectInternal(sp, objatt, attachmentPt, false, false);
  681. }
  682. catch (Exception e)
  683. {
  684. m_log.ErrorFormat(
  685. "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
  686. objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
  687. // Make sure the object doesn't stick around and bail
  688. sp.RemoveAttachment(objatt);
  689. m_scene.DeleteSceneObject(objatt, false);
  690. return null;
  691. }
  692. if (tainted)
  693. objatt.HasGroupChanged = true;
  694. // Fire after attach, so we don't get messy perms dialogs
  695. // 4 == AttachedRez
  696. objatt.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
  697. objatt.ResumeScripts();
  698. // Do this last so that event listeners have access to all the effects of the attachment
  699. m_scene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, sp.UUID);
  700. return objatt;
  701. }
  702. else
  703. {
  704. m_log.WarnFormat(
  705. "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
  706. itemID, sp.Name, attachmentPt);
  707. }
  708. }
  709. return null;
  710. }
  711. /// <summary>
  712. /// Update the user inventory to reflect an attachment
  713. /// </summary>
  714. /// <param name="sp"></param>
  715. /// <param name="AttachmentPt"></param>
  716. /// <param name="itemID"></param>
  717. /// <param name="att"></param>
  718. private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att)
  719. {
  720. // m_log.DebugFormat(
  721. // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
  722. // att.Name, sp.Name, AttachmentPt, itemID);
  723. if (UUID.Zero == itemID)
  724. {
  725. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
  726. return;
  727. }
  728. if (0 == AttachmentPt)
  729. {
  730. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
  731. return;
  732. }
  733. InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
  734. item = m_scene.InventoryService.GetItem(item);
  735. if (item == null)
  736. return;
  737. bool changed = sp.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID);
  738. if (changed && m_scene.AvatarFactory != null)
  739. {
  740. // m_log.DebugFormat(
  741. // "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
  742. // sp.Name, att.Name, AttachmentPt);
  743. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  744. }
  745. }
  746. #endregion
  747. #region Client Event Handlers
  748. private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
  749. {
  750. if (!Enabled)
  751. return null;
  752. // m_log.DebugFormat(
  753. // "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
  754. // (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
  755. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  756. if (sp == null)
  757. {
  758. m_log.ErrorFormat(
  759. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
  760. remoteClient.Name, remoteClient.AgentId);
  761. return null;
  762. }
  763. return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
  764. }
  765. private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
  766. {
  767. if (!Enabled)
  768. return;
  769. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  770. if (sp != null)
  771. RezMultipleAttachmentsFromInventory(sp, rezlist);
  772. else
  773. m_log.ErrorFormat(
  774. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
  775. remoteClient.Name, remoteClient.AgentId);
  776. }
  777. private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
  778. {
  779. // m_log.DebugFormat(
  780. // "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
  781. // objectLocalID, remoteClient.Name, AttachmentPt, silent);
  782. if (!Enabled)
  783. return;
  784. try
  785. {
  786. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  787. if (sp == null)
  788. {
  789. m_log.ErrorFormat(
  790. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
  791. return;
  792. }
  793. // If we can't take it, we can't attach it!
  794. SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
  795. if (part == null)
  796. return;
  797. if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
  798. {
  799. remoteClient.SendAgentAlertMessage(
  800. "You don't have sufficient permissions to attach this object", false);
  801. return;
  802. }
  803. // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
  804. // be removed when that functionality is implemented in opensim
  805. AttachmentPt &= 0x7f;
  806. // Calls attach with a Zero position
  807. AttachObject(sp, part.ParentGroup, AttachmentPt, false, false);
  808. }
  809. catch (Exception e)
  810. {
  811. m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
  812. }
  813. }
  814. private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
  815. {
  816. if (!Enabled)
  817. return;
  818. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  819. SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
  820. if (sp != null && group != null && group.FromItemID != UUID.Zero)
  821. DetachSingleAttachmentToInv(sp, group);
  822. }
  823. private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
  824. {
  825. if (!Enabled)
  826. return;
  827. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  828. if (sp != null)
  829. {
  830. lock (sp.AttachmentsSyncLock)
  831. {
  832. List<SceneObjectGroup> attachments = sp.GetAttachments();
  833. foreach (SceneObjectGroup group in attachments)
  834. {
  835. if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
  836. {
  837. DetachSingleAttachmentToInv(sp, group);
  838. return;
  839. }
  840. }
  841. }
  842. }
  843. }
  844. private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
  845. {
  846. if (!Enabled)
  847. return;
  848. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  849. if (sp != null)
  850. DetachSingleAttachmentToGround(sp, soLocalId);
  851. }
  852. #endregion
  853. }
  854. }