SunModule.cs 26 KB

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