1
0

WindModule.cs 16 KB

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