1
0

UuidGatherer.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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.IO;
  30. using System.Reflection;
  31. using System.Text.RegularExpressions;
  32. using System.Threading;
  33. using log4net;
  34. using OpenMetaverse;
  35. using OpenMetaverse.Assets;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Framework.Scenes.Serialization;
  39. using OpenSim.Services.Interfaces;
  40. namespace OpenSim.Region.Framework.Scenes
  41. {
  42. /// <summary>
  43. /// Gather uuids for a given entity.
  44. /// </summary>
  45. /// <remarks>
  46. /// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts
  47. /// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets
  48. /// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be
  49. /// retrieved to work out which assets it references).
  50. /// </remarks>
  51. public class UuidGatherer
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. protected IAssetService m_assetService;
  55. // /// <summary>
  56. // /// Used as a temporary store of an asset which represents an object. This can be a null if no appropriate
  57. // /// asset was found by the asset service.
  58. // /// </summary>
  59. // private AssetBase m_requestedObjectAsset;
  60. //
  61. // /// <summary>
  62. // /// Signal whether we are currently waiting for the asset service to deliver an asset.
  63. // /// </summary>
  64. // private bool m_waitingForObjectAsset;
  65. public UuidGatherer(IAssetService assetService)
  66. {
  67. m_assetService = assetService;
  68. }
  69. /// <summary>
  70. /// Gather all the asset uuids associated with the asset referenced by a given uuid
  71. /// </summary>
  72. /// <remarks>
  73. /// This includes both those directly associated with
  74. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  75. /// within this object).
  76. /// </remarks>
  77. /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
  78. /// <param name="assetType">The type of the asset for the uuid given</param>
  79. /// <param name="assetUuids">The assets gathered</param>
  80. public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
  81. {
  82. // avoid infinite loops
  83. if (assetUuids.ContainsKey(assetUuid))
  84. return;
  85. try
  86. {
  87. assetUuids[assetUuid] = assetType;
  88. if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType)
  89. {
  90. GetWearableAssetUuids(assetUuid, assetUuids);
  91. }
  92. else if (AssetType.Gesture == assetType)
  93. {
  94. GetGestureAssetUuids(assetUuid, assetUuids);
  95. }
  96. else if (AssetType.Notecard == assetType)
  97. {
  98. GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
  99. }
  100. else if (AssetType.LSLText == assetType)
  101. {
  102. GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
  103. }
  104. else if (AssetType.Object == assetType)
  105. {
  106. GetSceneObjectAssetUuids(assetUuid, assetUuids);
  107. }
  108. }
  109. catch (Exception)
  110. {
  111. m_log.ErrorFormat(
  112. "[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}",
  113. assetUuid, assetType);
  114. throw;
  115. }
  116. }
  117. /// <summary>
  118. /// Gather all the asset uuids associated with a given object.
  119. /// </summary>
  120. /// <remarks>
  121. /// This includes both those directly associated with
  122. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  123. /// within this object).
  124. /// </remarks>
  125. /// <param name="sceneObject">The scene object for which to gather assets</param>
  126. /// <param name="assetUuids">
  127. /// A dictionary which is populated with the asset UUIDs gathered and the type of that asset.
  128. /// For assets where the type is not clear (e.g. UUIDs extracted from LSL and notecards), the type is Unknown.
  129. /// </param>
  130. public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, AssetType> assetUuids)
  131. {
  132. // m_log.DebugFormat(
  133. // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
  134. SceneObjectPart[] parts = sceneObject.Parts;
  135. for (int i = 0; i < parts.Length; i++)
  136. {
  137. SceneObjectPart part = parts[i];
  138. // m_log.DebugFormat(
  139. // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
  140. try
  141. {
  142. Primitive.TextureEntry textureEntry = part.Shape.Textures;
  143. if (textureEntry != null)
  144. {
  145. // Get the prim's default texture. This will be used for faces which don't have their own texture
  146. if (textureEntry.DefaultTexture != null)
  147. assetUuids[textureEntry.DefaultTexture.TextureID] = AssetType.Texture;
  148. if (textureEntry.FaceTextures != null)
  149. {
  150. // Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture)
  151. foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
  152. {
  153. if (texture != null)
  154. assetUuids[texture.TextureID] = AssetType.Texture;
  155. }
  156. }
  157. }
  158. // If the prim is a sculpt then preserve this information too
  159. if (part.Shape.SculptTexture != UUID.Zero)
  160. assetUuids[part.Shape.SculptTexture] = AssetType.Texture;
  161. if (part.Shape.ProjectionTextureUUID != UUID.Zero)
  162. assetUuids[part.Shape.ProjectionTextureUUID] = AssetType.Texture;
  163. if (part.CollisionSound != UUID.Zero)
  164. assetUuids[part.CollisionSound] = AssetType.Sound;
  165. if (part.ParticleSystem.Length > 0)
  166. {
  167. Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0);
  168. if (ps.Texture != UUID.Zero)
  169. assetUuids[ps.Texture] = AssetType.Texture;
  170. }
  171. TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
  172. // Now analyze this prim's inventory items to preserve all the uuids that they reference
  173. foreach (TaskInventoryItem tii in taskDictionary.Values)
  174. {
  175. // m_log.DebugFormat(
  176. // "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
  177. // tii.Name, tii.Type, part.Name, part.UUID);
  178. if (!assetUuids.ContainsKey(tii.AssetID))
  179. GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids);
  180. }
  181. // FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
  182. // to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and
  183. // inventory transfer. There needs to be a way for a module to register a method without assuming a
  184. // Scene.EventManager is present.
  185. // part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids);
  186. GatherMaterialsUuids(part, assetUuids);
  187. }
  188. catch (Exception e)
  189. {
  190. m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
  191. m_log.DebugFormat(
  192. "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
  193. part.Shape.TextureEntry.Length);
  194. }
  195. }
  196. }
  197. // /// <summary>
  198. // /// The callback made when we request the asset for an object from the asset service.
  199. // /// </summary>
  200. // private void AssetReceived(string id, Object sender, AssetBase asset)
  201. // {
  202. // lock (this)
  203. // {
  204. // m_requestedObjectAsset = asset;
  205. // m_waitingForObjectAsset = false;
  206. // Monitor.Pulse(this);
  207. // }
  208. // }
  209. /// <summary>
  210. /// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
  211. /// </summary>
  212. /// <param name="part"></param>
  213. /// <param name="assetUuids"></param>
  214. public void GatherMaterialsUuids(SceneObjectPart part, IDictionary<UUID, AssetType> assetUuids)
  215. {
  216. // scan thru the dynAttrs map of this part for any textures used as materials
  217. OSD osdMaterials = null;
  218. lock (part.DynAttrs)
  219. {
  220. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  221. {
  222. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  223. if (materialsStore == null)
  224. return;
  225. materialsStore.TryGetValue("Materials", out osdMaterials);
  226. }
  227. if (osdMaterials != null)
  228. {
  229. //m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
  230. if (osdMaterials is OSDArray)
  231. {
  232. OSDArray matsArr = osdMaterials as OSDArray;
  233. foreach (OSDMap matMap in matsArr)
  234. {
  235. try
  236. {
  237. if (matMap.ContainsKey("Material"))
  238. {
  239. OSDMap mat = matMap["Material"] as OSDMap;
  240. if (mat.ContainsKey("NormMap"))
  241. {
  242. UUID normalMapId = mat["NormMap"].AsUUID();
  243. if (normalMapId != UUID.Zero)
  244. {
  245. assetUuids[normalMapId] = AssetType.Texture;
  246. //m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
  247. }
  248. }
  249. if (mat.ContainsKey("SpecMap"))
  250. {
  251. UUID specularMapId = mat["SpecMap"].AsUUID();
  252. if (specularMapId != UUID.Zero)
  253. {
  254. assetUuids[specularMapId] = AssetType.Texture;
  255. //m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
  256. }
  257. }
  258. }
  259. }
  260. catch (Exception e)
  261. {
  262. m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message);
  263. }
  264. }
  265. }
  266. }
  267. }
  268. }
  269. /// <summary>
  270. /// Get an asset synchronously, potentially using an asynchronous callback. If the
  271. /// asynchronous callback is used, we will wait for it to complete.
  272. /// </summary>
  273. /// <param name="uuid"></param>
  274. /// <returns></returns>
  275. protected virtual AssetBase GetAsset(UUID uuid)
  276. {
  277. return m_assetService.Get(uuid.ToString());
  278. // XXX: Switching to do this synchronously where the call was async before but we always waited for it
  279. // to complete anyway!
  280. // m_waitingForObjectAsset = true;
  281. // m_assetCache.Get(uuid.ToString(), this, AssetReceived);
  282. //
  283. // // The asset cache callback can either
  284. // //
  285. // // 1. Complete on the same thread (if the asset is already in the cache) or
  286. // // 2. Come in via a different thread (if we need to go fetch it).
  287. // //
  288. // // The code below handles both these alternatives.
  289. // lock (this)
  290. // {
  291. // if (m_waitingForObjectAsset)
  292. // {
  293. // Monitor.Wait(this);
  294. // m_waitingForObjectAsset = false;
  295. // }
  296. // }
  297. //
  298. // return m_requestedObjectAsset;
  299. }
  300. /// <summary>
  301. /// Record the asset uuids embedded within the given script.
  302. /// </summary>
  303. /// <param name="scriptUuid"></param>
  304. /// <param name="assetUuids">Dictionary in which to record the references</param>
  305. private void GetTextEmbeddedAssetUuids(UUID embeddingAssetId, IDictionary<UUID, AssetType> assetUuids)
  306. {
  307. // m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
  308. AssetBase embeddingAsset = GetAsset(embeddingAssetId);
  309. if (null != embeddingAsset)
  310. {
  311. string script = Utils.BytesToString(embeddingAsset.Data);
  312. // m_log.DebugFormat("[ARCHIVER]: Script {0}", script);
  313. MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(script);
  314. // m_log.DebugFormat("[ARCHIVER]: Found {0} matches in text", uuidMatches.Count);
  315. foreach (Match uuidMatch in uuidMatches)
  316. {
  317. UUID uuid = new UUID(uuidMatch.Value);
  318. // m_log.DebugFormat("[ARCHIVER]: Recording {0} in text", uuid);
  319. // Embedded asset references (if not false positives) could be for many types of asset, so we will
  320. // label these as unknown.
  321. assetUuids[uuid] = AssetType.Unknown;
  322. }
  323. }
  324. }
  325. /// <summary>
  326. /// Record the uuids referenced by the given wearable asset
  327. /// </summary>
  328. /// <param name="wearableAssetUuid"></param>
  329. /// <param name="assetUuids">Dictionary in which to record the references</param>
  330. private void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids)
  331. {
  332. AssetBase assetBase = GetAsset(wearableAssetUuid);
  333. if (null != assetBase)
  334. {
  335. //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data));
  336. AssetWearable wearableAsset = new AssetBodypart(wearableAssetUuid, assetBase.Data);
  337. wearableAsset.Decode();
  338. //m_log.DebugFormat(
  339. // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count);
  340. foreach (UUID uuid in wearableAsset.Textures.Values)
  341. {
  342. assetUuids[uuid] = AssetType.Texture;
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// Get all the asset uuids associated with a given object. This includes both those directly associated with
  348. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  349. /// within this object).
  350. /// </summary>
  351. /// <param name="sceneObject"></param>
  352. /// <param name="assetUuids"></param>
  353. private void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids)
  354. {
  355. AssetBase objectAsset = GetAsset(sceneObjectUuid);
  356. if (null != objectAsset)
  357. {
  358. string xml = Utils.BytesToString(objectAsset.Data);
  359. CoalescedSceneObjects coa;
  360. if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa))
  361. {
  362. foreach (SceneObjectGroup sog in coa.Objects)
  363. GatherAssetUuids(sog, assetUuids);
  364. }
  365. else
  366. {
  367. SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml);
  368. if (null != sog)
  369. GatherAssetUuids(sog, assetUuids);
  370. }
  371. }
  372. }
  373. /// <summary>
  374. /// Get the asset uuid associated with a gesture
  375. /// </summary>
  376. /// <param name="gestureUuid"></param>
  377. /// <param name="assetUuids"></param>
  378. private void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids)
  379. {
  380. AssetBase assetBase = GetAsset(gestureUuid);
  381. if (null == assetBase)
  382. return;
  383. MemoryStream ms = new MemoryStream(assetBase.Data);
  384. StreamReader sr = new StreamReader(ms);
  385. sr.ReadLine(); // Unknown (Version?)
  386. sr.ReadLine(); // Unknown
  387. sr.ReadLine(); // Unknown
  388. sr.ReadLine(); // Name
  389. sr.ReadLine(); // Comment ?
  390. int count = Convert.ToInt32(sr.ReadLine()); // Item count
  391. for (int i = 0 ; i < count ; i++)
  392. {
  393. string type = sr.ReadLine();
  394. if (type == null)
  395. break;
  396. string name = sr.ReadLine();
  397. if (name == null)
  398. break;
  399. string id = sr.ReadLine();
  400. if (id == null)
  401. break;
  402. string unknown = sr.ReadLine();
  403. if (unknown == null)
  404. break;
  405. // If it can be parsed as a UUID, it is an asset ID
  406. UUID uuid;
  407. if (UUID.TryParse(id, out uuid))
  408. assetUuids[uuid] = AssetType.Animation;
  409. }
  410. }
  411. }
  412. public class HGUuidGatherer : UuidGatherer
  413. {
  414. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  415. protected string m_assetServerURL;
  416. public HGUuidGatherer(IAssetService assetService, string assetServerURL)
  417. : base(assetService)
  418. {
  419. m_assetServerURL = assetServerURL;
  420. if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("="))
  421. m_assetServerURL = m_assetServerURL + "/";
  422. }
  423. protected override AssetBase GetAsset(UUID uuid)
  424. {
  425. if (string.Empty == m_assetServerURL)
  426. return base.GetAsset(uuid);
  427. else
  428. return FetchAsset(uuid);
  429. }
  430. public AssetBase FetchAsset(UUID assetID)
  431. {
  432. // Test if it's already here
  433. AssetBase asset = m_assetService.Get(assetID.ToString());
  434. if (asset == null)
  435. {
  436. // It's not, so fetch it from abroad
  437. asset = m_assetService.Get(m_assetServerURL + assetID.ToString());
  438. if (asset != null)
  439. m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL);
  440. else
  441. m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL);
  442. }
  443. //else
  444. // m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL);
  445. return asset;
  446. }
  447. }
  448. }