TerrainModule.cs 82 KB

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