TerrainChannel.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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.IO;
  29. using System.Text;
  30. using System.Reflection;
  31. using System.Xml;
  32. using System.Xml.Serialization;
  33. using OpenSim.Data;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenMetaverse;
  37. using log4net;
  38. namespace OpenSim.Region.Framework.Scenes
  39. {
  40. /// <summary>
  41. /// A new version of the old Channel class, simplified
  42. /// </summary>
  43. public class TerrainChannel : ITerrainChannel
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private static string LogHeader = "[TERRAIN CHANNEL]";
  47. protected TerrainData m_terrainData;
  48. public int Width { get { return m_terrainData.SizeX; } } // X dimension
  49. // Unfortunately, for historical reasons, in this module 'Width' is X and 'Height' is Y
  50. public int Height { get { return m_terrainData.SizeY; } } // Y dimension
  51. public int Altitude { get { return m_terrainData.SizeZ; } } // Y dimension
  52. // Default, not-often-used builder
  53. public TerrainChannel()
  54. {
  55. m_terrainData = new HeightmapTerrainData((int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionHeight);
  56. FlatLand();
  57. // PinHeadIsland();
  58. }
  59. // Create terrain of given size
  60. public TerrainChannel(int pX, int pY)
  61. {
  62. m_terrainData = new HeightmapTerrainData(pX, pY, (int)Constants.RegionHeight);
  63. }
  64. // Create terrain of specified size and initialize with specified terrain.
  65. // TODO: join this with the terrain initializers.
  66. public TerrainChannel(String type, int pX, int pY, int pZ)
  67. {
  68. m_terrainData = new HeightmapTerrainData(pX, pY, pZ);
  69. if (type.Equals("flat"))
  70. FlatLand();
  71. else
  72. PinHeadIsland();
  73. }
  74. // Create channel passed a heightmap and expected dimensions of the region.
  75. // The heightmap might not fit the passed size so accomodations must be made.
  76. public TerrainChannel(double[,] pM, int pSizeX, int pSizeY, int pAltitude)
  77. {
  78. int hmSizeX = pM.GetLength(0);
  79. int hmSizeY = pM.GetLength(1);
  80. m_terrainData = new HeightmapTerrainData(pSizeX, pSizeY, pAltitude);
  81. for (int xx = 0; xx < pSizeX; xx++)
  82. for (int yy = 0; yy < pSizeY; yy++)
  83. if (xx > hmSizeX || yy > hmSizeY)
  84. m_terrainData[xx, yy] = TerrainData.DefaultTerrainHeight;
  85. else
  86. m_terrainData[xx, yy] = (float)pM[xx, yy];
  87. }
  88. public TerrainChannel(TerrainData pTerrData)
  89. {
  90. m_terrainData = pTerrData;
  91. }
  92. #region ITerrainChannel Members
  93. // ITerrainChannel.MakeCopy()
  94. public ITerrainChannel MakeCopy()
  95. {
  96. return this.Copy();
  97. }
  98. // ITerrainChannel.GetTerrainData()
  99. public TerrainData GetTerrainData()
  100. {
  101. return m_terrainData;
  102. }
  103. // ITerrainChannel.GetFloatsSerialized()
  104. // This one dimensional version is ordered so height = map[y*sizeX+x];
  105. // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain
  106. // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256.
  107. public float[] GetFloatsSerialised()
  108. {
  109. return m_terrainData.GetFloatsSerialized();
  110. }
  111. // ITerrainChannel.GetDoubles()
  112. public double[,] GetDoubles()
  113. {
  114. double[,] heights = new double[Width, Height];
  115. int idx = 0; // index into serialized array
  116. for (int ii = 0; ii < Width; ii++)
  117. {
  118. for (int jj = 0; jj < Height; jj++)
  119. {
  120. heights[ii, jj] = (double)m_terrainData[ii, jj];
  121. idx++;
  122. }
  123. }
  124. return heights;
  125. }
  126. // ITerrainChannel.this[x,y]
  127. public double this[int x, int y]
  128. {
  129. get {
  130. if (x < 0 || x >= Width || y < 0 || y >= Height)
  131. return 0;
  132. return (double)m_terrainData[x, y];
  133. }
  134. set
  135. {
  136. if (Double.IsNaN(value) || Double.IsInfinity(value))
  137. return;
  138. if (value < 0)
  139. value = 0;
  140. else
  141. if (value > 655.35)
  142. value = 655.35;
  143. m_terrainData[x, y] = (float)value;
  144. }
  145. }
  146. // ITerrainChannel.GetHieghtAtXYZ(x, y, z)
  147. public float GetHeightAtXYZ(float x, float y, float z)
  148. {
  149. if (x < 0 || x >= Width || y < 0 || y >= Height)
  150. return 0;
  151. return m_terrainData[(int)x, (int)y];
  152. }
  153. // ITerrainChannel.Tainted()
  154. public bool Tainted(int x, int y)
  155. {
  156. return m_terrainData.IsTaintedAt(x, y);
  157. }
  158. // ITerrainChannel.SaveToXmlString()
  159. public string SaveToXmlString()
  160. {
  161. XmlWriterSettings settings = new XmlWriterSettings();
  162. settings.Encoding = Util.UTF8;
  163. using (StringWriter sw = new StringWriter())
  164. {
  165. using (XmlWriter writer = XmlWriter.Create(sw, settings))
  166. {
  167. WriteXml(writer);
  168. }
  169. string output = sw.ToString();
  170. return output;
  171. }
  172. }
  173. // ITerrainChannel.LoadFromXmlString()
  174. public void LoadFromXmlString(string data)
  175. {
  176. StringReader sr = new StringReader(data);
  177. XmlTextReader reader = new XmlTextReader(sr);
  178. reader.Read();
  179. ReadXml(reader);
  180. reader.Close();
  181. sr.Close();
  182. }
  183. // ITerrainChannel.Merge
  184. public void Merge(ITerrainChannel newTerrain, Vector3 displacement, float radianRotation, Vector2 rotationDisplacement)
  185. {
  186. m_log.DebugFormat("{0} Merge. inSize=<{1},{2}>, disp={3}, rot={4}, rotDisp={5}, outSize=<{6},{7}>", LogHeader,
  187. newTerrain.Width, newTerrain.Height,
  188. displacement, radianRotation, rotationDisplacement,
  189. m_terrainData.SizeX, m_terrainData.SizeY);
  190. for (int xx = 0; xx < newTerrain.Width; xx++)
  191. {
  192. for (int yy = 0; yy < newTerrain.Height; yy++)
  193. {
  194. int dispX = (int)displacement.X;
  195. int dispY = (int)displacement.Y;
  196. float newHeight = (float)newTerrain[xx, yy] + displacement.Z;
  197. if (radianRotation == 0)
  198. {
  199. // If no rotation, place the new height in the specified location
  200. dispX += xx;
  201. dispY += yy;
  202. if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
  203. {
  204. m_terrainData[dispX, dispY] = newHeight;
  205. }
  206. }
  207. else
  208. {
  209. // If rotating, we have to smooth the result because the conversion
  210. // to ints will mean heightmap entries will not get changed
  211. // First compute the rotation location for the new height.
  212. dispX += (int)(rotationDisplacement.X
  213. + ((float)xx - rotationDisplacement.X) * Math.Cos(radianRotation)
  214. - ((float)yy - rotationDisplacement.Y) * Math.Sin(radianRotation) );
  215. dispY += (int)(rotationDisplacement.Y
  216. + ((float)xx - rotationDisplacement.X) * Math.Sin(radianRotation)
  217. + ((float)yy - rotationDisplacement.Y) * Math.Cos(radianRotation) );
  218. if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
  219. {
  220. float oldHeight = m_terrainData[dispX, dispY];
  221. // Smooth the heights around this location if the old height is far from this one
  222. for (int sxx = dispX - 2; sxx < dispX + 2; sxx++)
  223. {
  224. for (int syy = dispY - 2; syy < dispY + 2; syy++)
  225. {
  226. if (sxx >= 0 && sxx < m_terrainData.SizeX && syy >= 0 && syy < m_terrainData.SizeY)
  227. {
  228. if (sxx == dispX && syy == dispY)
  229. {
  230. // Set height for the exact rotated point
  231. m_terrainData[dispX, dispY] = newHeight;
  232. }
  233. else
  234. {
  235. if (Math.Abs(m_terrainData[sxx, syy] - newHeight) > 1f)
  236. {
  237. // If the adjacent height is far off, force it to this height
  238. m_terrainData[sxx, syy] = newHeight;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. }
  245. if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY)
  246. {
  247. m_terrainData[dispX, dispY] = (float)newTerrain[xx, yy];
  248. }
  249. }
  250. }
  251. }
  252. }
  253. #endregion
  254. public TerrainChannel Copy()
  255. {
  256. TerrainChannel copy = new TerrainChannel();
  257. copy.m_terrainData = m_terrainData.Clone();
  258. return copy;
  259. }
  260. private void WriteXml(XmlWriter writer)
  261. {
  262. if (Width == Constants.RegionSize && Height == Constants.RegionSize)
  263. {
  264. // Downward compatibility for legacy region terrain maps.
  265. // If region is exactly legacy size, return the old format XML.
  266. writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty);
  267. ToXml(writer);
  268. writer.WriteEndElement();
  269. }
  270. else
  271. {
  272. // New format XML that includes width and length.
  273. writer.WriteStartElement(String.Empty, "TerrainMap2", String.Empty);
  274. ToXml2(writer);
  275. writer.WriteEndElement();
  276. }
  277. }
  278. private void ReadXml(XmlReader reader)
  279. {
  280. // Check the first element. If legacy element, use the legacy reader.
  281. if (reader.IsStartElement("TerrainMap"))
  282. {
  283. reader.ReadStartElement("TerrainMap");
  284. FromXml(reader);
  285. }
  286. else
  287. {
  288. reader.ReadStartElement("TerrainMap2");
  289. FromXml2(reader);
  290. }
  291. }
  292. // Write legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array.
  293. private void ToXml(XmlWriter xmlWriter)
  294. {
  295. float[] mapData = GetFloatsSerialised();
  296. byte[] buffer = new byte[mapData.Length * 4];
  297. for (int i = 0; i < mapData.Length; i++)
  298. {
  299. byte[] value = BitConverter.GetBytes(mapData[i]);
  300. Array.Copy(value, 0, buffer, (i * 4), 4);
  301. }
  302. XmlSerializer serializer = new XmlSerializer(typeof(byte[]));
  303. serializer.Serialize(xmlWriter, buffer);
  304. }
  305. // Read legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array.
  306. private void FromXml(XmlReader xmlReader)
  307. {
  308. XmlSerializer serializer = new XmlSerializer(typeof(byte[]));
  309. byte[] dataArray = (byte[])serializer.Deserialize(xmlReader);
  310. int index = 0;
  311. m_terrainData = new HeightmapTerrainData(Height, Width, (int)Constants.RegionHeight);
  312. for (int y = 0; y < Height; y++)
  313. {
  314. for (int x = 0; x < Width; x++)
  315. {
  316. float value;
  317. value = BitConverter.ToSingle(dataArray, index);
  318. index += 4;
  319. this[x, y] = (double)value;
  320. }
  321. }
  322. }
  323. private class TerrainChannelXMLPackage
  324. {
  325. public int Version;
  326. public int SizeX;
  327. public int SizeY;
  328. public int SizeZ;
  329. public float CompressionFactor;
  330. public float[] Map;
  331. public TerrainChannelXMLPackage(int pX, int pY, int pZ, float pCompressionFactor, float[] pMap)
  332. {
  333. Version = 1;
  334. SizeX = pX;
  335. SizeY = pY;
  336. SizeZ = pZ;
  337. CompressionFactor = pCompressionFactor;
  338. Map = pMap;
  339. }
  340. }
  341. // New terrain serialization format that includes the width and length.
  342. private void ToXml2(XmlWriter xmlWriter)
  343. {
  344. TerrainChannelXMLPackage package = new TerrainChannelXMLPackage(Width, Height, Altitude, m_terrainData.CompressionFactor,
  345. m_terrainData.GetCompressedMap());
  346. XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage));
  347. serializer.Serialize(xmlWriter, package);
  348. }
  349. // New terrain serialization format that includes the width and length.
  350. private void FromXml2(XmlReader xmlReader)
  351. {
  352. XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage));
  353. TerrainChannelXMLPackage package = (TerrainChannelXMLPackage)serializer.Deserialize(xmlReader);
  354. m_terrainData = new HeightmapTerrainData(package.Map, package.CompressionFactor, package.SizeX, package.SizeY, package.SizeZ);
  355. }
  356. // Fill the heightmap with the center bump terrain
  357. private void PinHeadIsland()
  358. {
  359. float cx = m_terrainData.SizeX * 0.5f;
  360. float cy = m_terrainData.SizeY * 0.5f;
  361. float h;
  362. for (int x = 0; x < Width; x++)
  363. {
  364. for (int y = 0; y < Height; y++)
  365. {
  366. // h = (float)TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10;
  367. h = 1.0f;
  368. float spherFacA = (float)(TerrainUtil.SphericalFactor(x, y, cx, cy, 50) * 0.01d);
  369. float spherFacB = (float)(TerrainUtil.SphericalFactor(x, y, cx, cy, 100) * 0.001d);
  370. if (h < spherFacA)
  371. h = spherFacA;
  372. if (h < spherFacB)
  373. h = spherFacB;
  374. m_terrainData[x, y] = h;
  375. }
  376. }
  377. }
  378. private void FlatLand()
  379. {
  380. m_terrainData.ClearLand();
  381. }
  382. }
  383. }