WindModule.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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. using OpenSim.Region.CoreModules.World.Wind;
  38. namespace OpenSim.Region.CoreModules
  39. {
  40. public class WindModule : IWindModule
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. private uint m_frame = 0;
  44. private uint m_frameLastUpdateClientArray = 0;
  45. private int m_frameUpdateRate = 150;
  46. //private Random m_rndnums = new Random(Environment.TickCount);
  47. private Scene m_scene = null;
  48. private bool m_ready = false;
  49. private bool m_enabled = false;
  50. private IWindModelPlugin m_activeWindPlugin = null;
  51. private const string m_dWindPluginName = "SimpleRandomWind";
  52. private Dictionary<string, IWindModelPlugin> m_availableWindPlugins = new Dictionary<string, IWindModelPlugin>();
  53. // Simplified windSpeeds based on the fact that the client protocal tracks at a resolution of 16m
  54. private Vector2[] windSpeeds = new Vector2[16 * 16];
  55. #region IRegion Methods
  56. public void Initialise(Scene scene, IConfigSource config)
  57. {
  58. IConfig windConfig = config.Configs["Wind"];
  59. string desiredWindPlugin = m_dWindPluginName;
  60. if (windConfig != null)
  61. {
  62. m_enabled = windConfig.GetBoolean("enabled", true);
  63. m_frameUpdateRate = windConfig.GetInt("wind_update_rate", 150);
  64. // Determine which wind model plugin is desired
  65. if (windConfig.Contains("wind_plugin"))
  66. {
  67. desiredWindPlugin = windConfig.GetString("wind_plugin");
  68. }
  69. }
  70. if (m_enabled)
  71. {
  72. m_log.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate);
  73. m_scene = scene;
  74. m_frame = 0;
  75. // Register all the Wind Model Plug-ins
  76. foreach (IWindModelPlugin windPlugin in AddinManager.GetExtensionObjects("/OpenSim/WindModule", false))
  77. {
  78. m_log.InfoFormat("[WIND] Found Plugin: {0}", windPlugin.Name);
  79. m_availableWindPlugins.Add(windPlugin.Name, windPlugin);
  80. }
  81. // Check for desired plugin
  82. if (m_availableWindPlugins.ContainsKey(desiredWindPlugin))
  83. {
  84. m_activeWindPlugin = m_availableWindPlugins[desiredWindPlugin];
  85. m_log.InfoFormat("[WIND] {0} plugin found, initializing.", desiredWindPlugin);
  86. if (windConfig != null)
  87. {
  88. m_activeWindPlugin.Initialise();
  89. m_activeWindPlugin.WindConfig(m_scene, windConfig);
  90. }
  91. }
  92. // if the plug-in wasn't found, default to no wind.
  93. if (m_activeWindPlugin == null)
  94. {
  95. m_log.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", desiredWindPlugin);
  96. m_log.ErrorFormat("[WIND] Defaulting to no wind.");
  97. }
  98. // This one puts an entry in the main help screen
  99. m_scene.AddCommand(this, String.Empty, "wind", "Usage: wind <plugin> <param> [value] - Get or Update Wind paramaters", null);
  100. // This one enables the ability to type just the base command without any parameters
  101. m_scene.AddCommand(this, "wind", "", "", HandleConsoleCommand);
  102. // Get a list of the parameters for each plugin
  103. foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
  104. {
  105. m_scene.AddCommand(this, String.Format("wind base wind_plugin {0}", windPlugin.Name), String.Format("{0} - {1}", windPlugin.Name, windPlugin.Description), "", HandleConsoleBaseCommand);
  106. m_scene.AddCommand(this, String.Format("wind base wind_update_rate"), "Change the wind update rate.", "", HandleConsoleBaseCommand);
  107. foreach (KeyValuePair<string, string> kvp in windPlugin.WindParams())
  108. {
  109. m_scene.AddCommand(this, String.Format("wind {0} {1}", windPlugin.Name, kvp.Key), String.Format("{0} : {1} - {2}", windPlugin.Name, kvp.Key, kvp.Value), "", HandleConsoleParamCommand);
  110. }
  111. }
  112. // Register event handlers for when Avatars enter the region, and frame ticks
  113. m_scene.EventManager.OnFrame += WindUpdate;
  114. m_scene.EventManager.OnMakeRootAgent += OnAgentEnteredRegion;
  115. // Register the wind module
  116. m_scene.RegisterModuleInterface<IWindModule>(this);
  117. // Generate initial wind values
  118. GenWindPos();
  119. // Mark Module Ready for duty
  120. m_ready = true;
  121. }
  122. }
  123. public void PostInitialise()
  124. {
  125. }
  126. public void Close()
  127. {
  128. if (m_enabled)
  129. {
  130. m_ready = false;
  131. // REVIEW: If a region module is closed, is there a possibility that it'll re-open/initialize ??
  132. m_activeWindPlugin = null;
  133. foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
  134. {
  135. windPlugin.Dispose();
  136. }
  137. m_availableWindPlugins.Clear();
  138. // Remove our hooks
  139. m_scene.EventManager.OnFrame -= WindUpdate;
  140. m_scene.EventManager.OnMakeRootAgent -= OnAgentEnteredRegion;
  141. }
  142. }
  143. public string Name
  144. {
  145. get { return "WindModule"; }
  146. }
  147. public bool IsSharedModule
  148. {
  149. get { return false; }
  150. }
  151. #endregion
  152. #region Console Commands
  153. private void ValidateConsole()
  154. {
  155. if (m_scene.ConsoleScene() == null)
  156. {
  157. // FIXME: If console region is root then this will be printed by every module. Currently, there is no
  158. // way to prevent this, short of making the entire module shared (which is complete overkill).
  159. // One possibility is to return a bool to signal whether the module has completely handled the command
  160. m_log.InfoFormat("[WIND]: Please change to a specific region in order to set Sun parameters.");
  161. return;
  162. }
  163. if (m_scene.ConsoleScene() != m_scene)
  164. {
  165. m_log.InfoFormat("[WIND]: Console Scene is not my scene.");
  166. return;
  167. }
  168. }
  169. /// <summary>
  170. /// Base console command handler, only used if a person specifies the base command with now options
  171. /// </summary>
  172. private void HandleConsoleCommand(string module, string[] cmdparams)
  173. {
  174. ValidateConsole();
  175. m_log.Info("[WIND] The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins.");
  176. }
  177. /// <summary>
  178. /// Called to change the active wind model plugin
  179. /// </summary>
  180. private void HandleConsoleBaseCommand(string module, string[] cmdparams)
  181. {
  182. ValidateConsole();
  183. if ((cmdparams.Length != 4)
  184. || !cmdparams[1].Equals("base"))
  185. {
  186. m_log.Info("[WIND] Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>");
  187. return;
  188. }
  189. switch (cmdparams[2])
  190. {
  191. case "wind_update_rate":
  192. int newRate = 1;
  193. if (int.TryParse(cmdparams[3], out newRate))
  194. {
  195. m_frameUpdateRate = newRate;
  196. }
  197. else
  198. {
  199. m_log.InfoFormat("[WIND] Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]);
  200. return;
  201. }
  202. break;
  203. case "wind_plugin":
  204. string desiredPlugin = cmdparams[3];
  205. if (desiredPlugin.Equals(m_activeWindPlugin.Name))
  206. {
  207. m_log.InfoFormat("[WIND] Wind model plugin {0} is already active", cmdparams[3]);
  208. return;
  209. }
  210. if (m_availableWindPlugins.ContainsKey(desiredPlugin))
  211. {
  212. m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]];
  213. m_log.InfoFormat("[WIND] {0} wind model plugin now active", m_activeWindPlugin.Name);
  214. }
  215. else
  216. {
  217. m_log.InfoFormat("[WIND] Could not find wind model plugin {0}", desiredPlugin);
  218. }
  219. break;
  220. }
  221. }
  222. /// <summary>
  223. /// Called to change plugin parameters.
  224. /// </summary>
  225. private void HandleConsoleParamCommand(string module, string[] cmdparams)
  226. {
  227. ValidateConsole();
  228. // wind <plugin> <param> [value]
  229. if ((cmdparams.Length != 4)
  230. && (cmdparams.Length != 3))
  231. {
  232. m_log.Info("[WIND] Usage: wind <plugin> <param> [value]");
  233. return;
  234. }
  235. string plugin = cmdparams[1];
  236. string param = cmdparams[2];
  237. float value = 0f;
  238. if (cmdparams.Length == 4)
  239. {
  240. if (!float.TryParse(cmdparams[3], out value))
  241. {
  242. m_log.InfoFormat("[WIND] Invalid value {0}", cmdparams[3]);
  243. }
  244. try
  245. {
  246. WindParamSet(plugin, param, value);
  247. }
  248. catch (Exception e)
  249. {
  250. m_log.InfoFormat("[WIND] {0}", e.Message);
  251. }
  252. }
  253. else
  254. {
  255. try
  256. {
  257. value = WindParamGet(plugin, param);
  258. m_log.InfoFormat("[WIND] {0} : {1}", param, value);
  259. }
  260. catch (Exception e)
  261. {
  262. m_log.InfoFormat("[WIND] {0}", e.Message);
  263. }
  264. }
  265. }
  266. #endregion
  267. #region IWindModule Methods
  268. /// <summary>
  269. /// Retrieve the wind speed at the given region coordinate. This
  270. /// implimentation ignores Z.
  271. /// </summary>
  272. /// <param name="x">0...255</param>
  273. /// <param name="y">0...255</param>
  274. public Vector3 WindSpeed(int x, int y, int z)
  275. {
  276. if (m_activeWindPlugin != null)
  277. {
  278. return m_activeWindPlugin.WindSpeed(x, y, z);
  279. }
  280. else
  281. {
  282. return new Vector3(0.0f, 0.0f, 0.0f);
  283. }
  284. }
  285. public void WindParamSet(string plugin, string param, float value)
  286. {
  287. if (m_availableWindPlugins.ContainsKey(plugin))
  288. {
  289. IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
  290. windPlugin.WindParamSet(param, value);
  291. m_log.InfoFormat("[WIND] {0} set to {1}", param, value);
  292. }
  293. else
  294. {
  295. throw new Exception(String.Format("Could not find plugin {0}", plugin));
  296. }
  297. }
  298. public float WindParamGet(string plugin, string param)
  299. {
  300. if (m_availableWindPlugins.ContainsKey(plugin))
  301. {
  302. IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
  303. return windPlugin.WindParamGet(param);
  304. }
  305. else
  306. {
  307. throw new Exception(String.Format("Could not find plugin {0}", plugin));
  308. }
  309. }
  310. public string WindActiveModelPluginName
  311. {
  312. get
  313. {
  314. if (m_activeWindPlugin != null)
  315. {
  316. return m_activeWindPlugin.Name;
  317. }
  318. else
  319. {
  320. return String.Empty;
  321. }
  322. }
  323. }
  324. #endregion
  325. /// <summary>
  326. /// Called on each frame update. Updates the wind model and clients as necessary.
  327. /// </summary>
  328. public void WindUpdate()
  329. {
  330. if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready)
  331. {
  332. return;
  333. }
  334. GenWindPos();
  335. SendWindAllClients();
  336. }
  337. public void OnAgentEnteredRegion(ScenePresence avatar)
  338. {
  339. if (m_ready)
  340. {
  341. if (m_activeWindPlugin != null)
  342. {
  343. // Ask wind plugin to generate a LL wind array to be cached locally
  344. // Try not to update this too often, as it may involve array copies
  345. if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
  346. {
  347. windSpeeds = m_activeWindPlugin.WindLLClientArray();
  348. m_frameLastUpdateClientArray = m_frame;
  349. }
  350. }
  351. avatar.ControllingClient.SendWindData(windSpeeds);
  352. }
  353. }
  354. private void SendWindAllClients()
  355. {
  356. if (m_ready)
  357. {
  358. if(m_scene.GetRootAgentCount() > 0)
  359. {
  360. // Ask wind plugin to generate a LL wind array to be cached locally
  361. // Try not to update this too often, as it may involve array copies
  362. if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
  363. {
  364. windSpeeds = m_activeWindPlugin.WindLLClientArray();
  365. m_frameLastUpdateClientArray = m_frame;
  366. }
  367. m_scene.ForEachScenePresence(delegate(ScenePresence sp)
  368. {
  369. if (!sp.IsChildAgent)
  370. sp.ControllingClient.SendWindData(windSpeeds);
  371. });
  372. }
  373. }
  374. }
  375. /// <summary>
  376. /// Calculate the sun's orbital position and its velocity.
  377. /// </summary>
  378. private void GenWindPos()
  379. {
  380. if (m_activeWindPlugin != null)
  381. {
  382. // Tell Wind Plugin to update it's wind data
  383. m_activeWindPlugin.WindUpdate(m_frame);
  384. }
  385. }
  386. }
  387. }