MaterialsModule.cs 34 KB

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