MaterialsModule.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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.Security.Cryptography; // for computing md5 hash
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Servers;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
  43. using Ionic.Zlib;
  44. // You will need to uncomment these lines if you are adding a region module to some other assembly which does not already
  45. // specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans
  46. // the available DLLs
  47. //[assembly: Addin("MaterialsModule", "1.0")]
  48. //[assembly: AddinDependency("OpenSim", "0.8.1")]
  49. namespace OpenSim.Region.OptionalModules.Materials
  50. {
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
  52. public class MaterialsModule : INonSharedRegionModule
  53. {
  54. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  55. public string Name { get { return "MaterialsModule"; } }
  56. public Type ReplaceableInterface { get { return null; } }
  57. private Scene m_scene = null;
  58. private bool m_enabled = false;
  59. public Dictionary<UUID, OSDMap> m_regionMaterials = new Dictionary<UUID, OSDMap>();
  60. public void Initialise(IConfigSource source)
  61. {
  62. IConfig config = source.Configs["Materials"];
  63. if (config == null)
  64. return;
  65. m_enabled = config.GetBoolean("enable_materials", true);
  66. if (!m_enabled)
  67. return;
  68. m_log.DebugFormat("[Materials]: Initialized");
  69. }
  70. public void Close()
  71. {
  72. if (!m_enabled)
  73. return;
  74. }
  75. public void AddRegion(Scene scene)
  76. {
  77. if (!m_enabled)
  78. return;
  79. m_scene = scene;
  80. m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  81. m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
  82. }
  83. private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
  84. {
  85. foreach (var part in obj.Parts)
  86. if (part != null)
  87. GetStoredMaterialsInPart(part);
  88. }
  89. private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
  90. {
  91. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  92. IRequestHandler renderMaterialsPostHandler
  93. = new RestStreamHandler("POST", capsBase + "/",
  94. (request, path, param, httpRequest, httpResponse)
  95. => RenderMaterialsPostCap(request, agentID),
  96. "RenderMaterials", null);
  97. caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler);
  98. // OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET
  99. // and POST handlers, (at least at the time this was originally written), so we first set up a POST
  100. // handler normally and then add a GET handler via MainServer
  101. IRequestHandler renderMaterialsGetHandler
  102. = new RestStreamHandler("GET", capsBase + "/",
  103. (request, path, param, httpRequest, httpResponse)
  104. => RenderMaterialsGetCap(request),
  105. "RenderMaterials", null);
  106. MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler);
  107. // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well
  108. IRequestHandler renderMaterialsPutHandler
  109. = new RestStreamHandler("PUT", capsBase + "/",
  110. (request, path, param, httpRequest, httpResponse)
  111. => RenderMaterialsPostCap(request, agentID),
  112. "RenderMaterials", null);
  113. MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler);
  114. }
  115. public void RemoveRegion(Scene scene)
  116. {
  117. if (!m_enabled)
  118. return;
  119. m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  120. m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
  121. }
  122. public void RegionLoaded(Scene scene)
  123. {
  124. }
  125. /// <summary>
  126. /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
  127. /// </summary>
  128. /// <param name="part"></param>
  129. private void GetLegacyStoredMaterialsInPart(SceneObjectPart part)
  130. {
  131. if (part.DynAttrs == null)
  132. return;
  133. OSD OSMaterials = null;
  134. OSDArray matsArr = null;
  135. lock (part.DynAttrs)
  136. {
  137. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  138. {
  139. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  140. if (materialsStore == null)
  141. return;
  142. materialsStore.TryGetValue("Materials", out OSMaterials);
  143. }
  144. if (OSMaterials != null && OSMaterials is OSDArray)
  145. matsArr = OSMaterials as OSDArray;
  146. else
  147. return;
  148. }
  149. if (matsArr == null)
  150. return;
  151. foreach (OSD elemOsd in matsArr)
  152. {
  153. if (elemOsd != null && elemOsd is OSDMap)
  154. {
  155. OSDMap matMap = elemOsd as OSDMap;
  156. if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
  157. {
  158. try
  159. {
  160. lock (m_regionMaterials)
  161. m_regionMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"];
  162. }
  163. catch (Exception e)
  164. {
  165. m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
  166. }
  167. }
  168. }
  169. }
  170. }
  171. /// <summary>
  172. /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
  173. /// </summary>
  174. private void GetStoredMaterialsInPart(SceneObjectPart part)
  175. {
  176. if (part.Shape == null)
  177. return;
  178. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  179. if (te == null)
  180. return;
  181. GetLegacyStoredMaterialsInPart(part);
  182. if (te.DefaultTexture != null)
  183. GetStoredMaterialInFace(part, te.DefaultTexture);
  184. else
  185. m_log.WarnFormat(
  186. "[Materials]: Default texture for part {0} (part of object {1)) in {2} unexpectedly null. Ignoring.",
  187. part.Name, part.ParentGroup.Name, m_scene.Name);
  188. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  189. {
  190. if (face != null)
  191. GetStoredMaterialInFace(part, face);
  192. }
  193. }
  194. /// <summary>
  195. /// Find the materials used in one Face, and add them to 'm_regionMaterials'.
  196. /// </summary>
  197. private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
  198. {
  199. UUID id = face.MaterialID;
  200. if (id == UUID.Zero)
  201. return;
  202. lock (m_regionMaterials)
  203. {
  204. if (m_regionMaterials.ContainsKey(id))
  205. return;
  206. byte[] data = m_scene.AssetService.GetData(id.ToString());
  207. if (data == null)
  208. {
  209. m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
  210. return;
  211. }
  212. OSDMap mat;
  213. try
  214. {
  215. mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  216. }
  217. catch (Exception e)
  218. {
  219. m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
  220. return;
  221. }
  222. m_regionMaterials[id] = mat;
  223. }
  224. }
  225. public string RenderMaterialsPostCap(string request, UUID agentID)
  226. {
  227. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  228. OSDMap resp = new OSDMap();
  229. OSDMap materialsFromViewer = null;
  230. OSDArray respArr = new OSDArray();
  231. if (req.ContainsKey("Zipped"))
  232. {
  233. OSD osd = null;
  234. byte[] inBytes = req["Zipped"].AsBinary();
  235. try
  236. {
  237. osd = ZDecompressBytesToOsd(inBytes);
  238. if (osd != null)
  239. {
  240. if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
  241. {
  242. foreach (OSD elem in (OSDArray)osd)
  243. {
  244. try
  245. {
  246. UUID id = new UUID(elem.AsBinary(), 0);
  247. lock (m_regionMaterials)
  248. {
  249. if (m_regionMaterials.ContainsKey(id))
  250. {
  251. OSDMap matMap = new OSDMap();
  252. matMap["ID"] = OSD.FromBinary(id.GetBytes());
  253. matMap["Material"] = m_regionMaterials[id];
  254. respArr.Add(matMap);
  255. }
  256. else
  257. {
  258. m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
  259. // Theoretically we could try to load the material from the assets service,
  260. // but that shouldn't be necessary because the viewer should only request
  261. // materials that exist in a prim on the region, and all of these materials
  262. // are already stored in m_regionMaterials.
  263. }
  264. }
  265. }
  266. catch (Exception e)
  267. {
  268. m_log.Error("Error getting materials in response to viewer request", e);
  269. continue;
  270. }
  271. }
  272. }
  273. else if (osd is OSDMap) // request to assign a material
  274. {
  275. materialsFromViewer = osd as OSDMap;
  276. if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
  277. {
  278. OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
  279. if (matsOsd is OSDArray)
  280. {
  281. OSDArray matsArr = matsOsd as OSDArray;
  282. try
  283. {
  284. foreach (OSDMap matsMap in matsArr)
  285. {
  286. uint primLocalID = 0;
  287. try {
  288. primLocalID = matsMap["ID"].AsUInteger();
  289. }
  290. catch (Exception e) {
  291. m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
  292. continue;
  293. }
  294. OSDMap mat = null;
  295. try
  296. {
  297. mat = matsMap["Material"] as OSDMap;
  298. }
  299. catch (Exception e)
  300. {
  301. m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
  302. continue;
  303. }
  304. SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
  305. if (sop == null)
  306. {
  307. m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
  308. continue;
  309. }
  310. if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
  311. {
  312. m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
  313. continue;
  314. }
  315. Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
  316. if (te == null)
  317. {
  318. m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
  319. continue;
  320. }
  321. UUID id;
  322. if (mat == null)
  323. {
  324. // This happens then the user removes a material from a prim
  325. id = UUID.Zero;
  326. }
  327. else
  328. {
  329. id = StoreMaterialAsAsset(agentID, mat, sop);
  330. }
  331. int face = -1;
  332. if (matsMap.ContainsKey("Face"))
  333. {
  334. face = matsMap["Face"].AsInteger();
  335. Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
  336. faceEntry.MaterialID = id;
  337. }
  338. else
  339. {
  340. if (te.DefaultTexture == null)
  341. m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
  342. else
  343. te.DefaultTexture.MaterialID = id;
  344. }
  345. //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
  346. // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
  347. sop.Shape.TextureEntry = te.GetBytes();
  348. if (sop.ParentGroup != null)
  349. {
  350. sop.TriggerScriptChangedEvent(Changed.TEXTURE);
  351. sop.UpdateFlag = UpdateRequired.FULL;
  352. sop.ParentGroup.HasGroupChanged = true;
  353. sop.ScheduleFullUpdate();
  354. }
  355. }
  356. }
  357. catch (Exception e)
  358. {
  359. m_log.Warn("[Materials]: exception processing received material ", e);
  360. }
  361. }
  362. }
  363. }
  364. }
  365. }
  366. catch (Exception e)
  367. {
  368. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  369. //return "";
  370. }
  371. }
  372. resp["Zipped"] = ZCompressOSD(respArr, false);
  373. string response = OSDParser.SerializeLLSDXmlString(resp);
  374. //m_log.Debug("[Materials]: cap request: " + request);
  375. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  376. //m_log.Debug("[Materials]: cap response: " + response);
  377. return response;
  378. }
  379. private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop)
  380. {
  381. UUID id;
  382. // Material UUID = hash of the material's data.
  383. // This makes materials deduplicate across the entire grid (but isn't otherwise required).
  384. byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
  385. using (var md5 = MD5.Create())
  386. id = new UUID(md5.ComputeHash(data), 0);
  387. lock (m_regionMaterials)
  388. {
  389. if (!m_regionMaterials.ContainsKey(id))
  390. {
  391. m_regionMaterials[id] = mat;
  392. // This asset might exist already, but it's ok to try to store it again
  393. string name = "Material " + ChooseMaterialName(mat, sop);
  394. name = name.Substring(0, Math.Min(64, name.Length)).Trim();
  395. AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString());
  396. asset.Data = data;
  397. m_scene.AssetService.Store(asset);
  398. }
  399. }
  400. return id;
  401. }
  402. /// <summary>
  403. /// Use heuristics to choose a good name for the material.
  404. /// </summary>
  405. private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop)
  406. {
  407. UUID normMap = mat["NormMap"].AsUUID();
  408. if (normMap != UUID.Zero)
  409. {
  410. AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString());
  411. if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
  412. return asset.Name;
  413. }
  414. UUID specMap = mat["SpecMap"].AsUUID();
  415. if (specMap != UUID.Zero)
  416. {
  417. AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString());
  418. if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
  419. return asset.Name;
  420. }
  421. if (sop.Name != "Primitive")
  422. return sop.Name;
  423. if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive"))
  424. return sop.ParentGroup.Name;
  425. return "";
  426. }
  427. public string RenderMaterialsGetCap(string request)
  428. {
  429. OSDMap resp = new OSDMap();
  430. int matsCount = 0;
  431. OSDArray allOsd = new OSDArray();
  432. lock (m_regionMaterials)
  433. {
  434. foreach (KeyValuePair<UUID, OSDMap> kvp in m_regionMaterials)
  435. {
  436. OSDMap matMap = new OSDMap();
  437. matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes());
  438. matMap["Material"] = kvp.Value;
  439. allOsd.Add(matMap);
  440. matsCount++;
  441. }
  442. }
  443. resp["Zipped"] = ZCompressOSD(allOsd, false);
  444. return OSDParser.SerializeLLSDXmlString(resp);
  445. }
  446. private static string ZippedOsdBytesToString(byte[] bytes)
  447. {
  448. try
  449. {
  450. return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
  451. }
  452. catch (Exception e)
  453. {
  454. return "ZippedOsdBytesToString caught an exception: " + e.ToString();
  455. }
  456. }
  457. /// <summary>
  458. /// computes a UUID by hashing a OSD object
  459. /// </summary>
  460. /// <param name="osd"></param>
  461. /// <returns></returns>
  462. private static UUID HashOsd(OSD osd)
  463. {
  464. byte[] data = OSDParser.SerializeLLSDBinary(osd, false);
  465. using (var md5 = MD5.Create())
  466. return new UUID(md5.ComputeHash(data), 0);
  467. }
  468. public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
  469. {
  470. OSD osd = null;
  471. byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
  472. using (MemoryStream msSinkCompressed = new MemoryStream())
  473. {
  474. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
  475. Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
  476. {
  477. zOut.Write(data, 0, data.Length);
  478. }
  479. msSinkCompressed.Seek(0L, SeekOrigin.Begin);
  480. osd = OSD.FromBinary(msSinkCompressed.ToArray());
  481. }
  482. return osd;
  483. }
  484. public static OSD ZDecompressBytesToOsd(byte[] input)
  485. {
  486. OSD osd = null;
  487. using (MemoryStream msSinkUnCompressed = new MemoryStream())
  488. {
  489. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
  490. {
  491. zOut.Write(input, 0, input.Length);
  492. }
  493. msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
  494. osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
  495. }
  496. return osd;
  497. }
  498. }
  499. }