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