MaterialsModule.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. IAssetCache m_cache;
  58. private Scene m_scene = null;
  59. private bool m_enabled = false;
  60. private int m_maxMaterialsPerTransaction = 50;
  61. public Dictionary<UUID, OSDMap> m_Materials = new Dictionary<UUID, OSDMap>();
  62. public Dictionary<UUID, int> m_MaterialsRefCount = new Dictionary<UUID, int>();
  63. private Dictionary<ulong, AssetBase> m_changes = new Dictionary<ulong, AssetBase>();
  64. private Dictionary<ulong, double> m_changesTime = new Dictionary<ulong, double>();
  65. public void Initialise(IConfigSource source)
  66. {
  67. m_enabled = true; // default is enabled
  68. IConfig config = source.Configs["Materials"];
  69. if (config != null)
  70. {
  71. m_enabled = config.GetBoolean("enable_materials", m_enabled);
  72. m_maxMaterialsPerTransaction = config.GetInt("MaxMaterialsPerTransaction", m_maxMaterialsPerTransaction);
  73. }
  74. if (m_enabled)
  75. m_log.DebugFormat("[Materials]: Initialized");
  76. }
  77. public void Close()
  78. {
  79. if (!m_enabled)
  80. return;
  81. }
  82. public void AddRegion(Scene scene)
  83. {
  84. if (!m_enabled)
  85. return;
  86. m_scene = scene;
  87. m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  88. m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
  89. m_scene.EventManager.OnBackup += EventManager_OnBackup;
  90. }
  91. private void EventManager_OnBackup(ISimulationDataService datastore, bool forcedBackup)
  92. {
  93. List<AssetBase> toStore;
  94. List<ulong> hashlist;
  95. lock (m_Materials)
  96. {
  97. if(m_changes.Count == 0)
  98. return;
  99. if(forcedBackup)
  100. {
  101. toStore = new List<AssetBase>(m_changes.Values);
  102. m_changes.Clear();
  103. m_changesTime.Clear();
  104. }
  105. else
  106. {
  107. toStore = new List<AssetBase>();
  108. hashlist = new List<ulong>();
  109. double storetime = Util.GetTimeStampMS() - 60000;
  110. foreach(KeyValuePair<ulong,double> kvp in m_changesTime)
  111. {
  112. if(kvp.Value < storetime)
  113. {
  114. toStore.Add(m_changes[kvp.Key]);
  115. hashlist.Add(kvp.Key);
  116. }
  117. }
  118. foreach(ulong u in hashlist)
  119. {
  120. m_changesTime.Remove(u);
  121. m_changes.Remove(u);
  122. }
  123. }
  124. if(toStore.Count > 0)
  125. Util.FireAndForget(delegate
  126. {
  127. foreach(AssetBase a in toStore)
  128. {
  129. a.Local = false;
  130. m_scene.AssetService.Store(a);
  131. }
  132. });
  133. }
  134. }
  135. private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
  136. {
  137. foreach (var part in obj.Parts)
  138. if (part != null)
  139. GetStoredMaterialsInPart(part);
  140. }
  141. private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
  142. {
  143. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  144. IRequestHandler renderMaterialsPostHandler
  145. = new RestStreamHandler("POST", capsBase + "/",
  146. (request, path, param, httpRequest, httpResponse)
  147. => RenderMaterialsPostCap(request, agentID),
  148. "RenderMaterials", null);
  149. caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler);
  150. // OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET
  151. // and POST handlers, (at least at the time this was originally written), so we first set up a POST
  152. // handler normally and then add a GET handler via MainServer
  153. IRequestHandler renderMaterialsGetHandler
  154. = new RestStreamHandler("GET", capsBase + "/",
  155. (request, path, param, httpRequest, httpResponse)
  156. => RenderMaterialsGetCap(request),
  157. "RenderMaterials", null);
  158. MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler);
  159. // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well
  160. IRequestHandler renderMaterialsPutHandler
  161. = new RestStreamHandler("PUT", capsBase + "/",
  162. (request, path, param, httpRequest, httpResponse)
  163. => RenderMaterialsPutCap(request, agentID),
  164. "RenderMaterials", null);
  165. MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler);
  166. }
  167. public void RemoveRegion(Scene scene)
  168. {
  169. if (!m_enabled)
  170. return;
  171. m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  172. m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
  173. m_scene.EventManager.OnBackup -= EventManager_OnBackup;
  174. }
  175. public void RegionLoaded(Scene scene)
  176. {
  177. if (!m_enabled) return;
  178. m_cache = scene.RequestModuleInterface<IAssetCache>();
  179. ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>();
  180. if (featuresModule != null)
  181. featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest;
  182. }
  183. private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features)
  184. {
  185. features["MaxMaterialsPerTransaction"] = m_maxMaterialsPerTransaction;
  186. }
  187. /// <summary>
  188. /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
  189. /// </summary>
  190. /// <param name="part"></param>
  191. private void GetLegacyStoredMaterialsInPart(SceneObjectPart part)
  192. {
  193. if (part.DynAttrs == null)
  194. return;
  195. OSD OSMaterials = null;
  196. OSDArray matsArr = null;
  197. lock (part.DynAttrs)
  198. {
  199. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  200. {
  201. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  202. if (materialsStore == null)
  203. return;
  204. materialsStore.TryGetValue("Materials", out OSMaterials);
  205. }
  206. if (OSMaterials != null && OSMaterials is OSDArray)
  207. matsArr = OSMaterials as OSDArray;
  208. else
  209. return;
  210. }
  211. if (matsArr == null)
  212. return;
  213. foreach (OSD elemOsd in matsArr)
  214. {
  215. if (elemOsd != null && elemOsd is OSDMap)
  216. {
  217. OSDMap matMap = elemOsd as OSDMap;
  218. if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
  219. {
  220. try
  221. {
  222. lock (m_Materials)
  223. {
  224. UUID id = matMap["ID"].AsUUID();
  225. if(m_Materials.ContainsKey(id))
  226. m_MaterialsRefCount[id]++;
  227. else
  228. {
  229. m_Materials[id] = (OSDMap)matMap["Material"];
  230. m_MaterialsRefCount[id] = 1;
  231. }
  232. }
  233. }
  234. catch (Exception e)
  235. {
  236. m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
  237. }
  238. }
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
  244. /// </summary>
  245. private void GetStoredMaterialsInPart(SceneObjectPart part)
  246. {
  247. if (part.Shape == null)
  248. return;
  249. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  250. if (te == null)
  251. return;
  252. GetLegacyStoredMaterialsInPart(part);
  253. if (te.DefaultTexture != null)
  254. GetStoredMaterialInFace(part, te.DefaultTexture);
  255. else
  256. m_log.WarnFormat(
  257. "[Materials]: Default texture for part {0} (part of object {1}) in {2} unexpectedly null. Ignoring.",
  258. part.Name, part.ParentGroup.Name, m_scene.Name);
  259. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  260. {
  261. if (face != null)
  262. GetStoredMaterialInFace(part, face);
  263. }
  264. }
  265. /// <summary>
  266. /// Find the materials used in one Face, and add them to 'm_regionMaterials'.
  267. /// </summary>
  268. private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
  269. {
  270. UUID id = face.MaterialID;
  271. if (id == UUID.Zero)
  272. return;
  273. lock (m_Materials)
  274. {
  275. if (m_Materials.ContainsKey(id))
  276. {
  277. m_MaterialsRefCount[id]++;
  278. return;
  279. }
  280. AssetBase matAsset = m_scene.AssetService.Get(id.ToString());
  281. if (matAsset == null || matAsset.Data == null || matAsset.Data.Length == 0 )
  282. {
  283. //m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
  284. return;
  285. }
  286. byte[] data = matAsset.Data;
  287. OSDMap mat;
  288. try
  289. {
  290. mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  291. }
  292. catch (Exception e)
  293. {
  294. m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
  295. return;
  296. }
  297. m_Materials[id] = mat;
  298. m_MaterialsRefCount[id] = 1;
  299. }
  300. }
  301. public string RenderMaterialsPostCap(string request, UUID agentID)
  302. {
  303. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  304. OSDMap resp = new OSDMap();
  305. OSDArray respArr = new OSDArray();
  306. if (req.ContainsKey("Zipped"))
  307. {
  308. OSD osd = null;
  309. byte[] inBytes = req["Zipped"].AsBinary();
  310. try
  311. {
  312. osd = ZDecompressBytesToOsd(inBytes);
  313. if (osd != null && osd is OSDArray)
  314. {
  315. foreach (OSD elem in (OSDArray)osd)
  316. {
  317. try
  318. {
  319. UUID id = new UUID(elem.AsBinary(), 0);
  320. lock (m_Materials)
  321. {
  322. if (m_Materials.ContainsKey(id))
  323. {
  324. OSDMap matMap = new OSDMap();
  325. matMap["ID"] = OSD.FromBinary(id.GetBytes());
  326. matMap["Material"] = m_Materials[id];
  327. respArr.Add(matMap);
  328. }
  329. else
  330. {
  331. m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
  332. // Theoretically we could try to load the material from the assets service,
  333. // but that shouldn't be necessary because the viewer should only request
  334. // materials that exist in a prim on the region, and all of these materials
  335. // are already stored in m_regionMaterials.
  336. }
  337. }
  338. }
  339. catch (Exception e)
  340. {
  341. m_log.Error("Error getting materials in response to viewer request", e);
  342. continue;
  343. }
  344. }
  345. }
  346. }
  347. catch (Exception e)
  348. {
  349. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  350. //return "";
  351. }
  352. }
  353. resp["Zipped"] = ZCompressOSD(respArr, false);
  354. string response = OSDParser.SerializeLLSDXmlString(resp);
  355. //m_log.Debug("[Materials]: cap request: " + request);
  356. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  357. //m_log.Debug("[Materials]: cap response: " + response);
  358. return response;
  359. }
  360. public string RenderMaterialsPutCap(string request, UUID agentID)
  361. {
  362. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  363. OSDMap resp = new OSDMap();
  364. OSDMap materialsFromViewer = null;
  365. OSDArray respArr = new OSDArray();
  366. HashSet<SceneObjectPart> parts = new HashSet<SceneObjectPart>();
  367. if (req.ContainsKey("Zipped"))
  368. {
  369. OSD osd = null;
  370. byte[] inBytes = req["Zipped"].AsBinary();
  371. try
  372. {
  373. osd = ZDecompressBytesToOsd(inBytes);
  374. if (osd != null && osd is OSDMap)
  375. {
  376. materialsFromViewer = osd as OSDMap;
  377. if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
  378. {
  379. OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
  380. if (matsOsd is OSDArray)
  381. {
  382. OSDArray matsArr = matsOsd as OSDArray;
  383. try
  384. {
  385. foreach (OSDMap matsMap in matsArr)
  386. {
  387. uint primLocalID = 0;
  388. try {
  389. primLocalID = matsMap["ID"].AsUInteger();
  390. }
  391. catch (Exception e) {
  392. m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
  393. continue;
  394. }
  395. SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
  396. if (sop == null)
  397. {
  398. m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
  399. continue;
  400. }
  401. if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
  402. {
  403. m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
  404. continue;
  405. }
  406. OSDMap mat = null;
  407. try
  408. {
  409. mat = matsMap["Material"] as OSDMap;
  410. }
  411. catch (Exception e)
  412. {
  413. m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
  414. continue;
  415. }
  416. Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
  417. if (te == null)
  418. {
  419. m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
  420. continue;
  421. }
  422. UUID id;
  423. if (mat == null)
  424. {
  425. // This happens then the user removes a material from a prim
  426. id = UUID.Zero;
  427. }
  428. else
  429. {
  430. id = getNewID(mat);
  431. }
  432. int face = -1;
  433. UUID oldid = UUID.Zero;
  434. if (matsMap.ContainsKey("Face"))
  435. {
  436. face = matsMap["Face"].AsInteger();
  437. Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
  438. oldid = faceEntry.MaterialID;
  439. faceEntry.MaterialID = id;
  440. }
  441. else
  442. {
  443. if (te.DefaultTexture == null)
  444. m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
  445. else
  446. {
  447. oldid = te.DefaultTexture.MaterialID;
  448. te.DefaultTexture.MaterialID = id;
  449. }
  450. }
  451. //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
  452. // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
  453. sop.Shape.TextureEntry = te.GetBytes();
  454. lock(m_Materials)
  455. {
  456. if(oldid != UUID.Zero && m_MaterialsRefCount.ContainsKey(oldid))
  457. {
  458. m_MaterialsRefCount[oldid]--;
  459. if(m_MaterialsRefCount[oldid] <= 0)
  460. {
  461. m_Materials.Remove(oldid);
  462. m_MaterialsRefCount.Remove(oldid);
  463. m_cache.Expire(oldid.ToString());
  464. }
  465. }
  466. if(id != UUID.Zero)
  467. {
  468. AssetBase asset = CacheMaterialAsAsset(id, agentID, mat, sop);
  469. if(asset != null)
  470. {
  471. ulong materialHash = (ulong)primLocalID << 32;
  472. if(face < 0)
  473. materialHash += 0xffffffff;
  474. else
  475. materialHash +=(ulong)face;
  476. m_changes[materialHash] = asset;
  477. m_changesTime[materialHash] = Util.GetTimeStampMS();
  478. }
  479. }
  480. }
  481. if(!parts.Contains(sop))
  482. parts.Add(sop);
  483. }
  484. foreach(SceneObjectPart sop in parts)
  485. {
  486. if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted)
  487. {
  488. sop.TriggerScriptChangedEvent(Changed.TEXTURE);
  489. sop.ScheduleFullUpdate();
  490. sop.ParentGroup.HasGroupChanged = true;
  491. }
  492. }
  493. }
  494. catch (Exception e)
  495. {
  496. m_log.Warn("[Materials]: exception processing received material ", e);
  497. }
  498. }
  499. }
  500. }
  501. }
  502. catch (Exception e)
  503. {
  504. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  505. //return "";
  506. }
  507. }
  508. resp["Zipped"] = ZCompressOSD(respArr, false);
  509. string response = OSDParser.SerializeLLSDXmlString(resp);
  510. //m_log.Debug("[Materials]: cap request: " + request);
  511. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  512. //m_log.Debug("[Materials]: cap response: " + response);
  513. return response;
  514. }
  515. private UUID getNewID(OSDMap mat)
  516. {
  517. // ugly and done twice but keep compatibility for now
  518. Byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
  519. using (var md5 = MD5.Create())
  520. return new UUID(md5.ComputeHash(data), 0);
  521. }
  522. private AssetBase CacheMaterialAsAsset(UUID id, UUID agentID, OSDMap mat, SceneObjectPart sop)
  523. {
  524. AssetBase asset = null;
  525. lock (m_Materials)
  526. {
  527. if (!m_Materials.ContainsKey(id))
  528. {
  529. m_Materials[id] = mat;
  530. m_MaterialsRefCount[id] = 1;
  531. byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
  532. // This asset might exist already, but it's ok to try to store it again
  533. string name = "Material " + ChooseMaterialName(mat, sop);
  534. name = name.Substring(0, Math.Min(64, name.Length)).Trim();
  535. asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString());
  536. asset.Data = data;
  537. asset.Local = true;
  538. m_cache.Cache(asset);
  539. }
  540. else
  541. m_MaterialsRefCount[id]++;
  542. }
  543. return asset;
  544. }
  545. private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop)
  546. {
  547. UUID id;
  548. // Material UUID = hash of the material's data.
  549. // This makes materials deduplicate across the entire grid (but isn't otherwise required).
  550. byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
  551. using (var md5 = MD5.Create())
  552. id = new UUID(md5.ComputeHash(data), 0);
  553. lock (m_Materials)
  554. {
  555. if (!m_Materials.ContainsKey(id))
  556. {
  557. m_Materials[id] = mat;
  558. m_MaterialsRefCount[id] = 1;
  559. // This asset might exist already, but it's ok to try to store it again
  560. string name = "Material " + ChooseMaterialName(mat, sop);
  561. name = name.Substring(0, Math.Min(64, name.Length)).Trim();
  562. AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString());
  563. asset.Data = data;
  564. m_scene.AssetService.Store(asset);
  565. }
  566. else
  567. m_MaterialsRefCount[id]++;
  568. }
  569. return id;
  570. }
  571. /// <summary>
  572. /// Use heuristics to choose a good name for the material.
  573. /// </summary>
  574. private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop)
  575. {
  576. UUID normMap = mat["NormMap"].AsUUID();
  577. if (normMap != UUID.Zero)
  578. {
  579. AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString());
  580. if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
  581. return asset.Name;
  582. }
  583. UUID specMap = mat["SpecMap"].AsUUID();
  584. if (specMap != UUID.Zero)
  585. {
  586. AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString());
  587. if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
  588. return asset.Name;
  589. }
  590. if (sop.Name != "Primitive")
  591. return sop.Name;
  592. if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive"))
  593. return sop.ParentGroup.Name;
  594. return "";
  595. }
  596. public string RenderMaterialsGetCap(string request)
  597. {
  598. OSDMap resp = new OSDMap();
  599. int matsCount = 0;
  600. OSDArray allOsd = new OSDArray();
  601. lock (m_Materials)
  602. {
  603. foreach (KeyValuePair<UUID, OSDMap> kvp in m_Materials)
  604. {
  605. OSDMap matMap = new OSDMap();
  606. matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes());
  607. matMap["Material"] = kvp.Value;
  608. allOsd.Add(matMap);
  609. matsCount++;
  610. }
  611. }
  612. resp["Zipped"] = ZCompressOSD(allOsd, false);
  613. return OSDParser.SerializeLLSDXmlString(resp);
  614. }
  615. private static string ZippedOsdBytesToString(byte[] bytes)
  616. {
  617. try
  618. {
  619. return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
  620. }
  621. catch (Exception e)
  622. {
  623. return "ZippedOsdBytesToString caught an exception: " + e.ToString();
  624. }
  625. }
  626. /// <summary>
  627. /// computes a UUID by hashing a OSD object
  628. /// </summary>
  629. /// <param name="osd"></param>
  630. /// <returns></returns>
  631. private static UUID HashOsd(OSD osd)
  632. {
  633. byte[] data = OSDParser.SerializeLLSDBinary(osd, false);
  634. using (var md5 = MD5.Create())
  635. return new UUID(md5.ComputeHash(data), 0);
  636. }
  637. public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
  638. {
  639. OSD osd = null;
  640. byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
  641. using (MemoryStream msSinkCompressed = new MemoryStream())
  642. {
  643. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
  644. Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
  645. {
  646. zOut.Write(data, 0, data.Length);
  647. }
  648. msSinkCompressed.Seek(0L, SeekOrigin.Begin);
  649. osd = OSD.FromBinary(msSinkCompressed.ToArray());
  650. }
  651. return osd;
  652. }
  653. public static OSD ZDecompressBytesToOsd(byte[] input)
  654. {
  655. OSD osd = null;
  656. using (MemoryStream msSinkUnCompressed = new MemoryStream())
  657. {
  658. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
  659. {
  660. zOut.Write(input, 0, input.Length);
  661. }
  662. msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
  663. osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
  664. }
  665. return osd;
  666. }
  667. }
  668. }