TerrainModule.cs 42 KB

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