MaterialsModule.cs 33 KB

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