TreePopulatorModule.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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]);
  98. this.m_treeline_low = float.Parse(field[4]);
  99. this.m_range = double.Parse(field[5]);
  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. if (uuid == UUID.Zero)
  266. uuid = m_scene.RegionInfo.MasterAvatarAssignedUUID;
  267. foreach (Copse copse in m_copse)
  268. {
  269. if (copse.m_name == copsename)
  270. {
  271. if (!copse.m_planted)
  272. {
  273. // The first tree for a copse is created here
  274. CreateTree(uuid, copse, copse.m_seed_point);
  275. copse.m_planted = true;
  276. return;
  277. }
  278. else
  279. {
  280. m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
  281. }
  282. }
  283. }
  284. m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename);
  285. }
  286. private void HandleTreeRate(Object[] args)
  287. {
  288. m_update_ms = (double)args[0];
  289. if (m_update_ms >= 1000.0)
  290. {
  291. if (m_active_trees)
  292. {
  293. activeizeTreeze(false);
  294. activeizeTreeze(true);
  295. }
  296. m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms);
  297. }
  298. else
  299. {
  300. m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed");
  301. }
  302. }
  303. private void HandleTreeReload(Object[] args)
  304. {
  305. if (m_active_trees)
  306. {
  307. CalculateTrees.Stop();
  308. }
  309. ReloadCopse();
  310. if (m_active_trees)
  311. {
  312. CalculateTrees.Start();
  313. }
  314. }
  315. private void HandleTreeRemove(Object[] args)
  316. {
  317. string copsename = ((string)args[0]).Trim();
  318. Copse copseIdentity = null;
  319. foreach (Copse cp in m_copse)
  320. {
  321. if (cp.m_name == copsename)
  322. {
  323. copseIdentity = cp;
  324. }
  325. }
  326. if (copseIdentity != null)
  327. {
  328. foreach (UUID tree in copseIdentity.m_trees)
  329. {
  330. if (m_scene.Entities.ContainsKey(tree))
  331. {
  332. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  333. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  334. m_scene.ForEachClient(delegate(IClientAPI controller)
  335. {
  336. controller.SendKillObject(m_scene.RegionInfo.RegionHandle,
  337. selectedTree.LocalId);
  338. });
  339. }
  340. else
  341. {
  342. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  343. }
  344. }
  345. copseIdentity.m_trees = new List<UUID>();
  346. m_copse.Remove(copseIdentity);
  347. m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
  348. }
  349. else
  350. {
  351. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  352. }
  353. }
  354. private void HandleTreeStatistics(Object[] args)
  355. {
  356. m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
  357. foreach (Copse cp in m_copse)
  358. {
  359. m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
  360. }
  361. }
  362. private void InstallCommands()
  363. {
  364. Command treeActiveCommand =
  365. new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module");
  366. treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean");
  367. Command treeFreezeCommand =
  368. new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse");
  369. treeFreezeCommand.AddArgument("copse", "The required copse", "String");
  370. treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean");
  371. Command treeLoadCommand =
  372. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file");
  373. treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String");
  374. Command treePlantCommand =
  375. new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse");
  376. treePlantCommand.AddArgument("copse", "The required copse", "String");
  377. Command treeRateCommand =
  378. new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)");
  379. treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
  380. Command treeReloadCommand =
  381. new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
  382. Command treeRemoveCommand =
  383. new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
  384. treeRemoveCommand.AddArgument("copse", "The required copse", "String");
  385. Command treeStatisticsCommand =
  386. new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees");
  387. m_commander.RegisterCommand("active", treeActiveCommand);
  388. m_commander.RegisterCommand("freeze", treeFreezeCommand);
  389. m_commander.RegisterCommand("load", treeLoadCommand);
  390. m_commander.RegisterCommand("plant", treePlantCommand);
  391. m_commander.RegisterCommand("rate", treeRateCommand);
  392. m_commander.RegisterCommand("reload", treeReloadCommand);
  393. m_commander.RegisterCommand("remove", treeRemoveCommand);
  394. m_commander.RegisterCommand("statistics", treeStatisticsCommand);
  395. m_scene.RegisterModuleCommander(m_commander);
  396. }
  397. /// <summary>
  398. /// Processes commandline input. Do not call directly.
  399. /// </summary>
  400. /// <param name="args">Commandline arguments</param>
  401. private void EventManager_OnPluginConsole(string[] args)
  402. {
  403. if (args[0] == "tree")
  404. {
  405. if (args.Length == 1)
  406. {
  407. m_commander.ProcessConsoleCommand("help", new string[0]);
  408. return;
  409. }
  410. string[] tmpArgs = new string[args.Length - 2];
  411. int i;
  412. for (i = 2; i < args.Length; i++)
  413. {
  414. tmpArgs[i - 2] = args[i];
  415. }
  416. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  417. }
  418. }
  419. #endregion
  420. #region IVegetationModule Members
  421. public SceneObjectGroup AddTree(
  422. UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree)
  423. {
  424. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  425. treeShape.PathCurve = 16;
  426. treeShape.PathEnd = 49900;
  427. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  428. treeShape.Scale = scale;
  429. treeShape.State = (byte)treeType;
  430. return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
  431. }
  432. #endregion
  433. #region IEntityCreator Members
  434. protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
  435. public PCode[] CreationCapabilities { get { return creationCapabilities; } }
  436. public SceneObjectGroup CreateEntity(
  437. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  438. {
  439. if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
  440. {
  441. m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
  442. return null;
  443. }
  444. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  445. SceneObjectPart rootPart = sceneObject.GetChildPart(sceneObject.UUID);
  446. rootPart.AddFlag(PrimFlags.Phantom);
  447. m_scene.AddNewSceneObject(sceneObject, true);
  448. sceneObject.SetGroup(groupID, null);
  449. return sceneObject;
  450. }
  451. #endregion
  452. //--------------------------------------------------------------
  453. #region Tree Utilities
  454. static public void SerializeObject(string fileName, Object obj)
  455. {
  456. try
  457. {
  458. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  459. using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
  460. {
  461. writer.Formatting = Formatting.Indented;
  462. xs.Serialize(writer, obj);
  463. }
  464. }
  465. catch (SystemException ex)
  466. {
  467. throw new ApplicationException("Unexpected failure in Tree serialization", ex);
  468. }
  469. }
  470. static public object DeserializeObject(string fileName)
  471. {
  472. try
  473. {
  474. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  475. using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
  476. return xs.Deserialize(fs);
  477. }
  478. catch (SystemException ex)
  479. {
  480. throw new ApplicationException("Unexpected failure in Tree de-serialization", ex);
  481. }
  482. }
  483. private void ReloadCopse()
  484. {
  485. m_copse = new List<Copse>();
  486. List<EntityBase> objs = m_scene.GetEntities();
  487. foreach (EntityBase obj in objs)
  488. {
  489. if (obj is SceneObjectGroup)
  490. {
  491. SceneObjectGroup grp = (SceneObjectGroup)obj;
  492. if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
  493. {
  494. // Create a new copse definition or add uuid to an existing definition
  495. try
  496. {
  497. Boolean copsefound = false;
  498. Copse copse = new Copse(grp.Name);
  499. foreach (Copse cp in m_copse)
  500. {
  501. if (cp.m_name == copse.m_name)
  502. {
  503. copsefound = true;
  504. cp.m_trees.Add(grp.UUID);
  505. //m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID);
  506. }
  507. }
  508. if (!copsefound)
  509. {
  510. m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
  511. m_copse.Add(copse);
  512. copse.m_trees.Add(grp.UUID);
  513. }
  514. }
  515. catch
  516. {
  517. m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
  518. }
  519. }
  520. }
  521. }
  522. }
  523. #endregion
  524. private void activeizeTreeze(bool activeYN)
  525. {
  526. if (activeYN)
  527. {
  528. CalculateTrees = new Timer(m_update_ms);
  529. CalculateTrees.Elapsed += CalculateTrees_Elapsed;
  530. CalculateTrees.Start();
  531. }
  532. else
  533. {
  534. CalculateTrees.Stop();
  535. }
  536. }
  537. private void growTrees()
  538. {
  539. foreach (Copse copse in m_copse)
  540. {
  541. if (!copse.m_frozen)
  542. {
  543. foreach (UUID tree in copse.m_trees)
  544. {
  545. if (m_scene.Entities.ContainsKey(tree))
  546. {
  547. SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  548. 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)
  549. {
  550. s_tree.Scale += copse.m_rate;
  551. s_tree.ParentGroup.HasGroupChanged = true;
  552. s_tree.ScheduleFullUpdate();
  553. }
  554. }
  555. else
  556. {
  557. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  558. }
  559. }
  560. }
  561. }
  562. }
  563. private void seedTrees()
  564. {
  565. foreach (Copse copse in m_copse)
  566. {
  567. if (!copse.m_frozen)
  568. {
  569. foreach (UUID tree in copse.m_trees)
  570. {
  571. if (m_scene.Entities.ContainsKey(tree))
  572. {
  573. SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  574. if (copse.m_trees.Count < copse.m_tree_quantity)
  575. {
  576. // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
  577. if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
  578. {
  579. if (Util.RandomClass.NextDouble() > 0.75)
  580. {
  581. SpawnChild(copse, s_tree);
  582. }
  583. }
  584. }
  585. }
  586. else
  587. {
  588. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  589. }
  590. }
  591. }
  592. }
  593. }
  594. private void killTrees()
  595. {
  596. foreach (Copse copse in m_copse)
  597. {
  598. if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
  599. {
  600. foreach (UUID tree in copse.m_trees)
  601. {
  602. double killLikelyhood = 0.0;
  603. if (m_scene.Entities.ContainsKey(tree))
  604. {
  605. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  606. double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
  607. Math.Pow(selectedTree.Scale.Y, 2) +
  608. Math.Pow(selectedTree.Scale.Z, 2));
  609. foreach (UUID picktree in copse.m_trees)
  610. {
  611. if (picktree != tree)
  612. {
  613. SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
  614. double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
  615. Math.Pow(pickedTree.Scale.Y, 2) +
  616. Math.Pow(pickedTree.Scale.Z, 2));
  617. double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
  618. killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
  619. }
  620. }
  621. if (Util.RandomClass.NextDouble() < killLikelyhood)
  622. {
  623. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  624. copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
  625. m_scene.ForEachClient(delegate(IClientAPI controller)
  626. {
  627. controller.SendKillObject(m_scene.RegionInfo.RegionHandle,
  628. selectedTree.LocalId);
  629. });
  630. break;
  631. }
  632. }
  633. else
  634. {
  635. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  636. }
  637. }
  638. }
  639. }
  640. }
  641. private void SpawnChild(Copse copse, SceneObjectPart s_tree)
  642. {
  643. Vector3 position = new Vector3();
  644. double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
  645. double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
  646. position.X = s_tree.AbsolutePosition.X + (float)randX;
  647. position.Y = s_tree.AbsolutePosition.Y + (float)randY;
  648. if (position.X <= ((int)Constants.RegionSize - 1) && position.X >= 0 &&
  649. position.Y <= ((int)Constants.RegionSize - 1) && position.Y >= 0 &&
  650. Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
  651. {
  652. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  653. if (uuid == UUID.Zero)
  654. uuid = m_scene.RegionInfo.MasterAvatarAssignedUUID;
  655. CreateTree(uuid, copse, position);
  656. }
  657. }
  658. private void CreateTree(UUID uuid, Copse copse, Vector3 position)
  659. {
  660. position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
  661. if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
  662. {
  663. SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
  664. tree.Name = copse.ToString();
  665. copse.m_trees.Add(tree.UUID);
  666. tree.SendGroupFullUpdate();
  667. }
  668. }
  669. private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
  670. {
  671. growTrees();
  672. seedTrees();
  673. killTrees();
  674. }
  675. }
  676. }