MaterialsModule.cs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  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 static OpenMetaverse.Primitive;
  38. using static OpenMetaverse.Primitive.RenderMaterials;
  39. using OpenMetaverse.StructuredData;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Servers.HttpServer;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes;
  44. using Ionic.Zlib;
  45. namespace OpenSim.Region.OptionalModules.Materials
  46. {
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
  48. public class MaterialsModule : INonSharedRegionModule, IMaterialsModule
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. public string Name { get { return "MaterialsModule"; } }
  52. public Type ReplaceableInterface { get { return null; } }
  53. IAssetCache m_cache;
  54. private Scene m_scene = null;
  55. private bool m_enabled = false;
  56. private int m_maxMaterialsPerTransaction = 50;
  57. private readonly object materialslock = new();
  58. public Dictionary<UUID, FaceMaterial> m_Materials = new();
  59. public Dictionary<UUID, int> m_MaterialsRefCount = new();
  60. private readonly Dictionary<FaceMaterial, double> m_changed = new();
  61. private readonly Queue<UUID> delayedDelete = new();
  62. private bool m_storeBusy;
  63. private static readonly byte[] GetPutEmptyResponseBytes = osUTF8.GetASCIIBytes("<llsd><map><key>Zipped</key><binary>eNqLZgCCWAAChQC5</binary></map></llsd>");
  64. public void Initialise(IConfigSource source)
  65. {
  66. m_enabled = true; // default is enabled
  67. IConfig config = source.Configs["Materials"];
  68. if (config is not null)
  69. {
  70. m_enabled = config.GetBoolean("enable_materials", m_enabled);
  71. m_maxMaterialsPerTransaction = config.GetInt("MaxMaterialsPerTransaction", m_maxMaterialsPerTransaction);
  72. }
  73. if (m_enabled)
  74. m_log.DebugFormat("[Materials]: Initialized");
  75. }
  76. public void Close()
  77. {
  78. if (!m_enabled)
  79. return;
  80. }
  81. public void AddRegion(Scene scene)
  82. {
  83. if (!m_enabled)
  84. return;
  85. m_scene = scene;
  86. m_scene.RegisterModuleInterface<IMaterialsModule>(this);
  87. m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  88. m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
  89. m_scene.EventManager.OnObjectBeingRemovedFromScene += EventManager_OnObjectDeleteFromScene;
  90. m_scene.EventManager.OnBackup += EventManager_OnBackup;
  91. }
  92. public void RemoveRegion(Scene scene)
  93. {
  94. if (!m_enabled)
  95. return;
  96. m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  97. m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
  98. m_scene.EventManager.OnObjectBeingRemovedFromScene -= EventManager_OnObjectDeleteFromScene;
  99. m_scene.EventManager.OnBackup -= EventManager_OnBackup;
  100. m_scene.UnregisterModuleInterface<IMaterialsModule>(this);
  101. }
  102. public void RegionLoaded(Scene scene)
  103. {
  104. if (!m_enabled) return;
  105. m_cache = scene.RequestModuleInterface<IAssetCache>();
  106. ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>();
  107. if (featuresModule is not null)
  108. {
  109. featuresModule.AddFeature("MaxMaterialsPerTransaction", m_maxMaterialsPerTransaction);
  110. featuresModule.AddFeature("RenderMaterialsCapability", 4);
  111. }
  112. }
  113. private void EventManager_OnBackup(ISimulationDataService datastore, bool forcedBackup)
  114. {
  115. List<FaceMaterial> toStore = null;
  116. lock (materialslock)
  117. {
  118. if(m_storeBusy && !forcedBackup)
  119. return;
  120. if(m_changed.Count == 0)
  121. {
  122. if(forcedBackup)
  123. return;
  124. UUID id;
  125. int throttle = 0;
  126. while(delayedDelete.Count > 0 && throttle < 5)
  127. {
  128. id = delayedDelete.Dequeue();
  129. if (m_Materials.ContainsKey(id))
  130. {
  131. if (m_MaterialsRefCount[id] <= 0)
  132. {
  133. m_Materials.Remove(id);
  134. m_MaterialsRefCount.Remove(id);
  135. m_cache.Expire(id.ToString());
  136. ++throttle;
  137. }
  138. }
  139. }
  140. return;
  141. }
  142. if (forcedBackup)
  143. {
  144. toStore = new List<FaceMaterial>(m_changed.Keys);
  145. m_changed.Clear();
  146. }
  147. else
  148. {
  149. toStore = new List<FaceMaterial>();
  150. double storetime = Util.GetTimeStamp() - 30.0;
  151. foreach(KeyValuePair<FaceMaterial, double> kvp in m_changed)
  152. {
  153. if(kvp.Value < storetime)
  154. {
  155. toStore.Add(kvp.Key);
  156. }
  157. }
  158. foreach(FaceMaterial fm in toStore)
  159. {
  160. m_changed.Remove(fm);
  161. }
  162. }
  163. }
  164. if(toStore.Count > 0)
  165. {
  166. m_storeBusy = true;
  167. if (forcedBackup)
  168. {
  169. foreach (FaceMaterial fm in toStore)
  170. {
  171. AssetBase a = MakeAsset(fm, false);
  172. m_scene.AssetService.Store(a);
  173. }
  174. m_storeBusy = false;
  175. }
  176. else
  177. {
  178. Util.FireAndForget(delegate
  179. {
  180. foreach (FaceMaterial fm in toStore)
  181. {
  182. AssetBase a = MakeAsset(fm, false);
  183. m_scene.AssetService.Store(a);
  184. }
  185. m_storeBusy = false;
  186. });
  187. }
  188. }
  189. }
  190. private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
  191. {
  192. foreach (var part in obj.Parts)
  193. {
  194. if (part is not null)
  195. GetStoredMaterialsInPart(part);
  196. }
  197. }
  198. private void EventManager_OnObjectDeleteFromScene(SceneObjectGroup obj)
  199. {
  200. foreach (var part in obj.Parts)
  201. {
  202. if (part is not null)
  203. RemoveMaterialsInPart(part);
  204. }
  205. }
  206. private void OnRegisterCaps(UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
  207. {
  208. caps.RegisterSimpleHandler("RenderMaterials",
  209. new SimpleStreamHandler("/" + UUID.Random(),
  210. (httpRequest, httpResponse)
  211. => preprocess(httpRequest, httpResponse, agentID)
  212. ));
  213. caps.RegisterSimpleHandler("ModifyMaterialParams",
  214. new SimpleStreamHandler("/" + UUID.Random(),
  215. (httpRequest, httpResponse)
  216. => ModifyMaterialParams(httpRequest, httpResponse, agentID)
  217. ));
  218. }
  219. private void preprocess(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
  220. {
  221. switch (request.HttpMethod)
  222. {
  223. case "GET":
  224. RenderMaterialsGetCap(request, response);
  225. break;
  226. case "PUT":
  227. RenderMaterialsPutCap(request, response, agentID);
  228. break;
  229. case "POST":
  230. RenderMaterialsPostCap(request, response, agentID);
  231. break;
  232. default:
  233. response.StatusCode = (int)HttpStatusCode.NotFound;
  234. return;
  235. }
  236. response.StatusCode = (int)HttpStatusCode.OK;
  237. }
  238. /// <summary>
  239. /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
  240. /// </summary>
  241. /// <param name="part"></param>
  242. private bool GetLegacyStoredMaterialsInPart(SceneObjectPart part)
  243. {
  244. if (part.DynAttrs is null)
  245. return false;
  246. OSD OSMaterials = null;
  247. OSDArray matsArr;
  248. bool partchanged = false;
  249. lock (part.DynAttrs)
  250. {
  251. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  252. {
  253. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  254. if (materialsStore is null)
  255. return false;
  256. materialsStore.TryGetValue("Materials", out OSMaterials);
  257. part.DynAttrs.RemoveStore("OpenSim", "Materials");
  258. partchanged = true;
  259. }
  260. if (OSMaterials is not OSDArray)
  261. return partchanged;
  262. matsArr = (OSDArray)OSMaterials;
  263. }
  264. if (matsArr is null)
  265. return partchanged;
  266. foreach (OSD elemOsd in matsArr)
  267. {
  268. if (elemOsd is OSDMap matMap)
  269. {
  270. if (matMap.TryGetValue("ID", out OSD OSDID) &&
  271. matMap.TryGetValue("Material", out OSD OSDMaterial) && OSDMaterial is OSDMap theMatMap)
  272. {
  273. try
  274. {
  275. lock (materialslock)
  276. {
  277. UUID id = OSDID.AsUUID();
  278. if (m_Materials.ContainsKey(id))
  279. continue;
  280. FaceMaterial fmat = new(theMatMap);
  281. if (fmat is null ||
  282. (fmat.DiffuseAlphaMode == 1
  283. && fmat.NormalMapID.IsZero()
  284. && fmat.SpecularMapID.IsZero()))
  285. continue;
  286. fmat.ID = id;
  287. m_Materials[id] = fmat;
  288. m_MaterialsRefCount[id] = 0;
  289. }
  290. }
  291. catch (Exception e)
  292. {
  293. m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
  294. }
  295. }
  296. }
  297. }
  298. return partchanged;
  299. }
  300. /// <summary>
  301. /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
  302. /// </summary>
  303. private void GetStoredMaterialsInPart(SceneObjectPart part)
  304. {
  305. if (part.Shape is null)
  306. return;
  307. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  308. if (te is null)
  309. return;
  310. bool partchanged = GetLegacyStoredMaterialsInPart(part);
  311. bool facechanged = false;
  312. if (te.DefaultTexture is not null)
  313. facechanged = GetStoredMaterialInFace(part, te.DefaultTexture);
  314. else
  315. m_log.WarnFormat(
  316. "[Materials]: Default texture for part {0} (part of object {1}) in {2} unexpectedly null. Ignoring.",
  317. part.Name, part.ParentGroup.Name, m_scene.Name);
  318. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  319. {
  320. if (face is not null)
  321. facechanged |= GetStoredMaterialInFace(part, face);
  322. }
  323. if(facechanged)
  324. part.Shape.TextureEntry = te.GetBytes(9);
  325. if(facechanged || partchanged)
  326. {
  327. if (part.ParentGroup is not null && !part.ParentGroup.IsDeleted)
  328. part.ParentGroup.HasGroupChanged = true;
  329. }
  330. }
  331. /// <summary>
  332. /// Find the materials used in one Face, and add them to 'm_regionMaterials'.
  333. /// </summary>
  334. private bool GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
  335. {
  336. UUID id = face.MaterialID;
  337. if (id.IsZero())
  338. return false;
  339. OSDMap mat;
  340. lock (materialslock)
  341. {
  342. if(m_Materials.ContainsKey(id))
  343. {
  344. m_MaterialsRefCount[id]++;
  345. return false;
  346. }
  347. AssetBase matAsset = m_scene.AssetService.Get(id.ToString());
  348. if (matAsset is null || matAsset.Data is null || matAsset.Data.Length == 0 )
  349. {
  350. // grid may just be down...
  351. return false;
  352. }
  353. byte[] data = matAsset.Data;
  354. // string txt = System.Text.Encoding.ASCII.GetString(data);
  355. try
  356. {
  357. mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  358. }
  359. catch (Exception e)
  360. {
  361. m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
  362. return false;
  363. }
  364. FaceMaterial fmat = new(mat);
  365. if(fmat is null ||
  366. (fmat.DiffuseAlphaMode == 1
  367. && fmat.NormalMapID.IsZero()
  368. && fmat.SpecularMapID.IsZero()))
  369. {
  370. face.MaterialID = UUID.Zero;
  371. return true;
  372. }
  373. fmat.ID = id;
  374. if (m_Materials.ContainsKey(id))
  375. {
  376. m_MaterialsRefCount[id]++;
  377. }
  378. else
  379. {
  380. m_Materials[id] = fmat;
  381. m_MaterialsRefCount[id] = 1;
  382. }
  383. return false;
  384. }
  385. }
  386. private void RemoveMaterialsInPart(SceneObjectPart part)
  387. {
  388. if (part.Shape is null)
  389. return;
  390. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  391. if (te is null)
  392. return;
  393. if (te.DefaultTexture is not null)
  394. RemoveMaterialInFace(te.DefaultTexture);
  395. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  396. {
  397. if(face is not null)
  398. RemoveMaterialInFace(face);
  399. }
  400. }
  401. private void RemoveMaterialInFace(Primitive.TextureEntryFace face)
  402. {
  403. UUID id = face.MaterialID;
  404. if (id.IsZero())
  405. return;
  406. lock (materialslock)
  407. {
  408. if(m_Materials.ContainsKey(id))
  409. {
  410. m_MaterialsRefCount[id]--;
  411. if (m_MaterialsRefCount[id] == 0)
  412. delayedDelete.Enqueue(id);
  413. }
  414. }
  415. }
  416. public void RenderMaterialsPostCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
  417. {
  418. OSDMap req;
  419. try
  420. {
  421. req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream);
  422. }
  423. catch
  424. {
  425. response.StatusCode = (int)HttpStatusCode.BadRequest;
  426. return;
  427. }
  428. OSDArray respArr = new();
  429. if (req.TryGetValue("Zipped", out OSD tmpOSD))
  430. {
  431. OSD osd;
  432. byte[] inBytes = tmpOSD.AsBinary();
  433. try
  434. {
  435. osd = ZDecompressBytesToOsd(inBytes);
  436. if (osd is OSDArray OSDArrayosd)
  437. {
  438. foreach (OSD elem in OSDArrayosd)
  439. {
  440. try
  441. {
  442. UUID id = new(elem.AsBinary(), 0);
  443. lock (materialslock)
  444. {
  445. if (m_Materials.ContainsKey(id))
  446. {
  447. OSDMap matMap = new()
  448. {
  449. ["ID"] = OSD.FromBinary(id.GetBytes()),
  450. ["Material"] = m_Materials[id].toOSD()
  451. };
  452. respArr.Add(matMap);
  453. }
  454. else
  455. {
  456. m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
  457. // Theoretically we could try to load the material from the assets service,
  458. // but that shouldn't be necessary because the viewer should only request
  459. // materials that exist in a prim on the region, and all of these materials
  460. // are already stored in m_regionMaterials.
  461. }
  462. }
  463. }
  464. catch (Exception e)
  465. {
  466. m_log.Error("Error getting materials in response to viewer request", e);
  467. continue;
  468. }
  469. }
  470. }
  471. }
  472. catch (Exception e)
  473. {
  474. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  475. response.StatusCode = (int)HttpStatusCode.BadRequest;
  476. return;
  477. }
  478. }
  479. OSDMap resp = new()
  480. {
  481. ["Zipped"] = ZCompressOSD(respArr, false)
  482. };
  483. response.RawBuffer = Encoding.UTF8.GetBytes(OSDParser.SerializeLLSDXmlString(resp));
  484. //m_log.Debug("[Materials]: cap request: " + request);
  485. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  486. //m_log.Debug("[Materials]: cap response: " + response);
  487. }
  488. public void RenderMaterialsPutCap(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
  489. {
  490. OSDMap req;
  491. try
  492. {
  493. req = (OSDMap)OSDParser.DeserializeLLSDXml(request.InputStream);
  494. }
  495. catch
  496. {
  497. response.StatusCode = (int)HttpStatusCode.BadRequest;
  498. return;
  499. }
  500. if (req.TryGetValue("Zipped", out OSD tmpOSD))
  501. {
  502. try
  503. {
  504. byte[] inBytes = tmpOSD.AsBinary();
  505. OSD osd = ZDecompressBytesToOsd(inBytes);
  506. if (osd is OSDMap materialsFromViewer)
  507. {
  508. if (materialsFromViewer.TryGetValue("FullMaterialsPerFace", out tmpOSD) && (tmpOSD is OSDArray))
  509. {
  510. Dictionary<uint, SceneObjectPart> parts = new();
  511. HashSet<uint> errorReported = new();
  512. OSDArray matsArr = tmpOSD as OSDArray;
  513. try
  514. {
  515. foreach (OSDMap matsMap in matsArr)
  516. {
  517. uint primLocalID = 0;
  518. try
  519. {
  520. primLocalID = matsMap["ID"].AsUInteger();
  521. }
  522. catch (Exception e)
  523. {
  524. m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
  525. continue;
  526. }
  527. SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
  528. if (sop is null)
  529. {
  530. m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
  531. continue;
  532. }
  533. if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
  534. {
  535. if(!errorReported.Contains(primLocalID))
  536. {
  537. m_log.WarnFormat("[Materials]: User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
  538. errorReported.Add(primLocalID);
  539. }
  540. continue;
  541. }
  542. OSDMap mat = null;
  543. try
  544. {
  545. mat = matsMap["Material"] as OSDMap;
  546. }
  547. catch (Exception e)
  548. {
  549. m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
  550. continue;
  551. }
  552. Primitive.TextureEntry te = new(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
  553. if (te is null)
  554. {
  555. m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
  556. continue;
  557. }
  558. int face = -1;
  559. UUID oldid = UUID.Zero;
  560. Primitive.TextureEntryFace faceEntry = null;
  561. if (matsMap.TryGetValue("Face", out tmpOSD))
  562. {
  563. face = tmpOSD.AsInteger();
  564. faceEntry = te.CreateFace((uint)face);
  565. }
  566. else
  567. faceEntry = te.DefaultTexture;
  568. if (faceEntry is null)
  569. continue;
  570. UUID id;
  571. FaceMaterial newFaceMat = null;
  572. if (mat is null)
  573. {
  574. // This happens then the user removes a material from a prim
  575. id = UUID.Zero;
  576. }
  577. else
  578. {
  579. newFaceMat = new FaceMaterial(mat);
  580. if (newFaceMat.DiffuseAlphaMode == 1
  581. && newFaceMat.NormalMapID.IsZero()
  582. && newFaceMat.SpecularMapID.IsZero())
  583. id = UUID.Zero;
  584. else
  585. {
  586. newFaceMat.genID();
  587. id = newFaceMat.ID;
  588. }
  589. }
  590. oldid = faceEntry.MaterialID;
  591. if (oldid == id)
  592. continue;
  593. if (faceEntry is not null)
  594. {
  595. faceEntry.MaterialID = id;
  596. //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
  597. // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
  598. sop.Shape.TextureEntry = te.GetBytes(9);
  599. }
  600. if (!oldid.IsZero())
  601. RemoveMaterial(oldid);
  602. lock (materialslock)
  603. {
  604. if (id.IsNotZero())
  605. {
  606. if (m_Materials.ContainsKey(id))
  607. m_MaterialsRefCount[id]++;
  608. else
  609. {
  610. m_Materials[id] = newFaceMat;
  611. m_MaterialsRefCount[id] = 1;
  612. m_changed[newFaceMat] = Util.GetTimeStamp();
  613. }
  614. }
  615. }
  616. parts[primLocalID] = sop;
  617. }
  618. foreach (SceneObjectPart sop in parts.Values)
  619. {
  620. if (sop.ParentGroup is not null && !sop.ParentGroup.IsDeleted)
  621. {
  622. sop.TriggerScriptChangedEvent(Changed.TEXTURE);
  623. sop.ScheduleFullUpdate();
  624. sop.ParentGroup.HasGroupChanged = true;
  625. }
  626. }
  627. }
  628. catch (Exception e)
  629. {
  630. m_log.Warn("[Materials]: exception processing received material ", e);
  631. response.StatusCode = (int)HttpStatusCode.BadRequest;
  632. return;
  633. }
  634. }
  635. }
  636. }
  637. catch (Exception e)
  638. {
  639. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  640. response.StatusCode = (int)HttpStatusCode.BadRequest;
  641. return;
  642. }
  643. }
  644. //OSDMap resp = new OSDMap();
  645. //OSDArray respArr = new OSDArray();
  646. //resp["Zipped"] = ZCompressOSD(respArr, false);
  647. //string tmp = OSDParser.SerializeLLSDXmlString(resp);
  648. //response.RawBuffer = OSDParser.SerializeLLSDXmlToBytes(resp);
  649. response.RawBuffer = GetPutEmptyResponseBytes;
  650. }
  651. private AssetBase MakeAsset(FaceMaterial fm, bool local)
  652. {
  653. byte[] data = fm.toLLSDxml();
  654. AssetBase asset = new(fm.ID, "osmaterial", (sbyte)AssetType.OSMaterial, "00000000-0000-0000-0000-000000000000")
  655. {
  656. Data = data,
  657. Local = local
  658. };
  659. return asset;
  660. }
  661. private byte[] CacheGet = null;
  662. private readonly object CacheGetLock = new();
  663. private double CacheGetTime = 0;
  664. public void RenderMaterialsGetCap(IOSHttpRequest request, IOSHttpResponse response)
  665. {
  666. lock(CacheGetLock)
  667. {
  668. OSDArray allOsd = new();
  669. double now = Util.GetTimeStamp();
  670. if(CacheGet is null || now - CacheGetTime > 30)
  671. {
  672. CacheGetTime = now;
  673. lock (m_Materials)
  674. {
  675. foreach (KeyValuePair<UUID, FaceMaterial> kvp in m_Materials)
  676. {
  677. OSDMap matMap = new()
  678. {
  679. ["ID"] = OSD.FromBinary(kvp.Key.GetBytes()),
  680. ["Material"] = kvp.Value.toOSD()
  681. };
  682. allOsd.Add(matMap);
  683. }
  684. }
  685. OSDMap resp = new()
  686. {
  687. ["Zipped"] = ZCompressOSD(allOsd, false)
  688. };
  689. CacheGet = OSDParser.SerializeLLSDXmlToBytes(resp);
  690. }
  691. response.RawBuffer = CacheGet ?? GetPutEmptyResponseBytes;
  692. }
  693. }
  694. private static string ZippedOsdBytesToString(byte[] bytes)
  695. {
  696. try
  697. {
  698. return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
  699. }
  700. catch (Exception e)
  701. {
  702. return "ZippedOsdBytesToString caught an exception: " + e.ToString();
  703. }
  704. }
  705. public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
  706. {
  707. byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
  708. using (MemoryStream msSinkCompressed = new())
  709. {
  710. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
  711. Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
  712. {
  713. zOut.Write(data, 0, data.Length);
  714. }
  715. msSinkCompressed.Seek(0L, SeekOrigin.Begin);
  716. return OSD.FromBinary(msSinkCompressed.ToArray());
  717. }
  718. }
  719. public static OSD ZDecompressBytesToOsd(byte[] input)
  720. {
  721. using (MemoryStream msSinkUnCompressed = new())
  722. {
  723. using (Ionic.Zlib.ZlibStream zOut = new(msSinkUnCompressed, CompressionMode.Decompress, true))
  724. {
  725. zOut.Write(input, 0, input.Length);
  726. }
  727. msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
  728. return OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
  729. }
  730. }
  731. public FaceMaterial GetMaterial(UUID ID)
  732. {
  733. if(m_Materials.TryGetValue(ID, out FaceMaterial fm))
  734. return fm;
  735. return null;
  736. }
  737. public FaceMaterial GetMaterialCopy(UUID ID)
  738. {
  739. if(m_Materials.TryGetValue(ID, out FaceMaterial fm))
  740. return new FaceMaterial(fm);
  741. return null;
  742. }
  743. public UUID AddNewMaterial(FaceMaterial fm)
  744. {
  745. if(fm.DiffuseAlphaMode == 1 && fm.NormalMapID.IsZero() && fm.SpecularMapID.IsZero())
  746. {
  747. fm.ID = UUID.Zero;
  748. return UUID.Zero;
  749. }
  750. fm.genID();
  751. UUID id = fm.ID;
  752. lock(materialslock)
  753. {
  754. if(m_Materials.ContainsKey(id))
  755. m_MaterialsRefCount[id]++;
  756. else
  757. {
  758. m_Materials[id] = fm;
  759. m_MaterialsRefCount[id] = 1;
  760. m_changed[fm] = Util.GetTimeStamp();
  761. }
  762. }
  763. return id;
  764. }
  765. public void RemoveMaterial(UUID id)
  766. {
  767. if(id.IsZero())
  768. return;
  769. lock(materialslock)
  770. {
  771. if(m_Materials.ContainsKey(id))
  772. {
  773. m_MaterialsRefCount[id]--;
  774. if(m_MaterialsRefCount[id] == 0)
  775. {
  776. FaceMaterial fm = m_Materials[id];
  777. m_changed.Remove(fm);
  778. delayedDelete.Enqueue(id);
  779. }
  780. }
  781. }
  782. }
  783. public void ModifyMaterialParams(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID)
  784. {
  785. if (httpRequest.HttpMethod != "POST")
  786. {
  787. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  788. return;
  789. }
  790. try
  791. {
  792. OSDArray req = (OSDArray)OSDParser.DeserializeLLSDXml(httpRequest.InputStream);
  793. httpRequest.InputStream.Dispose();
  794. OSD tmp;
  795. HashSet<SceneObjectPart> changedSOPs = new();
  796. foreach (OSDMap map in req)
  797. {
  798. if (!map.TryGetValue("object_id", out tmp))
  799. continue;
  800. UUID sopid = tmp.AsUUID();
  801. if (sopid.IsZero())
  802. continue;
  803. SceneObjectPart sop = m_scene.GetSceneObjectPart(sopid);
  804. if (sop is null)
  805. continue;
  806. PrimitiveBaseShape pbs = sop.Shape;
  807. if (pbs is null)
  808. continue;
  809. if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
  810. continue;
  811. if (!map.TryGetValue("side", out tmp))
  812. continue;
  813. int side = tmp.AsInteger();
  814. string overridedata;
  815. if (map.TryGetValue("gltf_json", out tmp))
  816. overridedata = tmp.AsString().TrimEnd('\n');
  817. else
  818. overridedata = string.Empty;
  819. bool changed = false;
  820. if (map.TryGetValue("asset_id", out tmp))
  821. {
  822. UUID assetID = tmp.AsUUID();
  823. if (assetID.IsNotZero())
  824. {
  825. pbs.RenderMaterials ??= new Primitive.RenderMaterials();
  826. if (pbs.RenderMaterials.entries is null)
  827. {
  828. var entries = new Primitive.RenderMaterials.RenderMaterialEntry[1];
  829. entries[0].te_index = (byte)side;
  830. entries[0].id = assetID;
  831. pbs.RenderMaterials.entries = entries;
  832. changed = true;
  833. }
  834. else
  835. {
  836. int indx = 0;
  837. while (indx < pbs.RenderMaterials.entries.Length)
  838. {
  839. if (pbs.RenderMaterials.entries[indx].te_index == side)
  840. {
  841. if(pbs.RenderMaterials.entries[indx].id .NotEqual(assetID))
  842. {
  843. pbs.RenderMaterials.entries[indx].id = assetID;
  844. changed = true;
  845. }
  846. break;
  847. }
  848. indx++;
  849. }
  850. if (indx == pbs.RenderMaterials.entries.Length)
  851. {
  852. Array.Resize(ref pbs.RenderMaterials.entries, indx + 1);
  853. pbs.RenderMaterials.entries[indx].te_index = (byte)side;
  854. pbs.RenderMaterials.entries[indx].id = assetID;
  855. changed = true;
  856. }
  857. }
  858. if (string.IsNullOrEmpty(overridedata))
  859. changed |= RemoveMaterialOverride(ref pbs.RenderMaterials.overrides, side);
  860. else
  861. changed |= AddMaterialOverride(ref pbs.RenderMaterials.overrides, overridedata, side);
  862. if(changed)
  863. changedSOPs.Add(sop);
  864. }
  865. else if(pbs.RenderMaterials is not null)
  866. {
  867. changed = RemoveMaterialEntry(ref pbs.RenderMaterials.entries, side);
  868. changed |= RemoveMaterialOverride(ref pbs.RenderMaterials.overrides, side);
  869. //if(pbs.RenderMaterials.entries is null && pbs.RenderMaterials.overrides is null)
  870. // pbs.RenderMaterials = null;
  871. // keep not null so viewer caches can be updated
  872. if(changed)
  873. changedSOPs.Add(sop);
  874. }
  875. }
  876. else if (pbs.RenderMaterials is not null)
  877. {
  878. if (string.IsNullOrEmpty(overridedata))
  879. {
  880. if (RemoveMaterialOverride(ref pbs.RenderMaterials.overrides, side))
  881. changedSOPs.Add(sop);
  882. }
  883. else
  884. {
  885. if (AddMaterialOverride(ref pbs.RenderMaterials.overrides, overridedata, side))
  886. changedSOPs.Add(sop);
  887. }
  888. }
  889. }
  890. foreach (SceneObjectPart sop in changedSOPs)
  891. {
  892. sop.ParentGroup.HasGroupChanged = true;
  893. sop.ScheduleUpdate(PrimUpdateFlags.MaterialOvr | PrimUpdateFlags.FullUpdate);
  894. }
  895. httpResponse.RawBuffer = XMLkeyMaterialSucess;
  896. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  897. }
  898. catch
  899. {
  900. httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
  901. httpResponse.RawBuffer = XMLkeyMaterialFail;
  902. }
  903. }
  904. public static readonly byte[] XMLkeyMaterialSucess = osUTF8.GetASCIIBytes("<llsd><map><key>success</key><integer>1</integer></map></llsd>\r\n");
  905. public static readonly byte[] XMLkeyMaterialFail = osUTF8.GetASCIIBytes("<llsd><map><key>success</key><integer>0</integer></map></llsd>\r\n");
  906. private static bool RemoveMaterialEntry(ref RenderMaterialEntry[] entries, int side)
  907. {
  908. if (entries is null || entries.Length == 0)
  909. return false;
  910. int indx = 0;
  911. while (entries[indx].te_index != side && indx < entries.Length)
  912. indx++;
  913. if (indx >= entries.Length)
  914. return false;
  915. if (entries.Length == 1)
  916. entries = null;
  917. else
  918. {
  919. var newentries = new RenderMaterialEntry[entries.Length - 1];
  920. if (indx > 0)
  921. Array.Copy(entries, newentries, indx);
  922. int left = newentries.Length - indx;
  923. if (left > 0)
  924. Array.Copy(entries, indx + 1, newentries, indx, left);
  925. entries = newentries;
  926. }
  927. return true;
  928. }
  929. private static bool RemoveMaterialOverride(ref RenderMaterialOverrideEntry[] overrides, int side)
  930. {
  931. if (overrides is null || overrides.Length == 0)
  932. return false;
  933. int indx = 0;
  934. while( overrides[indx].te_index != side && ++indx < overrides.Length);
  935. if (indx >= overrides.Length)
  936. return false;
  937. if (overrides.Length == 1)
  938. overrides = null;
  939. else
  940. {
  941. var entries = new RenderMaterialOverrideEntry[overrides.Length - 1];
  942. if (indx > 0)
  943. Array.Copy(overrides, entries, indx);
  944. int left = entries.Length - indx;
  945. if (left > 0)
  946. Array.Copy(overrides, indx + 1, entries, indx, left);
  947. overrides = entries;
  948. }
  949. return true;
  950. }
  951. private static bool GetExtentionTransform(OSDMap Inmap, out OSDMap outmap)
  952. {
  953. OSD tmposd;
  954. if (Inmap.TryGetValue("extensions", out tmposd) && tmposd is OSDMap extmap)
  955. {
  956. if (extmap.TryGetValue("KHR_texture_transform", out tmposd) && tmposd is OSDMap trmap)
  957. {
  958. OSDMap tmpmap = new OSDMap();
  959. if (trmap.TryGetValue("offset", out tmposd) && tmposd is OSDArray offset)
  960. {
  961. tmpmap["o"] = new OSDArray()
  962. {
  963. Math.Round((double) offset[0], 3),
  964. Math.Round((double) offset[1], 3)
  965. };
  966. }
  967. if (trmap.TryGetValue("rotation", out tmposd) && tmposd is OSDReal rotation)
  968. {
  969. tmpmap["r"] = Math.Round((double)rotation, 6);
  970. }
  971. if (trmap.TryGetValue("scale", out tmposd) && tmposd is OSDArray scale)
  972. {
  973. tmpmap["s"] = new OSDArray()
  974. {
  975. Math.Round((double) scale[0], 3),
  976. Math.Round((double) scale[1], 3)
  977. };
  978. }
  979. outmap = tmpmap;
  980. return true;
  981. }
  982. }
  983. outmap = null;
  984. return false;
  985. }
  986. private static bool AddMaterialOverride(ref RenderMaterialOverrideEntry[] overrides, string data, int side)
  987. {
  988. OSD tst;
  989. try
  990. {
  991. tst = OSDParser.DeserializeJson(data);
  992. if(tst is not OSDMap mainArr)
  993. return false;
  994. OSD tmposd;
  995. if (!mainArr.TryGetValue("materials", out tmposd) ||
  996. tmposd is not OSDArray materialsArray ||
  997. materialsArray.Count < 1 ||
  998. materialsArray[0] is not OSDMap material)
  999. return false;
  1000. UUID[] texturesURIs = null;
  1001. if (mainArr.TryGetValue("images", out tmposd) && tmposd is OSDArray imagesArray && imagesArray.Count > 0 && imagesArray.Count < 16)
  1002. {
  1003. Span<UUID> imageURIs = stackalloc UUID[imagesArray.Count];
  1004. for (int i = 0; i < imagesArray.Count; i++)
  1005. {
  1006. if (imagesArray[i] is OSDMap tmpim && tmpim.TryGetValue("uri", out OSD tmpimuri) && tmpimuri is OSDString tmpimuristr)
  1007. {
  1008. if(UUID.TryParse(tmpimuristr.value, out UUID tmpid))
  1009. imageURIs[i] = tmpid;
  1010. }
  1011. }
  1012. if (mainArr.TryGetValue("textures", out tmposd) && tmposd is OSDArray texturesArray && texturesArray.Count > 0 && texturesArray.Count < 16)
  1013. {
  1014. texturesURIs = new UUID[texturesArray.Count];
  1015. for (int i = 0; i < texturesArray.Count; i++)
  1016. {
  1017. if (texturesArray[i] is OSDMap tmptm && tmptm.TryGetValue("source", out OSD tmptmsrc) && tmptmsrc is OSDInteger tmptmsrci)
  1018. {
  1019. int v = tmptmsrci.value;
  1020. if( v < imageURIs.Length)
  1021. texturesURIs[i] = imageURIs[v];
  1022. }
  1023. }
  1024. }
  1025. }
  1026. bool hasTexURIS = texturesURIs is not null;
  1027. OSDMap outosd = new();
  1028. OSDArray ti = new(4);
  1029. OSDMap tmpmap;
  1030. bool texturesChanged = false;
  1031. Span<UUID> textureIDs = stackalloc UUID[4];
  1032. Span<bool> textureIDchanged = stackalloc bool[4];
  1033. if (material.TryGetValue("pbrMetallicRoughness", out tmposd) && tmposd is OSDMap pmrMap && pmrMap.Count > 0)
  1034. {
  1035. if (pmrMap.TryGetValue("baseColorTexture", out tmposd) && tmposd is OSDMap pmrMapbct && pmrMapbct.Count > 0)
  1036. {
  1037. if (hasTexURIS && pmrMapbct.TryGetValue("index", out tmposd) && tmposd is OSDInteger pmrMapbcti)
  1038. {
  1039. int v = pmrMapbcti.value;
  1040. if (v < texturesURIs.Length)
  1041. {
  1042. textureIDs[0] = texturesURIs[v];
  1043. textureIDchanged[0] = true;
  1044. texturesChanged = true;
  1045. }
  1046. }
  1047. if (GetExtentionTransform(pmrMapbct, out tmpmap))
  1048. {
  1049. ti.Add(tmpmap);
  1050. }
  1051. }
  1052. if (pmrMap.TryGetValue("metallicRoughnessTexture", out tmposd) && tmposd is OSDMap pmrMapmrt && pmrMapmrt.Count > 0)
  1053. {
  1054. if (hasTexURIS && pmrMapmrt.TryGetValue("index", out tmposd) && tmposd is OSDInteger pmrMapbcti)
  1055. {
  1056. int v = pmrMapbcti.value;
  1057. if (v < texturesURIs.Length)
  1058. {
  1059. textureIDs[2] = texturesURIs[v];
  1060. textureIDchanged[2] = true;
  1061. texturesChanged = true;
  1062. }
  1063. }
  1064. if (GetExtentionTransform(pmrMapmrt, out tmpmap))
  1065. {
  1066. while (ti.Count < 2)
  1067. ti.Add(new OSD());
  1068. ti.Add(tmpmap);
  1069. }
  1070. }
  1071. if (pmrMap.TryGetValue("baseColorFactor", out tmposd) && tmposd is OSDArray baseColorFactor)
  1072. {
  1073. outosd["bc"] = new OSDArray()
  1074. {
  1075. Math.Round((double) baseColorFactor[0], 4),
  1076. Math.Round((double) baseColorFactor[1], 4),
  1077. Math.Round((double) baseColorFactor[2], 4),
  1078. Math.Round((double) baseColorFactor[3], 4)
  1079. };
  1080. }
  1081. if (pmrMap.TryGetValue("metallicFactor", out tmposd) && tmposd is OSDReal metallicFactor)
  1082. {
  1083. outosd["mf"] = Math.Round((double)metallicFactor, 3);
  1084. }
  1085. if (pmrMap.TryGetValue("roughnessFactor", out tmposd) && tmposd is OSDReal roughnessFactor)
  1086. {
  1087. outosd["rf"] = Math.Round((double)roughnessFactor, 3);
  1088. }
  1089. }
  1090. if (material.TryGetValue("normalTexture", out tmposd) && tmposd is OSDMap ntMap && ntMap.Count > 0)
  1091. {
  1092. if (hasTexURIS && ntMap.TryGetValue("index", out tmposd) && tmposd is OSDInteger ntMapi)
  1093. {
  1094. int v = ntMapi.value;
  1095. if (v < texturesURIs.Length)
  1096. {
  1097. textureIDs[1] = texturesURIs[v];
  1098. textureIDchanged[1] = true;
  1099. texturesChanged = true;
  1100. }
  1101. }
  1102. if (GetExtentionTransform(ntMap, out tmpmap))
  1103. {
  1104. if (ti.Count < 2)
  1105. {
  1106. if (ti.Count == 0)
  1107. ti.Add(new OSD());
  1108. ti.Add(tmpmap);
  1109. }
  1110. else
  1111. ti[1] = tmpmap;
  1112. }
  1113. }
  1114. if (material.TryGetValue("occlusionTexture", out tmposd) && tmposd is OSDMap otMap && otMap.Count > 0)
  1115. {
  1116. if (hasTexURIS && otMap.TryGetValue("index", out tmposd) && tmposd is OSDInteger otMapi)
  1117. {
  1118. int v = otMapi.value;
  1119. if (v < texturesURIs.Length)
  1120. {
  1121. textureIDs[2] = texturesURIs[v];
  1122. textureIDchanged[2] = true;
  1123. texturesChanged = true;
  1124. }
  1125. }
  1126. if (GetExtentionTransform(otMap, out tmpmap))
  1127. {
  1128. if (ti.Count > 2)
  1129. ti[2] = tmpmap;
  1130. else
  1131. {
  1132. while (ti.Count < 2)
  1133. ti.Add(new OSD());
  1134. ti.Add(tmpmap);
  1135. }
  1136. }
  1137. }
  1138. if (material.TryGetValue("emissiveTexture", out tmposd) && tmposd is OSDMap etMap && etMap.Count > 0)
  1139. {
  1140. if (hasTexURIS && etMap.TryGetValue("index", out tmposd) && tmposd is OSDInteger etMapi)
  1141. {
  1142. int v = etMapi.value;
  1143. if (v < texturesURIs.Length)
  1144. {
  1145. textureIDs[3] = texturesURIs[v];
  1146. textureIDchanged[3] = true;
  1147. texturesChanged = true;
  1148. }
  1149. }
  1150. if (GetExtentionTransform(etMap, out tmpmap))
  1151. {
  1152. if (ti.Count > 3)
  1153. ti[3] = tmpmap;
  1154. else
  1155. {
  1156. while (ti.Count < 3)
  1157. ti.Add(new OSD());
  1158. ti.Add(tmpmap);
  1159. }
  1160. }
  1161. }
  1162. if (material.TryGetValue("alphaMode", out tmposd) && tmposd is OSDString aMode)
  1163. {
  1164. outosd["am"] = aMode.value switch
  1165. {
  1166. "BLEND" => 1,
  1167. "MASK" => 2,
  1168. _ => 0
  1169. };
  1170. }
  1171. if (material.TryGetValue("alphaCutoff", out tmposd) && tmposd is OSDReal alphaCutoff)
  1172. {
  1173. outosd["ac"] = Math.Round((double)alphaCutoff, 3);
  1174. }
  1175. if (material.TryGetValue("emissiveFactor", out tmposd) && tmposd is OSDArray emissiveFactor)
  1176. {
  1177. outosd["ec"] = new OSDArray()
  1178. {
  1179. Math.Round((double) emissiveFactor[0], 4),
  1180. Math.Round((double) emissiveFactor[1], 4),
  1181. Math.Round((double) emissiveFactor[2], 4)
  1182. };
  1183. }
  1184. if (material.TryGetValue("doubleSided", out tmposd) && tmposd is OSDBoolean doubleSided)
  1185. {
  1186. outosd["ds"] = doubleSided;
  1187. }
  1188. if (texturesChanged)
  1189. {
  1190. OSDArray tex = new(textureIDs.Length);
  1191. for(int i = 0; i < textureIDs.Length; i++)
  1192. {
  1193. if (textureIDchanged[i])
  1194. tex.Add(textureIDs[i]);
  1195. else
  1196. tex.Add(new OSD());
  1197. }
  1198. outosd["tex"] = tex;
  1199. }
  1200. if(ti.Count > 0)
  1201. outosd["ti"] = ti;
  1202. if (outosd.Count == 0)
  1203. return false;
  1204. data = OSDParser.SerializeLLSDNotation(outosd);
  1205. }
  1206. catch
  1207. {
  1208. return false;
  1209. }
  1210. if (overrides is null)
  1211. {
  1212. var entries = new RenderMaterialOverrideEntry[1];
  1213. entries[0].te_index = (byte)side;
  1214. entries[0].data = data;
  1215. overrides = entries;
  1216. return true;
  1217. }
  1218. int indx = 0;
  1219. while (indx < overrides.Length)
  1220. {
  1221. if (overrides[indx].te_index == side)
  1222. {
  1223. if(overrides[indx].data != data)
  1224. {
  1225. overrides[indx].data = data;
  1226. return true;
  1227. }
  1228. return false;
  1229. }
  1230. indx++;
  1231. }
  1232. Array.Resize(ref overrides, indx + 1);
  1233. overrides[indx].te_index = (byte)side;
  1234. overrides[indx].data = data;
  1235. return true;
  1236. }
  1237. }
  1238. }