SunModule.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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.Reflection;
  30. using log4net;
  31. using Mono.Addins;
  32. using Nini.Config;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes;
  37. namespace OpenSim.Region.CoreModules
  38. {
  39. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SunModule")]
  40. public class SunModule : ISunModule
  41. {
  42. /// <summary>
  43. /// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock
  44. /// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise.
  45. /// </summary>
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. //
  48. // Global Constants used to determine where in the sky the sun is
  49. //
  50. private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees
  51. private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt
  52. private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians
  53. private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto
  54. //
  55. // Per Region Values
  56. //
  57. private bool ready = false;
  58. // This solves a chick before the egg problem
  59. // the local SunFixedHour and SunFixed variables MUST be updated
  60. // at least once with the proper Region Settings before we start
  61. // updating those region settings in GenSunPos()
  62. private bool receivedEstateToolsSunUpdate = false;
  63. // Sun's position information is updated and sent to clients every m_UpdateInterval frames
  64. private int m_UpdateInterval = 0;
  65. // Number of real time hours per virtual day
  66. private double m_DayLengthHours = 0;
  67. // Number of virtual days to a virtual year
  68. private int m_YearLengthDays = 0;
  69. // Ratio of Daylight hours to Night time hours. This is accomplished by shifting the
  70. // sun's orbit above the horizon
  71. private double m_HorizonShift = 0;
  72. // Used to scale current and positional time to adjust length of an hour during day vs night.
  73. private double m_DayTimeSunHourScale;
  74. // private double m_longitude = 0;
  75. // private double m_latitude = 0;
  76. // Configurable defaults Defaults close to SL
  77. private int d_frame_mod = 100; // Every 10 seconds (actually less)
  78. private double d_day_length = 4; // A VW day is 4 RW hours long
  79. private int d_year_length = 60; // There are 60 VW days in a VW year
  80. private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer
  81. private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal
  82. // private double d_longitude = -73.53;
  83. // private double d_latitude = 41.29;
  84. // Frame counter
  85. private uint m_frame = 0;
  86. // Cached Scene reference
  87. private Scene m_scene = null;
  88. // Calculated Once in the lifetime of a region
  89. private long TicksToEpoch; // Elapsed time for 1/1/1970
  90. private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds
  91. private uint SecondsPerYear; // Length of a virtual year in RW seconds
  92. private double SunSpeed; // Rate of passage in radians/second
  93. private double SeasonSpeed; // Rate of change for seasonal effects
  94. // private double HoursToRadians; // Rate of change for seasonal effects
  95. private long TicksUTCOffset = 0; // seconds offset from UTC
  96. // Calculated every update
  97. private float OrbitalPosition; // Orbital placement at a point in time
  98. private double HorizonShift; // Axis offset to skew day and night
  99. private double TotalDistanceTravelled; // Distance since beginning of time (in radians)
  100. private double SeasonalOffset; // Seaonal variation of tilt
  101. private float Magnitude; // Normal tilt
  102. // private double VWTimeRatio; // VW time as a ratio of real time
  103. // Working values
  104. private Vector3 Position = Vector3.Zero;
  105. private Vector3 Velocity = Vector3.Zero;
  106. private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
  107. // Used to fix the sun in the sky so it doesn't move based on current time
  108. private bool m_SunFixed = false;
  109. private float m_SunFixedHour = 0f;
  110. private const int TICKS_PER_SECOND = 10000000;
  111. private ulong m_CurrentTimeOffset = 0;
  112. // Current time in elapsed seconds since Jan 1st 1970
  113. private ulong CurrentTime
  114. {
  115. get
  116. {
  117. ulong ctime = (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND);
  118. return ctime + m_CurrentTimeOffset;
  119. }
  120. }
  121. // Time in seconds since UTC to use to calculate sun position.
  122. ulong PosTime = 0;
  123. /// <summary>
  124. /// Calculate the sun's orbital position and its velocity.
  125. /// </summary>
  126. private void GenSunPos()
  127. {
  128. // Time in seconds since UTC to use to calculate sun position.
  129. PosTime = CurrentTime;
  130. if (m_SunFixed)
  131. {
  132. // SunFixedHour represents the "hour of day" we would like
  133. // It's represented in 24hr time, with 0 hour being sun-rise
  134. // Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math
  135. // Determine the current "day" from current time, so we can use "today"
  136. // to determine Seasonal Tilt and what'not
  137. // Integer math rounded is on purpose to drop fractional day, determines number
  138. // of virtual days since Epoch
  139. PosTime = CurrentTime / SecondsPerSunCycle;
  140. // Since we want number of seconds since Epoch, multiply back up
  141. PosTime *= SecondsPerSunCycle;
  142. // Then offset by the current Fixed Sun Hour
  143. // Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle
  144. PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle);
  145. }
  146. else
  147. {
  148. if (m_DayTimeSunHourScale != 0.5f)
  149. {
  150. ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle;
  151. double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle;
  152. ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle);
  153. ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds;
  154. PosTime = CurrentTime / SecondsPerSunCycle;
  155. PosTime *= SecondsPerSunCycle;
  156. if (CurDayPercentage < 0.5)
  157. {
  158. PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds);
  159. }
  160. else
  161. {
  162. PosTime += DayLightSeconds;
  163. PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds);
  164. }
  165. }
  166. }
  167. TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians
  168. OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians
  169. // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
  170. // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
  171. SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle
  172. Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
  173. // m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
  174. // m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
  175. // The sun rotates about the Z axis
  176. Position.X = (float)Math.Cos(-TotalDistanceTravelled);
  177. Position.Y = (float)Math.Sin(-TotalDistanceTravelled);
  178. Position.Z = 0;
  179. // For interest we rotate it slightly about the X access.
  180. // Celestial tilt is a value that ranges .025
  181. Position *= Tilt;
  182. // Finally we shift the axis so that more of the
  183. // circle is above the horizon than below. This
  184. // makes the nights shorter than the days.
  185. Position = Vector3.Normalize(Position);
  186. Position.Z = Position.Z + (float)HorizonShift;
  187. Position = Vector3.Normalize(Position);
  188. // m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
  189. Velocity.X = 0;
  190. Velocity.Y = 0;
  191. Velocity.Z = (float)SunSpeed;
  192. // Correct angular velocity to reflect the seasonal rotation
  193. Magnitude = Position.Length();
  194. if (m_SunFixed)
  195. {
  196. Velocity.X = 0;
  197. Velocity.Y = 0;
  198. Velocity.Z = 0;
  199. }
  200. else
  201. {
  202. Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
  203. }
  204. // TODO: Decouple this, so we can get rid of Linden Hour info
  205. // Update Region with new Sun Vector
  206. // set estate settings for region access to sun position
  207. if (receivedEstateToolsSunUpdate)
  208. {
  209. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  210. }
  211. }
  212. private float GetCurrentTimeAsLindenSunHour()
  213. {
  214. float curtime = m_SunFixed ? m_SunFixedHour : GetCurrentSunHour();
  215. return (curtime + 6.0f) % 24.0f;
  216. }
  217. #region INonSharedRegion Methods
  218. // Called immediately after the module is loaded for a given region
  219. // i.e. Immediately after instance creation.
  220. public void Initialise(IConfigSource config)
  221. {
  222. m_frame = 0;
  223. // This one puts an entry in the main help screen
  224. // m_scene.AddCommand("Regions", this, "sun", "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null);
  225. TimeZone local = TimeZone.CurrentTimeZone;
  226. TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
  227. m_log.DebugFormat("[SUN]: localtime offset is {0}", TicksUTCOffset);
  228. // Align ticks with Second Life
  229. TicksToEpoch = new DateTime(1970, 1, 1).Ticks;
  230. // Just in case they don't have the stanzas
  231. try
  232. {
  233. // Mode: determines how the sun is handled
  234. // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
  235. // Mode: determines how the sun is handled
  236. // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
  237. // Year length in days
  238. m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length);
  239. // Day length in decimal hours
  240. m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length);
  241. // Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio
  242. // must hard code to ~.5 to match sun position in LL based viewers
  243. m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
  244. // Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours
  245. m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale);
  246. // Update frequency in frames
  247. m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
  248. }
  249. catch (Exception e)
  250. {
  251. m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message);
  252. m_YearLengthDays = d_year_length;
  253. m_DayLengthHours = d_day_length;
  254. m_HorizonShift = d_day_night;
  255. m_UpdateInterval = d_frame_mod;
  256. m_DayTimeSunHourScale = d_DayTimeSunHourScale;
  257. // m_latitude = d_latitude;
  258. // m_longitude = d_longitude;
  259. }
  260. SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
  261. SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
  262. // Ration of real-to-virtual time
  263. // VWTimeRatio = 24/m_day_length;
  264. // Speed of rotation needed to complete a cycle in the
  265. // designated period (day and season)
  266. SunSpeed = m_SunCycle/SecondsPerSunCycle;
  267. SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
  268. // Horizon translation
  269. HorizonShift = m_HorizonShift; // Z axis translation
  270. // HoursToRadians = (SunCycle/24)*VWTimeRatio;
  271. m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days");
  272. m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift);
  273. m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale);
  274. m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames");
  275. }
  276. public Type ReplaceableInterface
  277. {
  278. get { return null; }
  279. }
  280. public void AddRegion(Scene scene)
  281. {
  282. m_scene = scene;
  283. // Insert our event handling hooks
  284. scene.EventManager.OnFrame += SunUpdate;
  285. scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  286. scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate;
  287. scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour;
  288. scene.RegisterModuleInterface<ISunModule>(this);
  289. // This one enables the ability to type just "sun" without any parameters
  290. // m_scene.AddCommand("Regions", this, "sun", "", "", HandleSunConsoleCommand);
  291. foreach (KeyValuePair<string, string> kvp in GetParamList())
  292. {
  293. string sunCommand = string.Format("sun {0}", kvp.Key);
  294. m_scene.AddCommand("Regions", this, sunCommand, string.Format("{0} [<value>]", sunCommand), kvp.Value, "", HandleSunConsoleCommand);
  295. }
  296. m_scene.AddCommand("Regions", this, "sun help", "sun help", "list parameters that can be changed", "", HandleSunConsoleCommand);
  297. m_scene.AddCommand("Regions", this, "sun list", "sun list", "list parameters that can be changed", "", HandleSunConsoleCommand);
  298. ready = true;
  299. }
  300. public void RemoveRegion(Scene scene)
  301. {
  302. ready = false;
  303. // Remove our hooks
  304. m_scene.EventManager.OnFrame -= SunUpdate;
  305. m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
  306. m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate;
  307. m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour;
  308. }
  309. public void RegionLoaded(Scene scene)
  310. {
  311. }
  312. public void Close()
  313. {
  314. }
  315. public string Name
  316. {
  317. get { return "SunModule"; }
  318. }
  319. #endregion
  320. #region EventManager Events
  321. public void SunToClient(IClientAPI client)
  322. {
  323. if (ready)
  324. {
  325. if (m_SunFixed)
  326. {
  327. // m_log.DebugFormat("[SUN]: Fixed SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ",
  328. // m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
  329. client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  330. }
  331. else
  332. {
  333. // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ",
  334. // m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
  335. client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  336. }
  337. }
  338. }
  339. public void SunUpdate()
  340. {
  341. if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate)
  342. return;
  343. GenSunPos(); // Generate shared values once
  344. SunUpdateToAllClients();
  345. }
  346. /// <summary>
  347. /// When an avatar enters the region, it's probably a good idea to send them the current sun info
  348. /// </summary>
  349. /// <param name="avatar"></param>
  350. /// <param name="localLandID"></param>
  351. /// <param name="regionID"></param>
  352. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  353. {
  354. SunToClient(avatar.ControllingClient);
  355. }
  356. public void EstateToolsSunUpdate(ulong regionHandle)
  357. {
  358. if (m_scene.RegionInfo.RegionHandle == regionHandle)
  359. {
  360. float sunFixedHour;
  361. bool fixedSun;
  362. if (m_scene.RegionInfo.RegionSettings.UseEstateSun)
  363. {
  364. sunFixedHour = (float)m_scene.RegionInfo.EstateSettings.SunPosition;
  365. fixedSun = m_scene.RegionInfo.EstateSettings.FixedSun;
  366. }
  367. else
  368. {
  369. sunFixedHour = (float)m_scene.RegionInfo.RegionSettings.SunPosition - 6.0f;
  370. fixedSun = m_scene.RegionInfo.RegionSettings.FixedSun;
  371. }
  372. // Must limit the Sun Hour to 0 ... 24
  373. while (sunFixedHour > 24.0f)
  374. sunFixedHour -= 24;
  375. while (sunFixedHour < 0)
  376. sunFixedHour += 24;
  377. m_SunFixedHour = sunFixedHour;
  378. m_SunFixed = fixedSun;
  379. // m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString());
  380. // m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString());
  381. receivedEstateToolsSunUpdate = true;
  382. // Generate shared values
  383. GenSunPos();
  384. // When sun settings are updated, we should update all clients with new settings.
  385. SunUpdateToAllClients();
  386. // m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString());
  387. }
  388. }
  389. #endregion
  390. private void SunUpdateToAllClients()
  391. {
  392. m_scene.ForEachRootClient(delegate(IClientAPI client)
  393. {
  394. SunToClient(client);
  395. });
  396. }
  397. #region ISunModule Members
  398. public double GetSunParameter(string param)
  399. {
  400. switch (param.ToLower())
  401. {
  402. case "year_length":
  403. return m_YearLengthDays;
  404. case "day_length":
  405. return m_DayLengthHours;
  406. case "day_night_offset":
  407. return m_HorizonShift;
  408. case "day_time_sun_hour_scale":
  409. return m_DayTimeSunHourScale;
  410. case "update_interval":
  411. return m_UpdateInterval;
  412. case "current_time":
  413. return GetCurrentTimeAsLindenSunHour();
  414. default:
  415. throw new Exception("Unknown sun parameter.");
  416. }
  417. }
  418. public void SetSunParameter(string param, double value)
  419. {
  420. switch (param)
  421. {
  422. case "year_length":
  423. m_YearLengthDays = (int)value;
  424. SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
  425. SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
  426. break;
  427. case "day_length":
  428. m_DayLengthHours = value;
  429. SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
  430. SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
  431. SunSpeed = m_SunCycle/SecondsPerSunCycle;
  432. SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
  433. break;
  434. case "day_night_offset":
  435. m_HorizonShift = value;
  436. HorizonShift = m_HorizonShift;
  437. break;
  438. case "day_time_sun_hour_scale":
  439. m_DayTimeSunHourScale = value;
  440. break;
  441. case "update_interval":
  442. m_UpdateInterval = (int)value;
  443. break;
  444. case "current_time":
  445. value = (value + 18.0) % 24.0;
  446. // set the current offset so that the effective sun time is the parameter
  447. m_CurrentTimeOffset = 0; // clear this first so we use raw time
  448. m_CurrentTimeOffset = (ulong)(SecondsPerSunCycle * value/ 24.0) - (CurrentTime % SecondsPerSunCycle);
  449. break;
  450. default:
  451. throw new Exception("Unknown sun parameter.");
  452. // Generate shared values
  453. GenSunPos();
  454. // When sun settings are updated, we should update all clients with new settings.
  455. SunUpdateToAllClients();
  456. }
  457. }
  458. public float GetCurrentSunHour()
  459. {
  460. float ticksleftover = CurrentTime % SecondsPerSunCycle;
  461. return (24.0f * (ticksleftover / SecondsPerSunCycle));
  462. }
  463. #endregion
  464. public void HandleSunConsoleCommand(string module, string[] cmdparams)
  465. {
  466. if (m_scene.ConsoleScene() == null)
  467. {
  468. // FIXME: If console region is root then this will be printed by every module. Currently, there is no
  469. // way to prevent this, short of making the entire module shared (which is complete overkill).
  470. // One possibility is to return a bool to signal whether the module has completely handled the command
  471. m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters.");
  472. return;
  473. }
  474. if (m_scene.ConsoleScene() != m_scene)
  475. {
  476. m_log.InfoFormat("[Sun]: Console Scene is not my scene.");
  477. return;
  478. }
  479. m_log.InfoFormat("[Sun]: Processing command.");
  480. foreach (string output in ParseCmdParams(cmdparams))
  481. {
  482. MainConsole.Instance.Output(output);
  483. }
  484. }
  485. private Dictionary<string, string> GetParamList()
  486. {
  487. Dictionary<string, string> Params = new Dictionary<string, string>();
  488. Params.Add("year_length", "number of days to a year");
  489. Params.Add("day_length", "number of hours to a day");
  490. Params.Add("day_night_offset", "induces a horizon shift");
  491. Params.Add("update_interval", "how often to update the sun's position in frames");
  492. Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio");
  493. Params.Add("current_time", "time in seconds of the simulator");
  494. return Params;
  495. }
  496. private List<string> ParseCmdParams(string[] args)
  497. {
  498. List<string> Output = new List<string>();
  499. if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list"))
  500. {
  501. Output.Add("The following parameters can be changed or viewed:");
  502. foreach (KeyValuePair<string, string> kvp in GetParamList())
  503. {
  504. Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value));
  505. }
  506. return Output;
  507. }
  508. if (args.Length == 2)
  509. {
  510. try
  511. {
  512. double value = GetSunParameter(args[1]);
  513. Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString()));
  514. }
  515. catch (Exception)
  516. {
  517. Output.Add(String.Format("Unknown parameter {0}.", args[1]));
  518. }
  519. }
  520. else if (args.Length == 3)
  521. {
  522. double value = 0.0;
  523. if (! double.TryParse(args[2], out value))
  524. {
  525. Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2]));
  526. return Output;
  527. }
  528. SetSunParameter(args[1].ToLower(), value);
  529. Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString()));
  530. }
  531. return Output;
  532. }
  533. }
  534. }