TerrainSplat.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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.Diagnostics;
  29. using System.Drawing;
  30. using System.Drawing.Imaging;
  31. using log4net;
  32. using OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Services.Interfaces;
  35. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  36. {
  37. public static class TerrainSplat
  38. {
  39. #region Constants
  40. private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
  41. private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
  42. private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
  43. private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
  44. private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
  45. {
  46. DIRT_DETAIL,
  47. GRASS_DETAIL,
  48. MOUNTAIN_DETAIL,
  49. ROCK_DETAIL
  50. };
  51. private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
  52. {
  53. Color.FromArgb(255, 164, 136, 117),
  54. Color.FromArgb(255, 65, 87, 47),
  55. Color.FromArgb(255, 157, 145, 131),
  56. Color.FromArgb(255, 125, 128, 130)
  57. };
  58. private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
  59. #endregion Constants
  60. private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
  61. /// <summary>
  62. /// Builds a composited terrain texture given the region texture
  63. /// and heightmap settings
  64. /// </summary>
  65. /// <param name="heightmap">Terrain heightmap</param>
  66. /// <param name="regionInfo">Region information including terrain texture parameters</param>
  67. /// <returns>A composited 256x256 RGB texture ready for rendering</returns>
  68. /// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
  69. /// </remarks>
  70. public static Bitmap Splat(float[] heightmap, UUID[] textureIDs, float[] startHeights, float[] heightRanges, Vector3d regionPosition, IAssetService assetService, bool textureTerrain)
  71. {
  72. Debug.Assert(heightmap.Length == 256 * 256);
  73. Debug.Assert(textureIDs.Length == 4);
  74. Debug.Assert(startHeights.Length == 4);
  75. Debug.Assert(heightRanges.Length == 4);
  76. Bitmap[] detailTexture = new Bitmap[4];
  77. Bitmap output = null;
  78. BitmapData outputData = null;
  79. try
  80. {
  81. if (textureTerrain)
  82. {
  83. // Swap empty terrain textureIDs with default IDs
  84. for (int i = 0; i < textureIDs.Length; i++)
  85. {
  86. if (textureIDs[i] == UUID.Zero)
  87. textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
  88. }
  89. #region Texture Fetching
  90. if (assetService != null)
  91. {
  92. for (int i = 0; i < 4; i++)
  93. {
  94. AssetBase asset;
  95. UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
  96. // Try to fetch a cached copy of the decoded/resized version of this texture
  97. asset = assetService.GetCached(cacheID.ToString());
  98. if (asset != null)
  99. {
  100. // m_log.DebugFormat(
  101. // "[TERRAIN SPLAT]: Got asset service cached terrain texture {0} {1}", i, asset.ID);
  102. try
  103. {
  104. using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
  105. detailTexture[i] = (Bitmap)Image.FromStream(stream);
  106. }
  107. catch (Exception ex)
  108. {
  109. m_log.Warn("Failed to decode cached terrain texture " + cacheID +
  110. " (textureID: " + textureIDs[i] + "): " + ex.Message);
  111. }
  112. }
  113. if (detailTexture[i] == null)
  114. {
  115. // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
  116. asset = assetService.Get(textureIDs[i].ToString());
  117. if (asset != null)
  118. {
  119. // m_log.DebugFormat(
  120. // "[TERRAIN SPLAT]: Got cached original JPEG2000 terrain texture {0} {1}", i, asset.ID);
  121. try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); }
  122. catch (Exception ex)
  123. {
  124. m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
  125. }
  126. }
  127. if (detailTexture[i] != null)
  128. {
  129. // Make sure this texture is the correct size, otherwise resize
  130. if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
  131. {
  132. using (Bitmap origBitmap = detailTexture[i])
  133. {
  134. detailTexture[i] = ImageUtils.ResizeImage(origBitmap, 256, 256);
  135. }
  136. }
  137. // Save the decoded and resized texture to the cache
  138. byte[] data;
  139. using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
  140. {
  141. detailTexture[i].Save(stream, ImageFormat.Png);
  142. data = stream.ToArray();
  143. }
  144. // Cache a PNG copy of this terrain texture
  145. AssetBase newAsset = new AssetBase
  146. {
  147. Data = data,
  148. Description = "PNG",
  149. Flags = AssetFlags.Collectable,
  150. FullID = cacheID,
  151. ID = cacheID.ToString(),
  152. Local = true,
  153. Name = String.Empty,
  154. Temporary = true,
  155. Type = (sbyte)AssetType.Unknown
  156. };
  157. newAsset.Metadata.ContentType = "image/png";
  158. assetService.Store(newAsset);
  159. }
  160. }
  161. }
  162. }
  163. #endregion Texture Fetching
  164. }
  165. // Fill in any missing textures with a solid color
  166. for (int i = 0; i < 4; i++)
  167. {
  168. if (detailTexture[i] == null)
  169. {
  170. // m_log.DebugFormat(
  171. // "[TERRAIN SPLAT]: Generating solid colour for missing texture {0}", i);
  172. // Create a solid color texture for this layer
  173. detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
  174. using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
  175. {
  176. using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
  177. gfx.FillRectangle(brush, 0, 0, 256, 256);
  178. }
  179. }
  180. }
  181. #region Layer Map
  182. float[] layermap = new float[256 * 256];
  183. for (int y = 0; y < 256; y++)
  184. {
  185. for (int x = 0; x < 256; x++)
  186. {
  187. float height = heightmap[y * 256 + x];
  188. float pctX = (float)x / 255f;
  189. float pctY = (float)y / 255f;
  190. // Use bilinear interpolation between the four corners of start height and
  191. // height range to select the current values at this position
  192. float startHeight = ImageUtils.Bilinear(
  193. startHeights[0],
  194. startHeights[2],
  195. startHeights[1],
  196. startHeights[3],
  197. pctX, pctY);
  198. startHeight = Utils.Clamp(startHeight, 0f, 255f);
  199. float heightRange = ImageUtils.Bilinear(
  200. heightRanges[0],
  201. heightRanges[2],
  202. heightRanges[1],
  203. heightRanges[3],
  204. pctX, pctY);
  205. heightRange = Utils.Clamp(heightRange, 0f, 255f);
  206. // Generate two frequencies of perlin noise based on our global position
  207. // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
  208. Vector3 vec = new Vector3
  209. (
  210. ((float)regionPosition.X + x) * 0.20319f,
  211. ((float)regionPosition.Y + y) * 0.20319f,
  212. height * 0.25f
  213. );
  214. float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
  215. float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
  216. float noise = (lowFreq + highFreq) * 2f;
  217. // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
  218. float layer = ((height + noise - startHeight) / heightRange) * 4f;
  219. if (Single.IsNaN(layer)) layer = 0f;
  220. layermap[y * 256 + x] = Utils.Clamp(layer, 0f, 3f);
  221. }
  222. }
  223. #endregion Layer Map
  224. #region Texture Compositing
  225. output = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
  226. outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  227. unsafe
  228. {
  229. // Get handles to all of the texture data arrays
  230. BitmapData[] datas = new BitmapData[]
  231. {
  232. detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
  233. detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
  234. detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
  235. detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
  236. };
  237. int[] comps = new int[]
  238. {
  239. (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
  240. (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
  241. (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
  242. (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
  243. };
  244. for (int y = 0; y < 256; y++)
  245. {
  246. for (int x = 0; x < 256; x++)
  247. {
  248. float layer = layermap[y * 256 + x];
  249. // Select two textures
  250. int l0 = (int)Math.Floor(layer);
  251. int l1 = Math.Min(l0 + 1, 3);
  252. byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
  253. byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
  254. byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3;
  255. float aB = *(ptrA + 0);
  256. float aG = *(ptrA + 1);
  257. float aR = *(ptrA + 2);
  258. float bB = *(ptrB + 0);
  259. float bG = *(ptrB + 1);
  260. float bR = *(ptrB + 2);
  261. float layerDiff = layer - l0;
  262. // Interpolate between the two selected textures
  263. *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
  264. *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
  265. *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
  266. }
  267. }
  268. for (int i = 0; i < 4; i++)
  269. detailTexture[i].UnlockBits(datas[i]);
  270. }
  271. }
  272. finally
  273. {
  274. for (int i = 0; i < 4; i++)
  275. if (detailTexture[i] != null)
  276. detailTexture[i].Dispose();
  277. }
  278. output.UnlockBits(outputData);
  279. // We generated the texture upside down, so flip it
  280. output.RotateFlip(RotateFlipType.RotateNoneFlipY);
  281. #endregion Texture Compositing
  282. return output;
  283. }
  284. public static Bitmap SplatSimple(float[] heightmap)
  285. {
  286. const float BASE_HSV_H = 93f / 360f;
  287. const float BASE_HSV_S = 44f / 100f;
  288. const float BASE_HSV_V = 34f / 100f;
  289. Bitmap img = new Bitmap(256, 256);
  290. BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  291. unsafe
  292. {
  293. for (int y = 255; y >= 0; y--)
  294. {
  295. for (int x = 0; x < 256; x++)
  296. {
  297. float normHeight = heightmap[y * 256 + x] / 255f;
  298. normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
  299. Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
  300. byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3;
  301. *(ptr + 0) = (byte)(color.B * 255f);
  302. *(ptr + 1) = (byte)(color.G * 255f);
  303. *(ptr + 2) = (byte)(color.R * 255f);
  304. }
  305. }
  306. }
  307. img.UnlockBits(bitmapData);
  308. return img;
  309. }
  310. }
  311. }