TreePopulatorModule.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 System.Timers;
  31. using OpenMetaverse;
  32. using log4net;
  33. using Nini.Config;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using System.Xml;
  39. using System.Xml.Serialization;
  40. using System.IO;
  41. namespace OpenSim.Region.OptionalModules.World.TreePopulator
  42. {
  43. /// <summary>
  44. /// Version 2.02 - Still hacky
  45. /// </summary>
  46. public class TreePopulatorModule : IRegionModule, ICommandableModule, IVegetationModule
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private readonly Commander m_commander = new Commander("tree");
  50. private Scene m_scene;
  51. [XmlRootAttribute(ElementName = "Copse", IsNullable = false)]
  52. public class Copse
  53. {
  54. public string m_name;
  55. public Boolean m_frozen;
  56. public Tree m_tree_type;
  57. public int m_tree_quantity;
  58. public float m_treeline_low;
  59. public float m_treeline_high;
  60. public Vector3 m_seed_point;
  61. public double m_range;
  62. public Vector3 m_initial_scale;
  63. public Vector3 m_maximum_scale;
  64. public Vector3 m_rate;
  65. [XmlIgnore]
  66. public Boolean m_planted;
  67. [XmlIgnore]
  68. public List<UUID> m_trees;
  69. public Copse()
  70. {
  71. }
  72. public Copse(string fileName, Boolean planted)
  73. {
  74. Copse cp = (Copse)DeserializeObject(fileName);
  75. this.m_name = cp.m_name;
  76. this.m_frozen = cp.m_frozen;
  77. this.m_tree_quantity = cp.m_tree_quantity;
  78. this.m_treeline_high = cp.m_treeline_high;
  79. this.m_treeline_low = cp.m_treeline_low;
  80. this.m_range = cp.m_range;
  81. this.m_tree_type = cp.m_tree_type;
  82. this.m_seed_point = cp.m_seed_point;
  83. this.m_initial_scale = cp.m_initial_scale;
  84. this.m_maximum_scale = cp.m_maximum_scale;
  85. this.m_initial_scale = cp.m_initial_scale;
  86. this.m_rate = cp.m_rate;
  87. this.m_planted = planted;
  88. this.m_trees = new List<UUID>();
  89. }
  90. public Copse(string copsedef)
  91. {
  92. char[] delimiterChars = {':', ';'};
  93. string[] field = copsedef.Split(delimiterChars);
  94. this.m_name = field[1].Trim();
  95. this.m_frozen = (copsedef[0] == 'F');
  96. this.m_tree_quantity = int.Parse(field[2]);
  97. this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
  98. this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
  99. this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
  100. this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
  101. this.m_seed_point = Vector3.Parse(field[7]);
  102. this.m_initial_scale = Vector3.Parse(field[8]);
  103. this.m_maximum_scale = Vector3.Parse(field[9]);
  104. this.m_rate = Vector3.Parse(field[10]);
  105. this.m_planted = true;
  106. this.m_trees = new List<UUID>();
  107. }
  108. public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees)
  109. {
  110. this.m_name = name;
  111. this.m_frozen = false;
  112. this.m_tree_quantity = quantity;
  113. this.m_treeline_high = high;
  114. this.m_treeline_low = low;
  115. this.m_range = range;
  116. this.m_tree_type = type;
  117. this.m_seed_point = point;
  118. this.m_initial_scale = scale;
  119. this.m_maximum_scale = max_scale;
  120. this.m_rate = rate;
  121. this.m_planted = false;
  122. this.m_trees = trees;
  123. }
  124. public override string ToString()
  125. {
  126. string frozen = (this.m_frozen ? "F" : "A");
  127. return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
  128. frozen,
  129. this.m_name,
  130. this.m_tree_quantity,
  131. this.m_treeline_high,
  132. this.m_treeline_low,
  133. this.m_range,
  134. this.m_tree_type,
  135. this.m_seed_point.ToString(),
  136. this.m_initial_scale.ToString(),
  137. this.m_maximum_scale.ToString(),
  138. this.m_rate.ToString());
  139. }
  140. }
  141. private List<Copse> m_copse;
  142. private double m_update_ms = 1000.0; // msec between updates
  143. private bool m_active_trees = false;
  144. Timer CalculateTrees;
  145. #region ICommandableModule Members
  146. public ICommander CommandInterface
  147. {
  148. get { return m_commander; }
  149. }
  150. #endregion
  151. #region IRegionModule Members
  152. public void Initialise(Scene scene, IConfigSource config)
  153. {
  154. m_scene = scene;
  155. m_scene.RegisterModuleInterface<IRegionModule>(this);
  156. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  157. // ini file settings
  158. try
  159. {
  160. m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
  161. }
  162. catch (Exception)
  163. {
  164. m_log.Debug("[TREES]: ini failure for active_trees - using default");
  165. }
  166. try
  167. {
  168. m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
  169. }
  170. catch (Exception)
  171. {
  172. m_log.Debug("[TREES]: ini failure for update_rate - using default");
  173. }
  174. InstallCommands();
  175. m_log.Debug("[TREES]: Initialised tree module");
  176. }
  177. public void PostInitialise()
  178. {
  179. ReloadCopse();
  180. if (m_copse.Count > 0)
  181. m_log.Info("[TREES]: Copse load complete");
  182. if (m_active_trees)
  183. activeizeTreeze(true);
  184. }
  185. public void Close()
  186. {
  187. }
  188. public string Name
  189. {
  190. get { return "TreePopulatorModule"; }
  191. }
  192. public bool IsSharedModule
  193. {
  194. get { return false; }
  195. }
  196. #endregion
  197. //--------------------------------------------------------------
  198. #region ICommandableModule Members
  199. private void HandleTreeActive(Object[] args)
  200. {
  201. if ((Boolean)args[0] && !m_active_trees)
  202. {
  203. m_log.InfoFormat("[TREES]: Activating Trees");
  204. m_active_trees = true;
  205. activeizeTreeze(m_active_trees);
  206. }
  207. else if (!(Boolean)args[0] && m_active_trees)
  208. {
  209. m_log.InfoFormat("[TREES]: Trees module is no longer active");
  210. m_active_trees = false;
  211. activeizeTreeze(m_active_trees);
  212. }
  213. else
  214. {
  215. m_log.InfoFormat("[TREES]: Trees module is already in the required state");
  216. }
  217. }
  218. private void HandleTreeFreeze(Object[] args)
  219. {
  220. string copsename = ((string)args[0]).Trim();
  221. Boolean freezeState = (Boolean) args[1];
  222. foreach (Copse cp in m_copse)
  223. {
  224. if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
  225. {
  226. cp.m_frozen = freezeState;
  227. foreach (UUID tree in cp.m_trees)
  228. {
  229. SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  230. sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
  231. sop.ParentGroup.HasGroupChanged = true;
  232. }
  233. m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
  234. return;
  235. }
  236. else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
  237. {
  238. m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
  239. return;
  240. }
  241. }
  242. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  243. }
  244. private void HandleTreeLoad(Object[] args)
  245. {
  246. Copse copse;
  247. m_log.InfoFormat("[TREES]: Loading copse definition....");
  248. copse = new Copse(((string)args[0]), false);
  249. foreach (Copse cp in m_copse)
  250. {
  251. if (cp.m_name == copse.m_name)
  252. {
  253. m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
  254. return;
  255. }
  256. }
  257. m_copse.Add(copse);
  258. m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
  259. }
  260. private void HandleTreePlant(Object[] args)
  261. {
  262. string copsename = ((string)args[0]).Trim();
  263. m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
  264. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  265. foreach (Copse copse in m_copse)
  266. {
  267. if (copse.m_name == copsename)
  268. {
  269. if (!copse.m_planted)
  270. {
  271. // The first tree for a copse is created here
  272. CreateTree(uuid, copse, copse.m_seed_point);
  273. copse.m_planted = true;
  274. return;
  275. }
  276. else
  277. {
  278. m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
  279. }
  280. }
  281. }
  282. m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename);
  283. }
  284. private void HandleTreeRate(Object[] args)
  285. {
  286. m_update_ms = (double)args[0];
  287. if (m_update_ms >= 1000.0)
  288. {
  289. if (m_active_trees)
  290. {
  291. activeizeTreeze(false);
  292. activeizeTreeze(true);
  293. }
  294. m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms);
  295. }
  296. else
  297. {
  298. m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed");
  299. }
  300. }
  301. private void HandleTreeReload(Object[] args)
  302. {
  303. if (m_active_trees)
  304. {
  305. CalculateTrees.Stop();
  306. }
  307. ReloadCopse();
  308. if (m_active_trees)
  309. {
  310. CalculateTrees.Start();
  311. }
  312. }
  313. private void HandleTreeRemove(Object[] args)
  314. {
  315. string copsename = ((string)args[0]).Trim();
  316. Copse copseIdentity = null;
  317. foreach (Copse cp in m_copse)
  318. {
  319. if (cp.m_name == copsename)
  320. {
  321. copseIdentity = cp;
  322. }
  323. }
  324. if (copseIdentity != null)
  325. {
  326. foreach (UUID tree in copseIdentity.m_trees)
  327. {
  328. if (m_scene.Entities.ContainsKey(tree))
  329. {
  330. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  331. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  332. m_scene.ForEachClient(delegate(IClientAPI controller)
  333. {
  334. controller.SendKillObject(m_scene.RegionInfo.RegionHandle,
  335. selectedTree.LocalId);
  336. });
  337. }
  338. else
  339. {
  340. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  341. }
  342. }
  343. copseIdentity.m_trees = new List<UUID>();
  344. m_copse.Remove(copseIdentity);
  345. m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
  346. }
  347. else
  348. {
  349. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  350. }
  351. }
  352. private void HandleTreeStatistics(Object[] args)
  353. {
  354. m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
  355. foreach (Copse cp in m_copse)
  356. {
  357. m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
  358. }
  359. }
  360. private void InstallCommands()
  361. {
  362. Command treeActiveCommand =
  363. new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module");
  364. treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean");
  365. Command treeFreezeCommand =
  366. new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse");
  367. treeFreezeCommand.AddArgument("copse", "The required copse", "String");
  368. treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean");
  369. Command treeLoadCommand =
  370. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file");
  371. treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String");
  372. Command treePlantCommand =
  373. new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse");
  374. treePlantCommand.AddArgument("copse", "The required copse", "String");
  375. Command treeRateCommand =
  376. new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)");
  377. treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
  378. Command treeReloadCommand =
  379. new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
  380. Command treeRemoveCommand =
  381. new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
  382. treeRemoveCommand.AddArgument("copse", "The required copse", "String");
  383. Command treeStatisticsCommand =
  384. new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees");
  385. m_commander.RegisterCommand("active", treeActiveCommand);
  386. m_commander.RegisterCommand("freeze", treeFreezeCommand);
  387. m_commander.RegisterCommand("load", treeLoadCommand);
  388. m_commander.RegisterCommand("plant", treePlantCommand);
  389. m_commander.RegisterCommand("rate", treeRateCommand);
  390. m_commander.RegisterCommand("reload", treeReloadCommand);
  391. m_commander.RegisterCommand("remove", treeRemoveCommand);
  392. m_commander.RegisterCommand("statistics", treeStatisticsCommand);
  393. m_scene.RegisterModuleCommander(m_commander);
  394. }
  395. /// <summary>
  396. /// Processes commandline input. Do not call directly.
  397. /// </summary>
  398. /// <param name="args">Commandline arguments</param>
  399. private void EventManager_OnPluginConsole(string[] args)
  400. {
  401. if (args[0] == "tree")
  402. {
  403. if (args.Length == 1)
  404. {
  405. m_commander.ProcessConsoleCommand("help", new string[0]);
  406. return;
  407. }
  408. string[] tmpArgs = new string[args.Length - 2];
  409. int i;
  410. for (i = 2; i < args.Length; i++)
  411. {
  412. tmpArgs[i - 2] = args[i];
  413. }
  414. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  415. }
  416. }
  417. #endregion
  418. #region IVegetationModule Members
  419. public SceneObjectGroup AddTree(
  420. UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree)
  421. {
  422. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  423. treeShape.PathCurve = 16;
  424. treeShape.PathEnd = 49900;
  425. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  426. treeShape.Scale = scale;
  427. treeShape.State = (byte)treeType;
  428. return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
  429. }
  430. #endregion
  431. #region IEntityCreator Members
  432. protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
  433. public PCode[] CreationCapabilities { get { return creationCapabilities; } }
  434. public SceneObjectGroup CreateEntity(
  435. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  436. {
  437. if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
  438. {
  439. m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
  440. return null;
  441. }
  442. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  443. SceneObjectPart rootPart = sceneObject.GetChildPart(sceneObject.UUID);
  444. rootPart.AddFlag(PrimFlags.Phantom);
  445. m_scene.AddNewSceneObject(sceneObject, true);
  446. sceneObject.SetGroup(groupID, null);
  447. return sceneObject;
  448. }
  449. #endregion
  450. //--------------------------------------------------------------
  451. #region Tree Utilities
  452. static public void SerializeObject(string fileName, Object obj)
  453. {
  454. try
  455. {
  456. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  457. using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
  458. {
  459. writer.Formatting = Formatting.Indented;
  460. xs.Serialize(writer, obj);
  461. }
  462. }
  463. catch (SystemException ex)
  464. {
  465. throw new ApplicationException("Unexpected failure in Tree serialization", ex);
  466. }
  467. }
  468. static public object DeserializeObject(string fileName)
  469. {
  470. try
  471. {
  472. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  473. using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
  474. return xs.Deserialize(fs);
  475. }
  476. catch (SystemException ex)
  477. {
  478. throw new ApplicationException("Unexpected failure in Tree de-serialization", ex);
  479. }
  480. }
  481. private void ReloadCopse()
  482. {
  483. m_copse = new List<Copse>();
  484. EntityBase[] objs = m_scene.GetEntities();
  485. foreach (EntityBase obj in objs)
  486. {
  487. if (obj is SceneObjectGroup)
  488. {
  489. SceneObjectGroup grp = (SceneObjectGroup)obj;
  490. if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
  491. {
  492. // Create a new copse definition or add uuid to an existing definition
  493. try
  494. {
  495. Boolean copsefound = false;
  496. Copse copse = new Copse(grp.Name);
  497. foreach (Copse cp in m_copse)
  498. {
  499. if (cp.m_name == copse.m_name)
  500. {
  501. copsefound = true;
  502. cp.m_trees.Add(grp.UUID);
  503. //m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID);
  504. }
  505. }
  506. if (!copsefound)
  507. {
  508. m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
  509. m_copse.Add(copse);
  510. copse.m_trees.Add(grp.UUID);
  511. }
  512. }
  513. catch
  514. {
  515. m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
  516. }
  517. }
  518. }
  519. }
  520. }
  521. #endregion
  522. private void activeizeTreeze(bool activeYN)
  523. {
  524. if (activeYN)
  525. {
  526. CalculateTrees = new Timer(m_update_ms);
  527. CalculateTrees.Elapsed += CalculateTrees_Elapsed;
  528. CalculateTrees.Start();
  529. }
  530. else
  531. {
  532. CalculateTrees.Stop();
  533. }
  534. }
  535. private void growTrees()
  536. {
  537. foreach (Copse copse in m_copse)
  538. {
  539. if (!copse.m_frozen)
  540. {
  541. foreach (UUID tree in copse.m_trees)
  542. {
  543. if (m_scene.Entities.ContainsKey(tree))
  544. {
  545. SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  546. if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
  547. {
  548. s_tree.Scale += copse.m_rate;
  549. s_tree.ParentGroup.HasGroupChanged = true;
  550. s_tree.ScheduleFullUpdate();
  551. }
  552. }
  553. else
  554. {
  555. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  556. }
  557. }
  558. }
  559. }
  560. }
  561. private void seedTrees()
  562. {
  563. foreach (Copse copse in m_copse)
  564. {
  565. if (!copse.m_frozen)
  566. {
  567. foreach (UUID tree in copse.m_trees)
  568. {
  569. if (m_scene.Entities.ContainsKey(tree))
  570. {
  571. SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  572. if (copse.m_trees.Count < copse.m_tree_quantity)
  573. {
  574. // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
  575. if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
  576. {
  577. if (Util.RandomClass.NextDouble() > 0.75)
  578. {
  579. SpawnChild(copse, s_tree);
  580. }
  581. }
  582. }
  583. }
  584. else
  585. {
  586. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  587. }
  588. }
  589. }
  590. }
  591. }
  592. private void killTrees()
  593. {
  594. foreach (Copse copse in m_copse)
  595. {
  596. if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
  597. {
  598. foreach (UUID tree in copse.m_trees)
  599. {
  600. double killLikelyhood = 0.0;
  601. if (m_scene.Entities.ContainsKey(tree))
  602. {
  603. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  604. double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
  605. Math.Pow(selectedTree.Scale.Y, 2) +
  606. Math.Pow(selectedTree.Scale.Z, 2));
  607. foreach (UUID picktree in copse.m_trees)
  608. {
  609. if (picktree != tree)
  610. {
  611. SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
  612. double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
  613. Math.Pow(pickedTree.Scale.Y, 2) +
  614. Math.Pow(pickedTree.Scale.Z, 2));
  615. double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
  616. killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
  617. }
  618. }
  619. if (Util.RandomClass.NextDouble() < killLikelyhood)
  620. {
  621. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  622. copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
  623. m_scene.ForEachClient(delegate(IClientAPI controller)
  624. {
  625. controller.SendKillObject(m_scene.RegionInfo.RegionHandle,
  626. selectedTree.LocalId);
  627. });
  628. break;
  629. }
  630. }
  631. else
  632. {
  633. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  634. }
  635. }
  636. }
  637. }
  638. }
  639. private void SpawnChild(Copse copse, SceneObjectPart s_tree)
  640. {
  641. Vector3 position = new Vector3();
  642. double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
  643. double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
  644. position.X = s_tree.AbsolutePosition.X + (float)randX;
  645. position.Y = s_tree.AbsolutePosition.Y + (float)randY;
  646. if (position.X <= ((int)Constants.RegionSize - 1) && position.X >= 0 &&
  647. position.Y <= ((int)Constants.RegionSize - 1) && position.Y >= 0 &&
  648. Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
  649. {
  650. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  651. CreateTree(uuid, copse, position);
  652. }
  653. }
  654. private void CreateTree(UUID uuid, Copse copse, Vector3 position)
  655. {
  656. position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
  657. if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
  658. {
  659. SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
  660. tree.Name = copse.ToString();
  661. copse.m_trees.Add(tree.UUID);
  662. tree.SendGroupFullUpdate();
  663. }
  664. }
  665. private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
  666. {
  667. growTrees();
  668. seedTrees();
  669. killTrees();
  670. }
  671. }
  672. }