TerrainSplat.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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.Region.Framework.Interfaces;
  35. using OpenSim.Services.Interfaces;
  36. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  37. {
  38. public static class TerrainSplat
  39. {
  40. #region Constants
  41. private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
  42. private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
  43. private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
  44. private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
  45. private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
  46. {
  47. DIRT_DETAIL,
  48. GRASS_DETAIL,
  49. MOUNTAIN_DETAIL,
  50. ROCK_DETAIL
  51. };
  52. private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
  53. {
  54. Color.FromArgb(255, 164, 136, 117),
  55. Color.FromArgb(255, 65, 87, 47),
  56. Color.FromArgb(255, 157, 145, 131),
  57. Color.FromArgb(255, 125, 128, 130)
  58. };
  59. private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
  60. #endregion Constants
  61. private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
  62. private static string LogHeader = "[WARP3D TERRAIN SPLAT]";
  63. /// <summary>
  64. /// Builds a composited terrain texture given the region texture
  65. /// and heightmap settings
  66. /// </summary>
  67. /// <param name="terrain">Terrain heightmap</param>
  68. /// <param name="regionInfo">Region information including terrain texture parameters</param>
  69. /// <returns>A 256x256 square RGB texture ready for rendering</returns>
  70. /// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
  71. /// Note we create a 256x256 dimension texture even if the actual terrain is larger.
  72. /// </remarks>
  73. public static Bitmap Splat(ITerrainChannel terrain, UUID[] textureIDs,
  74. float[] startHeights, float[] heightRanges,
  75. uint regionPositionX, uint regionPositionY,
  76. IAssetService assetService, IJ2KDecoder decoder,
  77. bool textureTerrain, bool averagetextureTerrain,
  78. int twidth, int theight)
  79. {
  80. Debug.Assert(textureIDs.Length == 4);
  81. Debug.Assert(startHeights.Length == 4);
  82. Debug.Assert(heightRanges.Length == 4);
  83. Bitmap[] detailTexture = new Bitmap[4];
  84. byte[] mapColorsRed = new byte[4];
  85. byte[] mapColorsGreen = new byte[4];
  86. byte[] mapColorsBlue = new byte[4];
  87. bool usecolors = false;
  88. if (textureTerrain)
  89. {
  90. // Swap empty terrain textureIDs with default IDs
  91. for(int i = 0; i < textureIDs.Length; i++)
  92. {
  93. if(textureIDs[i] == UUID.Zero)
  94. textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
  95. }
  96. #region Texture Fetching
  97. if(assetService != null)
  98. {
  99. for(int i = 0; i < 4; i++)
  100. {
  101. AssetBase asset = null;
  102. // asset cache indexes are strings
  103. string cacheName ="MAP-Patch" + textureIDs[i].ToString();
  104. // Try to fetch a cached copy of the decoded/resized version of this texture
  105. asset = assetService.GetCached(cacheName);
  106. if(asset != null)
  107. {
  108. try
  109. {
  110. using(System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
  111. detailTexture[i] = (Bitmap)Image.FromStream(stream);
  112. if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
  113. detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
  114. {
  115. detailTexture[i].Dispose();
  116. detailTexture[i] = null;
  117. }
  118. }
  119. catch(Exception ex)
  120. {
  121. m_log.Warn("Failed to decode cached terrain patch texture" + textureIDs[i] + "): " + ex.Message);
  122. }
  123. }
  124. if(detailTexture[i] == null)
  125. {
  126. // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
  127. asset = assetService.Get(textureIDs[i].ToString());
  128. if(asset != null)
  129. {
  130. try
  131. {
  132. detailTexture[i] = (Bitmap)decoder.DecodeToImage(asset.Data);
  133. }
  134. catch(Exception ex)
  135. {
  136. m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
  137. }
  138. }
  139. if(detailTexture[i] != null)
  140. {
  141. if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
  142. detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
  143. using(Bitmap origBitmap = detailTexture[i])
  144. detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
  145. // Save the decoded and resized texture to the cache
  146. byte[] data;
  147. using(System.IO.MemoryStream stream = new System.IO.MemoryStream())
  148. {
  149. detailTexture[i].Save(stream, ImageFormat.Png);
  150. data = stream.ToArray();
  151. }
  152. // Cache a PNG copy of this terrain texture
  153. AssetBase newAsset = new AssetBase
  154. {
  155. Data = data,
  156. Description = "PNG",
  157. Flags = AssetFlags.Collectable,
  158. FullID = UUID.Zero,
  159. ID = cacheName,
  160. Local = true,
  161. Name = String.Empty,
  162. Temporary = true,
  163. Type = (sbyte)AssetType.Unknown
  164. };
  165. newAsset.Metadata.ContentType = "image/png";
  166. assetService.Store(newAsset);
  167. }
  168. }
  169. }
  170. }
  171. #endregion Texture Fetching
  172. if(averagetextureTerrain)
  173. {
  174. for(int t = 0; t < 4; t++)
  175. {
  176. usecolors = true;
  177. if(detailTexture[t] == null)
  178. {
  179. mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
  180. mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
  181. mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
  182. continue;
  183. }
  184. int npixeis = 0;
  185. int cR = 0;
  186. int cG = 0;
  187. int cB = 0;
  188. BitmapData bmdata = detailTexture[t].LockBits(new Rectangle(0, 0, 16, 16),
  189. ImageLockMode.ReadOnly, detailTexture[t].PixelFormat);
  190. npixeis = bmdata.Height * bmdata.Width;
  191. int ylen = bmdata.Height * bmdata.Stride;
  192. unsafe
  193. {
  194. for(int y = 0; y < ylen; y += bmdata.Stride)
  195. {
  196. byte* ptrc = (byte*)bmdata.Scan0 + y;
  197. for(int x = 0 ; x < bmdata.Width; ++x)
  198. {
  199. cR += *(ptrc++);
  200. cG += *(ptrc++);
  201. cB += *(ptrc++);
  202. }
  203. }
  204. }
  205. detailTexture[t].UnlockBits(bmdata);
  206. detailTexture[t].Dispose();
  207. mapColorsRed[t] = (byte)Util.Clamp(cR / npixeis, 0 , 255);
  208. mapColorsGreen[t] = (byte)Util.Clamp(cG / npixeis, 0 , 255);
  209. mapColorsBlue[t] = (byte)Util.Clamp(cB / npixeis, 0 , 255);
  210. }
  211. }
  212. else
  213. {
  214. // Fill in any missing textures with a solid color
  215. for(int i = 0; i < 4; i++)
  216. {
  217. if(detailTexture[i] == null)
  218. {
  219. m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color", LogHeader, i);
  220. // Create a solid color texture for this layer
  221. detailTexture[i] = new Bitmap(16, 16, PixelFormat.Format24bppRgb);
  222. using(Graphics gfx = Graphics.FromImage(detailTexture[i]))
  223. {
  224. using(SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
  225. gfx.FillRectangle(brush, 0, 0, 16, 16);
  226. }
  227. }
  228. else
  229. {
  230. if(detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
  231. {
  232. using(Bitmap origBitmap = detailTexture[i])
  233. detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
  234. }
  235. }
  236. }
  237. }
  238. }
  239. else
  240. {
  241. usecolors = true;
  242. for(int t = 0; t < 4; t++)
  243. {
  244. mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
  245. mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
  246. mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
  247. }
  248. }
  249. #region Layer Map
  250. float xFactor = terrain.Width / twidth;
  251. float yFactor = terrain.Height / theight;
  252. #endregion Layer Map
  253. #region Texture Compositing
  254. Bitmap output = new Bitmap(twidth, theight, PixelFormat.Format24bppRgb);
  255. BitmapData outputData = output.LockBits(new Rectangle(0, 0, twidth, theight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
  256. // Unsafe work as we lock down the source textures for quicker access and access the
  257. // pixel data directly
  258. float invtwitdthMinus1 = 1.0f / (twidth - 1);
  259. float invtheightMinus1 = 1.0f / (theight - 1);
  260. int ty;
  261. int tx;
  262. float pctx;
  263. float pcty;
  264. float height;
  265. float layer;
  266. float layerDiff;
  267. int l0;
  268. int l1;
  269. uint yglobalpos;
  270. if(usecolors)
  271. {
  272. float a;
  273. float b;
  274. unsafe
  275. {
  276. byte* ptrO;
  277. for(int y = 0; y < theight; ++y)
  278. {
  279. pcty = y * invtheightMinus1;
  280. ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
  281. ty = (int)(y * yFactor);
  282. yglobalpos = (uint)ty + regionPositionY;
  283. for(int x = 0; x < twidth; ++x)
  284. {
  285. tx = (int)(x * xFactor);
  286. pctx = x * invtwitdthMinus1;
  287. height = (float)terrain[tx, ty];
  288. layer = getLayerTex(height, pctx, pcty,
  289. (uint)tx + regionPositionX, yglobalpos,
  290. startHeights, heightRanges);
  291. // Select two textures
  292. l0 = (int)layer;
  293. l1 = Math.Min(l0 + 1, 3);
  294. layerDiff = layer - l0;
  295. a = mapColorsRed[l0];
  296. b = mapColorsRed[l1];
  297. *(ptrO++) = (byte)(a + layerDiff * (b - a));
  298. a = mapColorsGreen[l0];
  299. b = mapColorsGreen[l1];
  300. *(ptrO++) = (byte)(a + layerDiff * (b - a));
  301. a = mapColorsBlue[l0];
  302. b = mapColorsBlue[l1];
  303. *(ptrO++) = (byte)(a + layerDiff * (b - a));
  304. }
  305. }
  306. }
  307. }
  308. else
  309. {
  310. float aB;
  311. float aG;
  312. float aR;
  313. float bB;
  314. float bG;
  315. float bR;
  316. unsafe
  317. {
  318. // Get handles to all of the texture data arrays
  319. BitmapData[] datas = new BitmapData[]
  320. {
  321. detailTexture[0].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
  322. detailTexture[1].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
  323. detailTexture[2].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
  324. detailTexture[3].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
  325. };
  326. byte* ptr;
  327. byte* ptrO;
  328. for(int y = 0; y < theight; y++)
  329. {
  330. pcty = y * invtheightMinus1;
  331. int ypatch = ((int)(y * yFactor) & 0x0f) * datas[0].Stride;
  332. ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
  333. ty = (int)(y * yFactor);
  334. yglobalpos = (uint)ty + regionPositionY;
  335. for(int x = 0; x < twidth; x++)
  336. {
  337. tx = (int)(x * xFactor);
  338. pctx = x * invtwitdthMinus1;
  339. height = (float)terrain[tx, ty];
  340. layer = getLayerTex(height, pctx, pcty,
  341. (uint)tx + regionPositionX, yglobalpos,
  342. startHeights, heightRanges);
  343. // Select two textures
  344. l0 = (int)layer;
  345. layerDiff = layer - l0;
  346. int patchOffset = (tx & 0x0f) * 3 + ypatch;
  347. ptr = (byte*)datas[l0].Scan0 + patchOffset;
  348. aB = *(ptr++);
  349. aG = *(ptr++);
  350. aR = *(ptr);
  351. l1 = Math.Min(l0 + 1, 3);
  352. ptr = (byte*)datas[l1].Scan0 + patchOffset;
  353. bB = *(ptr++);
  354. bG = *(ptr++);
  355. bR = *(ptr);
  356. // Interpolate between the two selected textures
  357. *(ptrO++) = (byte)(aB + layerDiff * (bB - aB));
  358. *(ptrO++) = (byte)(aG + layerDiff * (bG - aG));
  359. *(ptrO++) = (byte)(aR + layerDiff * (bR - aR));
  360. }
  361. }
  362. for(int i = 0; i < detailTexture.Length; i++)
  363. detailTexture[i].UnlockBits(datas[i]);
  364. }
  365. for(int i = 0; i < detailTexture.Length; i++)
  366. if(detailTexture[i] != null)
  367. detailTexture[i].Dispose();
  368. }
  369. output.UnlockBits(outputData);
  370. //output.Save("terr.png",ImageFormat.Png);
  371. #endregion Texture Compositing
  372. return output;
  373. }
  374. [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
  375. private static float getLayerTex(float height, float pctX, float pctY, uint X, uint Y,
  376. float[] startHeights, float[] heightRanges)
  377. {
  378. // Use bilinear interpolation between the four corners of start height and
  379. // height range to select the current values at this position
  380. float startHeight = ImageUtils.Bilinear(
  381. startHeights[0], startHeights[2],
  382. startHeights[1], startHeights[3],
  383. pctX, pctY);
  384. if (float.IsNaN(startHeight))
  385. return 0;
  386. startHeight = Utils.Clamp(startHeight, 0f, 255f);
  387. float heightRange = ImageUtils.Bilinear(
  388. heightRanges[0], heightRanges[2],
  389. heightRanges[1], heightRanges[3],
  390. pctX, pctY);
  391. heightRange = Utils.Clamp(heightRange, 0f, 255f);
  392. if(heightRange == 0f || float.IsNaN(heightRange))
  393. return 0;
  394. // Generate two frequencies of perlin noise based on our global position
  395. // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
  396. float sX = X * 0.20319f;
  397. float sY = Y * 0.20319f;
  398. float noise = Perlin.noise2(sX * 0.222222f, sY * 0.222222f) * 13.0f;
  399. noise += Perlin.turbulence2(sX, sY, 2f) * 4.5f;
  400. // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
  401. float layer = ((height + noise - startHeight) / heightRange) * 4f;
  402. return Utils.Clamp(layer, 0f, 3f);
  403. }
  404. }
  405. }