TerrainEngine.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using libTerrain;
  34. using OpenJPEGNet;
  35. namespace OpenSim.Region.Terrain
  36. {
  37. public class TerrainCommand
  38. {
  39. public virtual bool run(string[] cmdargs, ref string output)
  40. {
  41. return false;
  42. }
  43. public string args;
  44. public string help;
  45. }
  46. public class TerrainEngine
  47. {
  48. /// <summary>
  49. /// Plugin library for scripts
  50. /// </summary>
  51. public FilterHost customFilters = new FilterHost();
  52. /// <summary>
  53. /// A [normally] 256x256 heightmap
  54. /// </summary>
  55. public Channel heightmap;
  56. /// <summary>
  57. /// A copy of heightmap at the last save point (for reverting)
  58. /// </summary>
  59. public Channel revertmap;
  60. /// <summary>
  61. /// Water heightmap (needs clientside mods to work)
  62. /// </summary>
  63. public Channel watermap;
  64. /// <summary>
  65. /// Max amount the terrain can be raised from the revert parameters
  66. /// </summary>
  67. public double maxRaise = 500.0;
  68. /// <summary>
  69. /// Min amount the terrain can be lowered from the revert parameters
  70. /// </summary>
  71. public double minLower = 500.0;
  72. /// <summary>
  73. /// Whether or not the terrain has been modified since it was last saved and sent to the Physics engine.
  74. /// Counts the number of modifications since the last save. (0 = Untainted)
  75. /// </summary>
  76. public int tainted;
  77. int w, h;
  78. /// <summary>
  79. /// Used to determine what offset to use when loading singular heightmaps across multiple sims
  80. /// </summary>
  81. private int offsetX;
  82. private int offsetY;
  83. /// <summary>
  84. /// Generate a new TerrainEngine instance and creates a new heightmap
  85. /// </summary>
  86. public TerrainEngine(int X, int Y)
  87. {
  88. w = 256;
  89. h = 256;
  90. heightmap = new Channel(w, h);
  91. revertmap = new Channel(w, h);
  92. watermap = new Channel(w, h);
  93. watermap.Fill(20);
  94. offsetX = X;
  95. offsetY = Y;
  96. tainted++;
  97. }
  98. public bool Tainted()
  99. {
  100. return (tainted != 0);
  101. }
  102. public bool Tainted(int x, int y)
  103. {
  104. return (heightmap.diff[x / 16, y / 16] != 0);
  105. }
  106. public void ResetTaint()
  107. {
  108. tainted = 0;
  109. heightmap.diff = new int[w / 16, h / 16];
  110. }
  111. /// <summary>
  112. /// Checks to make sure the terrain is within baked values +/- maxRaise/minLower
  113. /// </summary>
  114. public void CheckHeightValues()
  115. {
  116. int x, y;
  117. for (x = 0; x < w; x++)
  118. {
  119. for (y = 0; y < h; y++)
  120. {
  121. if ((heightmap.Get(x, y) > revertmap.Get(x, y) + maxRaise))
  122. {
  123. heightmap.map[x, y] = revertmap.Get(x, y) + maxRaise;
  124. }
  125. if ((heightmap.Get(x, y) > revertmap.Get(x, y) - minLower))
  126. {
  127. heightmap.map[x, y] = revertmap.Get(x, y) - minLower;
  128. }
  129. }
  130. }
  131. }
  132. /// <summary>
  133. /// Converts the heightmap to a 65536 value 1D floating point array
  134. /// </summary>
  135. /// <returns>A float[65536] array containing the heightmap</returns>
  136. public float[] GetHeights1D()
  137. {
  138. float[] heights = new float[w * h];
  139. int i;
  140. for (i = 0; i < w * h; i++)
  141. {
  142. heights[i] = (float)heightmap.map[i % w, i / w];
  143. }
  144. return heights;
  145. }
  146. /// <summary>
  147. /// Converts the heightmap to a 256x256 value 2D floating point array.
  148. /// </summary>
  149. /// <returns>An array of 256,256 values containing the heightmap</returns>
  150. public float[,] GetHeights2D()
  151. {
  152. float[,] heights = new float[w, h];
  153. int x, y;
  154. for (x = 0; x < w; x++)
  155. {
  156. for (y = 0; y < h; y++)
  157. {
  158. heights[x, y] = (float)heightmap.map[x, y];
  159. }
  160. }
  161. return heights;
  162. }
  163. /// <summary>
  164. /// Converts the heightmap to a 256x256 value 2D floating point array. Double precision version.
  165. /// </summary>
  166. /// <returns>An array of 256,256 values containing the heightmap</returns>
  167. public double[,] GetHeights2DD()
  168. {
  169. return heightmap.map;
  170. }
  171. /// <summary>
  172. /// Imports a 1D floating point array into the 2D heightmap array
  173. /// </summary>
  174. /// <param name="heights">The array to import (must have 65536 members)</param>
  175. public void GetHeights1D(float[] heights)
  176. {
  177. int i;
  178. for (i = 0; i < w * h; i++)
  179. {
  180. heightmap.map[i % w, i / w] = heights[i];
  181. }
  182. tainted++;
  183. }
  184. /// <summary>
  185. /// Loads a 2D array of values into the heightmap
  186. /// </summary>
  187. /// <param name="heights">An array of 256,256 float values</param>
  188. public void SetHeights2D(float[,] heights)
  189. {
  190. int x, y;
  191. for (x = 0; x < w; x++)
  192. {
  193. for (y = 0; y < h; y++)
  194. {
  195. heightmap.Set(x, y, (double)heights[x, y]);
  196. }
  197. }
  198. SaveRevertMap();
  199. tainted++;
  200. }
  201. /// <summary>
  202. /// Loads a 2D array of values into the heightmap (Double Precision Version)
  203. /// </summary>
  204. /// <param name="heights">An array of 256,256 float values</param>
  205. public void SetHeights2D(double[,] heights)
  206. {
  207. int x, y;
  208. for (x = 0; x < w; x++)
  209. {
  210. for (y = 0; y < h; y++)
  211. {
  212. heightmap.Set(x, y, heights[x, y]);
  213. }
  214. }
  215. SaveRevertMap();
  216. tainted++;
  217. }
  218. /// <summary>
  219. /// Swaps the two heightmap buffers (the 'revert map' and the heightmap)
  220. /// </summary>
  221. public void SwapRevertMaps()
  222. {
  223. Channel backup = heightmap.Copy();
  224. heightmap = revertmap;
  225. revertmap = backup;
  226. }
  227. /// <summary>
  228. /// Saves the current heightmap into the revertmap
  229. /// </summary>
  230. public void SaveRevertMap()
  231. {
  232. revertmap = heightmap.Copy();
  233. }
  234. /// <summary>
  235. /// Processes a terrain-specific command
  236. /// </summary>
  237. /// <param name="args">Commandline arguments (space seperated)</param>
  238. /// <param name="resultText">Reference that returns error or help text if returning false</param>
  239. /// <returns>If the operation was successful (if not, the error is placed into resultText)</returns>
  240. public bool RunTerrainCmd(string[] args, ref string resultText, string simName)
  241. {
  242. string command;
  243. if (args.Length > 0)
  244. {
  245. command = args[0];
  246. }
  247. else
  248. {
  249. command = "help";
  250. }
  251. try
  252. {
  253. switch (command)
  254. {
  255. case "help":
  256. resultText += "terrain regenerate - rebuilds the sims terrain using a default algorithm\n";
  257. resultText += "terrain hills <type> <number of hills> <min height> <max height> <island t/f> <additive t/f> <noisy t/f>\n";
  258. resultText += " type should be spheres, blocks, cones, or squared\n";
  259. resultText += "terrain voronoi <points> <blocksize> - generates a worley fractal with X points per block";
  260. resultText += "terrain seed <seed> - sets the random seed value to <seed>\n";
  261. resultText += "terrain load <type> <filename> - loads a terrain from disk, type can be 'F32', 'F64', 'RAW' or 'IMG'\n";
  262. resultText += "terrain save <type> <filename> - saves a terrain to disk, type can be 'F32', 'F64', 'PNG', 'RAW' or 'HIRAW'\n";
  263. resultText += "terrain save grdmap <filename> <gradient map> - creates a PNG snapshot of the region using a named gradient map\n";
  264. resultText += "terrain rescale <min> <max> - rescales a terrain to be between <min> and <max> meters high\n";
  265. resultText += "terrain fill <val> - fills a terrain at the specified height\n";
  266. resultText += "terrain erode aerobic <windspeed> <pickupmin> <dropmin> <carry> <rounds> <lowest t/f> <fluid dynamics t/f>\n";
  267. resultText += "terrain erode thermal <talus> <rounds> <carry>\n";
  268. resultText += "terrain erode hydraulic <rain> <evaporation> <solubility> <frequency> <rounds>\n";
  269. resultText += "terrain multiply <val> - multiplies a terrain by <val>\n";
  270. resultText += "terrain revert - reverts the terrain to the stored original\n";
  271. resultText += "terrain bake - saves the current terrain into the revert map\n";
  272. resultText += "terrain csfilter <filename.cs> - loads a new filter from the specified .cs file\n";
  273. resultText += "terrain jsfilter <filename.js> - loads a new filter from the specified .js file\n";
  274. foreach (KeyValuePair<string, ITerrainFilter> filter in customFilters.filters)
  275. {
  276. resultText += filter.Value.Help();
  277. }
  278. return false;
  279. case "revert":
  280. SwapRevertMaps();
  281. SaveRevertMap();
  282. break;
  283. case "bake":
  284. SaveRevertMap();
  285. break;
  286. case "seed":
  287. SetSeed(Convert.ToInt32(args[1]));
  288. break;
  289. case "erode":
  290. return ConsoleErosion(args, ref resultText);
  291. case "voronoi":
  292. double[] c = new double[2];
  293. c[0] = -1;
  294. c[1] = 1;
  295. heightmap.VoronoiDiagram(Convert.ToInt32(args[1]), Convert.ToInt32(args[2]), c);
  296. break;
  297. case "hills":
  298. return ConsoleHills(args, ref resultText);
  299. case "regenerate":
  300. HillsGenerator();
  301. break;
  302. case "rescale":
  303. SetRange(Convert.ToSingle(args[1]), Convert.ToSingle(args[2]));
  304. break;
  305. case "fill":
  306. heightmap.Fill(Convert.ToDouble(args[1]));
  307. tainted++;
  308. break;
  309. case "clip":
  310. heightmap.Clip(Convert.ToDouble(args[1]), Convert.ToDouble(args[2]));
  311. tainted++;
  312. break;
  313. case "smooth":
  314. heightmap.Smooth(Convert.ToDouble(args[1]));
  315. tainted++;
  316. break;
  317. case "add":
  318. heightmap += Convert.ToDouble(args[1]);
  319. tainted++;
  320. break;
  321. case "multiply":
  322. heightmap *= Convert.ToDouble(args[1]);
  323. tainted++;
  324. break;
  325. case "load":
  326. string filenameL = args[2].Replace("%name%", simName);
  327. filenameL = filenameL.Replace("%x%", this.offsetX.ToString());
  328. filenameL = filenameL.Replace("%y%", this.offsetY.ToString());
  329. switch (args[1].ToLower())
  330. {
  331. case "f32":
  332. LoadFromFileF32(filenameL);
  333. break;
  334. case "f64":
  335. LoadFromFileF64(filenameL);
  336. break;
  337. case "raw":
  338. LoadFromFileSLRAW(filenameL);
  339. break;
  340. case "img":
  341. heightmap.LoadImage(filenameL);
  342. break;
  343. default:
  344. resultText = "Unknown image or data format";
  345. return false;
  346. }
  347. break;
  348. case "load-tile":
  349. switch (args[1].ToLower())
  350. {
  351. case "f32":
  352. LoadFromFileF32(args[2], Convert.ToInt32(args[3]), Convert.ToInt32(args[4]),
  353. Convert.ToInt32(args[5]), Convert.ToInt32(args[6]));
  354. break;
  355. case "img":
  356. LoadFromFileIMG(args[2], Convert.ToInt32(args[3]), Convert.ToInt32(args[4]),
  357. Convert.ToInt32(args[5]), Convert.ToInt32(args[6]));
  358. break;
  359. default:
  360. resultText = "Unknown or unsupported image or data format";
  361. return false;
  362. }
  363. break;
  364. case "save":
  365. string filename = args[2].Replace("%name%", simName);
  366. filename = filename.Replace("%x%", this.offsetX.ToString());
  367. filename = filename.Replace("%y%", this.offsetY.ToString());
  368. switch (args[1].ToLower())
  369. {
  370. case "f32":
  371. WriteToFileF32(filename);
  372. break;
  373. case "f64":
  374. WriteToFileF64(filename);
  375. break;
  376. case "grdmap":
  377. if (args.Length >= 4)
  378. ExportImage(filename, args[3]);
  379. else
  380. ExportImage(filename, "defaultstripe.png");
  381. break;
  382. case "png":
  383. heightmap.SaveImage(filename);
  384. break;
  385. case "raw":
  386. WriteToFileRAW(filename);
  387. break;
  388. case "hiraw":
  389. WriteToFileHiRAW(filename);
  390. break;
  391. default:
  392. resultText = "Unknown image or data format";
  393. return false;
  394. }
  395. break;
  396. case "csfilter":
  397. customFilters.LoadFilterCSharp(args[1]);
  398. break;
  399. case "jsfilter":
  400. customFilters.LoadFilterJScript(args[1]);
  401. break;
  402. default:
  403. // Run any custom registered filters
  404. if (customFilters.filters.ContainsKey(command))
  405. {
  406. customFilters.filters[command].Filter(heightmap, args);
  407. break;
  408. }
  409. else
  410. {
  411. resultText = "Unknown terrain command";
  412. return false;
  413. }
  414. }
  415. return true;
  416. }
  417. catch (Exception e)
  418. {
  419. resultText = "Error running terrain command: " + e.ToString();
  420. return false;
  421. }
  422. }
  423. private bool ConsoleErosion(string[] args, ref string resultText)
  424. {
  425. double min = heightmap.FindMin();
  426. double max = heightmap.FindMax();
  427. switch (args[1].ToLower())
  428. {
  429. case "aerobic":
  430. // WindSpeed, PickupMinimum,DropMinimum,Carry,Rounds,Lowest
  431. 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]), Convert.ToBoolean(args[8]));
  432. break;
  433. case "thermal":
  434. heightmap.ThermalWeathering(Convert.ToDouble(args[2]), Convert.ToInt32(args[3]), Convert.ToDouble(args[4]));
  435. break;
  436. case "hydraulic":
  437. Channel rainMap = new Channel(w, h);
  438. rainMap.Fill(Convert.ToDouble(args[2]));
  439. heightmap.HydraulicErosion(rainMap, Convert.ToDouble(args[3]), Convert.ToDouble(args[4]), Convert.ToInt32(args[5]), Convert.ToInt32(args[6]));
  440. break;
  441. default:
  442. resultText = "Unknown erosion type";
  443. return false;
  444. }
  445. heightmap.Normalise(min, max);
  446. tainted++;
  447. return true;
  448. }
  449. private bool ConsoleHills(string[] args, ref string resultText)
  450. {
  451. Random RandomClass = new Random();
  452. SetSeed(RandomClass.Next());
  453. int count;
  454. double sizeMin;
  455. double sizeRange;
  456. bool island;
  457. bool additive;
  458. bool noisy;
  459. if (args.GetLength(0) > 2)
  460. {
  461. int.TryParse(args[2].ToString(), out count);
  462. double.TryParse(args[3].ToString(), out sizeMin);
  463. double.TryParse(args[4].ToString(), out sizeRange);
  464. bool.TryParse(args[5].ToString(), out island);
  465. bool.TryParse(args[6].ToString(), out additive);
  466. bool.TryParse(args[7].ToString(), out noisy);
  467. }
  468. else
  469. {
  470. count = 200;
  471. sizeMin = 20;
  472. sizeRange = 40;
  473. island = true;
  474. additive = true;
  475. noisy = false;
  476. }
  477. switch (args[1].ToLower())
  478. {
  479. case "blocks":
  480. heightmap.HillsBlocks(count, sizeMin, sizeRange, island, additive, noisy);
  481. break;
  482. case "cones":
  483. heightmap.HillsCones(count, sizeMin, sizeRange, island, additive, noisy);
  484. break;
  485. case "spheres":
  486. heightmap.HillsSpheres(count, sizeMin, sizeRange, island, additive, noisy);
  487. break;
  488. case "squared":
  489. heightmap.HillsSquared(count, sizeMin, sizeRange, island, additive, noisy);
  490. break;
  491. default:
  492. resultText = "Unknown hills type";
  493. return false;
  494. }
  495. tainted++;
  496. return true;
  497. }
  498. /// <summary>
  499. /// Renormalises the array between min and max
  500. /// </summary>
  501. /// <param name="min">Minimum value of the new array</param>
  502. /// <param name="max">Maximum value of the new array</param>
  503. public void SetRange(float min, float max)
  504. {
  505. heightmap.Normalise((double)min, (double)max);
  506. tainted++;
  507. }
  508. /// <summary>
  509. /// Loads a file consisting of 256x256 doubles and imports it as an array into the map.
  510. /// </summary>
  511. /// <remarks>TODO: Move this to libTerrain itself</remarks>
  512. /// <param name="filename">The filename of the double array to import</param>
  513. public void LoadFromFileF64(string filename)
  514. {
  515. FileInfo file = new FileInfo(filename);
  516. FileStream s = file.Open(FileMode.Open, FileAccess.Read);
  517. BinaryReader bs = new BinaryReader(s);
  518. int x, y;
  519. for (y = 0; y < h; y++)
  520. {
  521. for (x = 0; x < h; x++)
  522. {
  523. heightmap.map[x, y] = bs.ReadDouble();
  524. }
  525. }
  526. bs.Close();
  527. s.Close();
  528. tainted++;
  529. }
  530. /// <summary>
  531. /// Loads a file consisting of 256x256 floats and imports it as an array into the map.
  532. /// </summary>
  533. /// <remarks>TODO: Move this to libTerrain itself</remarks>
  534. /// <param name="filename">The filename of the float array to import</param>
  535. public void LoadFromFileF32(string filename)
  536. {
  537. FileInfo file = new FileInfo(filename);
  538. FileStream s = file.Open(FileMode.Open, FileAccess.Read);
  539. BinaryReader bs = new BinaryReader(s);
  540. int x, y;
  541. for (y = 0; y < h; y++)
  542. {
  543. for (x = 0; x < w; x++)
  544. {
  545. heightmap.map[x, y] = (double)bs.ReadSingle();
  546. }
  547. }
  548. bs.Close();
  549. s.Close();
  550. tainted++;
  551. }
  552. /// <summary>
  553. /// Loads a section of a larger heightmap (F32)
  554. /// </summary>
  555. /// <param name="filename">File to load</param>
  556. /// <param name="dimensionX">Size of the file</param>
  557. /// <param name="dimensionY">Size of the file</param>
  558. /// <param name="lowerboundX">Where do the region coords start for this terrain?</param>
  559. /// <param name="lowerboundY">Where do the region coords start for this terrain?</param>
  560. public void LoadFromFileF32(string filename, int dimensionX, int dimensionY, int lowerboundX, int lowerboundY)
  561. {
  562. int sectionToLoadX = ((this.offsetX - lowerboundX) * this.w);
  563. int sectionToLoadY = ((this.offsetY - lowerboundY) * this.h);
  564. double[,] tempMap = new double[dimensionX, dimensionY];
  565. FileInfo file = new FileInfo(filename);
  566. FileStream s = file.Open(FileMode.Open, FileAccess.Read);
  567. BinaryReader bs = new BinaryReader(s);
  568. int x, y;
  569. for (x = 0; x < dimensionX; x++)
  570. {
  571. for (y = 0; y < dimensionY; y++)
  572. {
  573. tempMap[x,y] = (double)bs.ReadSingle();
  574. }
  575. }
  576. for (y = 0; y < h; y++)
  577. {
  578. for (x = 0; x < w; x++)
  579. {
  580. heightmap.Set(x, y, tempMap[x + sectionToLoadX, y + sectionToLoadY]);
  581. }
  582. }
  583. bs.Close();
  584. s.Close();
  585. tainted++;
  586. }
  587. /// <summary>
  588. /// Loads a larger tiled image across a terrain
  589. /// </summary>
  590. /// <param name="filename">Filename to load from (any generic image format should work)</param>
  591. /// <param name="dimensionX">The dimensions of the image</param>
  592. /// <param name="dimensionY">The dimensions of the image</param>
  593. /// <param name="lowerboundX">Where sim coords begin for this patch</param>
  594. /// <param name="lowerboundY">Where sim coords begin for this patch</param>
  595. public void LoadFromFileIMG(string filename, int dimensionX, int dimensionY, int lowerboundX, int lowerboundY)
  596. {
  597. int sectionToLoadX = ((this.offsetX - lowerboundX) * this.w);
  598. int sectionToLoadY = ((this.offsetY - lowerboundY) * this.h);
  599. double[,] tempMap = new double[dimensionX, dimensionY];
  600. System.Drawing.Bitmap lgrBmp = new Bitmap(filename);
  601. int x, y;
  602. for (x = 0; x < dimensionX; x++)
  603. {
  604. for (y = 0; y < dimensionY; y++)
  605. {
  606. tempMap[x, y] = (float)lgrBmp.GetPixel(x, y).GetBrightness();
  607. }
  608. }
  609. for (y = 0; y < h; y++)
  610. {
  611. for (x = 0; x < w; x++)
  612. {
  613. heightmap.Set(x, y, tempMap[x + sectionToLoadX, y + sectionToLoadY]);
  614. }
  615. }
  616. tainted++;
  617. }
  618. /// <summary>
  619. /// Loads a file formatted in the SL .RAW Format used on the main grid
  620. /// </summary>
  621. /// <remarks>This file format stinks and is best avoided.</remarks>
  622. /// <param name="filename">A path to the .RAW format</param>
  623. public void LoadFromFileSLRAW(string filename)
  624. {
  625. FileInfo file = new FileInfo(filename);
  626. FileStream s = file.Open(FileMode.Open, FileAccess.Read);
  627. BinaryReader bs = new BinaryReader(s);
  628. int x, y;
  629. for (y = 0; y < h; y++)
  630. {
  631. for (x = 0; x < w; x++)
  632. {
  633. heightmap.map[x, y] = (double)bs.ReadByte() * ((double)bs.ReadByte() / 127.0);
  634. bs.ReadBytes(11); // Advance the stream to next bytes.
  635. }
  636. }
  637. bs.Close();
  638. s.Close();
  639. tainted++;
  640. }
  641. /// <summary>
  642. /// Writes the current terrain heightmap to disk, in the format of a 65536 entry double[] array.
  643. /// </summary>
  644. /// <param name="filename">The desired output filename</param>
  645. public void WriteToFileF64(string filename)
  646. {
  647. FileInfo file = new FileInfo(filename);
  648. FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
  649. BinaryWriter bs = new BinaryWriter(s);
  650. int x, y;
  651. for (y = 0; y < h; y++)
  652. {
  653. for (x = 0; x < w; x++)
  654. {
  655. bs.Write(heightmap.Get(x, y));
  656. }
  657. }
  658. bs.Close();
  659. s.Close();
  660. }
  661. /// <summary>
  662. /// Writes the current terrain heightmap to disk, in the format of a 65536 entry float[] array
  663. /// </summary>
  664. /// <param name="filename">The desired output filename</param>
  665. public void WriteToFileF32(string filename)
  666. {
  667. FileInfo file = new FileInfo(filename);
  668. FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
  669. BinaryWriter bs = new BinaryWriter(s);
  670. int x, y;
  671. for (y = 0; y < h; y++)
  672. {
  673. for (x = 0; x < w; x++)
  674. {
  675. bs.Write((float)heightmap.Get(x, y));
  676. }
  677. }
  678. bs.Close();
  679. s.Close();
  680. }
  681. /// <summary>
  682. /// A very fast LL-RAW file output mechanism - lower precision mechanism but wont take 5 minutes to run either.
  683. /// (is also editable in an image application)
  684. /// </summary>
  685. /// <param name="filename">Filename to write to</param>
  686. public void WriteToFileRAW(string filename)
  687. {
  688. FileInfo file = new FileInfo(filename);
  689. FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
  690. BinaryWriter binStream = new BinaryWriter(s);
  691. int x, y;
  692. // Used for the 'green' channel.
  693. byte avgMultiplier = (byte)heightmap.Avg();
  694. byte backupMultiplier = (byte)revertmap.Avg();
  695. // Limit the multiplier so it can represent points >64m.
  696. if (avgMultiplier > 196)
  697. avgMultiplier = 196;
  698. if(backupMultiplier > 196)
  699. backupMultiplier = 196;
  700. // Make sure it's at least one to prevent a div by zero
  701. if (avgMultiplier < 1)
  702. avgMultiplier = 1;
  703. if(backupMultiplier < 1)
  704. backupMultiplier = 1;
  705. for (y = 0; y < h; y++)
  706. {
  707. for (x = 0; x < h; x++)
  708. {
  709. byte red = (byte)(heightmap.Get(x, y) / ((double)avgMultiplier / 128.0));
  710. byte green = avgMultiplier;
  711. byte blue = (byte)watermap.Get(x, y);
  712. byte alpha1 = 0; // Land Parcels
  713. byte alpha2 = 0; // For Sale Land
  714. byte alpha3 = 0; // Public Edit Object
  715. byte alpha4 = 0; // Public Edit Land
  716. byte alpha5 = 255; // Safe Land
  717. byte alpha6 = 255; // Flying Allowed
  718. byte alpha7 = 255; // Create Landmark
  719. byte alpha8 = 255; // Outside Scripts
  720. byte alpha9 = (byte)(revertmap.Get(x, y) / ((double)backupMultiplier / 128.0));
  721. byte alpha10 = backupMultiplier;
  722. binStream.Write(red);
  723. binStream.Write(green);
  724. binStream.Write(blue);
  725. binStream.Write(alpha1);
  726. binStream.Write(alpha2);
  727. binStream.Write(alpha3);
  728. binStream.Write(alpha4);
  729. binStream.Write(alpha5);
  730. binStream.Write(alpha6);
  731. binStream.Write(alpha7);
  732. binStream.Write(alpha8);
  733. binStream.Write(alpha9);
  734. binStream.Write(alpha10);
  735. }
  736. }
  737. binStream.Close();
  738. s.Close();
  739. }
  740. /// <summary>
  741. /// Outputs to a LL compatible RAW in the most efficient manner possible
  742. /// </summary>
  743. /// <remarks>Does not calculate the revert map</remarks>
  744. /// <param name="filename">The filename to output to</param>
  745. public void WriteToFileHiRAW(string filename)
  746. {
  747. FileInfo file = new FileInfo(filename);
  748. FileStream s = file.Open(FileMode.CreateNew, FileAccess.Write);
  749. BinaryWriter binStream = new BinaryWriter(s);
  750. // Generate a smegging big lookup table to speed the operation up (it needs it)
  751. double[] lookupHeightTable = new double[65536];
  752. int i, j, x, y;
  753. for (i = 0; i < 256; i++)
  754. {
  755. for (j = 0; j < 256; j++)
  756. {
  757. lookupHeightTable[i + (j * 256)] = ((double)i * ((double)j / 127.0));
  758. }
  759. }
  760. // Output the calculated raw
  761. for (y = 0; y < h; y++)
  762. {
  763. for (x = 0; x < w; x++)
  764. {
  765. double t = heightmap.Get(x, y);
  766. double min = double.MaxValue;
  767. int index = 0;
  768. for (i = 0; i < 65536; i++)
  769. {
  770. if (Math.Abs(t - lookupHeightTable[i]) < min)
  771. {
  772. min = Math.Abs(t - lookupHeightTable[i]);
  773. index = i;
  774. }
  775. }
  776. byte red = (byte)(index & 0xFF);
  777. byte green = (byte)((index >> 8) & 0xFF);
  778. byte blue = (byte)watermap.Get(x, y);
  779. byte alpha1 = 0; // Land Parcels
  780. byte alpha2 = 0; // For Sale Land
  781. byte alpha3 = 0; // Public Edit Object
  782. byte alpha4 = 0; // Public Edit Land
  783. byte alpha5 = 255; // Safe Land
  784. byte alpha6 = 255; // Flying Allowed
  785. byte alpha7 = 255; // Create Landmark
  786. byte alpha8 = 255; // Outside Scripts
  787. byte alpha9 = red;
  788. byte alpha10 = green;
  789. binStream.Write(red);
  790. binStream.Write(green);
  791. binStream.Write(blue);
  792. binStream.Write(alpha1);
  793. binStream.Write(alpha2);
  794. binStream.Write(alpha3);
  795. binStream.Write(alpha4);
  796. binStream.Write(alpha5);
  797. binStream.Write(alpha6);
  798. binStream.Write(alpha7);
  799. binStream.Write(alpha8);
  800. binStream.Write(alpha9);
  801. binStream.Write(alpha10);
  802. }
  803. }
  804. binStream.Close();
  805. s.Close();
  806. }
  807. /// <summary>
  808. /// Sets the random seed to be used by procedural functions which involve random numbers.
  809. /// </summary>
  810. /// <param name="val">The desired seed</param>
  811. public void SetSeed(int val)
  812. {
  813. heightmap.seed = val;
  814. }
  815. /// <summary>
  816. /// Raises land in a sphere around the specified coordinates
  817. /// </summary>
  818. /// <param name="rx">Center of the sphere on the X axis</param>
  819. /// <param name="ry">Center of the sphere on the Y axis</param>
  820. /// <param name="size">The radius of the sphere</param>
  821. /// <param name="amount">Scale the height of the sphere by this amount (recommended 0..2)</param>
  822. public void RaiseTerrain(double rx, double ry, double size, double amount)
  823. {
  824. lock (heightmap)
  825. {
  826. heightmap.Raise(rx, ry, size, amount);
  827. }
  828. tainted++;
  829. }
  830. /// <summary>
  831. /// Lowers the land in a sphere around the specified coordinates
  832. /// </summary>
  833. /// <param name="rx">The center of the sphere at the X axis</param>
  834. /// <param name="ry">The center of the sphere at the Y axis</param>
  835. /// <param name="size">The radius of the sphere in meters</param>
  836. /// <param name="amount">Scale the height of the sphere by this amount (recommended 0..2)</param>
  837. public void LowerTerrain(double rx, double ry, double size, double amount)
  838. {
  839. lock (heightmap)
  840. {
  841. heightmap.Lower(rx, ry, size, amount);
  842. }
  843. tainted++;
  844. }
  845. /// <summary>
  846. /// Flattens the land under the brush of specified coordinates (spherical mask)
  847. /// </summary>
  848. /// <param name="rx">Center of sphere</param>
  849. /// <param name="ry">Center of sphere</param>
  850. /// <param name="size">Radius of the sphere</param>
  851. /// <param name="amount">Thickness of the mask (0..2 recommended)</param>
  852. public void FlattenTerrain(double rx, double ry, double size, double amount)
  853. {
  854. lock (heightmap)
  855. {
  856. heightmap.Flatten(rx, ry, size, amount);
  857. }
  858. tainted++;
  859. }
  860. /// <summary>
  861. /// Creates noise within the specified bounds
  862. /// </summary>
  863. /// <param name="rx">Center of the bounding sphere</param>
  864. /// <param name="ry">Center of the bounding sphere</param>
  865. /// <param name="size">The radius of the sphere</param>
  866. /// <param name="amount">Strength of the mask (0..2) recommended</param>
  867. public void NoiseTerrain(double rx, double ry, double size, double amount)
  868. {
  869. lock (heightmap)
  870. {
  871. Channel smoothed = new Channel();
  872. smoothed.Noise();
  873. Channel mask = new Channel();
  874. mask.Raise(rx, ry, size, amount);
  875. heightmap.Blend(smoothed, mask);
  876. }
  877. tainted++;
  878. }
  879. /// <summary>
  880. /// Reverts land within the specified bounds
  881. /// </summary>
  882. /// <param name="rx">Center of the bounding sphere</param>
  883. /// <param name="ry">Center of the bounding sphere</param>
  884. /// <param name="size">The radius of the sphere</param>
  885. /// <param name="amount">Strength of the mask (0..2) recommended</param>
  886. public void RevertTerrain(double rx, double ry, double size, double amount)
  887. {
  888. lock (heightmap)
  889. {
  890. Channel mask = new Channel();
  891. mask.Raise(rx, ry, size, amount);
  892. heightmap.Blend(revertmap, mask);
  893. }
  894. tainted++;
  895. }
  896. /// <summary>
  897. /// Smooths land under the brush of specified coordinates (spherical mask)
  898. /// </summary>
  899. /// <param name="rx">Center of the sphere</param>
  900. /// <param name="ry">Center of the sphere</param>
  901. /// <param name="size">Radius of the sphere</param>
  902. /// <param name="amount">Thickness of the mask (0..2 recommended)</param>
  903. public void SmoothTerrain(double rx, double ry, double size, double amount)
  904. {
  905. lock (heightmap)
  906. {
  907. Channel smoothed = heightmap.Copy();
  908. smoothed.Smooth(amount);
  909. Channel mask = new Channel();
  910. mask.Raise(rx,ry,size,amount);
  911. heightmap.Blend(smoothed, mask);
  912. }
  913. tainted++;
  914. }
  915. /// <summary>
  916. /// Generates a simple set of hills in the shape of an island
  917. /// </summary>
  918. public void HillsGenerator()
  919. {
  920. lock (heightmap)
  921. {
  922. heightmap.HillsSpheres(200, 20, 40, true, true, false);
  923. heightmap.Normalise();
  924. heightmap *= 60.0; // Raise to 60m
  925. }
  926. tainted++;
  927. }
  928. /// <summary>
  929. /// Wrapper to heightmap.get()
  930. /// </summary>
  931. /// <param name="x">X coord</param>
  932. /// <param name="y">Y coord</param>
  933. /// <returns>Height at specified coordinates</returns>
  934. public double GetHeight(int x, int y)
  935. {
  936. return heightmap.Get(x, y);
  937. }
  938. /// <summary>
  939. /// Multiplies the heightfield by val
  940. /// </summary>
  941. /// <param name="meep">The heightfield</param>
  942. /// <param name="val">The multiplier</param>
  943. /// <returns></returns>
  944. public static TerrainEngine operator *(TerrainEngine terrain, Double val)
  945. {
  946. terrain.heightmap *= val;
  947. terrain.tainted++;
  948. return terrain;
  949. }
  950. /// <summary>
  951. /// Exports the current heightmap to a PNG file
  952. /// </summary>
  953. /// <param name="filename">The destination filename for the image</param>
  954. /// <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>
  955. public void ExportImage(string filename, string gradientmap)
  956. {
  957. try
  958. {
  959. Bitmap gradientmapLd = new Bitmap(gradientmap);
  960. int pallete = gradientmapLd.Height;
  961. Bitmap bmp = new Bitmap(heightmap.w, heightmap.h);
  962. Color[] colours = new Color[pallete];
  963. for (int i = 0; i < pallete; i++)
  964. {
  965. colours[i] = gradientmapLd.GetPixel(0, i);
  966. }
  967. Channel copy = heightmap.Copy();
  968. for (int y = 0; y < copy.h; y++)
  969. {
  970. for (int x = 0; x < copy.w; x++)
  971. {
  972. // 512 is the largest possible height before colours clamp
  973. int colorindex = (int)(Math.Max(Math.Min(1.0, copy.Get(x, y) / 512.0), 0.0) * (pallete - 1));
  974. bmp.SetPixel(x, y, colours[colorindex]);
  975. }
  976. }
  977. bmp.Save(filename, ImageFormat.Png);
  978. }
  979. catch (Exception e)
  980. {
  981. Console.WriteLine("Failed generating terrain map: " + e.ToString());
  982. }
  983. }
  984. /// <summary>
  985. /// Exports the current heightmap in Jpeg2000 format to a byte[]
  986. /// </summary>
  987. /// <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>
  988. public byte[] ExportJpegImage(string gradientmap)
  989. {
  990. byte[] imageData = null;
  991. try
  992. {
  993. Bitmap gradientmapLd = new Bitmap(gradientmap);
  994. int pallete = gradientmapLd.Height;
  995. Bitmap bmp = new Bitmap(heightmap.w, heightmap.h);
  996. Color[] colours = new Color[pallete];
  997. for (int i = 0; i < pallete; i++)
  998. {
  999. colours[i] = gradientmapLd.GetPixel(0, i);
  1000. }
  1001. Channel copy = heightmap.Copy();
  1002. for (int y = 0; y < copy.h; y++)
  1003. {
  1004. for (int x = 0; x < copy.w; x++)
  1005. {
  1006. // 512 is the largest possible height before colours clamp
  1007. int colorindex = (int)(Math.Max(Math.Min(1.0, copy.Get(x, copy.h - y) / 512.0), 0.0) * (pallete - 1));
  1008. bmp.SetPixel(x, y, colours[colorindex]);
  1009. }
  1010. }
  1011. //bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Png);
  1012. imageData = OpenJPEG.EncodeFromImage(bmp, true );
  1013. }
  1014. catch (Exception e)
  1015. {
  1016. Console.WriteLine("Failed generating terrain map: " + e.ToString());
  1017. }
  1018. return imageData;
  1019. }
  1020. }
  1021. }