1
0

UuidGatherer.cs 24 KB

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