SunModule.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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 with new Sun Vector
  207. // set estate settings for region access to sun position
  208. if (receivedEstateToolsSunUpdate)
  209. {
  210. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  211. }
  212. }
  213. private float GetCurrentTimeAsLindenSunHour()
  214. {
  215. if (m_SunFixed)
  216. return m_SunFixedHour + 6;
  217. return GetCurrentSunHour() + 6.0f;
  218. }
  219. #region INonSharedRegion Methods
  220. // Called immediately after the module is loaded for a given region
  221. // i.e. Immediately after instance creation.
  222. public void Initialise(IConfigSource config)
  223. {
  224. m_frame = 0;
  225. // This one puts an entry in the main help screen
  226. // m_scene.AddCommand("Regions", this, "sun", "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null);
  227. TimeZone local = TimeZone.CurrentTimeZone;
  228. TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
  229. m_log.DebugFormat("[SUN]: localtime offset is {0}", TicksUTCOffset);
  230. // Align ticks with Second Life
  231. TicksToEpoch = new DateTime(1970, 1, 1).Ticks;
  232. // Just in case they don't have the stanzas
  233. try
  234. {
  235. // Mode: determines how the sun is handled
  236. m_RegionMode = config.Configs["Sun"].GetString("mode", d_mode);
  237. // Mode: determines how the sun is handled
  238. // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
  239. // Mode: determines how the sun is handled
  240. // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
  241. // Year length in days
  242. m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length);
  243. // Day length in decimal hours
  244. m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length);
  245. // Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio
  246. // must hard code to ~.5 to match sun position in LL based viewers
  247. m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
  248. // Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours
  249. m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale);
  250. // Update frequency in frames
  251. m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
  252. }
  253. catch (Exception e)
  254. {
  255. m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message);
  256. m_RegionMode = d_mode;
  257. m_YearLengthDays = d_year_length;
  258. m_DayLengthHours = d_day_length;
  259. m_HorizonShift = d_day_night;
  260. m_UpdateInterval = d_frame_mod;
  261. m_DayTimeSunHourScale = d_DayTimeSunHourScale;
  262. // m_latitude = d_latitude;
  263. // m_longitude = d_longitude;
  264. }
  265. switch (m_RegionMode)
  266. {
  267. case "T1":
  268. default:
  269. case "SL":
  270. // Time taken to complete a cycle (day and season)
  271. SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
  272. SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
  273. // Ration of real-to-virtual time
  274. // VWTimeRatio = 24/m_day_length;
  275. // Speed of rotation needed to complete a cycle in the
  276. // designated period (day and season)
  277. SunSpeed = m_SunCycle/SecondsPerSunCycle;
  278. SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
  279. // Horizon translation
  280. HorizonShift = m_HorizonShift; // Z axis translation
  281. // HoursToRadians = (SunCycle/24)*VWTimeRatio;
  282. m_log.Debug("[SUN]: Mode is " + m_RegionMode);
  283. m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days");
  284. m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift);
  285. m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale);
  286. m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames");
  287. break;
  288. }
  289. }
  290. public Type ReplaceableInterface
  291. {
  292. get { return null; }
  293. }
  294. public void AddRegion(Scene scene)
  295. {
  296. m_scene = scene;
  297. // Insert our event handling hooks
  298. scene.EventManager.OnFrame += SunUpdate;
  299. scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  300. scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate;
  301. scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour;
  302. scene.RegisterModuleInterface<ISunModule>(this);
  303. // This one enables the ability to type just "sun" without any parameters
  304. // m_scene.AddCommand("Regions", this, "sun", "", "", HandleSunConsoleCommand);
  305. foreach (KeyValuePair<string, string> kvp in GetParamList())
  306. {
  307. string sunCommand = string.Format("sun {0}", kvp.Key);
  308. m_scene.AddCommand("Regions", this, sunCommand, string.Format("{0} [<value>]", sunCommand), kvp.Value, "", HandleSunConsoleCommand);
  309. }
  310. ready = true;
  311. }
  312. public void RemoveRegion(Scene scene)
  313. {
  314. ready = false;
  315. // Remove our hooks
  316. m_scene.EventManager.OnFrame -= SunUpdate;
  317. m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
  318. m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate;
  319. m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour;
  320. }
  321. public void RegionLoaded(Scene scene)
  322. {
  323. }
  324. public void Close()
  325. {
  326. }
  327. public string Name
  328. {
  329. get { return "SunModule"; }
  330. }
  331. #endregion
  332. #region EventManager Events
  333. public void SunToClient(IClientAPI client)
  334. {
  335. if (m_RegionMode != "T1")
  336. {
  337. if (ready)
  338. {
  339. if (m_SunFixed)
  340. {
  341. // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
  342. client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  343. }
  344. else
  345. {
  346. // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
  347. client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  348. }
  349. }
  350. }
  351. }
  352. public void SunUpdate()
  353. {
  354. if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate)
  355. return;
  356. GenSunPos(); // Generate shared values once
  357. SunUpdateToAllClients();
  358. }
  359. /// <summary>
  360. /// When an avatar enters the region, it's probably a good idea to send them the current sun info
  361. /// </summary>
  362. /// <param name="avatar"></param>
  363. /// <param name="localLandID"></param>
  364. /// <param name="regionID"></param>
  365. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  366. {
  367. SunToClient(avatar.ControllingClient);
  368. }
  369. public void EstateToolsSunUpdate(ulong regionHandle)
  370. {
  371. if (m_scene.RegionInfo.RegionHandle == regionHandle)
  372. {
  373. float sunFixedHour;
  374. bool fixedSun;
  375. if (m_scene.RegionInfo.RegionSettings.UseEstateSun)
  376. {
  377. sunFixedHour = (float)m_scene.RegionInfo.EstateSettings.SunPosition;
  378. fixedSun = m_scene.RegionInfo.EstateSettings.FixedSun;
  379. }
  380. else
  381. {
  382. sunFixedHour = (float)m_scene.RegionInfo.RegionSettings.SunPosition - 6.0f;
  383. fixedSun = m_scene.RegionInfo.RegionSettings.FixedSun;
  384. }
  385. // Must limit the Sun Hour to 0 ... 24
  386. while (sunFixedHour > 24.0f)
  387. sunFixedHour -= 24;
  388. while (sunFixedHour < 0)
  389. sunFixedHour += 24;
  390. m_SunFixedHour = sunFixedHour;
  391. m_SunFixed = fixedSun;
  392. // m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString());
  393. // m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString());
  394. receivedEstateToolsSunUpdate = true;
  395. // Generate shared values
  396. GenSunPos();
  397. // When sun settings are updated, we should update all clients with new settings.
  398. SunUpdateToAllClients();
  399. // m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString());
  400. }
  401. }
  402. #endregion
  403. private void SunUpdateToAllClients()
  404. {
  405. m_scene.ForEachRootClient(delegate(IClientAPI client)
  406. {
  407. SunToClient(client);
  408. });
  409. }
  410. #region ISunModule Members
  411. public double GetSunParameter(string param)
  412. {
  413. switch (param.ToLower())
  414. {
  415. case "year_length":
  416. return m_YearLengthDays;
  417. case "day_length":
  418. return m_DayLengthHours;
  419. case "day_night_offset":
  420. return m_HorizonShift;
  421. case "day_time_sun_hour_scale":
  422. return m_DayTimeSunHourScale;
  423. case "update_interval":
  424. return m_UpdateInterval;
  425. default:
  426. throw new Exception("Unknown sun parameter.");
  427. }
  428. }
  429. public void SetSunParameter(string param, double value)
  430. {
  431. HandleSunConsoleCommand("sun", new string[] {param, value.ToString() });
  432. }
  433. public float GetCurrentSunHour()
  434. {
  435. float ticksleftover = CurrentTime % SecondsPerSunCycle;
  436. return (24.0f * (ticksleftover / SecondsPerSunCycle));
  437. }
  438. #endregion
  439. public void HandleSunConsoleCommand(string module, string[] cmdparams)
  440. {
  441. if (m_scene.ConsoleScene() == null)
  442. {
  443. // FIXME: If console region is root then this will be printed by every module. Currently, there is no
  444. // way to prevent this, short of making the entire module shared (which is complete overkill).
  445. // One possibility is to return a bool to signal whether the module has completely handled the command
  446. m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters.");
  447. return;
  448. }
  449. if (m_scene.ConsoleScene() != m_scene)
  450. {
  451. m_log.InfoFormat("[Sun]: Console Scene is not my scene.");
  452. return;
  453. }
  454. m_log.InfoFormat("[Sun]: Processing command.");
  455. foreach (string output in ParseCmdParams(cmdparams))
  456. {
  457. m_log.Info("[SUN] " + output);
  458. }
  459. }
  460. private Dictionary<string, string> GetParamList()
  461. {
  462. Dictionary<string, string> Params = new Dictionary<string, string>();
  463. Params.Add("year_length", "number of days to a year");
  464. Params.Add("day_length", "number of seconds to a day");
  465. Params.Add("day_night_offset", "induces a horizon shift");
  466. Params.Add("update_interval", "how often to update the sun's position in frames");
  467. Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio");
  468. return Params;
  469. }
  470. private List<string> ParseCmdParams(string[] args)
  471. {
  472. List<string> Output = new List<string>();
  473. if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list"))
  474. {
  475. Output.Add("The following parameters can be changed or viewed:");
  476. foreach (KeyValuePair<string, string> kvp in GetParamList())
  477. {
  478. Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value));
  479. }
  480. return Output;
  481. }
  482. if (args.Length == 2)
  483. {
  484. try
  485. {
  486. double value = GetSunParameter(args[1]);
  487. Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString()));
  488. }
  489. catch (Exception)
  490. {
  491. Output.Add(String.Format("Unknown parameter {0}.", args[1]));
  492. }
  493. }
  494. else if (args.Length == 3)
  495. {
  496. float value = 0.0f;
  497. if (!float.TryParse(args[2], out value))
  498. {
  499. Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2]));
  500. }
  501. switch (args[1].ToLower())
  502. {
  503. case "year_length":
  504. m_YearLengthDays = (int)value;
  505. break;
  506. case "day_length":
  507. m_DayLengthHours = value;
  508. break;
  509. case "day_night_offset":
  510. m_HorizonShift = value;
  511. break;
  512. case "day_time_sun_hour_scale":
  513. m_DayTimeSunHourScale = value;
  514. break;
  515. case "update_interval":
  516. m_UpdateInterval = (int)value;
  517. break;
  518. default:
  519. Output.Add(String.Format("Unknown parameter {0}.", args[1]));
  520. return Output;
  521. }
  522. Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString()));
  523. // Generate shared values
  524. GenSunPos();
  525. // When sun settings are updated, we should update all clients with new settings.
  526. SunUpdateToAllClients();
  527. }
  528. return Output;
  529. }
  530. }
  531. }