EnvironmentModule.cs 44 KB

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