TerrainEngine.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /*
  2. * Copyright (c) Contributors, http://www.openmetaverse.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. *
  27. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Text;
  31. using System.Drawing;
  32. using libTerrain;
  33. using OpenJPEGNet;
  34. namespace OpenSim.Terrain
  35. {
  36. public class TerrainEngine
  37. {
  38. /// <summary>
  39. /// A [normally] 256x256 heightmap
  40. /// </summary>
  41. public Channel heightmap;
  42. /// <summary>
  43. /// Whether or not the terrain has been modified since it was last saved and sent to the Physics engine.
  44. /// Counts the number of modifications since the last save. (0 = Untainted)
  45. /// </summary>
  46. public int tainted;
  47. int w, h;
  48. /// <summary>
  49. /// Generate a new TerrainEngine instance and creates a new heightmap
  50. /// </summary>
  51. public TerrainEngine()
  52. {
  53. w = 256;
  54. h = 256;
  55. heightmap = new Channel(w, h);
  56. tainted++;
  57. }
  58. /// <summary>
  59. /// Converts the heightmap to a 65536 value 1D floating point array
  60. /// </summary>
  61. /// <returns>A float[65536] array containing the heightmap</returns>
  62. public float[] getHeights1D()
  63. {
  64. float[] heights = new float[w * h];
  65. int i;
  66. for (i = 0; i < w * h; i++)
  67. {
  68. heights[i] = (float)heightmap.map[i / w, i % w];
  69. }
  70. return heights;
  71. }
  72. /// <summary>
  73. /// Converts the heightmap to a 256x256 value 2D floating point array.
  74. /// </summary>
  75. /// <returns>An array of 256,256 values containing the heightmap</returns>
  76. public float[,] getHeights2D()
  77. {
  78. float[,] heights = new float[w, h];
  79. int x, y;
  80. for (x = 0; x < w; x++)
  81. {
  82. for (y = 0; y < h; y++)
  83. {
  84. heights[x, y] = (float)heightmap.map[x, y];
  85. }
  86. }
  87. return heights;
  88. }
  89. /// <summary>
  90. /// Imports a 1D floating point array into the 2D heightmap array
  91. /// </summary>
  92. /// <param name="heights">The array to import (must have 65536 members)</param>
  93. public void setHeights1D(float[] heights)
  94. {
  95. int i;
  96. for (i = 0; i < w * h; i++)
  97. {
  98. heightmap.map[i / w, i % w] = heights[i];
  99. }
  100. tainted++;
  101. }
  102. /// <summary>
  103. /// Loads a 2D array of values into the heightmap
  104. /// </summary>
  105. /// <param name="heights">An array of 256,256 float values</param>
  106. public void setHeights2D(float[,] heights)
  107. {
  108. int x, y;
  109. for (x = 0; x < w; x++)
  110. {
  111. for (y = 0; y < h; y++)
  112. {
  113. heightmap.set(x, y, (double)heights[x, y]);
  114. }
  115. }
  116. tainted++;
  117. }
  118. /// <summary>
  119. /// Processes a terrain-specific command
  120. /// </summary>
  121. /// <param name="args">Commandline arguments (space seperated)</param>
  122. /// <param name="resultText">Reference that returns error or help text if returning false</param>
  123. /// <returns>If the operation was successful (if not, the error is placed into resultText)</returns>
  124. public bool RunTerrainCmd(string[] args, ref string resultText)
  125. {
  126. string command = args[0];
  127. try
  128. {
  129. switch (command)
  130. {
  131. case "help":
  132. resultText += "terrain regenerate - rebuilds the sims terrain using a default algorithm\n";
  133. resultText += "terrain seed <seed> - sets the random seed value to <seed>\n";
  134. resultText += "terrain load <type> <filename> - loads a terrain from disk, type can be 'F32', 'F64', 'RAW' or 'IMG'\n";
  135. resultText += "terrain save <type> <filename> - saves a terrain to disk, type can be 'F32' or 'F64'\n";
  136. resultText += "terrain save grdmap <filename> <gradient map> - creates a PNG snapshot of the region using a named gradient map\n";
  137. resultText += "terrain rescale <min> <max> - rescales a terrain to be between <min> and <max> meters high\n";
  138. resultText += "terrain erode aerobic <windspeed> <pickupmin> <dropmin> <carry> <rounds> <lowest>\n";
  139. resultText += "terrain erode thermal <talus> <rounds> <carry>\n";
  140. resultText += "terrain multiply <val> - multiplies a terrain by <val>\n";
  141. return false;
  142. case "seed":
  143. setSeed(Convert.ToInt32(args[1]));
  144. break;
  145. case "erode":
  146. switch (args[1].ToLower())
  147. {
  148. case "aerobic":
  149. // WindSpeed, PickupMinimum,DropMinimum,Carry,Rounds,Lowest
  150. heightmap.AerobicErosion(Convert.ToDouble(args[2]), Convert.ToDouble(args[3]), Convert.ToDouble(args[4]), Convert.ToDouble(args[5]), Convert.ToInt32(args[6]), Convert.ToBoolean(args[7]));
  151. break;
  152. case "thermal":
  153. heightmap.thermalWeathering(Convert.ToDouble(args[2]), Convert.ToInt32(args[3]), Convert.ToDouble(args[4]));
  154. break;
  155. default:
  156. resultText = "Unknown erosion type";
  157. return false;
  158. }
  159. break;
  160. case "regenerate":
  161. hills();
  162. break;
  163. case "rescale":
  164. setRange(Convert.ToSingle(args[1]), Convert.ToSingle(args[2]));
  165. break;
  166. case "multiply":
  167. heightmap *= Convert.ToDouble(args[1]);
  168. break;
  169. case "load":
  170. switch (args[1].ToLower())
  171. {
  172. case "f32":
  173. loadFromFileF32(args[2]);
  174. break;
  175. case "f64":
  176. loadFromFileF64(args[2]);
  177. break;
  178. case "raw":
  179. loadFromFileSLRAW(args[2]);
  180. break;
  181. case "img":
  182. resultText = "Error - IMG mode is presently unsupported.";
  183. return false;
  184. default:
  185. resultText = "Unknown image or data format";
  186. return false;
  187. }
  188. break;
  189. case "save":
  190. switch (args[1].ToLower())
  191. {
  192. case "f32":
  193. writeToFileF32(args[2]);
  194. break;
  195. case "f64":
  196. writeToFileF64(args[2]);
  197. break;
  198. case "grdmap":
  199. exportImage(args[2], args[3]);
  200. break;
  201. default:
  202. resultText = "Unknown image or data format";
  203. return false;
  204. }
  205. break;
  206. default:
  207. resultText = "Unknown terrain command";
  208. return false;
  209. }
  210. return true;
  211. }
  212. catch (Exception e)
  213. {
  214. resultText = "Error running terrain command: " + e.ToString();
  215. return false;
  216. }
  217. }
  218. /// <summary>
  219. /// Renormalises the array between min and max
  220. /// </summary>
  221. /// <param name="min">Minimum value of the new array</param>
  222. /// <param name="max">Maximum value of the new array</param>
  223. public void setRange(float min, float max)
  224. {
  225. heightmap.normalise((double)min, (double)max);
  226. tainted++;
  227. }
  228. /// <summary>
  229. /// Loads a file consisting of 256x256 doubles and imports it as an array into the map.
  230. /// </summary>
  231. /// <remarks>TODO: Move this to libTerrain itself</remarks>
  232. /// <param name="filename">The filename of the double array to import</param>
  233. public void loadFromFileF64(string filename)
  234. {
  235. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  236. System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
  237. System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
  238. int x, y;
  239. for (x = 0; x < w; x++)
  240. {
  241. for (y = 0; y < h; y++)
  242. {
  243. heightmap.map[x, y] = bs.ReadDouble();
  244. }
  245. }
  246. bs.Close();
  247. s.Close();
  248. tainted++;
  249. }
  250. /// <summary>
  251. /// Loads a file consisting of 256x256 floats and imports it as an array into the map.
  252. /// </summary>
  253. /// <remarks>TODO: Move this to libTerrain itself</remarks>
  254. /// <param name="filename">The filename of the float array to import</param>
  255. public void loadFromFileF32(string filename)
  256. {
  257. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  258. System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
  259. System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
  260. int x, y;
  261. for (x = 0; x < w; x++)
  262. {
  263. for (y = 0; y < h; y++)
  264. {
  265. heightmap.map[x, y] = (double)bs.ReadSingle();
  266. }
  267. }
  268. bs.Close();
  269. s.Close();
  270. tainted++;
  271. }
  272. /// <summary>
  273. /// Loads a file formatted in the SL .RAW Format used on the main grid
  274. /// </summary>
  275. /// <remarks>This file format stinks and is best avoided.</remarks>
  276. /// <param name="filename">A path to the .RAW format</param>
  277. public void loadFromFileSLRAW(string filename)
  278. {
  279. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  280. System.IO.FileStream s = file.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
  281. System.IO.BinaryReader bs = new System.IO.BinaryReader(s);
  282. int x, y;
  283. for (x = 0; x < w; x++)
  284. {
  285. for (y = 0; y < h; y++)
  286. {
  287. heightmap.map[x, y] = (double)bs.ReadByte() * ((double)bs.ReadByte() / 127.0);
  288. bs.ReadBytes(11); // Advance the stream to next bytes.
  289. }
  290. }
  291. bs.Close();
  292. s.Close();
  293. tainted++;
  294. }
  295. /// <summary>
  296. /// Writes the current terrain heightmap to disk, in the format of a 65536 entry double[] array.
  297. /// </summary>
  298. /// <param name="filename">The desired output filename</param>
  299. public void writeToFileF64(string filename)
  300. {
  301. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  302. System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
  303. System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s);
  304. int x, y;
  305. for (x = 0; x < w; x++)
  306. {
  307. for (y = 0; y < h; y++)
  308. {
  309. bs.Write(heightmap.get(x, y));
  310. }
  311. }
  312. bs.Close();
  313. s.Close();
  314. }
  315. /// <summary>
  316. /// Writes the current terrain heightmap to disk, in the format of a 65536 entry float[] array
  317. /// </summary>
  318. /// <param name="filename">The desired output filename</param>
  319. public void writeToFileF32(string filename)
  320. {
  321. System.IO.FileInfo file = new System.IO.FileInfo(filename);
  322. System.IO.FileStream s = file.Open(System.IO.FileMode.CreateNew, System.IO.FileAccess.Write);
  323. System.IO.BinaryWriter bs = new System.IO.BinaryWriter(s);
  324. int x, y;
  325. for (x = 0; x < w; x++)
  326. {
  327. for (y = 0; y < h; y++)
  328. {
  329. bs.Write((float)heightmap.get(x, y));
  330. }
  331. }
  332. bs.Close();
  333. s.Close();
  334. }
  335. /// <summary>
  336. /// Sets the random seed to be used by procedural functions which involve random numbers.
  337. /// </summary>
  338. /// <param name="val">The desired seed</param>
  339. public void setSeed(int val)
  340. {
  341. heightmap.seed = val;
  342. }
  343. /// <summary>
  344. /// Raises land in a sphere around the specified coordinates
  345. /// </summary>
  346. /// <param name="rx">Center of the sphere on the X axis</param>
  347. /// <param name="ry">Center of the sphere on the Y axis</param>
  348. /// <param name="size">The radius of the sphere</param>
  349. /// <param name="amount">Scale the height of the sphere by this amount (recommended 0..2)</param>
  350. public void raise(double rx, double ry, double size, double amount)
  351. {
  352. lock (heightmap)
  353. {
  354. heightmap.raise(rx, ry, size, amount);
  355. }
  356. tainted++;
  357. }
  358. /// <summary>
  359. /// Lowers the land in a sphere around the specified coordinates
  360. /// </summary>
  361. /// <param name="rx">The center of the sphere at the X axis</param>
  362. /// <param name="ry">The center of the sphere at the Y axis</param>
  363. /// <param name="size">The radius of the sphere in meters</param>
  364. /// <param name="amount">Scale the height of the sphere by this amount (recommended 0..2)</param>
  365. public void lower(double rx, double ry, double size, double amount)
  366. {
  367. lock (heightmap)
  368. {
  369. heightmap.lower(rx, ry, size, amount);
  370. }
  371. tainted++;
  372. }
  373. /// <summary>
  374. /// Generates a simple set of hills in the shape of an island
  375. /// </summary>
  376. public void hills()
  377. {
  378. lock (heightmap)
  379. {
  380. heightmap.hillsSpheres(200, 20, 40, true, true, false);
  381. heightmap.normalise();
  382. heightmap *= 60.0; // Raise to 60m
  383. }
  384. tainted++;
  385. }
  386. /// <summary>
  387. /// Multiplies the heightfield by val
  388. /// </summary>
  389. /// <param name="meep">The heightfield</param>
  390. /// <param name="val">The multiplier</param>
  391. /// <returns></returns>
  392. public static TerrainEngine operator *(TerrainEngine meep, Double val)
  393. {
  394. meep.heightmap *= val;
  395. meep.tainted++;
  396. return meep;
  397. }
  398. /// <summary>
  399. /// Returns the height at the coordinates x,y
  400. /// </summary>
  401. /// <param name="x">X Coordinate</param>
  402. /// <param name="y">Y Coordinate</param>
  403. /// <returns></returns>
  404. public float this[int x, int y]
  405. {
  406. get
  407. {
  408. return (float)heightmap.get(x, y);
  409. }
  410. set
  411. {
  412. tainted++;
  413. heightmap.set(x, y, (double)value);
  414. }
  415. }
  416. /// <summary>
  417. /// Exports the current heightmap to a PNG file
  418. /// </summary>
  419. /// <param name="filename">The destination filename for the image</param>
  420. /// <param name="gradientmap">A 1x*height* image which contains the colour gradient to export with. Must be at least 1x2 pixels, 1x256 or more is ideal.</param>
  421. public void exportImage(string filename, string gradientmap)
  422. {
  423. try
  424. {
  425. Bitmap gradientmapLd = new Bitmap(gradientmap);
  426. int pallete = gradientmapLd.Height;
  427. Bitmap bmp = new Bitmap(heightmap.w, heightmap.h);
  428. Color[] colours = new Color[pallete];
  429. for (int i = 0; i < pallete; i++)
  430. {
  431. colours[i] = gradientmapLd.GetPixel(0, i);
  432. }
  433. Channel copy = heightmap.copy();
  434. for (int x = 0; x < copy.w; x++)
  435. {
  436. for (int y = 0; y < copy.h; y++)
  437. {
  438. // 512 is the largest possible height before colours clamp
  439. int colorindex = (int)(Math.Max(Math.Min(1.0, copy.get(x, y) / 512.0), 0.0) * pallete);
  440. bmp.SetPixel(x, y, colours[colorindex]);
  441. }
  442. }
  443. bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
  444. }
  445. catch (Exception e)
  446. {
  447. Console.WriteLine("Failed generating terrain map: " + e.ToString());
  448. }
  449. }
  450. /// <summary>
  451. /// Exports the current heightmap in Jpeg2000 format to a byte[]
  452. /// </summary>
  453. /// <param name="gradientmap">A 1x*height* image which contains the colour gradient to export with. Must be at least 1x2 pixels, 1x256 or more is ideal.</param>
  454. public byte[] exportJpegImage(string gradientmap)
  455. {
  456. byte[] imageData = null;
  457. try
  458. {
  459. Bitmap gradientmapLd = new Bitmap(gradientmap);
  460. int pallete = gradientmapLd.Height;
  461. Bitmap bmp = new Bitmap(heightmap.w, heightmap.h);
  462. Color[] colours = new Color[pallete];
  463. for (int i = 0; i < pallete; i++)
  464. {
  465. colours[i] = gradientmapLd.GetPixel(0, i);
  466. }
  467. Channel copy = heightmap.copy();
  468. for (int x = 0; x < copy.w; x++)
  469. {
  470. for (int y = 0; y < copy.h; y++)
  471. {
  472. // 512 is the largest possible height before colours clamp
  473. int colorindex = (int)(Math.Max(Math.Min(1.0, copy.get(copy.w -x, copy.h - y) / 512.0), 0.0) * pallete);
  474. bmp.SetPixel(x, y, colours[colorindex]);
  475. }
  476. }
  477. //bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
  478. imageData = OpenJPEGNet.OpenJPEG.EncodeFromImage(bmp, "map");
  479. }
  480. catch (Exception e)
  481. {
  482. Console.WriteLine("Failed generating terrain map: " + e.ToString());
  483. }
  484. return imageData;
  485. }
  486. }
  487. }