MaterialsModule.cs 25 KB

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