TerrainModule.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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 log4net;
  32. using Nini.Config;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  36. using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
  37. using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
  38. using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. namespace OpenSim.Region.CoreModules.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 available 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 available 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(m_commander);
  889. }
  890. #endregion
  891. }
  892. }