TerrainModule.cs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  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 System.Threading;
  33. using log4net;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using Mono.Addins;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  40. using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
  41. using OpenSim.Region.CoreModules.World.Terrain.Modifiers;
  42. using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
  43. using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. namespace OpenSim.Region.CoreModules.World.Terrain
  47. {
  48. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TerrainModule")]
  49. public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
  50. {
  51. #region StandardTerrainEffects enum
  52. /// <summary>
  53. /// A standard set of terrain brushes and effects recognised by viewers
  54. /// </summary>
  55. public enum StandardTerrainEffects : byte
  56. {
  57. Flatten = 0,
  58. Raise = 1,
  59. Lower = 2,
  60. Smooth = 3,
  61. Noise = 4,
  62. Revert = 5,
  63. }
  64. #endregion
  65. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  66. #pragma warning disable 414
  67. private static readonly string LogHeader = "[TERRAIN MODULE]";
  68. #pragma warning restore 414
  69. private readonly Commander m_commander = new Commander("terrain");
  70. private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
  71. private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
  72. new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
  73. private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
  74. new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
  75. private Dictionary<string, ITerrainModifier> m_modifyOperations = new Dictionary<string, ITerrainModifier>();
  76. private Dictionary<string, ITerrainEffect> m_plugineffects;
  77. private ITerrainChannel m_channel;
  78. private ITerrainChannel m_baked;
  79. private Scene m_scene;
  80. private volatile bool m_tainted;
  81. private String m_InitialTerrain = "pinhead-island";
  82. // If true, send terrain patch updates to clients based on their view distance
  83. private bool m_sendTerrainUpdatesByViewDistance = true;
  84. // Class to keep the per client collection of terrain patches that must be sent.
  85. // A patch is set to 'true' meaning it should be sent to the client. Once the
  86. // patch packet is queued to the client, the bit for that patch is set to 'false'.
  87. private class PatchUpdates
  88. {
  89. private bool[,] updated; // for each patch, whether it needs to be sent to this client
  90. private int updateCount; // number of patches that need to be sent
  91. public ScenePresence Presence; // a reference to the client to send to
  92. public bool sendAll;
  93. public int sendAllcurrentX;
  94. public int sendAllcurrentY;
  95. public PatchUpdates(TerrainData terrData, ScenePresence pPresence)
  96. {
  97. updated = new bool[terrData.SizeX / Constants.TerrainPatchSize, terrData.SizeY / Constants.TerrainPatchSize];
  98. updateCount = 0;
  99. Presence = pPresence;
  100. // Initially, send all patches to the client
  101. SetAll(true);
  102. }
  103. // Returns 'true' if there are any patches marked for sending
  104. public bool HasUpdates()
  105. {
  106. return (updateCount > 0);
  107. }
  108. public void SetByXY(int x, int y, bool state)
  109. {
  110. this.SetByPatch(x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, state);
  111. }
  112. public bool GetByPatch(int patchX, int patchY)
  113. {
  114. return updated[patchX, patchY];
  115. }
  116. public void SetByPatch(int patchX, int patchY, bool state)
  117. {
  118. bool prevState = updated[patchX, patchY];
  119. if (!prevState && state)
  120. updateCount++;
  121. if (prevState && !state)
  122. updateCount--;
  123. updated[patchX, patchY] = state;
  124. }
  125. public void SetAll(bool state)
  126. {
  127. updateCount = 0;
  128. for (int xx = 0; xx < updated.GetLength(0); xx++)
  129. for (int yy = 0; yy < updated.GetLength(1); yy++)
  130. updated[xx, yy] = state;
  131. if (state)
  132. updateCount = updated.GetLength(0) * updated.GetLength(1);
  133. sendAllcurrentX = 0;
  134. sendAllcurrentY = 0;
  135. sendAll = true;
  136. }
  137. // Logically OR's the terrain data's patch taint map into this client's update map.
  138. public void SetAll(TerrainData terrData)
  139. {
  140. if (updated.GetLength(0) != (terrData.SizeX / Constants.TerrainPatchSize)
  141. || updated.GetLength(1) != (terrData.SizeY / Constants.TerrainPatchSize))
  142. {
  143. throw new Exception(
  144. String.Format("{0} PatchUpdates.SetAll: patch array not same size as terrain. arr=<{1},{2}>, terr=<{3},{4}>",
  145. LogHeader, updated.GetLength(0), updated.GetLength(1),
  146. terrData.SizeX / Constants.TerrainPatchSize, terrData.SizeY / Constants.TerrainPatchSize)
  147. );
  148. }
  149. for (int xx = 0; xx < terrData.SizeX; xx += Constants.TerrainPatchSize)
  150. {
  151. for (int yy = 0; yy < terrData.SizeY; yy += Constants.TerrainPatchSize)
  152. {
  153. // Only set tainted. The patch bit may be set if the patch was to be sent later.
  154. if (terrData.IsTaintedAt(xx, yy, false))
  155. {
  156. this.SetByXY(xx, yy, true);
  157. }
  158. }
  159. }
  160. }
  161. }
  162. // The flags of which terrain patches to send for each of the ScenePresence's
  163. private Dictionary<UUID, PatchUpdates> m_perClientPatchUpdates = new Dictionary<UUID, PatchUpdates>();
  164. /// <summary>
  165. /// Human readable list of terrain file extensions that are supported.
  166. /// </summary>
  167. private string m_supportedFileExtensions = "";
  168. //For terrain save-tile file extensions
  169. private string m_supportFileExtensionsForTileSave = "";
  170. #region ICommandableModule Members
  171. public ICommander CommandInterface {
  172. get { return m_commander; }
  173. }
  174. #endregion
  175. #region INonSharedRegionModule Members
  176. /// <summary>
  177. /// Creates and initialises a terrain module for a region
  178. /// </summary>
  179. /// <param name="scene">Region initialising</param>
  180. /// <param name="config">Config for the region</param>
  181. public void Initialise(IConfigSource config)
  182. {
  183. IConfig terrainConfig = config.Configs["Terrain"];
  184. if (terrainConfig != null)
  185. {
  186. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  187. m_sendTerrainUpdatesByViewDistance =
  188. terrainConfig.GetBoolean(
  189. "SendTerrainUpdatesByViewDistance",m_sendTerrainUpdatesByViewDistance);
  190. }
  191. }
  192. public void AddRegion(Scene scene)
  193. {
  194. m_scene = scene;
  195. // Install terrain module in the simulator
  196. lock(m_scene)
  197. {
  198. if(m_scene.Bakedmap != null)
  199. {
  200. m_baked = m_scene.Bakedmap;
  201. }
  202. if (m_scene.Heightmap == null)
  203. {
  204. if(m_baked != null)
  205. m_channel = m_baked.MakeCopy();
  206. else
  207. m_channel = new TerrainChannel(m_InitialTerrain,
  208. (int)m_scene.RegionInfo.RegionSizeX,
  209. (int)m_scene.RegionInfo.RegionSizeY,
  210. (int)m_scene.RegionInfo.RegionSizeZ);
  211. m_scene.Heightmap = m_channel;
  212. }
  213. else
  214. {
  215. m_channel = m_scene.Heightmap;
  216. }
  217. if(m_baked == null)
  218. UpdateBakedMap();
  219. m_scene.RegisterModuleInterface<ITerrainModule>(this);
  220. m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
  221. m_scene.EventManager.OnClientClosed += EventManager_OnClientClosed;
  222. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  223. m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
  224. m_scene.EventManager.OnTerrainCheckUpdates += EventManager_TerrainCheckUpdates;
  225. }
  226. InstallDefaultEffects();
  227. LoadPlugins();
  228. // Generate user-readable extensions list
  229. string supportedFilesSeparator = "";
  230. string supportedFilesSeparatorForTileSave = "";
  231. m_supportFileExtensionsForTileSave = "";
  232. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  233. {
  234. m_supportedFileExtensions += supportedFilesSeparator + loader.Key + " (" + loader.Value + ")";
  235. supportedFilesSeparator = ", ";
  236. //For terrain save-tile file extensions
  237. if (loader.Value.SupportsTileSave() == true)
  238. {
  239. m_supportFileExtensionsForTileSave += supportedFilesSeparatorForTileSave + loader.Key + " (" + loader.Value + ")";
  240. supportedFilesSeparatorForTileSave = ", ";
  241. }
  242. }
  243. }
  244. public void RegionLoaded(Scene scene)
  245. {
  246. //Do this here to give file loaders time to initialize and
  247. //register their supported file extensions and file formats.
  248. InstallInterfaces();
  249. }
  250. public void RemoveRegion(Scene scene)
  251. {
  252. lock(m_scene)
  253. {
  254. // remove the commands
  255. m_scene.UnregisterModuleCommander(m_commander.Name);
  256. // remove the event-handlers
  257. m_scene.EventManager.OnTerrainCheckUpdates -= EventManager_TerrainCheckUpdates;
  258. m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
  259. m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
  260. m_scene.EventManager.OnClientClosed -= EventManager_OnClientClosed;
  261. m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
  262. // remove the interface
  263. m_scene.UnregisterModuleInterface<ITerrainModule>(this);
  264. }
  265. }
  266. public void Close()
  267. {
  268. }
  269. public Type ReplaceableInterface {
  270. get { return null; }
  271. }
  272. public string Name {
  273. get { return "TerrainModule"; }
  274. }
  275. #endregion
  276. #region ITerrainModule Members
  277. public void UndoTerrain(ITerrainChannel channel)
  278. {
  279. m_channel = channel;
  280. }
  281. /// <summary>
  282. /// Loads a terrain file from disk and installs it in the scene.
  283. /// </summary>
  284. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  285. public void LoadFromFile(string filename)
  286. {
  287. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  288. {
  289. if (filename.EndsWith(loader.Key))
  290. {
  291. lock(m_scene)
  292. {
  293. try
  294. {
  295. ITerrainChannel channel = loader.Value.LoadFile(filename);
  296. if (channel.Width != m_scene.RegionInfo.RegionSizeX || channel.Height != m_scene.RegionInfo.RegionSizeY)
  297. {
  298. // TerrainChannel expects a RegionSize x RegionSize map, currently
  299. throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
  300. m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY));
  301. }
  302. m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
  303. m_scene.Heightmap = channel;
  304. m_channel = channel;
  305. UpdateBakedMap();
  306. }
  307. catch(NotImplementedException)
  308. {
  309. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  310. " parser does not support file loading. (May be save only)");
  311. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  312. }
  313. catch(FileNotFoundException)
  314. {
  315. m_log.Error(
  316. "[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
  317. throw new TerrainException(
  318. String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
  319. }
  320. catch(ArgumentException e)
  321. {
  322. m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
  323. throw new TerrainException(
  324. String.Format("Unable to load heightmap: {0}", e.Message));
  325. }
  326. }
  327. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  328. return;
  329. }
  330. }
  331. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  332. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  333. }
  334. /// <summary>
  335. /// Saves the current heightmap to a specified file.
  336. /// </summary>
  337. /// <param name="filename">The destination filename</param>
  338. public void SaveToFile(string filename)
  339. {
  340. try
  341. {
  342. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  343. {
  344. if (filename.EndsWith(loader.Key))
  345. {
  346. loader.Value.SaveFile(filename, m_channel);
  347. m_log.InfoFormat("[TERRAIN]: Saved terrain from {0} to {1}", m_scene.RegionInfo.RegionName, filename);
  348. return;
  349. }
  350. }
  351. }
  352. catch(IOException ioe)
  353. {
  354. m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
  355. }
  356. m_log.ErrorFormat(
  357. "[TERRAIN]: Could not save terrain from {0} to {1}. Valid file extensions are {2}",
  358. m_scene.RegionInfo.RegionName, filename, m_supportedFileExtensions);
  359. }
  360. /// <summary>
  361. /// Loads a terrain file from the specified URI
  362. /// </summary>
  363. /// <param name="filename">The name of the terrain to load</param>
  364. /// <param name="pathToTerrainHeightmap">The URI to the terrain height map</param>
  365. public void LoadFromStream(string filename, Uri pathToTerrainHeightmap)
  366. {
  367. LoadFromStream(filename, URIFetch(pathToTerrainHeightmap));
  368. }
  369. public void LoadFromStream(string filename, Stream stream)
  370. {
  371. LoadFromStream(filename, Vector3.Zero, 0f, Vector2.Zero, stream);
  372. }
  373. /// <summary>
  374. /// Loads a terrain file from a stream and installs it in the scene.
  375. /// </summary>
  376. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  377. /// <param name="stream"></param>
  378. public void LoadFromStream(string filename, Vector3 displacement,
  379. float radianRotation, Vector2 rotationDisplacement, Stream stream)
  380. {
  381. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  382. {
  383. if (filename.EndsWith(loader.Key))
  384. {
  385. lock(m_scene)
  386. {
  387. try
  388. {
  389. ITerrainChannel channel = loader.Value.LoadStream(stream);
  390. m_channel.Merge(channel, displacement, radianRotation, rotationDisplacement);
  391. UpdateBakedMap();
  392. }
  393. catch(NotImplementedException)
  394. {
  395. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  396. " parser does not support file loading. (May be save only)");
  397. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  398. }
  399. }
  400. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  401. return;
  402. }
  403. }
  404. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  405. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  406. }
  407. public void LoadFromStream(string filename, Vector3 displacement,
  408. float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize, Stream stream)
  409. {
  410. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  411. {
  412. if (filename.EndsWith(loader.Key))
  413. {
  414. lock (m_scene)
  415. {
  416. try
  417. {
  418. ITerrainChannel channel = loader.Value.LoadStream(stream);
  419. m_channel.MergeWithBounding(channel, displacement, rotationDegrees, boundingOrigin, boundingSize);
  420. UpdateBakedMap();
  421. }
  422. catch (NotImplementedException)
  423. {
  424. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  425. " parser does not support file loading. (May be save only)");
  426. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  427. }
  428. }
  429. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  430. return;
  431. }
  432. }
  433. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  434. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  435. }
  436. private static Stream URIFetch(Uri uri)
  437. {
  438. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  439. // request.Credentials = credentials;
  440. request.ContentLength = 0;
  441. request.KeepAlive = false;
  442. WebResponse response = request.GetResponse();
  443. Stream file = response.GetResponseStream();
  444. if (response.ContentLength == 0)
  445. throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
  446. // return new BufferedStream(file, (int) response.ContentLength);
  447. return new BufferedStream(file, 1000000);
  448. }
  449. /// <summary>
  450. /// Modify Land
  451. /// </summary>
  452. /// <param name="pos">Land-position (X,Y,0)</param>
  453. /// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
  454. /// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
  455. /// <param name="agentId">UUID of script-owner</param>
  456. public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action)
  457. {
  458. float duration;
  459. float brushSize;
  460. if (size > 2)
  461. {
  462. size = 3;
  463. brushSize = 4.0f;
  464. }
  465. else
  466. {
  467. size++;
  468. brushSize = size;
  469. }
  470. switch((StandardTerrainEffects)action)
  471. {
  472. case StandardTerrainEffects.Flatten:
  473. duration = 7.29f * size * size;
  474. break;
  475. case StandardTerrainEffects.Smooth:
  476. case StandardTerrainEffects.Revert:
  477. duration = 0.06f * size * size;
  478. break;
  479. case StandardTerrainEffects.Noise:
  480. duration = 0.46f * size * size;
  481. break;
  482. default:
  483. duration = 0.25f;
  484. break;
  485. }
  486. client_OnModifyTerrain(user, pos.Z, duration, brushSize, action, pos.Y, pos.X, pos.Y, pos.X, -1);
  487. }
  488. /// <summary>
  489. /// Saves the current heightmap to a specified stream.
  490. /// </summary>
  491. /// <param name="filename">The destination filename. Used here only to identify the image type</param>
  492. /// <param name="stream"></param>
  493. public void SaveToStream(string filename, Stream stream)
  494. {
  495. try
  496. {
  497. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  498. {
  499. if (filename.EndsWith(loader.Key))
  500. {
  501. loader.Value.SaveStream(stream, m_channel);
  502. return;
  503. }
  504. }
  505. }
  506. catch(NotImplementedException)
  507. {
  508. m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
  509. throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
  510. }
  511. }
  512. // Someone diddled terrain outside the normal code paths. Set the taintedness for all clients.
  513. // ITerrainModule.TaintTerrain()
  514. public void TaintTerrain ()
  515. {
  516. lock (m_perClientPatchUpdates)
  517. {
  518. // Set the flags for all clients so the tainted patches will be sent out
  519. foreach (PatchUpdates pups in m_perClientPatchUpdates.Values)
  520. {
  521. pups.SetAll(m_scene.Heightmap.GetTerrainData());
  522. }
  523. }
  524. }
  525. // ITerrainModule.PushTerrain()
  526. public void PushTerrain(IClientAPI pClient)
  527. {
  528. if (m_sendTerrainUpdatesByViewDistance)
  529. {
  530. ScenePresence presence = m_scene.GetScenePresence(pClient.AgentId);
  531. if (presence != null)
  532. {
  533. lock (m_perClientPatchUpdates)
  534. {
  535. PatchUpdates pups;
  536. if (!m_perClientPatchUpdates.TryGetValue(pClient.AgentId, out pups))
  537. {
  538. // There is a ScenePresence without a send patch map. Create one.
  539. pups = new PatchUpdates(m_scene.Heightmap.GetTerrainData(), presence);
  540. m_perClientPatchUpdates.Add(presence.UUID, pups);
  541. }
  542. pups.SetAll(true);
  543. }
  544. }
  545. }
  546. else
  547. {
  548. // The traditional way is to call into the protocol stack to send them all.
  549. pClient.SendLayerData();
  550. }
  551. }
  552. #region Plugin Loading Methods
  553. private void LoadPlugins()
  554. {
  555. m_plugineffects = new Dictionary<string, ITerrainEffect>();
  556. LoadPlugins(Assembly.GetCallingAssembly());
  557. string plugineffectsPath = "Terrain";
  558. // Load the files in the Terrain/ dir
  559. if (!Directory.Exists(plugineffectsPath))
  560. return;
  561. string[] files = Directory.GetFiles(plugineffectsPath);
  562. foreach(string file in files)
  563. {
  564. m_log.Info("Loading effects in " + file);
  565. try
  566. {
  567. Assembly library = Assembly.LoadFrom(file);
  568. LoadPlugins(library);
  569. }
  570. catch(BadImageFormatException)
  571. {
  572. }
  573. }
  574. }
  575. private void LoadPlugins(Assembly library)
  576. {
  577. foreach(Type pluginType in library.GetTypes())
  578. {
  579. try
  580. {
  581. if (pluginType.IsAbstract || pluginType.IsNotPublic)
  582. continue;
  583. string typeName = pluginType.Name;
  584. if (pluginType.GetInterface("ITerrainEffect", false) != null)
  585. {
  586. ITerrainEffect terEffect = (ITerrainEffect)Activator.CreateInstance(library.GetType(pluginType.ToString()));
  587. InstallPlugin(typeName, terEffect);
  588. }
  589. else if (pluginType.GetInterface("ITerrainLoader", false) != null)
  590. {
  591. ITerrainLoader terLoader = (ITerrainLoader)Activator.CreateInstance(library.GetType(pluginType.ToString()));
  592. m_loaders[terLoader.FileExtension] = terLoader;
  593. m_log.Info("L ... " + typeName);
  594. }
  595. }
  596. catch(AmbiguousMatchException)
  597. {
  598. }
  599. }
  600. }
  601. public void InstallPlugin(string pluginName, ITerrainEffect effect)
  602. {
  603. lock(m_plugineffects)
  604. {
  605. if (!m_plugineffects.ContainsKey(pluginName))
  606. {
  607. m_plugineffects.Add(pluginName, effect);
  608. m_log.Info("E ... " + pluginName);
  609. }
  610. else
  611. {
  612. m_plugineffects[pluginName] = effect;
  613. m_log.Info("E ... " + pluginName + " (Replaced)");
  614. }
  615. }
  616. }
  617. #endregion
  618. #endregion
  619. /// <summary>
  620. /// Installs into terrain module the standard suite of brushes
  621. /// </summary>
  622. private void InstallDefaultEffects()
  623. {
  624. // Draggable Paint Brush Effects
  625. m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
  626. m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
  627. m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
  628. m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
  629. m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
  630. m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_baked);
  631. // Area of effect selection effects
  632. m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
  633. m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
  634. m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
  635. m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
  636. m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
  637. m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_baked);
  638. // Terrain Modifier operations
  639. m_modifyOperations["min"] = new MinModifier(this);
  640. m_modifyOperations["max"] = new MaxModifier(this);
  641. m_modifyOperations["raise"] = new RaiseModifier(this);
  642. m_modifyOperations["lower"] = new LowerModifier(this);
  643. m_modifyOperations["fill"] = new FillModifier(this);
  644. m_modifyOperations["smooth"] = new SmoothModifier(this);
  645. m_modifyOperations["noise"] = new NoiseModifier(this);
  646. // Filesystem load/save loaders
  647. m_loaders[".r32"] = new RAW32();
  648. m_loaders[".f32"] = m_loaders[".r32"];
  649. m_loaders[".ter"] = new Terragen();
  650. m_loaders[".raw"] = new LLRAW();
  651. m_loaders[".jpg"] = new JPEG();
  652. m_loaders[".jpeg"] = m_loaders[".jpg"];
  653. m_loaders[".bmp"] = new BMP();
  654. m_loaders[".png"] = new PNG();
  655. m_loaders[".gif"] = new GIF();
  656. m_loaders[".tif"] = new TIFF();
  657. m_loaders[".tiff"] = m_loaders[".tif"];
  658. }
  659. /// <summary>
  660. /// Saves the current state of the region into the baked map buffer.
  661. /// </summary>
  662. public void UpdateBakedMap()
  663. {
  664. m_baked = m_channel.MakeCopy();
  665. m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_baked);
  666. m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_baked);
  667. m_scene.Bakedmap = m_baked;
  668. m_scene.SaveBakedTerrain();
  669. }
  670. /// <summary>
  671. /// Loads a tile from a larger terrain file and installs it into the region.
  672. /// </summary>
  673. /// <param name="filename">The terrain file to load</param>
  674. /// <param name="fileWidth">The width of the file in units</param>
  675. /// <param name="fileHeight">The height of the file in units</param>
  676. /// <param name="fileStartX">Where to begin our slice</param>
  677. /// <param name="fileStartY">Where to begin our slice</param>
  678. public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  679. {
  680. int offsetX = (int)m_scene.RegionInfo.RegionLocX - fileStartX;
  681. int offsetY = (int)m_scene.RegionInfo.RegionLocY - fileStartY;
  682. if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
  683. {
  684. // this region is included in the tile request
  685. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  686. {
  687. if (filename.EndsWith(loader.Key))
  688. {
  689. lock(m_scene)
  690. {
  691. ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
  692. fileWidth, fileHeight,
  693. (int) m_scene.RegionInfo.RegionSizeX,
  694. (int) m_scene.RegionInfo.RegionSizeY);
  695. m_scene.Heightmap = channel;
  696. m_channel = channel;
  697. UpdateBakedMap();
  698. }
  699. return;
  700. }
  701. }
  702. }
  703. }
  704. /// <summary>
  705. /// Save a number of map tiles to a single big image file.
  706. /// </summary>
  707. /// <remarks>
  708. /// If the image file already exists then the tiles saved will replace those already in the file - other tiles
  709. /// will be untouched.
  710. /// </remarks>
  711. /// <param name="filename">The terrain file to save</param>
  712. /// <param name="fileWidth">The number of tiles to save along the X axis.</param>
  713. /// <param name="fileHeight">The number of tiles to save along the Y axis.</param>
  714. /// <param name="fileStartX">The map x co-ordinate at which to begin the save.</param>
  715. /// <param name="fileStartY">The may y co-ordinate at which to begin the save.</param>
  716. public void SaveToFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  717. {
  718. int offsetX = (int)m_scene.RegionInfo.RegionLocX - fileStartX;
  719. int offsetY = (int)m_scene.RegionInfo.RegionLocY - fileStartY;
  720. if (offsetX < 0 || offsetX >= fileWidth || offsetY < 0 || offsetY >= fileHeight)
  721. {
  722. MainConsole.Instance.Output(
  723. "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.",
  724. m_scene.RegionInfo.RegionLocX, m_scene.RegionInfo.RegionLocY, fileWidth, fileStartX, fileHeight, fileStartY);
  725. return;
  726. }
  727. // this region is included in the tile request
  728. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  729. {
  730. if (filename.EndsWith(loader.Key) && loader.Value.SupportsTileSave())
  731. {
  732. lock(m_scene)
  733. {
  734. loader.Value.SaveFile(m_channel, filename, offsetX, offsetY,
  735. fileWidth, fileHeight,
  736. (int)m_scene.RegionInfo.RegionSizeX,
  737. (int)m_scene.RegionInfo.RegionSizeY);
  738. MainConsole.Instance.Output(
  739. "Saved terrain from ({0},{1}) to ({2},{3}) from {4} to {5}",
  740. fileStartX, fileStartY, fileStartX + fileWidth - 1, fileStartY + fileHeight - 1,
  741. m_scene.RegionInfo.RegionName, filename);
  742. }
  743. return;
  744. }
  745. }
  746. MainConsole.Instance.Output(
  747. "ERROR: Could not save terrain from {0} to {1}. Valid file extensions are {2}",
  748. m_scene.RegionInfo.RegionName, filename, m_supportFileExtensionsForTileSave);
  749. }
  750. /// <summary>
  751. /// This is used to check to see of any of the terrain is tainted and, if so, schedule
  752. /// updates for all the presences.
  753. /// This also checks to see if there are updates that need to be sent for each presence.
  754. /// This is where the logic is to send terrain updates to clients.
  755. /// </summary>
  756. /// doing it async, since currently this is 2 heavy for heartbeat
  757. private void EventManager_TerrainCheckUpdates()
  758. {
  759. Util.FireAndForget(
  760. EventManager_TerrainCheckUpdatesAsync);
  761. }
  762. object TerrainCheckUpdatesLock = new object();
  763. private void EventManager_TerrainCheckUpdatesAsync(object o)
  764. {
  765. // dont overlap execution
  766. if(Monitor.TryEnter(TerrainCheckUpdatesLock))
  767. {
  768. // this needs fixing
  769. TerrainData terrData = m_channel.GetTerrainData();
  770. bool shouldTaint = false;
  771. for (int x = 0; x < terrData.SizeX; x += Constants.TerrainPatchSize)
  772. {
  773. for (int y = 0; y < terrData.SizeY; y += Constants.TerrainPatchSize)
  774. {
  775. if (terrData.IsTaintedAt(x, y,true))
  776. {
  777. // Found a patch that was modified. Push this flag into the clients.
  778. SendToClients(terrData, x, y);
  779. shouldTaint = true;
  780. }
  781. }
  782. }
  783. // This event also causes changes to be sent to the clients
  784. CheckSendingPatchesToClients();
  785. // If things changes, generate some events
  786. if (shouldTaint)
  787. {
  788. m_scene.EventManager.TriggerTerrainTainted();
  789. m_tainted = true;
  790. }
  791. Monitor.Exit(TerrainCheckUpdatesLock);
  792. }
  793. }
  794. /// <summary>
  795. /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
  796. /// Called infrequently (like every 5 seconds or so). Best used for storing terrain.
  797. /// </summary>
  798. private void EventManager_OnTerrainTick()
  799. {
  800. if (m_tainted)
  801. {
  802. m_tainted = false;
  803. m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
  804. m_scene.SaveTerrain();
  805. // Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
  806. //m_scene.CreateTerrainTexture(true);
  807. }
  808. }
  809. /// <summary>
  810. /// Processes commandline input. Do not call directly.
  811. /// </summary>
  812. /// <param name="args">Commandline arguments</param>
  813. private void EventManager_OnPluginConsole(string[] args)
  814. {
  815. if (args[0] == "terrain")
  816. {
  817. if (args.Length == 1)
  818. {
  819. m_commander.ProcessConsoleCommand("help", new string[0]);
  820. return;
  821. }
  822. string[] tmpArgs = new string[args.Length - 2];
  823. int i;
  824. for(i = 2; i < args.Length; i++)
  825. tmpArgs[i - 2] = args[i];
  826. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  827. }
  828. }
  829. /// <summary>
  830. /// Installs terrain brush hook to IClientAPI
  831. /// </summary>
  832. /// <param name="client"></param>
  833. private void EventManager_OnNewClient(IClientAPI client)
  834. {
  835. client.OnModifyTerrain += client_OnModifyTerrain;
  836. client.OnBakeTerrain += client_OnBakeTerrain;
  837. client.OnLandUndo += client_OnLandUndo;
  838. client.OnUnackedTerrain += client_OnUnackedTerrain;
  839. }
  840. /// <summary>
  841. /// Installs terrain brush hook to IClientAPI
  842. /// </summary>
  843. /// <param name="client"></param>
  844. private void EventManager_OnClientClosed(UUID client, Scene scene)
  845. {
  846. ScenePresence presence = scene.GetScenePresence(client);
  847. if (presence != null)
  848. {
  849. presence.ControllingClient.OnModifyTerrain -= client_OnModifyTerrain;
  850. presence.ControllingClient.OnBakeTerrain -= client_OnBakeTerrain;
  851. presence.ControllingClient.OnLandUndo -= client_OnLandUndo;
  852. presence.ControllingClient.OnUnackedTerrain -= client_OnUnackedTerrain;
  853. }
  854. lock (m_perClientPatchUpdates)
  855. m_perClientPatchUpdates.Remove(client);
  856. }
  857. /// <summary>
  858. /// Scan over changes in the terrain and limit height changes. This enforces the
  859. /// non-estate owner limits on rate of terrain editting.
  860. /// Returns 'true' if any heights were limited.
  861. /// </summary>
  862. private bool EnforceEstateLimits()
  863. {
  864. TerrainData terrData = m_channel.GetTerrainData();
  865. bool wasLimited = false;
  866. for (int x = 0; x < terrData.SizeX; x += Constants.TerrainPatchSize)
  867. {
  868. for (int y = 0; y < terrData.SizeY; y += Constants.TerrainPatchSize)
  869. {
  870. if (terrData.IsTaintedAt(x, y, false /* clearOnTest */))
  871. {
  872. // If we should respect the estate settings then
  873. // fixup and height deltas that don't respect them.
  874. // Note that LimitChannelChanges() modifies the TerrainChannel with the limited height values.
  875. wasLimited |= LimitChannelChanges(terrData, x, y);
  876. }
  877. }
  878. }
  879. return wasLimited;
  880. }
  881. private bool EnforceEstateLimits(int startX, int startY, int endX, int endY)
  882. {
  883. TerrainData terrData = m_channel.GetTerrainData();
  884. bool wasLimited = false;
  885. for (int x = startX; x <= endX; x += Constants.TerrainPatchSize)
  886. {
  887. for (int y = startX; y <= endY; y += Constants.TerrainPatchSize)
  888. {
  889. if (terrData.IsTaintedAt(x, y, false /* clearOnTest */))
  890. {
  891. // If we should respect the estate settings then
  892. // fixup and height deltas that don't respect them.
  893. // Note that LimitChannelChanges() modifies the TerrainChannel with the limited height values.
  894. wasLimited |= LimitChannelChanges(terrData, x, y);
  895. }
  896. }
  897. }
  898. return wasLimited;
  899. }
  900. /// <summary>
  901. /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
  902. /// are all within the current estate limits
  903. /// <returns>true if changes were limited, false otherwise</returns>
  904. /// </summary>
  905. private bool LimitChannelChanges(TerrainData terrData, int xStart, int yStart)
  906. {
  907. bool changesLimited = false;
  908. float minDelta = (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
  909. float maxDelta = (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
  910. // loop through the height map for this patch and compare it against
  911. // the baked map
  912. for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
  913. {
  914. for(int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
  915. {
  916. float requestedHeight = terrData[x, y];
  917. float bakedHeight = (float)m_baked[x, y];
  918. float requestedDelta = requestedHeight - bakedHeight;
  919. if (requestedDelta > maxDelta)
  920. {
  921. terrData[x, y] = bakedHeight + maxDelta;
  922. changesLimited = true;
  923. }
  924. else if (requestedDelta < minDelta)
  925. {
  926. terrData[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
  927. changesLimited = true;
  928. }
  929. }
  930. }
  931. return changesLimited;
  932. }
  933. private void client_OnLandUndo(IClientAPI client)
  934. {
  935. }
  936. /// <summary>
  937. /// Sends a copy of the current terrain to the scenes clients
  938. /// </summary>
  939. /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
  940. /// <param name="x">The patch corner to send</param>
  941. /// <param name="y">The patch corner to send</param>
  942. private void SendToClients(TerrainData terrData, int x, int y)
  943. {
  944. if (m_sendTerrainUpdatesByViewDistance)
  945. {
  946. // Add that this patch needs to be sent to the accounting for each client.
  947. lock (m_perClientPatchUpdates)
  948. {
  949. m_scene.ForEachScenePresence(presence =>
  950. {
  951. PatchUpdates thisClientUpdates;
  952. if (!m_perClientPatchUpdates.TryGetValue(presence.UUID, out thisClientUpdates))
  953. {
  954. // There is a ScenePresence without a send patch map. Create one.
  955. thisClientUpdates = new PatchUpdates(terrData, presence);
  956. m_perClientPatchUpdates.Add(presence.UUID, thisClientUpdates);
  957. }
  958. thisClientUpdates.SetByXY(x, y, true);
  959. }
  960. );
  961. }
  962. }
  963. else
  964. {
  965. // Legacy update sending where the update is sent out as soon as noticed
  966. // We know the actual terrain data that is passed is ignored so this passes a dummy heightmap.
  967. //float[] heightMap = terrData.GetFloatsSerialized();
  968. int[] map = new int[]{ x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize };
  969. m_scene.ForEachClient(
  970. delegate (IClientAPI controller)
  971. {
  972. controller.SendLayerData(map);
  973. }
  974. );
  975. }
  976. }
  977. private class PatchesToSend : IComparable<PatchesToSend>
  978. {
  979. public int PatchX;
  980. public int PatchY;
  981. public float Dist;
  982. public PatchesToSend(int pX, int pY, float pDist)
  983. {
  984. PatchX = pX;
  985. PatchY = pY;
  986. Dist = pDist;
  987. }
  988. public int CompareTo(PatchesToSend other)
  989. {
  990. return Dist.CompareTo(other.Dist);
  991. }
  992. }
  993. // Called each frame time to see if there are any patches to send to any of the
  994. // ScenePresences.
  995. // Loop through all the per-client info and send any patches necessary.
  996. private void CheckSendingPatchesToClients()
  997. {
  998. lock (m_perClientPatchUpdates)
  999. {
  1000. foreach (PatchUpdates pups in m_perClientPatchUpdates.Values)
  1001. {
  1002. if(pups.Presence.IsDeleted)
  1003. continue;
  1004. // limit rate acording to udp land queue state
  1005. if (!pups.Presence.ControllingClient.CanSendLayerData())
  1006. continue;
  1007. if (pups.HasUpdates())
  1008. {
  1009. if (m_sendTerrainUpdatesByViewDistance)
  1010. {
  1011. // There is something that could be sent to this client.
  1012. List<PatchesToSend> toSend = GetModifiedPatchesInViewDistance(pups);
  1013. if (toSend.Count > 0)
  1014. {
  1015. // m_log.DebugFormat("{0} CheckSendingPatchesToClient: sending {1} patches to {2} in region {3}",
  1016. // LogHeader, toSend.Count, pups.Presence.Name, m_scene.RegionInfo.RegionName);
  1017. // Sort the patches to send by the distance from the presence
  1018. toSend.Sort();
  1019. /*
  1020. foreach (PatchesToSend pts in toSend)
  1021. {
  1022. pups.Presence.ControllingClient.SendLayerData(pts.PatchX, pts.PatchY, null);
  1023. // presence.ControllingClient.SendLayerData(xs.ToArray(), ys.ToArray(), null, TerrainPatch.LayerType.Land);
  1024. }
  1025. */
  1026. int[] patchPieces = new int[toSend.Count * 2];
  1027. int pieceIndex = 0;
  1028. foreach (PatchesToSend pts in toSend)
  1029. {
  1030. patchPieces[pieceIndex++] = pts.PatchX;
  1031. patchPieces[pieceIndex++] = pts.PatchY;
  1032. }
  1033. pups.Presence.ControllingClient.SendLayerData(patchPieces);
  1034. }
  1035. if (pups.sendAll && toSend.Count < 1024)
  1036. SendAllModifiedPatchs(pups);
  1037. }
  1038. else
  1039. SendAllModifiedPatchs(pups);
  1040. }
  1041. }
  1042. }
  1043. }
  1044. private void SendAllModifiedPatchs(PatchUpdates pups)
  1045. {
  1046. if (!pups.sendAll) // sanity
  1047. return;
  1048. int limitX = (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize;
  1049. int limitY = (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize;
  1050. if (pups.sendAllcurrentX >= limitX && pups.sendAllcurrentY >= limitY)
  1051. {
  1052. pups.sendAll = false;
  1053. pups.sendAllcurrentX = 0;
  1054. pups.sendAllcurrentY = 0;
  1055. return;
  1056. }
  1057. int npatchs = 0;
  1058. List<PatchesToSend> patchs = new List<PatchesToSend>();
  1059. int x = pups.sendAllcurrentX;
  1060. int y = pups.sendAllcurrentY;
  1061. // send it in the order viewer draws it
  1062. // even if not best for memory scan
  1063. for (; y < limitY; y++)
  1064. {
  1065. for (; x < limitX; x++)
  1066. {
  1067. if (pups.GetByPatch(x, y))
  1068. {
  1069. pups.SetByPatch(x, y, false);
  1070. patchs.Add(new PatchesToSend(x, y, 0));
  1071. if (++npatchs >= 128)
  1072. {
  1073. x++;
  1074. break;
  1075. }
  1076. }
  1077. }
  1078. if (npatchs >= 128)
  1079. break;
  1080. x = 0;
  1081. }
  1082. if (x >= limitX && y >= limitY)
  1083. {
  1084. pups.sendAll = false;
  1085. pups.sendAllcurrentX = 0;
  1086. pups.sendAllcurrentY = 0;
  1087. }
  1088. else
  1089. {
  1090. pups.sendAllcurrentX = x;
  1091. pups.sendAllcurrentY = y;
  1092. }
  1093. npatchs = patchs.Count;
  1094. if (npatchs > 0)
  1095. {
  1096. int[] patchPieces = new int[npatchs * 2];
  1097. int pieceIndex = 0;
  1098. foreach (PatchesToSend pts in patchs)
  1099. {
  1100. patchPieces[pieceIndex++] = pts.PatchX;
  1101. patchPieces[pieceIndex++] = pts.PatchY;
  1102. }
  1103. pups.Presence.ControllingClient.SendLayerData(patchPieces);
  1104. }
  1105. }
  1106. private List<PatchesToSend> GetModifiedPatchesInViewDistance(PatchUpdates pups)
  1107. {
  1108. List<PatchesToSend> ret = new List<PatchesToSend>();
  1109. int npatchs = 0;
  1110. ScenePresence presence = pups.Presence;
  1111. if (presence == null)
  1112. return ret;
  1113. float minz = presence.AbsolutePosition.Z;
  1114. if (presence.CameraPosition.Z < minz)
  1115. minz = presence.CameraPosition.Z;
  1116. // this limit should be max terrainheight + max draw
  1117. if (minz > 1500f)
  1118. return ret;
  1119. int DrawDistance = (int)presence.DrawDistance;
  1120. DrawDistance = DrawDistance / Constants.TerrainPatchSize;
  1121. int testposX;
  1122. int testposY;
  1123. if (Math.Abs(presence.AbsolutePosition.X - presence.CameraPosition.X) > 30
  1124. || Math.Abs(presence.AbsolutePosition.Y - presence.CameraPosition.Y) > 30)
  1125. {
  1126. testposX = (int)presence.CameraPosition.X / Constants.TerrainPatchSize;
  1127. testposY = (int)presence.CameraPosition.Y / Constants.TerrainPatchSize;
  1128. }
  1129. else
  1130. {
  1131. testposX = (int)presence.AbsolutePosition.X / Constants.TerrainPatchSize;
  1132. testposY = (int)presence.AbsolutePosition.Y / Constants.TerrainPatchSize;
  1133. }
  1134. int limitX = (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize;
  1135. int limitY = (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize;
  1136. // Compute the area of patches within our draw distance
  1137. int startX = testposX - DrawDistance;
  1138. if (startX < 0)
  1139. startX = 0;
  1140. else if (startX >= limitX)
  1141. startX = limitX - 1;
  1142. int startY = testposY - DrawDistance;
  1143. if (startY < 0)
  1144. startY = 0;
  1145. else if (startY >= limitY)
  1146. startY = limitY - 1;
  1147. int endX = testposX + DrawDistance;
  1148. if (endX < 0)
  1149. endX = 0;
  1150. else if (endX > limitX)
  1151. endX = limitX;
  1152. int endY = testposY + DrawDistance;
  1153. if (endY < 0)
  1154. endY = 0;
  1155. else if (endY > limitY)
  1156. endY = limitY;
  1157. int distx;
  1158. int disty;
  1159. int distsq;
  1160. DrawDistance *= DrawDistance;
  1161. for (int x = startX; x < endX; x++)
  1162. {
  1163. for (int y = startY; y < endY; y++)
  1164. {
  1165. if (pups.GetByPatch(x, y))
  1166. {
  1167. distx = x - testposX;
  1168. disty = y - testposY;
  1169. distsq = distx * distx + disty * disty;
  1170. if (distsq < DrawDistance)
  1171. {
  1172. pups.SetByPatch(x, y, false);
  1173. ret.Add(new PatchesToSend(x, y, (float)distsq));
  1174. if (npatchs++ > 1024)
  1175. {
  1176. y = endY;
  1177. x = endX;
  1178. }
  1179. }
  1180. }
  1181. }
  1182. }
  1183. return ret;
  1184. }
  1185. private double NextModifyTerrainTime = double.MinValue;
  1186. private void client_OnModifyTerrain(UUID user, float height, float seconds, float brushSize, byte action,
  1187. float north, float west, float south, float east, int parcelLocalID)
  1188. {
  1189. double now = Util.GetTimeStamp();
  1190. if(now < NextModifyTerrainTime)
  1191. return;
  1192. NextModifyTerrainTime = double.MaxValue; // block it
  1193. //m_log.DebugFormat("brushs {0} seconds {1} height {2}, parcel {3}", brushSize, seconds, height, parcelLocalID);
  1194. bool god = m_scene.Permissions.IsGod(user);
  1195. bool allowed = false;
  1196. if (north == south && east == west)
  1197. {
  1198. if (m_painteffects.ContainsKey((StandardTerrainEffects)action))
  1199. {
  1200. bool[,] allowMask = new bool[m_channel.Width, m_channel.Height];
  1201. allowMask.Initialize();
  1202. int startX = (int)(west - brushSize + 0.5);
  1203. if (startX < 0)
  1204. startX = 0;
  1205. int startY = (int)(north - brushSize + 0.5);
  1206. if (startY < 0)
  1207. startY = 0;
  1208. int endX = (int)(west + brushSize + 0.5);
  1209. if (endX >= m_channel.Width)
  1210. endX = m_channel.Width - 1;
  1211. int endY = (int)(north + brushSize + 0.5);
  1212. if (endY >= m_channel.Height)
  1213. endY = m_channel.Height - 1;
  1214. int x, y;
  1215. for (x = startX; x <= endX; x++)
  1216. {
  1217. for (y = startY; y <= endY; y++)
  1218. {
  1219. if (m_scene.Permissions.CanTerraformLand(user, new Vector3(x, y, -1)))
  1220. {
  1221. allowMask[x, y] = true;
  1222. allowed = true;
  1223. }
  1224. }
  1225. }
  1226. if (allowed)
  1227. {
  1228. StoreUndoState();
  1229. m_painteffects[(StandardTerrainEffects) action].PaintEffect(
  1230. m_channel, allowMask, west, south, height, brushSize, seconds,
  1231. startX, endX, startY, endY);
  1232. //block changes outside estate limits
  1233. if (!god)
  1234. EnforceEstateLimits(startX, endX, startY, endY);
  1235. }
  1236. }
  1237. else
  1238. {
  1239. m_log.Debug("Unknown terrain brush type " + action);
  1240. }
  1241. }
  1242. else
  1243. {
  1244. if (m_floodeffects.ContainsKey((StandardTerrainEffects)action))
  1245. {
  1246. bool[,] fillArea = new bool[m_channel.Width, m_channel.Height];
  1247. fillArea.Initialize();
  1248. int startX = (int)west;
  1249. int startY = (int)south;
  1250. int endX = (int)east;
  1251. int endY = (int)north;
  1252. if (startX < 0)
  1253. startX = 0;
  1254. else if (startX >= m_channel.Width)
  1255. startX = m_channel.Width - 1;
  1256. if (endX < 0)
  1257. endX = 0;
  1258. else if (endX >= m_channel.Width)
  1259. endX = m_channel.Width - 1;
  1260. if (startY < 0)
  1261. startY = 0;
  1262. else if (startY >= m_channel.Height)
  1263. startY = m_channel.Height - 1;
  1264. if (endY < 0)
  1265. endY = 0;
  1266. else if (endY >= m_channel.Height)
  1267. endY = m_channel.Height - 1;
  1268. int x, y;
  1269. if (parcelLocalID == -1)
  1270. {
  1271. for (x = startX; x <= endX; x++)
  1272. {
  1273. for (y = startY; y <= endY; y++)
  1274. {
  1275. if (m_scene.Permissions.CanTerraformLand(user, new Vector3(x, y, -1)))
  1276. {
  1277. fillArea[x, y] = true;
  1278. allowed = true;
  1279. }
  1280. }
  1281. }
  1282. }
  1283. else
  1284. {
  1285. if (!m_scene.Permissions.CanTerraformLand(user, new Vector3(-1, -1, parcelLocalID)))
  1286. return;
  1287. ILandObject parcel = m_scene.LandChannel.GetLandObject(parcelLocalID);
  1288. if(parcel == null)
  1289. return;
  1290. bool [,] parcelmap = parcel.GetLandBitmap();
  1291. //ugly
  1292. for (x = startX; x <= endX; x++)
  1293. {
  1294. int px = x >> 2;
  1295. y = startY;
  1296. while( y <= endY)
  1297. {
  1298. int py = y >> 2;
  1299. bool inp = parcelmap[px, py];
  1300. fillArea[x, y++] = inp;
  1301. fillArea[x, y++] = inp;
  1302. fillArea[x, y++] = inp;
  1303. fillArea[x, y++] = inp;
  1304. }
  1305. }
  1306. allowed = true;
  1307. }
  1308. if (allowed)
  1309. {
  1310. StoreUndoState();
  1311. m_floodeffects[(StandardTerrainEffects)action].FloodEffect(m_channel, fillArea, height, seconds,
  1312. startX, endX, startY, endY);
  1313. //block changes outside estate limits
  1314. if (!god)
  1315. EnforceEstateLimits(startX, endX, startY, endY);
  1316. }
  1317. }
  1318. else
  1319. {
  1320. m_log.Debug("Unknown terrain flood type " + action);
  1321. }
  1322. }
  1323. NextModifyTerrainTime = Util.GetTimeStamp() + 0.02; // 20ms cooldown
  1324. }
  1325. private void client_OnBakeTerrain(IClientAPI remoteClient)
  1326. {
  1327. // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
  1328. // for now check a point in the centre of the region
  1329. if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
  1330. {
  1331. InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
  1332. }
  1333. }
  1334. protected void client_OnUnackedTerrain(IClientAPI client, int patchX, int patchY)
  1335. {
  1336. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  1337. // SendLayerData does not use the heightmap parameter. This kludge is so as to not change IClientAPI.
  1338. client.SendLayerData(new int[]{patchX, patchY});
  1339. }
  1340. private void StoreUndoState()
  1341. {
  1342. }
  1343. #region Console Commands
  1344. private void InterfaceLoadFile(Object[] args)
  1345. {
  1346. LoadFromFile((string) args[0]);
  1347. }
  1348. private void InterfaceLoadTileFile(Object[] args)
  1349. {
  1350. LoadFromFile((string) args[0],
  1351. (int) args[1],
  1352. (int) args[2],
  1353. (int) args[3],
  1354. (int) args[4]);
  1355. }
  1356. private void InterfaceSaveFile(Object[] args)
  1357. {
  1358. SaveToFile((string)args[0]);
  1359. }
  1360. private void InterfaceSaveTileFile(Object[] args)
  1361. {
  1362. SaveToFile((string)args[0],
  1363. (int)args[1],
  1364. (int)args[2],
  1365. (int)args[3],
  1366. (int)args[4]);
  1367. }
  1368. private void InterfaceBakeTerrain(Object[] args)
  1369. {
  1370. UpdateBakedMap();
  1371. }
  1372. private void InterfaceRevertTerrain(Object[] args)
  1373. {
  1374. int x, y;
  1375. for (x = 0; x < m_channel.Width; x++)
  1376. for (y = 0; y < m_channel.Height; y++)
  1377. m_channel[x, y] = m_baked[x, y];
  1378. }
  1379. private void InterfaceFlipTerrain(Object[] args)
  1380. {
  1381. String direction = (String)args[0];
  1382. if (direction.ToLower().StartsWith("y"))
  1383. {
  1384. for (int x = 0; x < m_channel.Width; x++)
  1385. {
  1386. for (int y = 0; y < m_channel.Height / 2; y++)
  1387. {
  1388. float height = m_channel[x, y];
  1389. float flippedHeight = m_channel[x, (int)m_channel.Height - 1 - y];
  1390. m_channel[x, y] = flippedHeight;
  1391. m_channel[x, (int)m_channel.Height - 1 - y] = height;
  1392. }
  1393. }
  1394. }
  1395. else if (direction.ToLower().StartsWith("x"))
  1396. {
  1397. for (int y = 0; y < m_channel.Height; y++)
  1398. {
  1399. for (int x = 0; x < m_channel.Width / 2; x++)
  1400. {
  1401. float height = m_channel[x, y];
  1402. float flippedHeight = m_channel[(int)m_channel.Width - 1 - x, y];
  1403. m_channel[x, y] = flippedHeight;
  1404. m_channel[(int)m_channel.Width - 1 - x, y] = height;
  1405. }
  1406. }
  1407. }
  1408. else
  1409. {
  1410. MainConsole.Instance.Output("ERROR: Unrecognised direction {0} - need x or y", direction);
  1411. }
  1412. }
  1413. private void InterfaceRescaleTerrain(Object[] args)
  1414. {
  1415. float desiredMin = (float)args[0];
  1416. float desiredMax = (float)args[1];
  1417. // determine desired scaling factor
  1418. float desiredRange = desiredMax - desiredMin;
  1419. //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
  1420. if (desiredRange == 0d)
  1421. {
  1422. // delta is zero so flatten at requested height
  1423. InterfaceFillTerrain(new Object[] { args[1] });
  1424. }
  1425. else
  1426. {
  1427. //work out current heightmap range
  1428. float currMin = float.MaxValue;
  1429. float currMax = float.MinValue;
  1430. int width = m_channel.Width;
  1431. int height = m_channel.Height;
  1432. for(int x = 0; x < width; x++)
  1433. {
  1434. for(int y = 0; y < height; y++)
  1435. {
  1436. float currHeight = m_channel[x, y];
  1437. if (currHeight < currMin)
  1438. {
  1439. currMin = currHeight;
  1440. }
  1441. else if (currHeight > currMax)
  1442. {
  1443. currMax = currHeight;
  1444. }
  1445. }
  1446. }
  1447. float currRange = currMax - currMin;
  1448. float scale = desiredRange / currRange;
  1449. //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
  1450. //m_log.InfoFormat("Scale = {0}", scale);
  1451. // scale the heightmap accordingly
  1452. for(int x = 0; x < width; x++)
  1453. {
  1454. for(int y = 0; y < height; y++)
  1455. {
  1456. float currHeight = m_channel[x, y] - currMin;
  1457. m_channel[x, y] = desiredMin + (currHeight * scale);
  1458. }
  1459. }
  1460. }
  1461. }
  1462. private void InterfaceElevateTerrain(Object[] args)
  1463. {
  1464. float val = (float)args[0];
  1465. int x, y;
  1466. for (x = 0; x < m_channel.Width; x++)
  1467. for (y = 0; y < m_channel.Height; y++)
  1468. m_channel[x, y] += val;
  1469. }
  1470. private void InterfaceMultiplyTerrain(Object[] args)
  1471. {
  1472. int x, y;
  1473. float val = (float)args[0];
  1474. for (x = 0; x < m_channel.Width; x++)
  1475. for (y = 0; y < m_channel.Height; y++)
  1476. m_channel[x, y] *= val;
  1477. }
  1478. private void InterfaceLowerTerrain(Object[] args)
  1479. {
  1480. int x, y;
  1481. float val = (float)args[0];
  1482. for (x = 0; x < m_channel.Width; x++)
  1483. for (y = 0; y < m_channel.Height; y++)
  1484. m_channel[x, y] -= val;
  1485. }
  1486. public void InterfaceFillTerrain(Object[] args)
  1487. {
  1488. int x, y;
  1489. float val = (float)args[0];
  1490. for (x = 0; x < m_channel.Width; x++)
  1491. for (y = 0; y < m_channel.Height; y++)
  1492. m_channel[x, y] = val;
  1493. }
  1494. private void InterfaceMinTerrain(Object[] args)
  1495. {
  1496. int x, y;
  1497. float val = (float)args[0];
  1498. for (x = 0; x < m_channel.Width; x++)
  1499. {
  1500. for(y = 0; y < m_channel.Height; y++)
  1501. {
  1502. m_channel[x, y] = Math.Max(val, m_channel[x, y]);
  1503. }
  1504. }
  1505. }
  1506. private void InterfaceMaxTerrain(Object[] args)
  1507. {
  1508. int x, y;
  1509. float val = (float)args[0];
  1510. for (x = 0; x < m_channel.Width; x++)
  1511. {
  1512. for(y = 0; y < m_channel.Height; y++)
  1513. {
  1514. m_channel[x, y] = Math.Min(val, m_channel[x, y]);
  1515. }
  1516. }
  1517. }
  1518. private void InterfaceShow(Object[] args)
  1519. {
  1520. Vector2 point;
  1521. if (!ConsoleUtil.TryParseConsole2DVector((string)args[0], null, out point))
  1522. {
  1523. Console.WriteLine("ERROR: {0} is not a valid vector", args[0]);
  1524. return;
  1525. }
  1526. double height = m_channel[(int)point.X, (int)point.Y];
  1527. Console.WriteLine("Terrain height at {0} is {1}", point, height);
  1528. }
  1529. private void InterfaceShowDebugStats(Object[] args)
  1530. {
  1531. float max = float.MinValue;
  1532. float min = float.MaxValue;
  1533. double sum = 0;
  1534. int x;
  1535. for(x = 0; x < m_channel.Width; x++)
  1536. {
  1537. int y;
  1538. for(y = 0; y < m_channel.Height; y++)
  1539. {
  1540. sum += m_channel[x, y];
  1541. if (max < m_channel[x, y])
  1542. max = m_channel[x, y];
  1543. if (min > m_channel[x, y])
  1544. min = m_channel[x, y];
  1545. }
  1546. }
  1547. double avg = sum / (m_channel.Height * m_channel.Width);
  1548. MainConsole.Instance.Output("Channel {0}x{1}", m_channel.Width, m_channel.Height);
  1549. MainConsole.Instance.Output("max/min/avg/sum: {0}/{1}/{2}/{3}", max, min, avg, sum);
  1550. }
  1551. private void InterfaceRunPluginEffect(Object[] args)
  1552. {
  1553. string firstArg = (string)args[0];
  1554. if (firstArg == "list")
  1555. {
  1556. MainConsole.Instance.Output("List of loaded plugins");
  1557. foreach(KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
  1558. {
  1559. MainConsole.Instance.Output(kvp.Key);
  1560. }
  1561. return;
  1562. }
  1563. if (firstArg == "reload")
  1564. {
  1565. LoadPlugins();
  1566. return;
  1567. }
  1568. if (m_plugineffects.ContainsKey(firstArg))
  1569. {
  1570. m_plugineffects[firstArg].RunEffect(m_channel);
  1571. }
  1572. else
  1573. {
  1574. MainConsole.Instance.Output("WARNING: No such plugin effect {0} loaded.", firstArg);
  1575. }
  1576. }
  1577. private void InstallInterfaces()
  1578. {
  1579. Command loadFromFileCommand =
  1580. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
  1581. loadFromFileCommand.AddArgument("filename",
  1582. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  1583. m_supportedFileExtensions, "String");
  1584. Command saveToFileCommand =
  1585. new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
  1586. saveToFileCommand.AddArgument("filename",
  1587. "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
  1588. m_supportedFileExtensions, "String");
  1589. Command loadFromTileCommand =
  1590. new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
  1591. loadFromTileCommand.AddArgument("filename",
  1592. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  1593. m_supportedFileExtensions, "String");
  1594. loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  1595. loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  1596. loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  1597. "Integer");
  1598. loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
  1599. "Integer");
  1600. Command saveToTileCommand =
  1601. new Command("save-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceSaveTileFile, "Saves the current heightmap to the larger file.");
  1602. saveToTileCommand.AddArgument("filename",
  1603. "The file you wish to save to, the file extension determines the loader to be used. Supported extensions include: " +
  1604. m_supportFileExtensionsForTileSave, "String");
  1605. saveToTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  1606. saveToTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  1607. saveToTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  1608. "Integer");
  1609. saveToTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first tile on the file\n"
  1610. + "= Example =\n"
  1611. + "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"
  1612. + " # terrain save-tile ST06.png 2 3 9910 10234\n",
  1613. "Integer");
  1614. // Terrain adjustments
  1615. Command fillRegionCommand =
  1616. new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
  1617. fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
  1618. "Float");
  1619. Command elevateCommand =
  1620. new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
  1621. elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Float");
  1622. Command lowerCommand =
  1623. new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
  1624. lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Float");
  1625. Command multiplyCommand =
  1626. new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
  1627. multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Float");
  1628. Command bakeRegionCommand =
  1629. new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions baked map.");
  1630. Command revertRegionCommand =
  1631. new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the baked map terrain into the regions heightmap.");
  1632. Command flipCommand =
  1633. new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
  1634. flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
  1635. Command rescaleCommand =
  1636. new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
  1637. rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Float");
  1638. rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Float");
  1639. Command minCommand = new Command("min", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMinTerrain, "Sets the minimum terrain height to the specified value.");
  1640. minCommand.AddArgument("min", "terrain height to use as minimum", "Float");
  1641. Command maxCommand = new Command("max", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMaxTerrain, "Sets the maximum terrain height to the specified value.");
  1642. maxCommand.AddArgument("min", "terrain height to use as maximum", "Float");
  1643. // Debug
  1644. Command showDebugStatsCommand =
  1645. new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
  1646. "Shows some information about the regions heightmap for debugging purposes.");
  1647. Command showCommand =
  1648. new Command("show", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceShow,
  1649. "Shows terrain height at a given co-ordinate.");
  1650. showCommand.AddArgument("point", "point in <x>,<y> format with no spaces (e.g. 45,45)", "String");
  1651. // Plugins
  1652. Command pluginRunCommand =
  1653. new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
  1654. pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
  1655. m_commander.RegisterCommand("load", loadFromFileCommand);
  1656. m_commander.RegisterCommand("load-tile", loadFromTileCommand);
  1657. m_commander.RegisterCommand("save", saveToFileCommand);
  1658. m_commander.RegisterCommand("save-tile", saveToTileCommand);
  1659. m_commander.RegisterCommand("fill", fillRegionCommand);
  1660. m_commander.RegisterCommand("elevate", elevateCommand);
  1661. m_commander.RegisterCommand("lower", lowerCommand);
  1662. m_commander.RegisterCommand("multiply", multiplyCommand);
  1663. m_commander.RegisterCommand("bake", bakeRegionCommand);
  1664. m_commander.RegisterCommand("revert", revertRegionCommand);
  1665. m_commander.RegisterCommand("show", showCommand);
  1666. m_commander.RegisterCommand("stats", showDebugStatsCommand);
  1667. m_commander.RegisterCommand("effect", pluginRunCommand);
  1668. m_commander.RegisterCommand("flip", flipCommand);
  1669. m_commander.RegisterCommand("rescale", rescaleCommand);
  1670. m_commander.RegisterCommand("min", minCommand);
  1671. m_commander.RegisterCommand("max", maxCommand);
  1672. // Add this to our scene so scripts can call these functions
  1673. m_scene.RegisterModuleCommander(m_commander);
  1674. // Add Modify command to Scene, since Command object requires fixed-length arglists
  1675. m_scene.AddCommand("Terrain", this, "terrain modify",
  1676. "terrain modify <operation> <value> [<area>] [<taper>]",
  1677. "Modifies the terrain as instructed." +
  1678. "\nEach operation can be limited to an area of effect:" +
  1679. "\n * -ell=x,y,rx[,ry] constrains the operation to an ellipse centred at x,y" +
  1680. "\n * -rec=x,y,dx[,dy] constrains the operation to a rectangle based at x,y" +
  1681. "\nEach operation can have its effect tapered based on distance from centre:" +
  1682. "\n * elliptical operations taper as cones" +
  1683. "\n * rectangular operations taper as pyramids"
  1684. ,
  1685. ModifyCommand);
  1686. }
  1687. public void ModifyCommand(string module, string[] cmd)
  1688. {
  1689. string result;
  1690. Scene scene = SceneManager.Instance.CurrentScene;
  1691. if ((scene != null) && (scene != m_scene))
  1692. {
  1693. result = String.Empty;
  1694. }
  1695. else if (cmd.Length > 2)
  1696. {
  1697. string operationType = cmd[2];
  1698. ITerrainModifier operation;
  1699. if (!m_modifyOperations.TryGetValue(operationType, out operation))
  1700. {
  1701. result = String.Format("Terrain Modify \"{0}\" not found.", operationType);
  1702. }
  1703. else if ((cmd.Length > 3) && (cmd[3] == "usage"))
  1704. {
  1705. result = "Usage: " + operation.GetUsage();
  1706. }
  1707. else
  1708. {
  1709. result = operation.ModifyTerrain(m_channel, cmd);
  1710. }
  1711. if (result == String.Empty)
  1712. {
  1713. result = "Modified terrain";
  1714. m_log.DebugFormat("Performed terrain operation {0}", operationType);
  1715. }
  1716. }
  1717. else
  1718. {
  1719. result = "Usage: <operation-name> <arg1> <arg2>...";
  1720. }
  1721. if (result != String.Empty)
  1722. {
  1723. MainConsole.Instance.Output(result);
  1724. }
  1725. }
  1726. #endregion
  1727. }
  1728. }