EnvironmentModule.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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.Net;
  30. using System.Reflection;
  31. using System.Text;
  32. using OpenMetaverse;
  33. using OpenMetaverse.StructuredData;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Capabilities;
  36. using OpenSim.Framework.Servers.HttpServer;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Services.Interfaces;
  40. using log4net;
  41. using Nini.Config;
  42. using Mono.Addins;
  43. using Caps = OpenSim.Framework.Capabilities.Caps;
  44. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  45. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  46. using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;
  47. namespace OpenSim.Region.CoreModules.World.LightShare
  48. {
  49. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EnvironmentModule")]
  50. public class EnvironmentModule : INonSharedRegionModule, IEnvironmentModule
  51. {
  52. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. private Scene m_scene = null;
  54. private UUID regionID = UUID.Zero;
  55. private bool Enabled = false;
  56. private IEstateModule m_estateModule;
  57. private IEventQueue m_eventQueue;
  58. private IAssetService m_assetService;
  59. private ILandChannel m_landChannel;
  60. private static ViewerEnvironment m_DefaultEnv = null;
  61. // 1/1 day-to-night ratio
  62. //private static readonly string m_defaultDayAssetID = "5646d39e-d3d7-6aff-ed71-30fc87d64a91"; // Default Daycycle
  63. // 3/1 day-to-night ratio
  64. private static string m_defaultDayAssetID = "5646d39e-d3d7-6aff-ed71-30fc87d64a92"; // Default Daycycle (More Daylight)
  65. private static UUID m_defaultDayAssetUUID = new UUID("5646d39e-d3d7-6aff-ed71-30fc87d64a92");
  66. //private static string m_defaultSkyAssetID = "3ae23978-ac82-bcf3-a9cb-ba6e52dcb9ad";
  67. private static UUID m_defaultSkyAssetUUID = new UUID("3ae23978-ac82-bcf3-a9cb-ba6e52dcb9ad");
  68. //private static string m_defaultWaterAssetID = "59d1a851-47e7-0e5f-1ed7-6b715154f41a";
  69. private static UUID m_defaultWaterAssetUUID = new UUID("59d1a851-47e7-0e5f-1ed7-6b715154f41a");
  70. private int m_regionEnvVersion = -1;
  71. private double m_framets;
  72. #region INonSharedRegionModule
  73. public void Initialise(IConfigSource source)
  74. {
  75. IConfig config = source.Configs["ClientStack.LindenCaps"];
  76. if (null == config)
  77. return;
  78. if (config.GetString("Cap_EnvironmentSettings", String.Empty) != "localhost")
  79. {
  80. m_log.InfoFormat("[{0}]: Module is disabled.", Name);
  81. return;
  82. }
  83. Enabled = true;
  84. m_log.InfoFormat("[{0}]: Module is enabled.", Name);
  85. }
  86. public void Close()
  87. {
  88. }
  89. public string Name
  90. {
  91. get { return "EnvironmentModule"; }
  92. }
  93. public Type ReplaceableInterface
  94. {
  95. get { return null; }
  96. }
  97. public void AddRegion(Scene scene)
  98. {
  99. if (!Enabled)
  100. return;
  101. scene.RegisterModuleInterface<IEnvironmentModule>(this);
  102. m_scene = scene;
  103. regionID = scene.RegionInfo.RegionID;
  104. }
  105. public void RegionLoaded(Scene scene)
  106. {
  107. if (!Enabled)
  108. return;
  109. m_estateModule = scene.RequestModuleInterface<IEstateModule>();
  110. if (m_estateModule == null)
  111. {
  112. Enabled = false;
  113. return;
  114. }
  115. m_eventQueue = m_scene.RequestModuleInterface<IEventQueue>();
  116. if (m_eventQueue == null)
  117. {
  118. Enabled = false;
  119. return;
  120. }
  121. m_assetService = m_scene.AssetService;
  122. if (m_assetService == null)
  123. {
  124. Enabled = false;
  125. return;
  126. }
  127. m_landChannel = m_scene.LandChannel;
  128. if (m_landChannel == null)
  129. {
  130. Enabled = false;
  131. return;
  132. }
  133. if (m_DefaultEnv == null)
  134. {
  135. AssetBase defEnv = m_assetService.Get(m_defaultDayAssetID);
  136. if(defEnv != null)
  137. {
  138. byte[] envData = defEnv.Data;
  139. try
  140. {
  141. OSD oenv = OSDParser.Deserialize(envData);
  142. m_DefaultEnv = new ViewerEnvironment();
  143. m_DefaultEnv.CycleFromOSD(oenv);
  144. }
  145. catch (Exception e)
  146. {
  147. m_DefaultEnv = null;
  148. m_log.Warn(string.Format("[Environment {0}] failed to decode default environment asset ", m_scene.Name), e);
  149. }
  150. }
  151. }
  152. if (m_DefaultEnv == null)
  153. m_DefaultEnv = new ViewerEnvironment();
  154. string senv = scene.SimulationDataService.LoadRegionEnvironmentSettings(scene.RegionInfo.RegionID);
  155. if(!string.IsNullOrEmpty(senv))
  156. {
  157. try
  158. {
  159. OSD oenv = OSDParser.Deserialize(senv);
  160. ViewerEnvironment VEnv = new ViewerEnvironment();
  161. if (oenv is OSDArray)
  162. {
  163. VEnv.FromWLOSD(oenv);
  164. StoreOnRegion(VEnv);
  165. m_log.InfoFormat("[Environment {0}] migrated WindLight environment settings to EEP", m_scene.Name);
  166. }
  167. else
  168. {
  169. VEnv.FromOSD(oenv);
  170. }
  171. scene.RegionEnvironment = VEnv;
  172. m_regionEnvVersion = VEnv.version;
  173. }
  174. catch (Exception e)
  175. {
  176. m_log.Error(string.Format("[Environment {0}] failed to load initial Environment ", m_scene.Name), e);
  177. scene.RegionEnvironment = null;
  178. m_regionEnvVersion = -1;
  179. }
  180. }
  181. else
  182. {
  183. scene.RegionEnvironment = null;
  184. m_regionEnvVersion = -1;
  185. }
  186. m_framets = 0;
  187. UpdateEnvTime();
  188. scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  189. scene.EventManager.OnFrame += UpdateEnvTime;
  190. scene.EventManager.OnAvatarEnteringNewParcel += OnAvatarEnteringNewParcel;
  191. }
  192. public void RemoveRegion(Scene scene)
  193. {
  194. if (!Enabled)
  195. return;
  196. scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  197. }
  198. #endregion
  199. #region IEnvironmentModule
  200. public void StoreOnRegion(ViewerEnvironment VEnv)
  201. {
  202. try
  203. {
  204. if (VEnv == null)
  205. {
  206. m_scene.SimulationDataService.RemoveRegionEnvironmentSettings(regionID);
  207. m_scene.RegionEnvironment = null;
  208. m_regionEnvVersion = -1;
  209. }
  210. else
  211. {
  212. m_regionEnvVersion++;
  213. VEnv.version = m_regionEnvVersion;
  214. OSD env = VEnv.ToOSD();
  215. //m_scene.SimulationDataService.StoreRegionEnvironmentSettings(regionID, OSDParser.SerializeLLSDXmlString(env));
  216. m_scene.SimulationDataService.StoreRegionEnvironmentSettings(regionID, OSDParser.SerializeLLSDNotationFull(env));
  217. m_scene.RegionEnvironment = VEnv;
  218. }
  219. m_framets = 0;
  220. UpdateEnvTime();
  221. }
  222. catch (Exception e)
  223. {
  224. m_log.Error(string.Format("[Environment {0}] failed to store Environment ", m_scene.Name), e);
  225. }
  226. }
  227. public void ResetEnvironmentSettings(UUID regionUUID)
  228. {
  229. if (!Enabled)
  230. return;
  231. StoreOnRegion(null);
  232. WindlightRefresh(0);
  233. }
  234. public void WindlightRefresh(int interpolate, bool forRegion = true)
  235. {
  236. List<byte[]> ls = null;
  237. m_scene.ForEachRootScenePresence(delegate (ScenePresence sp)
  238. {
  239. if(sp.IsInTransit || sp.IsNPC)
  240. return;
  241. IClientAPI client = sp.ControllingClient;
  242. if (!client.IsActive)
  243. return;
  244. uint vflags = client.GetViewerCaps();
  245. if ((vflags & 0x8000) != 0)
  246. {
  247. if (forRegion)
  248. m_estateModule.HandleRegionInfoRequest(client);
  249. }
  250. else if ((vflags & 0x4000) != 0)
  251. m_eventQueue.WindlightRefreshEvent(interpolate, client.AgentId);
  252. else
  253. {
  254. if (ls == null)
  255. ls = MakeLightShareData();
  256. SendLightShare(client, ls);
  257. }
  258. });
  259. }
  260. public void WindlightRefreshForced(IScenePresence isp, int interpolate)
  261. {
  262. List<byte[]> ls = null;
  263. IClientAPI client = isp.ControllingClient;
  264. if (!client.IsActive)
  265. return;
  266. uint vflags = client.GetViewerCaps();
  267. if ((vflags & 0x8000) != 0)
  268. {
  269. ScenePresence sp = isp as ScenePresence;
  270. ILandObject lo = m_scene.LandChannel.GetLandObject(sp.AbsolutePosition.X, sp.AbsolutePosition.Y);
  271. if (lo != null && lo.LandData != null && lo.LandData.Environment != null)
  272. lo.SendLandUpdateToClient(client);
  273. m_estateModule.HandleRegionInfoRequest(client);
  274. }
  275. else if ((vflags & 0x4000) != 0)
  276. m_eventQueue.WindlightRefreshEvent(interpolate, client.AgentId);
  277. else
  278. {
  279. if (ls == null)
  280. ls = MakeLightShareData();
  281. SendLightShare(client, ls);
  282. }
  283. }
  284. public void FromLightShare(RegionLightShareData ls)
  285. {
  286. if (!Enabled)
  287. return;
  288. ViewerEnvironment VEnv = new ViewerEnvironment();
  289. VEnv.FromLightShare(ls);
  290. StoreOnRegion(VEnv);
  291. WindlightRefresh(0);
  292. }
  293. public RegionLightShareData ToLightShare()
  294. {
  295. if (!Enabled)
  296. return new RegionLightShareData();
  297. RegionLightShareData ls = null;
  298. try
  299. {
  300. ViewerEnvironment VEnv = m_scene.RegionEnvironment;
  301. if(VEnv == null)
  302. return new RegionLightShareData();
  303. ls = VEnv.ToLightShare();
  304. }
  305. catch (Exception e)
  306. {
  307. m_log.ErrorFormat("[{0}]: Unable to convert environment to lightShare, Exception: {1} - {2}",
  308. Name, e.Message, e.StackTrace);
  309. }
  310. if(ls == null)
  311. return new RegionLightShareData();
  312. return ls;
  313. }
  314. #endregion
  315. #region Events
  316. private void OnRegisterCaps(UUID agentID, Caps caps)
  317. {
  318. // m_log.DebugFormat("[{0}]: Register capability for agentID {1} in region {2}",
  319. // Name, agentID, caps.RegionName);
  320. caps.RegisterSimpleHandler("EnvironmentSettings",
  321. new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  322. {
  323. processEnv(httpRequest, httpResponse, agentID);
  324. }));
  325. //Extended
  326. caps.RegisterSimpleHandler("ExtEnvironment",
  327. new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  328. {
  329. processExtEnv(httpRequest, httpResponse, agentID, caps);
  330. }));
  331. }
  332. #endregion
  333. private void processEnv(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
  334. {
  335. switch (request.HttpMethod)
  336. {
  337. case "POST":
  338. SetEnvironmentSettings(request, response, agentID);
  339. return;
  340. case "GET":
  341. GetEnvironmentSettings(response, agentID);
  342. return;
  343. default:
  344. {
  345. response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
  346. return;
  347. }
  348. }
  349. }
  350. private void processExtEnv(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Caps caps)
  351. {
  352. switch(request.HttpMethod)
  353. {
  354. case "PUT":
  355. case "POST":
  356. SetExtEnvironmentSettings(request, response, agentID, caps);
  357. return;
  358. case "GET":
  359. GetExtEnvironmentSettings(request, response, agentID);
  360. return;
  361. case "DELETE":
  362. DeleteExtEnvironmentSettings(request, response, agentID);
  363. return;
  364. default:
  365. {
  366. response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
  367. return;
  368. }
  369. }
  370. }
  371. private void DeleteExtEnvironmentSettings(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID)
  372. {
  373. int parcel = -1;
  374. if (httpRequest.Query.Count > 0)
  375. {
  376. if (httpRequest.Query.ContainsKey("parcelid"))
  377. {
  378. Int32.TryParse((string)httpRequest.Query["parcelid"], out parcel);
  379. }
  380. }
  381. if(parcel == -1)
  382. {
  383. StoreOnRegion(null);
  384. WindlightRefresh(0);
  385. }
  386. else
  387. {
  388. ILandObject land = m_scene.LandChannel.GetLandObject(parcel);
  389. if (land != null && land.LandData != null)
  390. {
  391. land.StoreEnvironment(null);
  392. WindlightRefresh(0, false);
  393. }
  394. }
  395. osUTF8 sb = LLSDxmlEncode2.Start();
  396. LLSDxmlEncode2.AddMap(sb);
  397. LLSDxmlEncode2.AddElem("messageID", UUID.Zero, sb);
  398. LLSDxmlEncode2.AddElem("regionID", regionID, sb);
  399. LLSDxmlEncode2.AddElem("success", true, sb);
  400. LLSDxmlEncode2.AddEndMap(sb);
  401. httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
  402. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  403. }
  404. private void GetExtEnvironmentSettings(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID)
  405. {
  406. int parcelid = -1;
  407. if (httpRequest.Query.Count > 0)
  408. {
  409. if (httpRequest.Query.ContainsKey("parcelid"))
  410. {
  411. Int32.TryParse((string)httpRequest.Query["parcelid"], out parcelid);
  412. }
  413. }
  414. ScenePresence sp = m_scene.GetScenePresence(agentID);
  415. if (sp == null)
  416. {
  417. httpResponse.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  418. httpResponse.AddHeader("Retry-After", "5");
  419. return;
  420. }
  421. ViewerEnvironment VEnv = null;
  422. if (sp.Environment != null)
  423. VEnv = sp.Environment;
  424. else if (parcelid == -1)
  425. VEnv = GetRegionEnvironment();
  426. else
  427. {
  428. if (m_scene.RegionInfo.EstateSettings.AllowEnvironmentOverride)
  429. {
  430. ILandObject land = m_scene.LandChannel.GetLandObject(parcelid);
  431. if(land != null && land.LandData != null && land.LandData.Environment != null)
  432. VEnv = land.LandData.Environment;
  433. }
  434. if(VEnv == null)
  435. {
  436. OSD def = ViewerEnvironment.DefaultToOSD(regionID, parcelid);
  437. httpResponse.RawBuffer = OSDParser.SerializeLLSDXmlToBytes(def);
  438. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  439. return;
  440. }
  441. }
  442. byte[] envBytes = VEnv.ToCapBytes(regionID, parcelid);
  443. if(envBytes == null)
  444. {
  445. osUTF8 sb = LLSDxmlEncode2.Start();
  446. LLSDxmlEncode2.AddArray(sb);
  447. LLSDxmlEncode2.AddMap(sb);
  448. LLSDxmlEncode2.AddElem("messageID", UUID.Zero, sb);
  449. LLSDxmlEncode2.AddElem("regionID", regionID, sb);
  450. LLSDxmlEncode2.AddEndMap(sb);
  451. LLSDxmlEncode2.AddEndArray(sb);
  452. httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
  453. }
  454. else
  455. httpResponse.RawBuffer = envBytes;
  456. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  457. }
  458. private void SetExtEnvironmentSettings(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID agentID, Caps caps)
  459. {
  460. bool success = false;
  461. string message = "Could not process request";
  462. int parcel = -1;
  463. int track = -1;
  464. osUTF8 sb = LLSDxmlEncode2.Start();
  465. ScenePresence sp = m_scene.GetScenePresence(agentID);
  466. if (sp == null || sp.IsChildAgent || sp.IsNPC)
  467. {
  468. message = "Could not locate your avatar";
  469. goto Error;
  470. }
  471. if (httpRequest.Query.Count > 0)
  472. {
  473. if (httpRequest.Query.ContainsKey("parcelid"))
  474. {
  475. if (!Int32.TryParse((string)httpRequest.Query["parcelid"], out parcel))
  476. {
  477. message = "Failed to decode request";
  478. goto Error;
  479. }
  480. }
  481. if (httpRequest.Query.ContainsKey("trackno"))
  482. {
  483. if (!Int32.TryParse((string)httpRequest.Query["trackno"], out track))
  484. {
  485. message = "Failed to decode request";
  486. goto Error;
  487. }
  488. }
  489. if (track != -1)
  490. {
  491. message = "Environment Track not supported";
  492. goto Error;
  493. }
  494. }
  495. ViewerEnvironment VEnv = m_scene.RegionEnvironment;
  496. ILandObject lchannel;
  497. if (parcel == -1)
  498. {
  499. if (!m_scene.Permissions.CanIssueEstateCommand(agentID, false))
  500. {
  501. message = "Insufficient estate permissions, settings has not been saved.";
  502. goto Error;
  503. }
  504. VEnv = m_scene.RegionEnvironment;
  505. lchannel = null;
  506. }
  507. else
  508. {
  509. lchannel = m_landChannel.GetLandObject(parcel);
  510. if(lchannel == null || lchannel.LandData == null)
  511. {
  512. message = "Could not locate requested parcel";
  513. goto Error;
  514. }
  515. if (!m_scene.Permissions.CanEditParcelProperties(agentID, lchannel, GroupPowers.AllowEnvironment, true)) // wrong
  516. {
  517. message = "No permission to change parcel environment";
  518. goto Error;
  519. }
  520. VEnv = lchannel.LandData.Environment;
  521. }
  522. try
  523. {
  524. OSD req = OSDParser.Deserialize(httpRequest.InputStream);
  525. if(req is OSDMap)
  526. {
  527. OSDMap map = req as OSDMap;
  528. if(map.TryGetValue("environment", out OSD env))
  529. {
  530. if (VEnv == null)
  531. // need a proper clone
  532. VEnv = m_DefaultEnv.Clone();
  533. OSDMap evmap = env as OSDMap;
  534. if(evmap.TryGetValue("day_asset", out OSD tmp) && !evmap.ContainsKey("day_cycle"))
  535. {
  536. string id = tmp.AsString();
  537. AssetBase asset = m_assetService.Get(id);
  538. if(asset == null || asset.Data == null || asset.Data.Length == 0)
  539. {
  540. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  541. return;
  542. }
  543. try
  544. {
  545. OSD oenv = OSDParser.Deserialize(asset.Data);
  546. evmap.TryGetValue("day_name", out tmp);
  547. if(tmp is OSDString)
  548. VEnv.FromAssetOSD(tmp.AsString(), oenv);
  549. else
  550. VEnv.FromAssetOSD(null, oenv);
  551. }
  552. catch
  553. {
  554. httpResponse.StatusCode = (int)HttpStatusCode.NotFound;
  555. return;
  556. }
  557. }
  558. else
  559. VEnv.FromOSD(env);
  560. if(lchannel == null)
  561. {
  562. StoreOnRegion(VEnv);
  563. m_log.InfoFormat("[{0}]: ExtEnvironment region {1} settings from agentID {2} saved",
  564. Name, caps.RegionName, agentID);
  565. }
  566. else
  567. {
  568. lchannel.StoreEnvironment(VEnv);
  569. m_log.InfoFormat("[{0}]: ExtEnvironment parcel {1} of region {2} settings from agentID {3} saved",
  570. Name, parcel, caps.RegionName, agentID);
  571. }
  572. WindlightRefresh(0, lchannel == null);
  573. success = true;
  574. }
  575. }
  576. else if (req is OSDArray)
  577. {
  578. VEnv = new ViewerEnvironment();
  579. VEnv.FromWLOSD(req);
  580. StoreOnRegion(VEnv);
  581. success = true;
  582. WindlightRefresh(0);
  583. m_log.InfoFormat("[{0}]: ExtEnvironment region {1} settings from agentID {2} saved",
  584. Name, caps.RegionName, agentID);
  585. LLSDxmlEncode2.AddMap(sb);
  586. LLSDxmlEncode2.AddElem("messageID", UUID.Zero, sb);
  587. LLSDxmlEncode2.AddElem("regionID", regionID, sb);
  588. LLSDxmlEncode2.AddElem("success", success, sb);
  589. LLSDxmlEncode2.AddEndMap(sb);
  590. httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
  591. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  592. return;
  593. }
  594. }
  595. catch (Exception e)
  596. {
  597. m_log.ErrorFormat("[{0}]: ExtEnvironment settings not saved for region {1}, Exception: {2} - {3}",
  598. Name, caps.RegionName, e.Message, e.StackTrace);
  599. success = false;
  600. message = String.Format("ExtEnvironment Set for region {0} has failed, settings not saved.", caps.RegionName);
  601. }
  602. Error:
  603. LLSDxmlEncode2.AddMap(sb);
  604. LLSDxmlEncode2.AddElem("success", success, sb);
  605. if(!success)
  606. LLSDxmlEncode2.AddElem("message", message, sb);
  607. LLSDxmlEncode2.AddEndMap(sb);
  608. httpResponse.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
  609. httpResponse.StatusCode = (int)HttpStatusCode.OK;
  610. }
  611. private void GetEnvironmentSettings(IOSHttpResponse response, UUID agentID)
  612. {
  613. // m_log.DebugFormat("[{0}]: Environment GET handle for agentID {1} in region {2}",
  614. // Name, agentID, caps.RegionName);
  615. ViewerEnvironment VEnv = null;
  616. ScenePresence sp = m_scene.GetScenePresence(agentID);
  617. if (sp == null)
  618. {
  619. response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
  620. response.AddHeader("Retry-After", "5");
  621. return;
  622. }
  623. if (sp.Environment != null)
  624. VEnv = sp.Environment;
  625. else
  626. {
  627. if(m_scene.RegionInfo.EstateSettings.AllowEnvironmentOverride)
  628. {
  629. ILandObject land = m_scene.LandChannel.GetLandObject(sp.AbsolutePosition.X, sp.AbsolutePosition.Y);
  630. if (land != null && land.LandData != null && land.LandData.Environment != null)
  631. VEnv = land.LandData.Environment;
  632. }
  633. }
  634. if (VEnv == null)
  635. VEnv = GetRegionEnvironment();
  636. byte[] envBytes = VEnv.ToCapWLBytes(UUID.Zero, regionID);
  637. if(envBytes == null)
  638. {
  639. osUTF8 sb = LLSDxmlEncode2.Start();
  640. LLSDxmlEncode2.AddArray(sb);
  641. LLSDxmlEncode2.AddMap(sb);
  642. LLSDxmlEncode2.AddElem("messageID", UUID.Zero, sb);
  643. LLSDxmlEncode2.AddElem("regionID", regionID, sb);
  644. LLSDxmlEncode2.AddEndMap(sb);
  645. LLSDxmlEncode2.AddEndArray(sb);
  646. response.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
  647. }
  648. else
  649. response.RawBuffer = envBytes;
  650. response.StatusCode = (int)HttpStatusCode.OK;
  651. }
  652. private void SetEnvironmentSettings(IOSHttpRequest request, IOSHttpResponse response, UUID agentID)
  653. {
  654. // m_log.DebugFormat("[{0}]: Environment SET handle from agentID {1} in region {2}",
  655. // Name, agentID, caps.RegionName);
  656. bool success = false;
  657. string fail_reason = "";
  658. if (!m_scene.Permissions.CanIssueEstateCommand(agentID, false))
  659. {
  660. fail_reason = "Insufficient estate permissions, settings has not been saved.";
  661. goto Error;
  662. }
  663. ScenePresence sp = m_scene.GetScenePresence(agentID);
  664. if (sp == null || sp.IsChildAgent || sp.IsNPC)
  665. {
  666. response.StatusCode = (int)HttpStatusCode.NotFound;
  667. return;
  668. }
  669. if (sp.Environment != null)
  670. {
  671. fail_reason = "The environment you see is a forced one. Disable if on control object or tp out and back to region";
  672. goto Error;
  673. }
  674. ILandObject land = m_scene.LandChannel.GetLandObject(sp.AbsolutePosition.X, sp.AbsolutePosition.Y);
  675. if (land != null && land.LandData != null && land.LandData.Environment != null)
  676. {
  677. fail_reason = "The parcel where you are has own environment set. You need a updated viewer to change environment";
  678. goto Error;
  679. }
  680. try
  681. {
  682. ViewerEnvironment VEnv = new ViewerEnvironment();
  683. OSD env = OSDParser.Deserialize(request.InputStream);
  684. VEnv.FromWLOSD(env);
  685. StoreOnRegion(VEnv);
  686. WindlightRefresh(0);
  687. m_log.InfoFormat("[{0}]: New Environment settings has been saved from agentID {1} in region {2}",
  688. Name, agentID, m_scene.Name);
  689. success = true;
  690. }
  691. catch (Exception e)
  692. {
  693. m_log.ErrorFormat("[{0}]: Environment settings has not been saved for region {1}, Exception: {2} - {3}",
  694. Name, m_scene.Name, e.Message, e.StackTrace);
  695. success = false;
  696. fail_reason = String.Format("Environment Set for region {0} has failed, settings not saved.", m_scene.Name);
  697. }
  698. Error:
  699. osUTF8 sb = LLSDxmlEncode2.Start();
  700. LLSDxmlEncode2.AddMap(sb);
  701. LLSDxmlEncode2.AddElem("messageID", UUID.Zero, sb);
  702. LLSDxmlEncode2.AddElem("regionID", regionID, sb);
  703. LLSDxmlEncode2.AddElem("success", success, sb);
  704. if(!success)
  705. LLSDxmlEncode2.AddElem("fail_reason", fail_reason, sb);
  706. LLSDxmlEncode2.AddEndMap(sb);
  707. response.RawBuffer = LLSDxmlEncode2.EndToBytes(sb);
  708. response.StatusCode = (int)HttpStatusCode.OK;
  709. }
  710. public byte[] GetDefaultAssetData(int type)
  711. {
  712. OSD osddata;
  713. switch(type)
  714. {
  715. case 0:
  716. SkyData sky = new SkyData();
  717. sky.Name = "DefaultSky";
  718. osddata = sky.ToOSD();
  719. break;
  720. case 1:
  721. WaterData water = new WaterData();
  722. water.Name = "DefaultWater";
  723. osddata = water.ToOSD();
  724. break;
  725. case 2:
  726. DayCycle day = new DayCycle();
  727. day.Name="New Daycycle";
  728. DayCycle.TrackEntry te = new DayCycle.TrackEntry();
  729. WaterData dwater = new WaterData();
  730. dwater.Name = "DefaultWater";
  731. day.waterframes["DefaultWater"] = dwater;
  732. te.time = 0;
  733. te.frameName = "DefaultWater";
  734. day.waterTrack.Add(te);
  735. SkyData dsky = new SkyData();
  736. dsky.Name = "DefaultSky";
  737. day.skyframes["DefaultSky"] = dsky;
  738. te.time = 0;
  739. te.frameName = "DefaultSky";
  740. day.skyTrack0.Add(te);
  741. osddata = day.ToOSD();
  742. break;
  743. default:
  744. return null;
  745. }
  746. return OSDParser.SerializeLLSDNotationToBytes(osddata,true);
  747. }
  748. public UUID GetDefaultAsset(int type)
  749. {
  750. switch (type)
  751. {
  752. case 0:
  753. return m_defaultSkyAssetUUID;
  754. case 1:
  755. return m_defaultWaterAssetUUID;
  756. case 2:
  757. return m_defaultDayAssetUUID;
  758. default:
  759. return UUID.Zero;
  760. }
  761. }
  762. public List<byte[]> MakeLightShareData()
  763. {
  764. if(m_scene.RegionEnvironment == null)
  765. return null;
  766. RegionLightShareData wl = ToLightShare();
  767. byte[] mBlock = new Byte[249];
  768. int pos = 0;
  769. wl.waterColor.ToBytes(mBlock, 0); pos += 12;
  770. Utils.FloatToBytes(wl.waterFogDensityExponent).CopyTo(mBlock, pos); pos += 4;
  771. Utils.FloatToBytes(wl.underwaterFogModifier).CopyTo(mBlock, pos); pos += 4;
  772. wl.reflectionWaveletScale.ToBytes(mBlock, pos); pos += 12;
  773. Utils.FloatToBytes(wl.fresnelScale).CopyTo(mBlock, pos); pos += 4;
  774. Utils.FloatToBytes(wl.fresnelOffset).CopyTo(mBlock, pos); pos += 4;
  775. Utils.FloatToBytes(wl.refractScaleAbove).CopyTo(mBlock, pos); pos += 4;
  776. Utils.FloatToBytes(wl.refractScaleBelow).CopyTo(mBlock, pos); pos += 4;
  777. Utils.FloatToBytes(wl.blurMultiplier).CopyTo(mBlock, pos); pos += 4;
  778. wl.bigWaveDirection.ToBytes(mBlock, pos); pos += 8;
  779. wl.littleWaveDirection.ToBytes(mBlock, pos); pos += 8;
  780. wl.normalMapTexture.ToBytes(mBlock, pos); pos += 16;
  781. wl.horizon.ToBytes(mBlock, pos); pos += 16;
  782. Utils.FloatToBytes(wl.hazeHorizon).CopyTo(mBlock, pos); pos += 4;
  783. wl.blueDensity.ToBytes(mBlock, pos); pos += 16;
  784. Utils.FloatToBytes(wl.hazeDensity).CopyTo(mBlock, pos); pos += 4;
  785. Utils.FloatToBytes(wl.densityMultiplier).CopyTo(mBlock, pos); pos += 4;
  786. Utils.FloatToBytes(wl.distanceMultiplier).CopyTo(mBlock, pos); pos += 4;
  787. wl.sunMoonColor.ToBytes(mBlock, pos); pos += 16;
  788. Utils.FloatToBytes(wl.sunMoonPosition).CopyTo(mBlock, pos); pos += 4;
  789. wl.ambient.ToBytes(mBlock, pos); pos += 16;
  790. Utils.FloatToBytes(wl.eastAngle).CopyTo(mBlock, pos); pos += 4;
  791. Utils.FloatToBytes(wl.sunGlowFocus).CopyTo(mBlock, pos); pos += 4;
  792. Utils.FloatToBytes(wl.sunGlowSize).CopyTo(mBlock, pos); pos += 4;
  793. Utils.FloatToBytes(wl.sceneGamma).CopyTo(mBlock, pos); pos += 4;
  794. Utils.FloatToBytes(wl.starBrightness).CopyTo(mBlock, pos); pos += 4;
  795. wl.cloudColor.ToBytes(mBlock, pos); pos += 16;
  796. wl.cloudXYDensity.ToBytes(mBlock, pos); pos += 12;
  797. Utils.FloatToBytes(wl.cloudCoverage).CopyTo(mBlock, pos); pos += 4;
  798. Utils.FloatToBytes(wl.cloudScale).CopyTo(mBlock, pos); pos += 4;
  799. wl.cloudDetailXYDensity.ToBytes(mBlock, pos); pos += 12;
  800. Utils.FloatToBytes(wl.cloudScrollX).CopyTo(mBlock, pos); pos += 4;
  801. Utils.FloatToBytes(wl.cloudScrollY).CopyTo(mBlock, pos); pos += 4;
  802. Utils.UInt16ToBytes(wl.maxAltitude).CopyTo(mBlock, pos); pos += 2;
  803. mBlock[pos] = Convert.ToByte(wl.cloudScrollXLock); pos++;
  804. mBlock[pos] = Convert.ToByte(wl.cloudScrollYLock); pos++;
  805. mBlock[pos] = Convert.ToByte(wl.drawClassicClouds); pos++;
  806. List<byte[]> param = new List<byte[]>();
  807. param.Add(mBlock);
  808. return param;
  809. }
  810. public void SendLightShare(IClientAPI client, List<byte[]> param)
  811. {
  812. if(param == null || param.Count == 0)
  813. client.SendGenericMessage("WindlightReset", UUID.Random(), new List<byte[]>());
  814. else
  815. client.SendGenericMessage("Windlight", UUID.Random(), param);
  816. }
  817. private void OnAvatarEnteringNewParcel(ScenePresence sp, int localLandID, UUID regionID)
  818. {
  819. if (sp.Environment != null || sp.IsNPC)
  820. return;
  821. if (!m_scene.RegionInfo.EstateSettings.AllowEnvironmentOverride)
  822. return;
  823. IClientAPI client = sp.ControllingClient;
  824. uint vflags = client.GetViewerCaps();
  825. if((vflags & 0x8000) != 0)
  826. return;
  827. m_eventQueue.WindlightRefreshEvent(1, client.AgentId);
  828. }
  829. private void UpdateEnvTime()
  830. {
  831. double now = Util.GetTimeStamp();
  832. if (now - m_framets < 2.5) // this will be a conf option
  833. return;
  834. m_framets = now;
  835. UpdateClientsSunTime();
  836. }
  837. private void UpdateClientsSunTime()
  838. {
  839. if(m_scene.GetNumberOfClients() == 0)
  840. return;
  841. //m_log.DebugFormat("{0} {1} {2} {3}", dayFrac, eepDayFrac, wldayFrac, Util.UnixTimeSinceEpoch_uS());
  842. m_scene.ForEachRootScenePresence(delegate (ScenePresence sp)
  843. {
  844. if(sp.IsDeleted || sp.IsInTransit || sp.IsNPC)
  845. return;
  846. ViewerEnvironment VEnv;
  847. if(sp.Environment != null)
  848. VEnv = sp.Environment;
  849. else
  850. VEnv = GetEnvironment(sp.AbsolutePosition.X, sp.AbsolutePosition.Y);
  851. float dayFrac = GetDayFractionTime(VEnv);
  852. IClientAPI client = sp.ControllingClient;
  853. uint vflags = client.GetViewerCaps();
  854. if ((vflags & 0x8000) != 0)
  855. {
  856. client.SendViewerTime(Vector3.Zero, dayFrac * Utils.TWO_PI);
  857. return;
  858. }
  859. if (dayFrac <= 0.25f)
  860. dayFrac += 1.5f;
  861. else if (dayFrac > 0.75f)
  862. dayFrac += 0.5f;
  863. else if (dayFrac >= 0.333333f)
  864. dayFrac = 3f * dayFrac - 1f;
  865. else
  866. dayFrac = 3f * dayFrac + 1f;
  867. dayFrac = Utils.Clamp(dayFrac, 0, 2f);
  868. dayFrac *= Utils.PI;
  869. client.SendViewerTime(Vector3.Zero, dayFrac);
  870. });
  871. }
  872. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  873. public ViewerEnvironment GetEnvironment(Vector3 pos)
  874. {
  875. ILandObject lo = m_landChannel.GetLandObject(pos.X, pos.Y);
  876. if (lo != null && lo.LandData != null && lo.LandData.Environment != null)
  877. return lo.LandData.Environment;
  878. return m_scene.RegionEnvironment == null ? m_DefaultEnv : m_scene.RegionEnvironment;
  879. }
  880. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  881. public ViewerEnvironment GetEnvironment(float x, float y)
  882. {
  883. ILandObject lo = m_landChannel.GetLandObject(x, y);
  884. if (lo != null && lo.LandData != null && lo.LandData.Environment != null)
  885. return lo.LandData.Environment;
  886. return m_scene.RegionEnvironment == null ? m_DefaultEnv : m_scene.RegionEnvironment;
  887. }
  888. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  889. public ViewerEnvironment GetRegionEnvironment()
  890. {
  891. return m_scene.RegionEnvironment == null ? m_DefaultEnv : m_scene.RegionEnvironment;
  892. }
  893. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  894. public float GetDayFractionTime(ViewerEnvironment env)
  895. {
  896. double dayfrac = env.DayLength;
  897. dayfrac = ((Util.UnixTimeSinceEpochSecs() + env.DayOffset) % dayfrac) / dayfrac;
  898. return (float)Utils.Clamp(dayfrac, 0, 1);
  899. }
  900. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  901. public float GetRegionDayFractionTime()
  902. {
  903. return GetDayFractionTime(GetRegionEnvironment());
  904. }
  905. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  906. public int GetDayLength(ViewerEnvironment env)
  907. {
  908. return env.DayLength;
  909. }
  910. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  911. public int GetDayOffset(ViewerEnvironment env)
  912. {
  913. return env.DayOffset;
  914. }
  915. public Vector3 GetSunDir(ViewerEnvironment env, float altitude)
  916. {
  917. env.getPositions(altitude, GetDayFractionTime(env), out Vector3 sundir, out Vector3 moondir,
  918. out Quaternion sunrot, out Quaternion moonrot);
  919. return sundir;
  920. }
  921. public Quaternion GetSunRot(ViewerEnvironment env, float altitude)
  922. {
  923. env.getPositions(altitude, GetDayFractionTime(env), out Vector3 sundir, out Vector3 moondir,
  924. out Quaternion sunrot, out Quaternion moonrot);
  925. return sunrot;
  926. }
  927. public Vector3 GetMoonDir(ViewerEnvironment env, float altitude)
  928. {
  929. env.getPositions(altitude, GetDayFractionTime(env), out Vector3 sundir, out Vector3 moondir,
  930. out Quaternion sunrot, out Quaternion moonrot);
  931. return moondir;
  932. }
  933. public Quaternion GetMoonRot(ViewerEnvironment env, float altitude)
  934. {
  935. env.getPositions(altitude, GetDayFractionTime(env), out Vector3 sundir, out Vector3 moondir,
  936. out Quaternion sunrot, out Quaternion moonrot);
  937. return moonrot;
  938. }
  939. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  940. public int GetRegionDayLength()
  941. {
  942. return GetRegionEnvironment().DayLength;
  943. }
  944. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  945. public int GetRegionDayOffset()
  946. {
  947. return GetRegionEnvironment().DayOffset;
  948. }
  949. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  950. public Vector3 GetRegionSunDir(float altitude)
  951. {
  952. return GetSunDir(GetRegionEnvironment(), altitude);
  953. }
  954. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  955. public Quaternion GetRegionSunRot(float altitude)
  956. {
  957. return GetSunRot(GetRegionEnvironment(), altitude);
  958. }
  959. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  960. public Vector3 GetRegionMoonDir(float altitude)
  961. {
  962. return GetMoonDir(GetRegionEnvironment(), altitude);
  963. }
  964. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  965. public Quaternion GetRegionMoonRot(float altitude)
  966. {
  967. return GetMoonRot(GetRegionEnvironment(), altitude);
  968. }
  969. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  970. public int GetDayLength(Vector3 pos)
  971. {
  972. return GetEnvironment(pos.X, pos.Y).DayLength;
  973. }
  974. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  975. public int GetDayOffset(Vector3 pos)
  976. {
  977. return GetEnvironment(pos.X, pos.Y).DayOffset;
  978. }
  979. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  980. public Vector3 GetSunDir(Vector3 pos)
  981. {
  982. return GetSunDir(GetEnvironment(pos.X, pos.Y), pos.Z);
  983. }
  984. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  985. public Quaternion GetSunRot(Vector3 pos)
  986. {
  987. return GetSunRot(GetEnvironment(pos.X, pos.Y), pos.Z);
  988. }
  989. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  990. public Vector3 GetMoonDir(Vector3 pos)
  991. {
  992. return GetMoonDir(GetEnvironment(pos.X, pos.Y), pos.Z);
  993. }
  994. [System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.AggressiveInlining)]
  995. public Quaternion GetMoonRot(Vector3 pos)
  996. {
  997. return GetMoonRot(GetEnvironment(pos.X, pos.Y), pos.Z);
  998. }
  999. }
  1000. }