TerrainModule.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  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. // Load the files in the Terrain/ dir
  340. string[] files = Directory.GetFiles("Terrain");
  341. foreach (string file in files)
  342. {
  343. m_log.Info("Loading effects in " + file);
  344. try
  345. {
  346. Assembly library = Assembly.LoadFrom(file);
  347. foreach (Type pluginType in library.GetTypes())
  348. {
  349. try
  350. {
  351. if (pluginType.IsAbstract || pluginType.IsNotPublic)
  352. continue;
  353. string typeName = pluginType.Name;
  354. if (pluginType.GetInterface("ITerrainEffect", false) != null)
  355. {
  356. ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString()));
  357. InstallPlugin(typeName, terEffect);
  358. }
  359. else if (pluginType.GetInterface("ITerrainLoader", false) != null)
  360. {
  361. ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString()));
  362. m_loaders[terLoader.FileExtension] = terLoader;
  363. m_log.Info("L ... " + typeName);
  364. }
  365. }
  366. catch (AmbiguousMatchException)
  367. {
  368. }
  369. }
  370. }
  371. catch (BadImageFormatException)
  372. {
  373. }
  374. }
  375. }
  376. public void InstallPlugin(string pluginName, ITerrainEffect effect)
  377. {
  378. lock (m_plugineffects)
  379. {
  380. if (!m_plugineffects.ContainsKey(pluginName))
  381. {
  382. m_plugineffects.Add(pluginName, effect);
  383. m_log.Info("E ... " + pluginName);
  384. }
  385. else
  386. {
  387. m_plugineffects[pluginName] = effect;
  388. m_log.Warn("E ... " + pluginName + " (Replaced)");
  389. }
  390. }
  391. }
  392. #endregion
  393. #endregion
  394. /// <summary>
  395. /// Installs into terrain module the standard suite of brushes
  396. /// </summary>
  397. private void InstallDefaultEffects()
  398. {
  399. // Draggable Paint Brush Effects
  400. m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
  401. m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
  402. m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
  403. m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
  404. m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
  405. m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
  406. m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
  407. m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
  408. m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
  409. // Area of effect selection effects
  410. m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
  411. m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
  412. m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
  413. m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
  414. m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
  415. m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
  416. // Filesystem load/save loaders
  417. m_loaders[".r32"] = new RAW32();
  418. m_loaders[".f32"] = m_loaders[".r32"];
  419. m_loaders[".ter"] = new Terragen();
  420. m_loaders[".raw"] = new LLRAW();
  421. m_loaders[".jpg"] = new JPEG();
  422. m_loaders[".jpeg"] = m_loaders[".jpg"];
  423. m_loaders[".bmp"] = new BMP();
  424. m_loaders[".png"] = new PNG();
  425. m_loaders[".gif"] = new GIF();
  426. m_loaders[".tif"] = new TIFF();
  427. m_loaders[".tiff"] = m_loaders[".tif"];
  428. }
  429. /// <summary>
  430. /// Saves the current state of the region into the revert map buffer.
  431. /// </summary>
  432. public void UpdateRevertMap()
  433. {
  434. int x;
  435. for (x = 0; x < m_channel.Width; x++)
  436. {
  437. int y;
  438. for (y = 0; y < m_channel.Height; y++)
  439. {
  440. m_revert[x, y] = m_channel[x, y];
  441. }
  442. }
  443. }
  444. /// <summary>
  445. /// Loads a tile from a larger terrain file and installs it into the region.
  446. /// </summary>
  447. /// <param name="filename">The terrain file to load</param>
  448. /// <param name="fileWidth">The width of the file in units</param>
  449. /// <param name="fileHeight">The height of the file in units</param>
  450. /// <param name="fileStartX">Where to begin our slice</param>
  451. /// <param name="fileStartY">Where to begin our slice</param>
  452. public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  453. {
  454. int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX;
  455. int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY;
  456. if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
  457. {
  458. // this region is included in the tile request
  459. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  460. {
  461. if (filename.EndsWith(loader.Key))
  462. {
  463. lock (m_scene)
  464. {
  465. ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
  466. fileWidth, fileHeight,
  467. (int) Constants.RegionSize,
  468. (int) Constants.RegionSize);
  469. m_scene.Heightmap = channel;
  470. m_channel = channel;
  471. UpdateRevertMap();
  472. }
  473. return;
  474. }
  475. }
  476. }
  477. }
  478. /// <summary>
  479. /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
  480. /// </summary>
  481. private void EventManager_OnTerrainTick()
  482. {
  483. if (m_tainted)
  484. {
  485. m_tainted = false;
  486. m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
  487. m_scene.SaveTerrain();
  488. // Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
  489. //m_scene.CreateTerrainTexture(true);
  490. }
  491. }
  492. /// <summary>
  493. /// Processes commandline input. Do not call directly.
  494. /// </summary>
  495. /// <param name="args">Commandline arguments</param>
  496. private void EventManager_OnPluginConsole(string[] args)
  497. {
  498. if (args[0] == "terrain")
  499. {
  500. if (args.Length == 1)
  501. {
  502. m_commander.ProcessConsoleCommand("help", new string[0]);
  503. return;
  504. }
  505. string[] tmpArgs = new string[args.Length - 2];
  506. int i;
  507. for (i = 2; i < args.Length; i++)
  508. tmpArgs[i - 2] = args[i];
  509. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  510. }
  511. }
  512. /// <summary>
  513. /// Installs terrain brush hook to IClientAPI
  514. /// </summary>
  515. /// <param name="client"></param>
  516. private void EventManager_OnNewClient(IClientAPI client)
  517. {
  518. client.OnModifyTerrain += client_OnModifyTerrain;
  519. client.OnBakeTerrain += client_OnBakeTerrain;
  520. client.OnLandUndo += client_OnLandUndo;
  521. }
  522. /// <summary>
  523. /// Checks to see if the terrain has been modified since last check
  524. /// but won't attempt to limit those changes to the limits specified in the estate settings
  525. /// currently invoked by the command line operations in the region server only
  526. /// </summary>
  527. private void CheckForTerrainUpdates()
  528. {
  529. CheckForTerrainUpdates(false);
  530. }
  531. /// <summary>
  532. /// Checks to see if the terrain has been modified since last check.
  533. /// If it has been modified, every all the terrain patches are sent to the client.
  534. /// If the call is asked to respect the estate settings for terrain_raise_limit and
  535. /// terrain_lower_limit, it will clamp terrain updates between these values
  536. /// currently invoked by client_OnModifyTerrain only and not the Commander interfaces
  537. /// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param>
  538. /// </summary>
  539. private void CheckForTerrainUpdates(bool respectEstateSettings)
  540. {
  541. bool shouldTaint = false;
  542. float[] serialised = m_channel.GetFloatsSerialised();
  543. int x;
  544. for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize)
  545. {
  546. int y;
  547. for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize)
  548. {
  549. if (m_channel.Tainted(x, y))
  550. {
  551. // if we should respect the estate settings then
  552. // fixup and height deltas that don't respect them
  553. if (respectEstateSettings && LimitChannelChanges(x, y))
  554. {
  555. // this has been vetoed, so update
  556. // what we are going to send to the client
  557. serialised = m_channel.GetFloatsSerialised();
  558. }
  559. SendToClients(serialised, x, y);
  560. shouldTaint = true;
  561. }
  562. }
  563. }
  564. if (shouldTaint)
  565. {
  566. m_tainted = true;
  567. }
  568. }
  569. /// <summary>
  570. /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
  571. /// are all within the current estate limits
  572. /// <returns>true if changes were limited, false otherwise</returns>
  573. /// </summary>
  574. private bool LimitChannelChanges(int xStart, int yStart)
  575. {
  576. bool changesLimited = false;
  577. double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
  578. double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
  579. // loop through the height map for this patch and compare it against
  580. // the revert map
  581. for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
  582. {
  583. for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
  584. {
  585. double requestedHeight = m_channel[x, y];
  586. double bakedHeight = m_revert[x, y];
  587. double requestedDelta = requestedHeight - bakedHeight;
  588. if (requestedDelta > maxDelta)
  589. {
  590. m_channel[x, y] = bakedHeight + maxDelta;
  591. changesLimited = true;
  592. }
  593. else if (requestedDelta < minDelta)
  594. {
  595. m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
  596. changesLimited = true;
  597. }
  598. }
  599. }
  600. return changesLimited;
  601. }
  602. private void client_OnLandUndo(IClientAPI client)
  603. {
  604. lock (m_undo)
  605. {
  606. if (m_undo.Count > 0)
  607. {
  608. LandUndoState goback = m_undo.Pop();
  609. if (goback != null)
  610. goback.PlaybackState();
  611. }
  612. }
  613. }
  614. /// <summary>
  615. /// Sends a copy of the current terrain to the scenes clients
  616. /// </summary>
  617. /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
  618. /// <param name="x">The patch corner to send</param>
  619. /// <param name="y">The patch corner to send</param>
  620. private void SendToClients(float[] serialised, int x, int y)
  621. {
  622. m_scene.ForEachClient(
  623. delegate(IClientAPI controller)
  624. { controller.SendLayerData(
  625. x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, serialised);
  626. }
  627. );
  628. }
  629. private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
  630. float north, float west, float south, float east, UUID agentId)
  631. {
  632. bool god = m_scene.Permissions.IsGod(user);
  633. bool allowed = false;
  634. if (north == south && east == west)
  635. {
  636. if (m_painteffects.ContainsKey((StandardTerrainEffects) action))
  637. {
  638. bool[,] allowMask = new bool[m_channel.Width,m_channel.Height];
  639. allowMask.Initialize();
  640. int n = size + 1;
  641. if (n > 2)
  642. n = 4;
  643. int zx = (int) (west + 0.5);
  644. int zy = (int) (north + 0.5);
  645. int dx;
  646. for (dx=-n; dx<=n; dx++)
  647. {
  648. int dy;
  649. for (dy=-n; dy<=n; dy++)
  650. {
  651. int x = zx + dx;
  652. int y = zy + dy;
  653. if (x>=0 && y>=0 && x<m_channel.Width && y<m_channel.Height)
  654. {
  655. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
  656. {
  657. allowMask[x, y] = true;
  658. allowed = true;
  659. }
  660. }
  661. }
  662. }
  663. if (allowed)
  664. {
  665. StoreUndoState();
  666. m_painteffects[(StandardTerrainEffects) action].PaintEffect(
  667. m_channel, allowMask, west, south, height, size, seconds);
  668. CheckForTerrainUpdates(!god); //revert changes outside estate limits
  669. }
  670. }
  671. else
  672. {
  673. m_log.Debug("Unknown terrain brush type " + action);
  674. }
  675. }
  676. else
  677. {
  678. if (m_floodeffects.ContainsKey((StandardTerrainEffects) action))
  679. {
  680. bool[,] fillArea = new bool[m_channel.Width,m_channel.Height];
  681. fillArea.Initialize();
  682. int x;
  683. for (x = 0; x < m_channel.Width; x++)
  684. {
  685. int y;
  686. for (y = 0; y < m_channel.Height; y++)
  687. {
  688. if (x < east && x > west)
  689. {
  690. if (y < north && y > south)
  691. {
  692. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
  693. {
  694. fillArea[x, y] = true;
  695. allowed = true;
  696. }
  697. }
  698. }
  699. }
  700. }
  701. if (allowed)
  702. {
  703. StoreUndoState();
  704. m_floodeffects[(StandardTerrainEffects) action].FloodEffect(
  705. m_channel, fillArea, size);
  706. CheckForTerrainUpdates(!god); //revert changes outside estate limits
  707. }
  708. }
  709. else
  710. {
  711. m_log.Debug("Unknown terrain flood type " + action);
  712. }
  713. }
  714. }
  715. private void client_OnBakeTerrain(IClientAPI remoteClient)
  716. {
  717. // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
  718. // for now check a point in the centre of the region
  719. if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
  720. {
  721. InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
  722. }
  723. }
  724. private void StoreUndoState()
  725. {
  726. lock (m_undo)
  727. {
  728. if (m_undo.Count > 0)
  729. {
  730. LandUndoState last = m_undo.Peek();
  731. if (last != null)
  732. {
  733. if (last.Compare(m_channel))
  734. return;
  735. }
  736. }
  737. LandUndoState nUndo = new LandUndoState(this, m_channel);
  738. m_undo.Push(nUndo);
  739. }
  740. }
  741. #region Console Commands
  742. private void InterfaceLoadFile(Object[] args)
  743. {
  744. LoadFromFile((string) args[0]);
  745. CheckForTerrainUpdates();
  746. }
  747. private void InterfaceLoadTileFile(Object[] args)
  748. {
  749. LoadFromFile((string) args[0],
  750. (int) args[1],
  751. (int) args[2],
  752. (int) args[3],
  753. (int) args[4]);
  754. CheckForTerrainUpdates();
  755. }
  756. private void InterfaceSaveFile(Object[] args)
  757. {
  758. SaveToFile((string) args[0]);
  759. }
  760. private void InterfaceBakeTerrain(Object[] args)
  761. {
  762. UpdateRevertMap();
  763. }
  764. private void InterfaceRevertTerrain(Object[] args)
  765. {
  766. int x, y;
  767. for (x = 0; x < m_channel.Width; x++)
  768. for (y = 0; y < m_channel.Height; y++)
  769. m_channel[x, y] = m_revert[x, y];
  770. CheckForTerrainUpdates();
  771. }
  772. private void InterfaceFlipTerrain(Object[] args)
  773. {
  774. String direction = (String)args[0];
  775. if (direction.ToLower().StartsWith("y"))
  776. {
  777. for (int x = 0; x < Constants.RegionSize; x++)
  778. {
  779. for (int y = 0; y < Constants.RegionSize / 2; y++)
  780. {
  781. double height = m_channel[x, y];
  782. double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y];
  783. m_channel[x, y] = flippedHeight;
  784. m_channel[x, (int)Constants.RegionSize - 1 - y] = height;
  785. }
  786. }
  787. }
  788. else if (direction.ToLower().StartsWith("x"))
  789. {
  790. for (int y = 0; y < Constants.RegionSize; y++)
  791. {
  792. for (int x = 0; x < Constants.RegionSize / 2; x++)
  793. {
  794. double height = m_channel[x, y];
  795. double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y];
  796. m_channel[x, y] = flippedHeight;
  797. m_channel[(int)Constants.RegionSize - 1 - x, y] = height;
  798. }
  799. }
  800. }
  801. else
  802. {
  803. m_log.Error("Unrecognised direction - need x or y");
  804. }
  805. CheckForTerrainUpdates();
  806. }
  807. private void InterfaceRescaleTerrain(Object[] args)
  808. {
  809. double desiredMin = (double)args[0];
  810. double desiredMax = (double)args[1];
  811. // determine desired scaling factor
  812. double desiredRange = desiredMax - desiredMin;
  813. //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
  814. if (desiredRange == 0d)
  815. {
  816. // delta is zero so flatten at requested height
  817. InterfaceFillTerrain(new Object[] { args[1] });
  818. }
  819. else
  820. {
  821. //work out current heightmap range
  822. double currMin = double.MaxValue;
  823. double currMax = double.MinValue;
  824. int width = m_channel.Width;
  825. int height = m_channel.Height;
  826. for (int x = 0; x < width; x++)
  827. {
  828. for (int y = 0; y < height; y++)
  829. {
  830. double currHeight = m_channel[x, y];
  831. if (currHeight < currMin)
  832. {
  833. currMin = currHeight;
  834. }
  835. else if (currHeight > currMax)
  836. {
  837. currMax = currHeight;
  838. }
  839. }
  840. }
  841. double currRange = currMax - currMin;
  842. double scale = desiredRange / currRange;
  843. //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
  844. //m_log.InfoFormat("Scale = {0}", scale);
  845. // scale the heightmap accordingly
  846. for (int x = 0; x < width; x++)
  847. {
  848. for (int y = 0; y < height; y++)
  849. {
  850. double currHeight = m_channel[x, y] - currMin;
  851. m_channel[x, y] = desiredMin + (currHeight * scale);
  852. }
  853. }
  854. CheckForTerrainUpdates();
  855. }
  856. }
  857. private void InterfaceElevateTerrain(Object[] args)
  858. {
  859. int x, y;
  860. for (x = 0; x < m_channel.Width; x++)
  861. for (y = 0; y < m_channel.Height; y++)
  862. m_channel[x, y] += (double) args[0];
  863. CheckForTerrainUpdates();
  864. }
  865. private void InterfaceMultiplyTerrain(Object[] args)
  866. {
  867. int x, y;
  868. for (x = 0; x < m_channel.Width; x++)
  869. for (y = 0; y < m_channel.Height; y++)
  870. m_channel[x, y] *= (double) args[0];
  871. CheckForTerrainUpdates();
  872. }
  873. private void InterfaceLowerTerrain(Object[] args)
  874. {
  875. int x, y;
  876. for (x = 0; x < m_channel.Width; x++)
  877. for (y = 0; y < m_channel.Height; y++)
  878. m_channel[x, y] -= (double) args[0];
  879. CheckForTerrainUpdates();
  880. }
  881. private void InterfaceFillTerrain(Object[] args)
  882. {
  883. int x, y;
  884. for (x = 0; x < m_channel.Width; x++)
  885. for (y = 0; y < m_channel.Height; y++)
  886. m_channel[x, y] = (double) args[0];
  887. CheckForTerrainUpdates();
  888. }
  889. private void InterfaceShowDebugStats(Object[] args)
  890. {
  891. double max = Double.MinValue;
  892. double min = double.MaxValue;
  893. double sum = 0;
  894. int x;
  895. for (x = 0; x < m_channel.Width; x++)
  896. {
  897. int y;
  898. for (y = 0; y < m_channel.Height; y++)
  899. {
  900. sum += m_channel[x, y];
  901. if (max < m_channel[x, y])
  902. max = m_channel[x, y];
  903. if (min > m_channel[x, y])
  904. min = m_channel[x, y];
  905. }
  906. }
  907. double avg = sum / (m_channel.Height * m_channel.Width);
  908. m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height);
  909. m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum);
  910. }
  911. private void InterfaceEnableExperimentalBrushes(Object[] args)
  912. {
  913. if ((bool) args[0])
  914. {
  915. m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
  916. m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
  917. m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
  918. }
  919. else
  920. {
  921. InstallDefaultEffects();
  922. }
  923. }
  924. private void InterfaceRunPluginEffect(Object[] args)
  925. {
  926. if ((string) args[0] == "list")
  927. {
  928. m_log.Info("List of loaded plugins");
  929. foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
  930. {
  931. m_log.Info(kvp.Key);
  932. }
  933. return;
  934. }
  935. if ((string) args[0] == "reload")
  936. {
  937. LoadPlugins();
  938. return;
  939. }
  940. if (m_plugineffects.ContainsKey((string) args[0]))
  941. {
  942. m_plugineffects[(string) args[0]].RunEffect(m_channel);
  943. CheckForTerrainUpdates();
  944. }
  945. else
  946. {
  947. m_log.Warn("No such plugin effect loaded.");
  948. }
  949. }
  950. private void InstallInterfaces()
  951. {
  952. // Load / Save
  953. string supportedFileExtensions = "";
  954. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  955. supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")";
  956. Command loadFromFileCommand =
  957. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
  958. loadFromFileCommand.AddArgument("filename",
  959. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  960. supportedFileExtensions, "String");
  961. Command saveToFileCommand =
  962. new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
  963. saveToFileCommand.AddArgument("filename",
  964. "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
  965. supportedFileExtensions, "String");
  966. Command loadFromTileCommand =
  967. new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
  968. loadFromTileCommand.AddArgument("filename",
  969. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  970. supportedFileExtensions, "String");
  971. loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  972. loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  973. loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  974. "Integer");
  975. loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
  976. "Integer");
  977. // Terrain adjustments
  978. Command fillRegionCommand =
  979. new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
  980. fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
  981. "Double");
  982. Command elevateCommand =
  983. new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
  984. elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
  985. Command lowerCommand =
  986. new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
  987. lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
  988. Command multiplyCommand =
  989. new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
  990. multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
  991. Command bakeRegionCommand =
  992. new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
  993. Command revertRegionCommand =
  994. new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
  995. Command flipCommand =
  996. new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
  997. flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
  998. Command rescaleCommand =
  999. new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
  1000. rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
  1001. rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
  1002. // Debug
  1003. Command showDebugStatsCommand =
  1004. new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
  1005. "Shows some information about the regions heightmap for debugging purposes.");
  1006. Command experimentalBrushesCommand =
  1007. new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
  1008. "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
  1009. experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
  1010. //Plugins
  1011. Command pluginRunCommand =
  1012. new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
  1013. pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
  1014. m_commander.RegisterCommand("load", loadFromFileCommand);
  1015. m_commander.RegisterCommand("load-tile", loadFromTileCommand);
  1016. m_commander.RegisterCommand("save", saveToFileCommand);
  1017. m_commander.RegisterCommand("fill", fillRegionCommand);
  1018. m_commander.RegisterCommand("elevate", elevateCommand);
  1019. m_commander.RegisterCommand("lower", lowerCommand);
  1020. m_commander.RegisterCommand("multiply", multiplyCommand);
  1021. m_commander.RegisterCommand("bake", bakeRegionCommand);
  1022. m_commander.RegisterCommand("revert", revertRegionCommand);
  1023. m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
  1024. m_commander.RegisterCommand("stats", showDebugStatsCommand);
  1025. m_commander.RegisterCommand("effect", pluginRunCommand);
  1026. m_commander.RegisterCommand("flip", flipCommand);
  1027. m_commander.RegisterCommand("rescale", rescaleCommand);
  1028. // Add this to our scene so scripts can call these functions
  1029. m_scene.RegisterModuleCommander(m_commander);
  1030. }
  1031. #endregion
  1032. }
  1033. }