SunModule.cs 26 KB

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