UuidGatherer.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. try
  168. {
  169. Primitive.ParticleSystem ps = new Primitive.ParticleSystem(part.ParticleSystem, 0);
  170. if (ps.Texture != UUID.Zero)
  171. assetUuids[ps.Texture] = AssetType.Texture;
  172. }
  173. catch (Exception e)
  174. {
  175. m_log.WarnFormat(
  176. "[UUID GATHERER]: Could not check particle system for part {0} {1} in object {2} {3} since it is corrupt. Continuing.",
  177. part.Name, part.UUID, sceneObject.Name, sceneObject.UUID);
  178. }
  179. }
  180. TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
  181. // Now analyze this prim's inventory items to preserve all the uuids that they reference
  182. foreach (TaskInventoryItem tii in taskDictionary.Values)
  183. {
  184. // m_log.DebugFormat(
  185. // "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
  186. // tii.Name, tii.Type, part.Name, part.UUID);
  187. if (!assetUuids.ContainsKey(tii.AssetID))
  188. GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids);
  189. }
  190. // FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
  191. // to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and
  192. // inventory transfer. There needs to be a way for a module to register a method without assuming a
  193. // Scene.EventManager is present.
  194. // part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids);
  195. GatherMaterialsUuids(part, assetUuids);
  196. }
  197. catch (Exception e)
  198. {
  199. m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
  200. m_log.DebugFormat(
  201. "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
  202. part.Shape.TextureEntry.Length);
  203. }
  204. }
  205. }
  206. // /// <summary>
  207. // /// The callback made when we request the asset for an object from the asset service.
  208. // /// </summary>
  209. // private void AssetReceived(string id, Object sender, AssetBase asset)
  210. // {
  211. // lock (this)
  212. // {
  213. // m_requestedObjectAsset = asset;
  214. // m_waitingForObjectAsset = false;
  215. // Monitor.Pulse(this);
  216. // }
  217. // }
  218. /// <summary>
  219. /// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
  220. /// </summary>
  221. /// <param name="part"></param>
  222. /// <param name="assetUuids"></param>
  223. public void GatherMaterialsUuids(SceneObjectPart part, IDictionary<UUID, AssetType> assetUuids)
  224. {
  225. // scan thru the dynAttrs map of this part for any textures used as materials
  226. OSD osdMaterials = null;
  227. lock (part.DynAttrs)
  228. {
  229. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  230. {
  231. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  232. if (materialsStore == null)
  233. return;
  234. materialsStore.TryGetValue("Materials", out osdMaterials);
  235. }
  236. if (osdMaterials != null)
  237. {
  238. //m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
  239. if (osdMaterials is OSDArray)
  240. {
  241. OSDArray matsArr = osdMaterials as OSDArray;
  242. foreach (OSDMap matMap in matsArr)
  243. {
  244. try
  245. {
  246. if (matMap.ContainsKey("Material"))
  247. {
  248. OSDMap mat = matMap["Material"] as OSDMap;
  249. if (mat.ContainsKey("NormMap"))
  250. {
  251. UUID normalMapId = mat["NormMap"].AsUUID();
  252. if (normalMapId != UUID.Zero)
  253. {
  254. assetUuids[normalMapId] = AssetType.Texture;
  255. //m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
  256. }
  257. }
  258. if (mat.ContainsKey("SpecMap"))
  259. {
  260. UUID specularMapId = mat["SpecMap"].AsUUID();
  261. if (specularMapId != UUID.Zero)
  262. {
  263. assetUuids[specularMapId] = AssetType.Texture;
  264. //m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
  265. }
  266. }
  267. }
  268. }
  269. catch (Exception e)
  270. {
  271. m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message);
  272. }
  273. }
  274. }
  275. }
  276. }
  277. }
  278. /// <summary>
  279. /// Get an asset synchronously, potentially using an asynchronous callback. If the
  280. /// asynchronous callback is used, we will wait for it to complete.
  281. /// </summary>
  282. /// <param name="uuid"></param>
  283. /// <returns></returns>
  284. protected virtual AssetBase GetAsset(UUID uuid)
  285. {
  286. return m_assetService.Get(uuid.ToString());
  287. // XXX: Switching to do this synchronously where the call was async before but we always waited for it
  288. // to complete anyway!
  289. // m_waitingForObjectAsset = true;
  290. // m_assetCache.Get(uuid.ToString(), this, AssetReceived);
  291. //
  292. // // The asset cache callback can either
  293. // //
  294. // // 1. Complete on the same thread (if the asset is already in the cache) or
  295. // // 2. Come in via a different thread (if we need to go fetch it).
  296. // //
  297. // // The code below handles both these alternatives.
  298. // lock (this)
  299. // {
  300. // if (m_waitingForObjectAsset)
  301. // {
  302. // Monitor.Wait(this);
  303. // m_waitingForObjectAsset = false;
  304. // }
  305. // }
  306. //
  307. // return m_requestedObjectAsset;
  308. }
  309. /// <summary>
  310. /// Record the asset uuids embedded within the given script.
  311. /// </summary>
  312. /// <param name="scriptUuid"></param>
  313. /// <param name="assetUuids">Dictionary in which to record the references</param>
  314. private void GetTextEmbeddedAssetUuids(UUID embeddingAssetId, IDictionary<UUID, AssetType> assetUuids)
  315. {
  316. // m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
  317. AssetBase embeddingAsset = GetAsset(embeddingAssetId);
  318. if (null != embeddingAsset)
  319. {
  320. string script = Utils.BytesToString(embeddingAsset.Data);
  321. // m_log.DebugFormat("[ARCHIVER]: Script {0}", script);
  322. MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(script);
  323. // m_log.DebugFormat("[ARCHIVER]: Found {0} matches in text", uuidMatches.Count);
  324. foreach (Match uuidMatch in uuidMatches)
  325. {
  326. UUID uuid = new UUID(uuidMatch.Value);
  327. // m_log.DebugFormat("[ARCHIVER]: Recording {0} in text", uuid);
  328. // Embedded asset references (if not false positives) could be for many types of asset, so we will
  329. // label these as unknown.
  330. assetUuids[uuid] = AssetType.Unknown;
  331. }
  332. }
  333. }
  334. /// <summary>
  335. /// Record the uuids referenced by the given wearable asset
  336. /// </summary>
  337. /// <param name="wearableAssetUuid"></param>
  338. /// <param name="assetUuids">Dictionary in which to record the references</param>
  339. private void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids)
  340. {
  341. AssetBase assetBase = GetAsset(wearableAssetUuid);
  342. if (null != assetBase)
  343. {
  344. //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data));
  345. AssetWearable wearableAsset = new AssetBodypart(wearableAssetUuid, assetBase.Data);
  346. wearableAsset.Decode();
  347. //m_log.DebugFormat(
  348. // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count);
  349. foreach (UUID uuid in wearableAsset.Textures.Values)
  350. {
  351. assetUuids[uuid] = AssetType.Texture;
  352. }
  353. }
  354. }
  355. /// <summary>
  356. /// Get all the asset uuids associated with a given object. This includes both those directly associated with
  357. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  358. /// within this object).
  359. /// </summary>
  360. /// <param name="sceneObject"></param>
  361. /// <param name="assetUuids"></param>
  362. private void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids)
  363. {
  364. AssetBase objectAsset = GetAsset(sceneObjectUuid);
  365. if (null != objectAsset)
  366. {
  367. string xml = Utils.BytesToString(objectAsset.Data);
  368. CoalescedSceneObjects coa;
  369. if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa))
  370. {
  371. foreach (SceneObjectGroup sog in coa.Objects)
  372. GatherAssetUuids(sog, assetUuids);
  373. }
  374. else
  375. {
  376. SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml);
  377. if (null != sog)
  378. GatherAssetUuids(sog, assetUuids);
  379. }
  380. }
  381. }
  382. /// <summary>
  383. /// Get the asset uuid associated with a gesture
  384. /// </summary>
  385. /// <param name="gestureUuid"></param>
  386. /// <param name="assetUuids"></param>
  387. private void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids)
  388. {
  389. AssetBase assetBase = GetAsset(gestureUuid);
  390. if (null == assetBase)
  391. return;
  392. MemoryStream ms = new MemoryStream(assetBase.Data);
  393. StreamReader sr = new StreamReader(ms);
  394. sr.ReadLine(); // Unknown (Version?)
  395. sr.ReadLine(); // Unknown
  396. sr.ReadLine(); // Unknown
  397. sr.ReadLine(); // Name
  398. sr.ReadLine(); // Comment ?
  399. int count = Convert.ToInt32(sr.ReadLine()); // Item count
  400. for (int i = 0 ; i < count ; i++)
  401. {
  402. string type = sr.ReadLine();
  403. if (type == null)
  404. break;
  405. string name = sr.ReadLine();
  406. if (name == null)
  407. break;
  408. string id = sr.ReadLine();
  409. if (id == null)
  410. break;
  411. string unknown = sr.ReadLine();
  412. if (unknown == null)
  413. break;
  414. // If it can be parsed as a UUID, it is an asset ID
  415. UUID uuid;
  416. if (UUID.TryParse(id, out uuid))
  417. assetUuids[uuid] = AssetType.Animation;
  418. }
  419. }
  420. }
  421. public class HGUuidGatherer : UuidGatherer
  422. {
  423. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  424. protected string m_assetServerURL;
  425. public HGUuidGatherer(IAssetService assetService, string assetServerURL)
  426. : base(assetService)
  427. {
  428. m_assetServerURL = assetServerURL;
  429. if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("="))
  430. m_assetServerURL = m_assetServerURL + "/";
  431. }
  432. protected override AssetBase GetAsset(UUID uuid)
  433. {
  434. if (string.Empty == m_assetServerURL)
  435. return base.GetAsset(uuid);
  436. else
  437. return FetchAsset(uuid);
  438. }
  439. public AssetBase FetchAsset(UUID assetID)
  440. {
  441. // Test if it's already here
  442. AssetBase asset = m_assetService.Get(assetID.ToString());
  443. if (asset == null)
  444. {
  445. // It's not, so fetch it from abroad
  446. asset = m_assetService.Get(m_assetServerURL + assetID.ToString());
  447. if (asset != null)
  448. m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL);
  449. else
  450. m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL);
  451. }
  452. //else
  453. // m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL);
  454. return asset;
  455. }
  456. }
  457. }