TreePopulatorModule.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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.IO;
  30. using System.Reflection;
  31. using System.Timers;
  32. using System.Threading;
  33. using System.Xml;
  34. using System.Xml.Serialization;
  35. using OpenMetaverse;
  36. using log4net;
  37. using Mono.Addins;
  38. using Nini.Config;
  39. using OpenSim.Framework;
  40. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  41. using OpenSim.Region.Framework.Interfaces;
  42. using OpenSim.Region.Framework.Scenes;
  43. using Timer= System.Timers.Timer;
  44. namespace OpenSim.Region.OptionalModules.World.TreePopulator
  45. {
  46. /// <summary>
  47. /// Version 2.02 - Still hacky
  48. /// </summary>
  49. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")]
  50. public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule
  51. {
  52. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. private readonly Commander m_commander = new Commander("tree");
  54. private Scene m_scene;
  55. [XmlRootAttribute(ElementName = "Copse", IsNullable = false)]
  56. public class Copse
  57. {
  58. public string m_name;
  59. public Boolean m_frozen;
  60. public Tree m_tree_type;
  61. public int m_tree_quantity;
  62. public float m_treeline_low;
  63. public float m_treeline_high;
  64. public Vector3 m_seed_point;
  65. public double m_range;
  66. public Vector3 m_initial_scale;
  67. public Vector3 m_maximum_scale;
  68. public Vector3 m_rate;
  69. [XmlIgnore]
  70. public Boolean m_planted;
  71. [XmlIgnore]
  72. public List<UUID> m_trees;
  73. public Copse()
  74. {
  75. }
  76. public Copse(string fileName, Boolean planted)
  77. {
  78. Copse cp = (Copse)DeserializeObject(fileName);
  79. m_name = cp.m_name;
  80. m_frozen = cp.m_frozen;
  81. m_tree_quantity = cp.m_tree_quantity;
  82. m_treeline_high = cp.m_treeline_high;
  83. m_treeline_low = cp.m_treeline_low;
  84. m_range = cp.m_range;
  85. m_tree_type = cp.m_tree_type;
  86. m_seed_point = cp.m_seed_point;
  87. m_initial_scale = cp.m_initial_scale;
  88. m_maximum_scale = cp.m_maximum_scale;
  89. m_initial_scale = cp.m_initial_scale;
  90. m_rate = cp.m_rate;
  91. m_planted = planted;
  92. m_trees = new List<UUID>();
  93. }
  94. public Copse(string copsedef)
  95. {
  96. char[] delimiterChars = {':', ';'};
  97. string[] field = copsedef.Split(delimiterChars);
  98. m_name = field[1].Trim();
  99. m_frozen = (copsedef[0] == 'F');
  100. m_tree_quantity = int.Parse(field[2]);
  101. m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
  102. m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
  103. m_range = double.Parse(field[5], Culture.NumberFormatInfo);
  104. m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
  105. m_seed_point = Vector3.Parse(field[7]);
  106. m_initial_scale = Vector3.Parse(field[8]);
  107. m_maximum_scale = Vector3.Parse(field[9]);
  108. m_rate = Vector3.Parse(field[10]);
  109. m_planted = true;
  110. m_trees = new List<UUID>();
  111. }
  112. 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)
  113. {
  114. m_name = name;
  115. m_frozen = false;
  116. m_tree_quantity = quantity;
  117. m_treeline_high = high;
  118. m_treeline_low = low;
  119. m_range = range;
  120. m_tree_type = type;
  121. m_seed_point = point;
  122. m_initial_scale = scale;
  123. m_maximum_scale = max_scale;
  124. m_rate = rate;
  125. m_planted = false;
  126. m_trees = trees;
  127. }
  128. public override string ToString()
  129. {
  130. string frozen = (m_frozen ? "F" : "A");
  131. 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};",
  132. frozen,
  133. m_name,
  134. m_tree_quantity,
  135. m_treeline_high,
  136. m_treeline_low,
  137. m_range,
  138. m_tree_type,
  139. m_seed_point.ToString(),
  140. m_initial_scale.ToString(),
  141. m_maximum_scale.ToString(),
  142. m_rate.ToString());
  143. }
  144. }
  145. private List<Copse> m_copses = new List<Copse>();
  146. private object mylock;
  147. private double m_update_ms = 1000.0; // msec between updates
  148. private bool m_active_trees = false;
  149. private bool m_enabled = true; // original default
  150. private bool m_allowGrow = true; // original default
  151. Timer CalculateTrees;
  152. #region ICommandableModule Members
  153. public ICommander CommandInterface
  154. {
  155. get { return m_commander; }
  156. }
  157. #endregion
  158. #region Region Module interface
  159. public void Initialise(IConfigSource config)
  160. {
  161. IConfig moduleConfig = config.Configs["Trees"];
  162. if (moduleConfig != null)
  163. {
  164. m_enabled = moduleConfig.GetBoolean("enabled", m_enabled);
  165. m_active_trees = moduleConfig.GetBoolean("active_trees", m_active_trees);
  166. m_allowGrow = moduleConfig.GetBoolean("allowGrow", m_allowGrow);
  167. m_update_ms = moduleConfig.GetDouble("update_rate", m_update_ms);
  168. }
  169. if(!m_enabled)
  170. return;
  171. m_copses = new List<Copse>();
  172. mylock = new object();
  173. InstallCommands();
  174. m_log.Debug("[TREES]: Initialised tree populator module");
  175. }
  176. public void AddRegion(Scene scene)
  177. {
  178. if(!m_enabled)
  179. return;
  180. m_scene = scene;
  181. m_scene.RegisterModuleCommander(m_commander);
  182. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  183. m_scene.EventManager.OnPrimsLoaded += EventManager_OnPrimsLoaded;
  184. }
  185. public void RemoveRegion(Scene scene)
  186. {
  187. if(!m_enabled)
  188. return;
  189. if(m_active_trees && CalculateTrees != null)
  190. {
  191. CalculateTrees.Dispose();
  192. CalculateTrees = null;
  193. }
  194. m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
  195. m_scene.EventManager.OnPrimsLoaded -= EventManager_OnPrimsLoaded;
  196. }
  197. public void RegionLoaded(Scene scene)
  198. {
  199. }
  200. public void Close()
  201. {
  202. }
  203. public string Name
  204. {
  205. get { return "TreePopulatorModule"; }
  206. }
  207. public Type ReplaceableInterface
  208. {
  209. get { return null; }
  210. }
  211. #endregion
  212. //--------------------------------------------------------------
  213. private void EventManager_OnPrimsLoaded(Scene s)
  214. {
  215. ReloadCopse();
  216. if (m_copses.Count > 0)
  217. m_log.Info("[TREES]: Copses loaded" );
  218. if (m_active_trees)
  219. activeizeTreeze(true);
  220. }
  221. #region ICommandableModule Members
  222. private void HandleTreeActive(Object[] args)
  223. {
  224. if ((Boolean)args[0] && !m_active_trees)
  225. {
  226. m_log.InfoFormat("[TREES]: Activating Trees");
  227. m_active_trees = true;
  228. activeizeTreeze(m_active_trees);
  229. }
  230. else if (!(Boolean)args[0] && m_active_trees)
  231. {
  232. m_log.InfoFormat("[TREES]: Trees module is no longer active");
  233. m_active_trees = false;
  234. activeizeTreeze(m_active_trees);
  235. }
  236. else
  237. {
  238. m_log.InfoFormat("[TREES]: Trees module is already in the required state");
  239. }
  240. }
  241. private void HandleTreeFreeze(Object[] args)
  242. {
  243. string copsename = ((string)args[0]).Trim();
  244. Boolean freezeState = (Boolean) args[1];
  245. lock(mylock)
  246. {
  247. foreach (Copse cp in m_copses)
  248. {
  249. if (cp.m_name != copsename)
  250. continue;
  251. if(!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)
  252. {
  253. cp.m_frozen = freezeState;
  254. List<UUID> losttrees = new List<UUID>();
  255. foreach (UUID tree in cp.m_trees)
  256. {
  257. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
  258. if(sog != null && !sog.IsDeleted)
  259. {
  260. SceneObjectPart sop = sog.RootPart;
  261. string name = sop.Name;
  262. if(freezeState)
  263. {
  264. if(name.StartsWith("FTPM"))
  265. continue;
  266. if(!name.StartsWith("ATPM"))
  267. continue;
  268. sop.Name = sop.Name.Replace("ATPM", "FTPM");
  269. }
  270. else
  271. {
  272. if(name.StartsWith("ATPM"))
  273. continue;
  274. if(!name.StartsWith("FTPM"))
  275. continue;
  276. sop.Name = sop.Name.Replace("FTPM", "ATPM");
  277. }
  278. sop.ParentGroup.HasGroupChanged = true;
  279. sog.ScheduleGroupForFullUpdate();
  280. }
  281. else
  282. losttrees.Add(tree);
  283. }
  284. foreach (UUID tree in losttrees)
  285. cp.m_trees.Remove(tree);
  286. m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
  287. return;
  288. }
  289. else
  290. {
  291. m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
  292. return;
  293. }
  294. }
  295. }
  296. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  297. }
  298. private void HandleTreeLoad(Object[] args)
  299. {
  300. Copse copse;
  301. m_log.InfoFormat("[TREES]: Loading copse definition....");
  302. lock(mylock)
  303. {
  304. copse = new Copse(((string)args[0]), false);
  305. {
  306. foreach (Copse cp in m_copses)
  307. {
  308. if (cp.m_name == copse.m_name)
  309. {
  310. m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
  311. return;
  312. }
  313. }
  314. }
  315. m_copses.Add(copse);
  316. }
  317. m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
  318. }
  319. private void HandleTreePlant(Object[] args)
  320. {
  321. string copsename = ((string)args[0]).Trim();
  322. m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
  323. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  324. lock(mylock)
  325. {
  326. foreach (Copse copse in m_copses)
  327. {
  328. if (copse.m_name == copsename)
  329. {
  330. if (!copse.m_planted)
  331. {
  332. // The first tree for a copse is created here
  333. CreateTree(uuid, copse, copse.m_seed_point, true);
  334. copse.m_planted = true;
  335. return;
  336. }
  337. else
  338. {
  339. m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
  340. return;
  341. }
  342. }
  343. }
  344. }
  345. m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename);
  346. }
  347. private void HandleTreeRate(Object[] args)
  348. {
  349. m_update_ms = (double)args[0];
  350. if (m_update_ms >= 1000.0)
  351. {
  352. if (m_active_trees)
  353. {
  354. activeizeTreeze(false);
  355. activeizeTreeze(true);
  356. }
  357. m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms);
  358. }
  359. else
  360. {
  361. m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed");
  362. }
  363. }
  364. private void HandleTreeReload(Object[] args)
  365. {
  366. if (m_active_trees)
  367. {
  368. CalculateTrees.Stop();
  369. }
  370. ReloadCopse();
  371. if (m_active_trees)
  372. {
  373. CalculateTrees.Start();
  374. }
  375. }
  376. private void HandleTreeRemove(Object[] args)
  377. {
  378. string copsename = ((string)args[0]).Trim();
  379. Copse copseIdentity = null;
  380. lock(mylock)
  381. {
  382. foreach (Copse cp in m_copses)
  383. {
  384. if (cp.m_name == copsename)
  385. {
  386. copseIdentity = cp;
  387. }
  388. }
  389. if (copseIdentity != null)
  390. {
  391. foreach (UUID tree in copseIdentity.m_trees)
  392. {
  393. if (m_scene.Entities.ContainsKey(tree))
  394. {
  395. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  396. // Delete tree and alert clients (not silent)
  397. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  398. }
  399. else
  400. {
  401. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  402. }
  403. }
  404. copseIdentity.m_trees = null;
  405. m_copses.Remove(copseIdentity);
  406. m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
  407. }
  408. else
  409. {
  410. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  411. }
  412. }
  413. }
  414. private void HandleTreeStatistics(Object[] args)
  415. {
  416. m_log.InfoFormat("[TREES]: region {0}:", m_scene.Name);
  417. m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
  418. foreach (Copse cp in m_copses)
  419. {
  420. m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
  421. }
  422. }
  423. private void InstallCommands()
  424. {
  425. Command treeActiveCommand =
  426. new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module");
  427. treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean");
  428. Command treeFreezeCommand =
  429. new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse");
  430. treeFreezeCommand.AddArgument("copse", "The required copse", "String");
  431. treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean");
  432. Command treeLoadCommand =
  433. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file");
  434. treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String");
  435. Command treePlantCommand =
  436. new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse");
  437. treePlantCommand.AddArgument("copse", "The required copse", "String");
  438. Command treeRateCommand =
  439. new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)");
  440. treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
  441. Command treeReloadCommand =
  442. new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copses from the in-scene trees");
  443. Command treeRemoveCommand =
  444. new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
  445. treeRemoveCommand.AddArgument("copse", "The required copse", "String");
  446. Command treeStatisticsCommand =
  447. new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees");
  448. m_commander.RegisterCommand("active", treeActiveCommand);
  449. m_commander.RegisterCommand("freeze", treeFreezeCommand);
  450. m_commander.RegisterCommand("load", treeLoadCommand);
  451. m_commander.RegisterCommand("plant", treePlantCommand);
  452. m_commander.RegisterCommand("rate", treeRateCommand);
  453. m_commander.RegisterCommand("reload", treeReloadCommand);
  454. m_commander.RegisterCommand("remove", treeRemoveCommand);
  455. m_commander.RegisterCommand("statistics", treeStatisticsCommand);
  456. }
  457. /// <summary>
  458. /// Processes commandline input. Do not call directly.
  459. /// </summary>
  460. /// <param name="args">Commandline arguments</param>
  461. private void EventManager_OnPluginConsole(string[] args)
  462. {
  463. if (args[0] == "tree")
  464. {
  465. if (args.Length == 1)
  466. {
  467. m_commander.ProcessConsoleCommand("help", new string[0]);
  468. return;
  469. }
  470. string[] tmpArgs = new string[args.Length - 2];
  471. int i;
  472. for (i = 2; i < args.Length; i++)
  473. {
  474. tmpArgs[i - 2] = args[i];
  475. }
  476. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  477. }
  478. }
  479. #endregion
  480. #region IVegetationModule Members
  481. public SceneObjectGroup AddTree(
  482. UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree)
  483. {
  484. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  485. treeShape.PathCurve = 16;
  486. treeShape.PathEnd = 49900;
  487. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  488. treeShape.Scale = scale;
  489. treeShape.State = (byte)treeType;
  490. SceneObjectGroup sog = new SceneObjectGroup(uuid, position, rotation, treeShape);
  491. SceneObjectPart rootPart = sog.RootPart;
  492. rootPart.AddFlag(PrimFlags.Phantom);
  493. sog.SetGroup(groupID, null);
  494. m_scene.AddNewSceneObject(sog, true, false);
  495. sog.IsSelected = false;
  496. rootPart.IsSelected = false;
  497. sog.InvalidateEffectivePerms();
  498. return sog;
  499. }
  500. #endregion
  501. //--------------------------------------------------------------
  502. #region Tree Utilities
  503. static public void SerializeObject(string fileName, Object obj)
  504. {
  505. try
  506. {
  507. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  508. using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
  509. {
  510. writer.Formatting = Formatting.Indented;
  511. xs.Serialize(writer, obj);
  512. }
  513. }
  514. catch (SystemException ex)
  515. {
  516. throw new ApplicationException("Unexpected failure in Tree serialization", ex);
  517. }
  518. }
  519. static public object DeserializeObject(string fileName)
  520. {
  521. try
  522. {
  523. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  524. using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
  525. return xs.Deserialize(fs);
  526. }
  527. catch (SystemException ex)
  528. {
  529. throw new ApplicationException("Unexpected failure in Tree de-serialization", ex);
  530. }
  531. }
  532. private void ReloadCopse()
  533. {
  534. m_copses = new List<Copse>();
  535. List<SceneObjectGroup> grps = m_scene.GetSceneObjectGroups();
  536. foreach (SceneObjectGroup grp in grps)
  537. {
  538. if(grp.RootPart.Shape.PCode != (byte)PCode.NewTree && grp.RootPart.Shape.PCode != (byte)PCode.Tree)
  539. continue;
  540. string grpname = grp.Name;
  541. if (grpname.Length > 5 && (grpname.Substring(0, 5) == "ATPM:" || grpname.Substring(0, 5) == "FTPM:"))
  542. {
  543. // Create a new copse definition or add uuid to an existing definition
  544. try
  545. {
  546. Boolean copsefound = false;
  547. Copse grpcopse = new Copse(grpname);
  548. lock(mylock)
  549. {
  550. foreach (Copse cp in m_copses)
  551. {
  552. if (cp.m_name == grpcopse.m_name)
  553. {
  554. copsefound = true;
  555. cp.m_trees.Add(grp.UUID);
  556. //m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID);
  557. }
  558. }
  559. if (!copsefound)
  560. {
  561. m_log.InfoFormat("[TREES]: adding copse {0}", grpcopse.m_name);
  562. grpcopse.m_trees.Add(grp.UUID);
  563. m_copses.Add(grpcopse);
  564. }
  565. }
  566. }
  567. catch
  568. {
  569. m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
  570. }
  571. }
  572. }
  573. }
  574. #endregion
  575. private void activeizeTreeze(bool activeYN)
  576. {
  577. if (activeYN)
  578. {
  579. if(CalculateTrees == null)
  580. CalculateTrees = new Timer(m_update_ms);
  581. CalculateTrees.Elapsed += CalculateTrees_Elapsed;
  582. CalculateTrees.AutoReset = false;
  583. CalculateTrees.Start();
  584. }
  585. else
  586. {
  587. CalculateTrees.Stop();
  588. }
  589. }
  590. private void growTrees()
  591. {
  592. if(!m_allowGrow)
  593. return;
  594. foreach (Copse copse in m_copses)
  595. {
  596. if (copse.m_frozen)
  597. continue;
  598. if(copse.m_trees.Count == 0)
  599. continue;
  600. float maxscale = copse.m_maximum_scale.Z;
  601. float ratescale = 1.0f;
  602. List<UUID> losttrees = new List<UUID>();
  603. foreach (UUID tree in copse.m_trees)
  604. {
  605. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
  606. if (sog != null && !sog.IsDeleted)
  607. {
  608. SceneObjectPart s_tree = sog.RootPart;
  609. if (s_tree.Scale.Z < maxscale)
  610. {
  611. ratescale = (float)Util.RandomClass.NextDouble();
  612. if(ratescale < 0.2f)
  613. ratescale = 0.2f;
  614. s_tree.Scale += copse.m_rate * ratescale;
  615. sog.HasGroupChanged = true;
  616. s_tree.ScheduleFullUpdate();
  617. }
  618. }
  619. else
  620. losttrees.Add(tree);
  621. }
  622. foreach (UUID tree in losttrees)
  623. copse.m_trees.Remove(tree);
  624. }
  625. }
  626. private void seedTrees()
  627. {
  628. foreach (Copse copse in m_copses)
  629. {
  630. if (copse.m_frozen)
  631. continue;
  632. if(copse.m_trees.Count == 0)
  633. return;
  634. bool low = copse.m_trees.Count < (int)(copse.m_tree_quantity * 0.8f);
  635. if (!low && Util.RandomClass.NextDouble() < 0.75)
  636. return;
  637. int maxbirths = (int)(copse.m_tree_quantity) - copse.m_trees.Count;
  638. if(maxbirths <= 1)
  639. return;
  640. if(maxbirths > 20)
  641. maxbirths = 20;
  642. float minscale = 0;
  643. if(!low && m_allowGrow)
  644. minscale = copse.m_maximum_scale.Z * 0.75f;;
  645. int i = 0;
  646. UUID[] current = copse.m_trees.ToArray();
  647. while(--maxbirths > 0)
  648. {
  649. if(current.Length > 1)
  650. i = Util.RandomClass.Next(current.Length -1);
  651. UUID tree = current[i];
  652. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
  653. if (sog != null && !sog.IsDeleted)
  654. {
  655. SceneObjectPart s_tree = sog.RootPart;
  656. // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
  657. if (s_tree.Scale.Z > minscale)
  658. SpawnChild(copse, s_tree, true);
  659. }
  660. else if(copse.m_trees.Contains(tree))
  661. copse.m_trees.Remove(tree);
  662. }
  663. }
  664. }
  665. private void killTrees()
  666. {
  667. foreach (Copse copse in m_copses)
  668. {
  669. if (copse.m_frozen)
  670. continue;
  671. if (Util.RandomClass.NextDouble() < 0.25)
  672. return;
  673. int maxbdeaths = copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) ;
  674. if(maxbdeaths < 1)
  675. return;
  676. float odds;
  677. float scale = 1.0f / copse.m_maximum_scale.Z;
  678. int ntries = maxbdeaths * 4;
  679. while(ntries-- > 0 )
  680. {
  681. int next = 0;
  682. if (copse.m_trees.Count > 1)
  683. next = Util.RandomClass.Next(copse.m_trees.Count - 1);
  684. UUID tree = copse.m_trees[next];
  685. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(tree);
  686. if (sog != null && !sog.IsDeleted)
  687. {
  688. if(m_allowGrow)
  689. {
  690. odds = sog.RootPart.Scale.Z * scale;
  691. odds = odds * odds * odds;
  692. odds *= (float)Util.RandomClass.NextDouble();
  693. }
  694. else
  695. {
  696. odds = (float)Util.RandomClass.NextDouble();
  697. odds = odds * odds * odds;
  698. }
  699. if(odds > 0.9f)
  700. {
  701. m_scene.DeleteSceneObject(sog, false);
  702. if(maxbdeaths <= 0)
  703. break;
  704. }
  705. }
  706. else
  707. {
  708. copse.m_trees.Remove(tree);
  709. if(copse.m_trees.Count - (int)(copse.m_tree_quantity * .98f) <= 0 )
  710. break;
  711. }
  712. }
  713. }
  714. }
  715. private void SpawnChild(Copse copse, SceneObjectPart s_tree, bool low)
  716. {
  717. Vector3 position = new Vector3();
  718. float randX = copse.m_maximum_scale.X * 1.25f;
  719. float randY = copse.m_maximum_scale.Y * 1.25f;
  720. float r = (float)Util.RandomClass.NextDouble();
  721. randX *= 2.0f * r - 1.0f;
  722. position.X = s_tree.AbsolutePosition.X + (float)randX;
  723. r = (float)Util.RandomClass.NextDouble();
  724. randY *= 2.0f * r - 1.0f;
  725. position.Y = s_tree.AbsolutePosition.Y + (float)randY;
  726. if (position.X > (m_scene.RegionInfo.RegionSizeX - 1) || position.X <= 0 ||
  727. position.Y > (m_scene.RegionInfo.RegionSizeY - 1) || position.Y <= 0)
  728. return;
  729. randX = position.X - copse.m_seed_point.X;
  730. randX *= randX;
  731. randY = position.Y - copse.m_seed_point.Y;
  732. randY *= randY;
  733. randX += randY;
  734. if(randX > copse.m_range * copse.m_range)
  735. return;
  736. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  737. CreateTree(uuid, copse, position, low);
  738. }
  739. private void CreateTree(UUID uuid, Copse copse, Vector3 position, bool randomScale)
  740. {
  741. position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
  742. if (position.Z < copse.m_treeline_low || position.Z > copse.m_treeline_high)
  743. return;
  744. Vector3 scale = copse.m_initial_scale;
  745. if(randomScale)
  746. {
  747. try
  748. {
  749. float t;
  750. float r = (float)Util.RandomClass.NextDouble();
  751. r *= (float)Util.RandomClass.NextDouble();
  752. r *= (float)Util.RandomClass.NextDouble();
  753. t = copse.m_maximum_scale.X / copse.m_initial_scale.X;
  754. if(t < 1.0)
  755. t = 1 / t;
  756. t = t * r + 1.0f;
  757. scale.X *= t;
  758. t = copse.m_maximum_scale.Y / copse.m_initial_scale.Y;
  759. if(t < 1.0)
  760. t = 1 / t;
  761. t = t * r + 1.0f;
  762. scale.Y *= t;
  763. t = copse.m_maximum_scale.Z / copse.m_initial_scale.Z;
  764. if(t < 1.0)
  765. t = 1 / t;
  766. t = t * r + 1.0f;
  767. scale.Z *= t;
  768. }
  769. catch
  770. {
  771. scale = copse.m_initial_scale;
  772. }
  773. }
  774. SceneObjectGroup tree = AddTree(uuid, UUID.Zero, scale, Quaternion.Identity, position, copse.m_tree_type, false);
  775. tree.Name = copse.ToString();
  776. copse.m_trees.Add(tree.UUID);
  777. tree.RootPart.ScheduleFullUpdate();
  778. }
  779. private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
  780. {
  781. if(!m_scene.IsRunning)
  782. return;
  783. if(Monitor.TryEnter(mylock))
  784. {
  785. try
  786. {
  787. if(m_scene.LoginsEnabled )
  788. {
  789. growTrees();
  790. seedTrees();
  791. killTrees();
  792. }
  793. }
  794. catch { }
  795. if(CalculateTrees != null)
  796. CalculateTrees.Start();
  797. Monitor.Exit(mylock);
  798. }
  799. }
  800. }
  801. }