TerrainSplat.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. if (textureTerrain)
  78. {
  79. // Swap empty terrain textureIDs with default IDs
  80. for (int i = 0; i < textureIDs.Length; i++)
  81. {
  82. if (textureIDs[i] == UUID.Zero)
  83. textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
  84. }
  85. #region Texture Fetching
  86. if (assetService != null)
  87. {
  88. for (int i = 0; i < 4; i++)
  89. {
  90. AssetBase asset;
  91. UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
  92. // Try to fetch a cached copy of the decoded/resized version of this texture
  93. asset = assetService.GetCached(cacheID.ToString());
  94. if (asset != null)
  95. {
  96. try
  97. {
  98. using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
  99. detailTexture[i] = (Bitmap)Image.FromStream(stream);
  100. }
  101. catch (Exception ex)
  102. {
  103. m_log.Warn("Failed to decode cached terrain texture " + cacheID +
  104. " (textureID: " + textureIDs[i] + "): " + ex.Message);
  105. }
  106. }
  107. if (detailTexture[i] == null)
  108. {
  109. // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
  110. asset = assetService.Get(textureIDs[i].ToString());
  111. if (asset != null)
  112. {
  113. try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); }
  114. catch (Exception ex)
  115. {
  116. m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
  117. }
  118. }
  119. if (detailTexture[i] != null)
  120. {
  121. Bitmap bitmap = detailTexture[i];
  122. // Make sure this texture is the correct size, otherwise resize
  123. if (bitmap.Width != 256 || bitmap.Height != 256)
  124. bitmap = ImageUtils.ResizeImage(bitmap, 256, 256);
  125. // Save the decoded and resized texture to the cache
  126. byte[] data;
  127. using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
  128. {
  129. bitmap.Save(stream, ImageFormat.Png);
  130. data = stream.ToArray();
  131. }
  132. // Cache a PNG copy of this terrain texture
  133. AssetBase newAsset = new AssetBase
  134. {
  135. Data = data,
  136. Description = "PNG",
  137. Flags = AssetFlags.Collectable,
  138. FullID = cacheID,
  139. ID = cacheID.ToString(),
  140. Local = true,
  141. Name = String.Empty,
  142. Temporary = true,
  143. Type = (sbyte)AssetType.Unknown
  144. };
  145. newAsset.Metadata.ContentType = "image/png";
  146. assetService.Store(newAsset);
  147. }
  148. }
  149. }
  150. }
  151. #endregion Texture Fetching
  152. }
  153. // Fill in any missing textures with a solid color
  154. for (int i = 0; i < 4; i++)
  155. {
  156. if (detailTexture[i] == null)
  157. {
  158. // Create a solid color texture for this layer
  159. detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
  160. using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
  161. {
  162. using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
  163. gfx.FillRectangle(brush, 0, 0, 256, 256);
  164. }
  165. }
  166. }
  167. #region Layer Map
  168. float[] layermap = new float[256 * 256];
  169. for (int y = 0; y < 256; y++)
  170. {
  171. for (int x = 0; x < 256; x++)
  172. {
  173. float height = heightmap[y * 256 + x];
  174. float pctX = (float)x / 255f;
  175. float pctY = (float)y / 255f;
  176. // Use bilinear interpolation between the four corners of start height and
  177. // height range to select the current values at this position
  178. float startHeight = ImageUtils.Bilinear(
  179. startHeights[0],
  180. startHeights[2],
  181. startHeights[1],
  182. startHeights[3],
  183. pctX, pctY);
  184. startHeight = Utils.Clamp(startHeight, 0f, 255f);
  185. float heightRange = ImageUtils.Bilinear(
  186. heightRanges[0],
  187. heightRanges[2],
  188. heightRanges[1],
  189. heightRanges[3],
  190. pctX, pctY);
  191. heightRange = Utils.Clamp(heightRange, 0f, 255f);
  192. // Generate two frequencies of perlin noise based on our global position
  193. // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
  194. Vector3 vec = new Vector3
  195. (
  196. ((float)regionPosition.X + x) * 0.20319f,
  197. ((float)regionPosition.Y + y) * 0.20319f,
  198. height * 0.25f
  199. );
  200. float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
  201. float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
  202. float noise = (lowFreq + highFreq) * 2f;
  203. // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
  204. float layer = ((height + noise - startHeight) / heightRange) * 4f;
  205. if (Single.IsNaN(layer)) layer = 0f;
  206. layermap[y * 256 + x] = Utils.Clamp(layer, 0f, 3f);
  207. }
  208. }
  209. #endregion Layer Map
  210. #region Texture Compositing
  211. Bitmap output = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
  212. BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  213. unsafe
  214. {
  215. // Get handles to all of the texture data arrays
  216. BitmapData[] datas = new BitmapData[]
  217. {
  218. detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
  219. detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
  220. detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
  221. detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
  222. };
  223. int[] comps = new int[]
  224. {
  225. (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
  226. (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
  227. (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
  228. (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
  229. };
  230. for (int y = 0; y < 256; y++)
  231. {
  232. for (int x = 0; x < 256; x++)
  233. {
  234. float layer = layermap[y * 256 + x];
  235. // Select two textures
  236. int l0 = (int)Math.Floor(layer);
  237. int l1 = Math.Min(l0 + 1, 3);
  238. byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
  239. byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
  240. byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3;
  241. float aB = *(ptrA + 0);
  242. float aG = *(ptrA + 1);
  243. float aR = *(ptrA + 2);
  244. float bB = *(ptrB + 0);
  245. float bG = *(ptrB + 1);
  246. float bR = *(ptrB + 2);
  247. float layerDiff = layer - l0;
  248. // Interpolate between the two selected textures
  249. *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
  250. *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
  251. *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
  252. }
  253. }
  254. for (int i = 0; i < 4; i++)
  255. detailTexture[i].UnlockBits(datas[i]);
  256. }
  257. output.UnlockBits(outputData);
  258. // We generated the texture upside down, so flip it
  259. output.RotateFlip(RotateFlipType.RotateNoneFlipY);
  260. #endregion Texture Compositing
  261. return output;
  262. }
  263. public static Bitmap SplatSimple(float[] heightmap)
  264. {
  265. const float BASE_HSV_H = 93f / 360f;
  266. const float BASE_HSV_S = 44f / 100f;
  267. const float BASE_HSV_V = 34f / 100f;
  268. Bitmap img = new Bitmap(256, 256);
  269. BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  270. unsafe
  271. {
  272. for (int y = 255; y >= 0; y--)
  273. {
  274. for (int x = 0; x < 256; x++)
  275. {
  276. float normHeight = heightmap[y * 256 + x] / 255f;
  277. normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
  278. Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
  279. byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3;
  280. *(ptr + 0) = (byte)(color.B * 255f);
  281. *(ptr + 1) = (byte)(color.G * 255f);
  282. *(ptr + 2) = (byte)(color.R * 255f);
  283. }
  284. }
  285. }
  286. img.UnlockBits(bitmapData);
  287. return img;
  288. }
  289. }
  290. }