TerrainModule.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  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.Net;
  32. using log4net;
  33. using Nini.Config;
  34. using OpenMetaverse;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  37. using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
  38. using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
  39. using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. namespace OpenSim.Region.CoreModules.World.Terrain
  43. {
  44. public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
  45. {
  46. #region StandardTerrainEffects enum
  47. /// <summary>
  48. /// A standard set of terrain brushes and effects recognised by viewers
  49. /// </summary>
  50. public enum StandardTerrainEffects : byte
  51. {
  52. Flatten = 0,
  53. Raise = 1,
  54. Lower = 2,
  55. Smooth = 3,
  56. Noise = 4,
  57. Revert = 5,
  58. // Extended brushes
  59. Erode = 255,
  60. Weather = 254,
  61. Olsen = 253
  62. }
  63. #endregion
  64. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  65. private readonly Commander m_commander = new Commander("terrain");
  66. private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
  67. new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
  68. private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
  69. private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
  70. new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
  71. private ITerrainChannel m_channel;
  72. private Dictionary<string, ITerrainEffect> m_plugineffects;
  73. private ITerrainChannel m_revert;
  74. private Scene m_scene;
  75. private volatile bool m_tainted;
  76. private readonly UndoStack<LandUndoState> m_undo = new UndoStack<LandUndoState>(5);
  77. #region ICommandableModule Members
  78. public ICommander CommandInterface
  79. {
  80. get { return m_commander; }
  81. }
  82. #endregion
  83. #region INonSharedRegionModule Members
  84. /// <summary>
  85. /// Creates and initialises a terrain module for a region
  86. /// </summary>
  87. /// <param name="scene">Region initialising</param>
  88. /// <param name="config">Config for the region</param>
  89. public void Initialise(IConfigSource config)
  90. {
  91. }
  92. public void AddRegion(Scene scene)
  93. {
  94. m_scene = scene;
  95. // Install terrain module in the simulator
  96. lock (m_scene)
  97. {
  98. if (m_scene.Heightmap == null)
  99. {
  100. m_channel = new TerrainChannel();
  101. m_scene.Heightmap = m_channel;
  102. m_revert = new TerrainChannel();
  103. UpdateRevertMap();
  104. }
  105. else
  106. {
  107. m_channel = m_scene.Heightmap;
  108. m_revert = new TerrainChannel();
  109. UpdateRevertMap();
  110. }
  111. m_scene.RegisterModuleInterface<ITerrainModule>(this);
  112. m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
  113. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  114. m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
  115. InstallInterfaces();
  116. }
  117. InstallDefaultEffects();
  118. LoadPlugins();
  119. }
  120. public void RegionLoaded(Scene scene)
  121. {
  122. }
  123. public void RemoveRegion(Scene scene)
  124. {
  125. lock (m_scene)
  126. {
  127. // remove the commands
  128. m_scene.UnregisterModuleCommander(m_commander.Name);
  129. // remove the event-handlers
  130. m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
  131. m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
  132. m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
  133. // remove the interface
  134. m_scene.UnregisterModuleInterface<ITerrainModule>(this);
  135. }
  136. }
  137. public void Close()
  138. {
  139. }
  140. public Type ReplaceableInterface
  141. {
  142. get { return null; }
  143. }
  144. public string Name
  145. {
  146. get { return "TerrainModule"; }
  147. }
  148. #endregion
  149. #region ITerrainModule Members
  150. public void UndoTerrain(ITerrainChannel channel)
  151. {
  152. m_channel = channel;
  153. }
  154. /// <summary>
  155. /// Loads a terrain file from disk and installs it in the scene.
  156. /// </summary>
  157. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  158. public void LoadFromFile(string filename)
  159. {
  160. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  161. {
  162. if (filename.EndsWith(loader.Key))
  163. {
  164. lock (m_scene)
  165. {
  166. try
  167. {
  168. ITerrainChannel channel = loader.Value.LoadFile(filename);
  169. if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize)
  170. {
  171. // TerrainChannel expects a RegionSize x RegionSize map, currently
  172. throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
  173. Constants.RegionSize, Constants.RegionSize));
  174. }
  175. m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
  176. m_scene.Heightmap = channel;
  177. m_channel = channel;
  178. UpdateRevertMap();
  179. }
  180. catch (NotImplementedException)
  181. {
  182. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  183. " parser does not support file loading. (May be save only)");
  184. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  185. }
  186. catch (FileNotFoundException)
  187. {
  188. m_log.Error(
  189. "[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
  190. throw new TerrainException(
  191. String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
  192. }
  193. catch (ArgumentException e)
  194. {
  195. m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
  196. throw new TerrainException(
  197. String.Format("Unable to load heightmap: {0}", e.Message));
  198. }
  199. }
  200. CheckForTerrainUpdates();
  201. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  202. return;
  203. }
  204. }
  205. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  206. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  207. }
  208. /// <summary>
  209. /// Saves the current heightmap to a specified file.
  210. /// </summary>
  211. /// <param name="filename">The destination filename</param>
  212. public void SaveToFile(string filename)
  213. {
  214. try
  215. {
  216. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  217. {
  218. if (filename.EndsWith(loader.Key))
  219. {
  220. loader.Value.SaveFile(filename, m_channel);
  221. return;
  222. }
  223. }
  224. }
  225. catch (NotImplementedException)
  226. {
  227. m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
  228. throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
  229. }
  230. catch (IOException ioe)
  231. {
  232. m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
  233. throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message));
  234. }
  235. }
  236. /// <summary>
  237. /// Loads a terrain file from the specified URI
  238. /// </summary>
  239. /// <param name="filename">The name of the terrain to load</param>
  240. /// <param name="pathToTerrainHeightmap">The URI to the terrain height map</param>
  241. public void LoadFromStream(string filename, Uri pathToTerrainHeightmap)
  242. {
  243. LoadFromStream(filename, URIFetch(pathToTerrainHeightmap));
  244. }
  245. /// <summary>
  246. /// Loads a terrain file from a stream and installs it in the scene.
  247. /// </summary>
  248. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  249. /// <param name="stream"></param>
  250. public void LoadFromStream(string filename, Stream stream)
  251. {
  252. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  253. {
  254. if (filename.EndsWith(loader.Key))
  255. {
  256. lock (m_scene)
  257. {
  258. try
  259. {
  260. ITerrainChannel channel = loader.Value.LoadStream(stream);
  261. m_scene.Heightmap = channel;
  262. m_channel = channel;
  263. UpdateRevertMap();
  264. }
  265. catch (NotImplementedException)
  266. {
  267. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  268. " parser does not support file loading. (May be save only)");
  269. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  270. }
  271. }
  272. CheckForTerrainUpdates();
  273. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  274. return;
  275. }
  276. }
  277. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  278. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  279. }
  280. private static Stream URIFetch(Uri uri)
  281. {
  282. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  283. // request.Credentials = credentials;
  284. request.ContentLength = 0;
  285. request.KeepAlive = false;
  286. WebResponse response = request.GetResponse();
  287. Stream file = response.GetResponseStream();
  288. if (response.ContentLength == 0)
  289. throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
  290. // return new BufferedStream(file, (int) response.ContentLength);
  291. return new BufferedStream(file, 1000000);
  292. }
  293. /// <summary>
  294. /// Modify Land
  295. /// </summary>
  296. /// <param name="pos">Land-position (X,Y,0)</param>
  297. /// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
  298. /// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
  299. /// <param name="agentId">UUID of script-owner</param>
  300. public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId)
  301. {
  302. float duration = 0.25f;
  303. if (action == 0)
  304. duration = 4.0f;
  305. client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, agentId);
  306. }
  307. /// <summary>
  308. /// Saves the current heightmap to a specified stream.
  309. /// </summary>
  310. /// <param name="filename">The destination filename. Used here only to identify the image type</param>
  311. /// <param name="stream"></param>
  312. public void SaveToStream(string filename, Stream stream)
  313. {
  314. try
  315. {
  316. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  317. {
  318. if (filename.EndsWith(loader.Key))
  319. {
  320. loader.Value.SaveStream(stream, m_channel);
  321. return;
  322. }
  323. }
  324. }
  325. catch (NotImplementedException)
  326. {
  327. m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
  328. throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
  329. }
  330. }
  331. public void TaintTerrain ()
  332. {
  333. CheckForTerrainUpdates();
  334. }
  335. #region Plugin Loading Methods
  336. private void LoadPlugins()
  337. {
  338. m_plugineffects = new Dictionary<string, ITerrainEffect>();
  339. string plugineffectsPath = "Terrain";
  340. // Load the files in the Terrain/ dir
  341. if (!Directory.Exists(plugineffectsPath))
  342. return;
  343. string[] files = Directory.GetFiles(plugineffectsPath);
  344. foreach (string file in files)
  345. {
  346. m_log.Info("Loading effects in " + file);
  347. try
  348. {
  349. Assembly library = Assembly.LoadFrom(file);
  350. foreach (Type pluginType in library.GetTypes())
  351. {
  352. try
  353. {
  354. if (pluginType.IsAbstract || pluginType.IsNotPublic)
  355. continue;
  356. string typeName = pluginType.Name;
  357. if (pluginType.GetInterface("ITerrainEffect", false) != null)
  358. {
  359. ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString()));
  360. InstallPlugin(typeName, terEffect);
  361. }
  362. else if (pluginType.GetInterface("ITerrainLoader", false) != null)
  363. {
  364. ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString()));
  365. m_loaders[terLoader.FileExtension] = terLoader;
  366. m_log.Info("L ... " + typeName);
  367. }
  368. }
  369. catch (AmbiguousMatchException)
  370. {
  371. }
  372. }
  373. }
  374. catch (BadImageFormatException)
  375. {
  376. }
  377. }
  378. }
  379. public void InstallPlugin(string pluginName, ITerrainEffect effect)
  380. {
  381. lock (m_plugineffects)
  382. {
  383. if (!m_plugineffects.ContainsKey(pluginName))
  384. {
  385. m_plugineffects.Add(pluginName, effect);
  386. m_log.Info("E ... " + pluginName);
  387. }
  388. else
  389. {
  390. m_plugineffects[pluginName] = effect;
  391. m_log.Warn("E ... " + pluginName + " (Replaced)");
  392. }
  393. }
  394. }
  395. #endregion
  396. #endregion
  397. /// <summary>
  398. /// Installs into terrain module the standard suite of brushes
  399. /// </summary>
  400. private void InstallDefaultEffects()
  401. {
  402. // Draggable Paint Brush Effects
  403. m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
  404. m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
  405. m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
  406. m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
  407. m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
  408. m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
  409. m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
  410. m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
  411. m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
  412. // Area of effect selection effects
  413. m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
  414. m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
  415. m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
  416. m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
  417. m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
  418. m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
  419. // Filesystem load/save loaders
  420. m_loaders[".r32"] = new RAW32();
  421. m_loaders[".f32"] = m_loaders[".r32"];
  422. m_loaders[".ter"] = new Terragen();
  423. m_loaders[".raw"] = new LLRAW();
  424. m_loaders[".jpg"] = new JPEG();
  425. m_loaders[".jpeg"] = m_loaders[".jpg"];
  426. m_loaders[".bmp"] = new BMP();
  427. m_loaders[".png"] = new PNG();
  428. m_loaders[".gif"] = new GIF();
  429. m_loaders[".tif"] = new TIFF();
  430. m_loaders[".tiff"] = m_loaders[".tif"];
  431. }
  432. /// <summary>
  433. /// Saves the current state of the region into the revert map buffer.
  434. /// </summary>
  435. public void UpdateRevertMap()
  436. {
  437. int x;
  438. for (x = 0; x < m_channel.Width; x++)
  439. {
  440. int y;
  441. for (y = 0; y < m_channel.Height; y++)
  442. {
  443. m_revert[x, y] = m_channel[x, y];
  444. }
  445. }
  446. }
  447. /// <summary>
  448. /// Loads a tile from a larger terrain file and installs it into the region.
  449. /// </summary>
  450. /// <param name="filename">The terrain file to load</param>
  451. /// <param name="fileWidth">The width of the file in units</param>
  452. /// <param name="fileHeight">The height of the file in units</param>
  453. /// <param name="fileStartX">Where to begin our slice</param>
  454. /// <param name="fileStartY">Where to begin our slice</param>
  455. public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  456. {
  457. int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX;
  458. int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY;
  459. if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
  460. {
  461. // this region is included in the tile request
  462. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  463. {
  464. if (filename.EndsWith(loader.Key))
  465. {
  466. lock (m_scene)
  467. {
  468. ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
  469. fileWidth, fileHeight,
  470. (int) Constants.RegionSize,
  471. (int) Constants.RegionSize);
  472. m_scene.Heightmap = channel;
  473. m_channel = channel;
  474. UpdateRevertMap();
  475. }
  476. return;
  477. }
  478. }
  479. }
  480. }
  481. /// <summary>
  482. /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
  483. /// </summary>
  484. private void EventManager_OnTerrainTick()
  485. {
  486. if (m_tainted)
  487. {
  488. m_tainted = false;
  489. m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
  490. m_scene.SaveTerrain();
  491. // Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
  492. //m_scene.CreateTerrainTexture(true);
  493. }
  494. }
  495. /// <summary>
  496. /// Processes commandline input. Do not call directly.
  497. /// </summary>
  498. /// <param name="args">Commandline arguments</param>
  499. private void EventManager_OnPluginConsole(string[] args)
  500. {
  501. if (args[0] == "terrain")
  502. {
  503. if (args.Length == 1)
  504. {
  505. m_commander.ProcessConsoleCommand("help", new string[0]);
  506. return;
  507. }
  508. string[] tmpArgs = new string[args.Length - 2];
  509. int i;
  510. for (i = 2; i < args.Length; i++)
  511. tmpArgs[i - 2] = args[i];
  512. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  513. }
  514. }
  515. /// <summary>
  516. /// Installs terrain brush hook to IClientAPI
  517. /// </summary>
  518. /// <param name="client"></param>
  519. private void EventManager_OnNewClient(IClientAPI client)
  520. {
  521. client.OnModifyTerrain += client_OnModifyTerrain;
  522. client.OnBakeTerrain += client_OnBakeTerrain;
  523. client.OnLandUndo += client_OnLandUndo;
  524. client.OnUnackedTerrain += client_OnUnackedTerrain;
  525. }
  526. /// <summary>
  527. /// Checks to see if the terrain has been modified since last check
  528. /// but won't attempt to limit those changes to the limits specified in the estate settings
  529. /// currently invoked by the command line operations in the region server only
  530. /// </summary>
  531. private void CheckForTerrainUpdates()
  532. {
  533. CheckForTerrainUpdates(false);
  534. }
  535. /// <summary>
  536. /// Checks to see if the terrain has been modified since last check.
  537. /// If it has been modified, every all the terrain patches are sent to the client.
  538. /// If the call is asked to respect the estate settings for terrain_raise_limit and
  539. /// terrain_lower_limit, it will clamp terrain updates between these values
  540. /// currently invoked by client_OnModifyTerrain only and not the Commander interfaces
  541. /// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param>
  542. /// </summary>
  543. private void CheckForTerrainUpdates(bool respectEstateSettings)
  544. {
  545. bool shouldTaint = false;
  546. float[] serialised = m_channel.GetFloatsSerialised();
  547. int x;
  548. for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize)
  549. {
  550. int y;
  551. for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize)
  552. {
  553. if (m_channel.Tainted(x, y))
  554. {
  555. // if we should respect the estate settings then
  556. // fixup and height deltas that don't respect them
  557. if (respectEstateSettings && LimitChannelChanges(x, y))
  558. {
  559. // this has been vetoed, so update
  560. // what we are going to send to the client
  561. serialised = m_channel.GetFloatsSerialised();
  562. }
  563. SendToClients(serialised, x, y);
  564. shouldTaint = true;
  565. }
  566. }
  567. }
  568. if (shouldTaint)
  569. {
  570. m_tainted = true;
  571. }
  572. }
  573. /// <summary>
  574. /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
  575. /// are all within the current estate limits
  576. /// <returns>true if changes were limited, false otherwise</returns>
  577. /// </summary>
  578. private bool LimitChannelChanges(int xStart, int yStart)
  579. {
  580. bool changesLimited = false;
  581. double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
  582. double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
  583. // loop through the height map for this patch and compare it against
  584. // the revert map
  585. for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
  586. {
  587. for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
  588. {
  589. double requestedHeight = m_channel[x, y];
  590. double bakedHeight = m_revert[x, y];
  591. double requestedDelta = requestedHeight - bakedHeight;
  592. if (requestedDelta > maxDelta)
  593. {
  594. m_channel[x, y] = bakedHeight + maxDelta;
  595. changesLimited = true;
  596. }
  597. else if (requestedDelta < minDelta)
  598. {
  599. m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
  600. changesLimited = true;
  601. }
  602. }
  603. }
  604. return changesLimited;
  605. }
  606. private void client_OnLandUndo(IClientAPI client)
  607. {
  608. lock (m_undo)
  609. {
  610. if (m_undo.Count > 0)
  611. {
  612. LandUndoState goback = m_undo.Pop();
  613. if (goback != null)
  614. goback.PlaybackState();
  615. }
  616. }
  617. }
  618. /// <summary>
  619. /// Sends a copy of the current terrain to the scenes clients
  620. /// </summary>
  621. /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
  622. /// <param name="x">The patch corner to send</param>
  623. /// <param name="y">The patch corner to send</param>
  624. private void SendToClients(float[] serialised, int x, int y)
  625. {
  626. m_scene.ForEachClient(
  627. delegate(IClientAPI controller)
  628. { controller.SendLayerData(
  629. x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, serialised);
  630. }
  631. );
  632. }
  633. private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
  634. float north, float west, float south, float east, UUID agentId)
  635. {
  636. bool god = m_scene.Permissions.IsGod(user);
  637. bool allowed = false;
  638. if (north == south && east == west)
  639. {
  640. if (m_painteffects.ContainsKey((StandardTerrainEffects) action))
  641. {
  642. bool[,] allowMask = new bool[m_channel.Width,m_channel.Height];
  643. allowMask.Initialize();
  644. int n = size + 1;
  645. if (n > 2)
  646. n = 4;
  647. int zx = (int) (west + 0.5);
  648. int zy = (int) (north + 0.5);
  649. int dx;
  650. for (dx=-n; dx<=n; dx++)
  651. {
  652. int dy;
  653. for (dy=-n; dy<=n; dy++)
  654. {
  655. int x = zx + dx;
  656. int y = zy + dy;
  657. if (x>=0 && y>=0 && x<m_channel.Width && y<m_channel.Height)
  658. {
  659. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
  660. {
  661. allowMask[x, y] = true;
  662. allowed = true;
  663. }
  664. }
  665. }
  666. }
  667. if (allowed)
  668. {
  669. StoreUndoState();
  670. m_painteffects[(StandardTerrainEffects) action].PaintEffect(
  671. m_channel, allowMask, west, south, height, size, seconds);
  672. CheckForTerrainUpdates(!god); //revert changes outside estate limits
  673. }
  674. }
  675. else
  676. {
  677. m_log.Debug("Unknown terrain brush type " + action);
  678. }
  679. }
  680. else
  681. {
  682. if (m_floodeffects.ContainsKey((StandardTerrainEffects) action))
  683. {
  684. bool[,] fillArea = new bool[m_channel.Width,m_channel.Height];
  685. fillArea.Initialize();
  686. int x;
  687. for (x = 0; x < m_channel.Width; x++)
  688. {
  689. int y;
  690. for (y = 0; y < m_channel.Height; y++)
  691. {
  692. if (x < east && x > west)
  693. {
  694. if (y < north && y > south)
  695. {
  696. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
  697. {
  698. fillArea[x, y] = true;
  699. allowed = true;
  700. }
  701. }
  702. }
  703. }
  704. }
  705. if (allowed)
  706. {
  707. StoreUndoState();
  708. m_floodeffects[(StandardTerrainEffects) action].FloodEffect(
  709. m_channel, fillArea, size);
  710. CheckForTerrainUpdates(!god); //revert changes outside estate limits
  711. }
  712. }
  713. else
  714. {
  715. m_log.Debug("Unknown terrain flood type " + action);
  716. }
  717. }
  718. }
  719. private void client_OnBakeTerrain(IClientAPI remoteClient)
  720. {
  721. // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
  722. // for now check a point in the centre of the region
  723. if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
  724. {
  725. InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
  726. }
  727. }
  728. protected void client_OnUnackedTerrain(IClientAPI client, int patchX, int patchY)
  729. {
  730. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  731. client.SendLayerData(patchX, patchY, m_scene.Heightmap.GetFloatsSerialised());
  732. }
  733. private void StoreUndoState()
  734. {
  735. lock (m_undo)
  736. {
  737. if (m_undo.Count > 0)
  738. {
  739. LandUndoState last = m_undo.Peek();
  740. if (last != null)
  741. {
  742. if (last.Compare(m_channel))
  743. return;
  744. }
  745. }
  746. LandUndoState nUndo = new LandUndoState(this, m_channel);
  747. m_undo.Push(nUndo);
  748. }
  749. }
  750. #region Console Commands
  751. private void InterfaceLoadFile(Object[] args)
  752. {
  753. LoadFromFile((string) args[0]);
  754. CheckForTerrainUpdates();
  755. }
  756. private void InterfaceLoadTileFile(Object[] args)
  757. {
  758. LoadFromFile((string) args[0],
  759. (int) args[1],
  760. (int) args[2],
  761. (int) args[3],
  762. (int) args[4]);
  763. CheckForTerrainUpdates();
  764. }
  765. private void InterfaceSaveFile(Object[] args)
  766. {
  767. SaveToFile((string) args[0]);
  768. }
  769. private void InterfaceBakeTerrain(Object[] args)
  770. {
  771. UpdateRevertMap();
  772. }
  773. private void InterfaceRevertTerrain(Object[] args)
  774. {
  775. int x, y;
  776. for (x = 0; x < m_channel.Width; x++)
  777. for (y = 0; y < m_channel.Height; y++)
  778. m_channel[x, y] = m_revert[x, y];
  779. CheckForTerrainUpdates();
  780. }
  781. private void InterfaceFlipTerrain(Object[] args)
  782. {
  783. String direction = (String)args[0];
  784. if (direction.ToLower().StartsWith("y"))
  785. {
  786. for (int x = 0; x < Constants.RegionSize; x++)
  787. {
  788. for (int y = 0; y < Constants.RegionSize / 2; y++)
  789. {
  790. double height = m_channel[x, y];
  791. double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y];
  792. m_channel[x, y] = flippedHeight;
  793. m_channel[x, (int)Constants.RegionSize - 1 - y] = height;
  794. }
  795. }
  796. }
  797. else if (direction.ToLower().StartsWith("x"))
  798. {
  799. for (int y = 0; y < Constants.RegionSize; y++)
  800. {
  801. for (int x = 0; x < Constants.RegionSize / 2; x++)
  802. {
  803. double height = m_channel[x, y];
  804. double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y];
  805. m_channel[x, y] = flippedHeight;
  806. m_channel[(int)Constants.RegionSize - 1 - x, y] = height;
  807. }
  808. }
  809. }
  810. else
  811. {
  812. m_log.Error("Unrecognised direction - need x or y");
  813. }
  814. CheckForTerrainUpdates();
  815. }
  816. private void InterfaceRescaleTerrain(Object[] args)
  817. {
  818. double desiredMin = (double)args[0];
  819. double desiredMax = (double)args[1];
  820. // determine desired scaling factor
  821. double desiredRange = desiredMax - desiredMin;
  822. //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
  823. if (desiredRange == 0d)
  824. {
  825. // delta is zero so flatten at requested height
  826. InterfaceFillTerrain(new Object[] { args[1] });
  827. }
  828. else
  829. {
  830. //work out current heightmap range
  831. double currMin = double.MaxValue;
  832. double currMax = double.MinValue;
  833. int width = m_channel.Width;
  834. int height = m_channel.Height;
  835. for (int x = 0; x < width; x++)
  836. {
  837. for (int y = 0; y < height; y++)
  838. {
  839. double currHeight = m_channel[x, y];
  840. if (currHeight < currMin)
  841. {
  842. currMin = currHeight;
  843. }
  844. else if (currHeight > currMax)
  845. {
  846. currMax = currHeight;
  847. }
  848. }
  849. }
  850. double currRange = currMax - currMin;
  851. double scale = desiredRange / currRange;
  852. //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
  853. //m_log.InfoFormat("Scale = {0}", scale);
  854. // scale the heightmap accordingly
  855. for (int x = 0; x < width; x++)
  856. {
  857. for (int y = 0; y < height; y++)
  858. {
  859. double currHeight = m_channel[x, y] - currMin;
  860. m_channel[x, y] = desiredMin + (currHeight * scale);
  861. }
  862. }
  863. CheckForTerrainUpdates();
  864. }
  865. }
  866. private void InterfaceElevateTerrain(Object[] args)
  867. {
  868. int x, y;
  869. for (x = 0; x < m_channel.Width; x++)
  870. for (y = 0; y < m_channel.Height; y++)
  871. m_channel[x, y] += (double) args[0];
  872. CheckForTerrainUpdates();
  873. }
  874. private void InterfaceMultiplyTerrain(Object[] args)
  875. {
  876. int x, y;
  877. for (x = 0; x < m_channel.Width; x++)
  878. for (y = 0; y < m_channel.Height; y++)
  879. m_channel[x, y] *= (double) args[0];
  880. CheckForTerrainUpdates();
  881. }
  882. private void InterfaceLowerTerrain(Object[] args)
  883. {
  884. int x, y;
  885. for (x = 0; x < m_channel.Width; x++)
  886. for (y = 0; y < m_channel.Height; y++)
  887. m_channel[x, y] -= (double) args[0];
  888. CheckForTerrainUpdates();
  889. }
  890. private void InterfaceFillTerrain(Object[] args)
  891. {
  892. int x, y;
  893. for (x = 0; x < m_channel.Width; x++)
  894. for (y = 0; y < m_channel.Height; y++)
  895. m_channel[x, y] = (double) args[0];
  896. CheckForTerrainUpdates();
  897. }
  898. private void InterfaceShowDebugStats(Object[] args)
  899. {
  900. double max = Double.MinValue;
  901. double min = double.MaxValue;
  902. double sum = 0;
  903. int x;
  904. for (x = 0; x < m_channel.Width; x++)
  905. {
  906. int y;
  907. for (y = 0; y < m_channel.Height; y++)
  908. {
  909. sum += m_channel[x, y];
  910. if (max < m_channel[x, y])
  911. max = m_channel[x, y];
  912. if (min > m_channel[x, y])
  913. min = m_channel[x, y];
  914. }
  915. }
  916. double avg = sum / (m_channel.Height * m_channel.Width);
  917. m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height);
  918. m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum);
  919. }
  920. private void InterfaceEnableExperimentalBrushes(Object[] args)
  921. {
  922. if ((bool) args[0])
  923. {
  924. m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
  925. m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
  926. m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
  927. }
  928. else
  929. {
  930. InstallDefaultEffects();
  931. }
  932. }
  933. private void InterfaceRunPluginEffect(Object[] args)
  934. {
  935. if ((string) args[0] == "list")
  936. {
  937. m_log.Info("List of loaded plugins");
  938. foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
  939. {
  940. m_log.Info(kvp.Key);
  941. }
  942. return;
  943. }
  944. if ((string) args[0] == "reload")
  945. {
  946. LoadPlugins();
  947. return;
  948. }
  949. if (m_plugineffects.ContainsKey((string) args[0]))
  950. {
  951. m_plugineffects[(string) args[0]].RunEffect(m_channel);
  952. CheckForTerrainUpdates();
  953. }
  954. else
  955. {
  956. m_log.Warn("No such plugin effect loaded.");
  957. }
  958. }
  959. private void InstallInterfaces()
  960. {
  961. // Load / Save
  962. string supportedFileExtensions = "";
  963. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  964. supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")";
  965. Command loadFromFileCommand =
  966. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
  967. loadFromFileCommand.AddArgument("filename",
  968. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  969. supportedFileExtensions, "String");
  970. Command saveToFileCommand =
  971. new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
  972. saveToFileCommand.AddArgument("filename",
  973. "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
  974. supportedFileExtensions, "String");
  975. Command loadFromTileCommand =
  976. new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
  977. loadFromTileCommand.AddArgument("filename",
  978. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  979. supportedFileExtensions, "String");
  980. loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  981. loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  982. loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  983. "Integer");
  984. loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
  985. "Integer");
  986. // Terrain adjustments
  987. Command fillRegionCommand =
  988. new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
  989. fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
  990. "Double");
  991. Command elevateCommand =
  992. new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
  993. elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
  994. Command lowerCommand =
  995. new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
  996. lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
  997. Command multiplyCommand =
  998. new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
  999. multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
  1000. Command bakeRegionCommand =
  1001. new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
  1002. Command revertRegionCommand =
  1003. new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
  1004. Command flipCommand =
  1005. new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
  1006. flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
  1007. Command rescaleCommand =
  1008. new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
  1009. rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
  1010. rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
  1011. // Debug
  1012. Command showDebugStatsCommand =
  1013. new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
  1014. "Shows some information about the regions heightmap for debugging purposes.");
  1015. Command experimentalBrushesCommand =
  1016. new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
  1017. "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
  1018. experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
  1019. //Plugins
  1020. Command pluginRunCommand =
  1021. new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
  1022. pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
  1023. m_commander.RegisterCommand("load", loadFromFileCommand);
  1024. m_commander.RegisterCommand("load-tile", loadFromTileCommand);
  1025. m_commander.RegisterCommand("save", saveToFileCommand);
  1026. m_commander.RegisterCommand("fill", fillRegionCommand);
  1027. m_commander.RegisterCommand("elevate", elevateCommand);
  1028. m_commander.RegisterCommand("lower", lowerCommand);
  1029. m_commander.RegisterCommand("multiply", multiplyCommand);
  1030. m_commander.RegisterCommand("bake", bakeRegionCommand);
  1031. m_commander.RegisterCommand("revert", revertRegionCommand);
  1032. m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
  1033. m_commander.RegisterCommand("stats", showDebugStatsCommand);
  1034. m_commander.RegisterCommand("effect", pluginRunCommand);
  1035. m_commander.RegisterCommand("flip", flipCommand);
  1036. m_commander.RegisterCommand("rescale", rescaleCommand);
  1037. // Add this to our scene so scripts can call these functions
  1038. m_scene.RegisterModuleCommander(m_commander);
  1039. }
  1040. #endregion
  1041. }
  1042. }