TerrainModule.cs 56 KB

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