1
0

MaterialsModule.cs 35 KB

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