OpenSim
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros
TerrainSplat.cs
Go to the documentation of this file.
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 
28 using System;
29 using System.Diagnostics;
30 using System.Drawing;
31 using System.Drawing.Imaging;
32 using log4net;
33 using OpenMetaverse;
34 using OpenSim.Framework;
35 using OpenSim.Region.Framework.Interfaces;
36 using OpenSim.Services.Interfaces;
37 
38 namespace OpenSim.Region.CoreModules.World.Warp3DMap
39 {
40  public static class TerrainSplat
41  {
42  #region Constants
43 
44  private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
45  private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
46  private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
47  private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
48 
49  private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[]
50  {
51  DIRT_DETAIL,
52  GRASS_DETAIL,
53  MOUNTAIN_DETAIL,
54  ROCK_DETAIL
55  };
56 
57  private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[]
58  {
59  Color.FromArgb(255, 164, 136, 117),
60  Color.FromArgb(255, 65, 87, 47),
61  Color.FromArgb(255, 157, 145, 131),
62  Color.FromArgb(255, 125, 128, 130)
63  };
64 
65  private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
66 
67  #endregion Constants
68 
69  private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
70  private static string LogHeader = "[WARP3D TERRAIN SPLAT]";
71 
82 
83  public static Bitmap Splat(ITerrainChannel terrain,
84  UUID[] textureIDs, float[] startHeights, float[] heightRanges,
85  Vector3d regionPosition, IAssetService assetService, bool textureTerrain)
86  {
87  Debug.Assert(textureIDs.Length == 4);
88  Debug.Assert(startHeights.Length == 4);
89  Debug.Assert(heightRanges.Length == 4);
90 
91  Bitmap[] detailTexture = new Bitmap[4];
92 
93  if (textureTerrain)
94  {
95  // Swap empty terrain textureIDs with default IDs
96  for (int i = 0; i < textureIDs.Length; i++)
97  {
98  if (textureIDs[i] == UUID.Zero)
99  textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
100  }
101 
102  #region Texture Fetching
103 
104  if (assetService != null)
105  {
106  for (int i = 0; i < 4; i++)
107  {
108  AssetBase asset;
109  UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
110 
111  // Try to fetch a cached copy of the decoded/resized version of this texture
112  asset = assetService.GetCached(cacheID.ToString());
113  if (asset != null)
114  {
115  try
116  {
117  using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
118  detailTexture[i] = (Bitmap)Image.FromStream(stream);
119  }
120  catch (Exception ex)
121  {
122  m_log.Warn("Failed to decode cached terrain texture " + cacheID +
123  " (textureID: " + textureIDs[i] + "): " + ex.Message);
124  }
125  }
126 
127  if (detailTexture[i] == null)
128  {
129  // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
130  asset = assetService.Get(textureIDs[i].ToString());
131  if (asset != null)
132  {
133  // m_log.DebugFormat(
134  // "[TERRAIN SPLAT]: Got cached original JPEG2000 terrain texture {0} {1}", i, asset.ID);
135 
136  try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); }
137  catch (Exception ex)
138  {
139  m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
140  }
141  }
142 
143  if (detailTexture[i] != null)
144  {
145  // Make sure this texture is the correct size, otherwise resize
146  if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
147  {
148  using (Bitmap origBitmap = detailTexture[i])
149  {
150  detailTexture[i] = ImageUtils.ResizeImage(origBitmap, 256, 256);
151  }
152  }
153 
154  // Save the decoded and resized texture to the cache
155  byte[] data;
156  using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
157  {
158  detailTexture[i].Save(stream, ImageFormat.Png);
159  data = stream.ToArray();
160  }
161 
162  // Cache a PNG copy of this terrain texture
163  AssetBase newAsset = new AssetBase
164  {
165  Data = data,
166  Description = "PNG",
167  Flags = AssetFlags.Collectable,
168  FullID = cacheID,
169  ID = cacheID.ToString(),
170  Local = true,
171  Name = String.Empty,
172  Temporary = true,
173  Type = (sbyte)AssetType.Unknown
174  };
175  newAsset.Metadata.ContentType = "image/png";
176  assetService.Store(newAsset);
177  }
178  }
179  }
180  }
181 
182  #endregion Texture Fetching
183  }
184 
185  // Fill in any missing textures with a solid color
186  for (int i = 0; i < 4; i++)
187  {
188  if (detailTexture[i] == null)
189  {
190  m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color",
191  LogHeader, i);
192  // Create a solid color texture for this layer
193  detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
194  using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
195  {
196  using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
197  gfx.FillRectangle(brush, 0, 0, 256, 256);
198  }
199  }
200  else
201  {
202  if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256)
203  {
204  detailTexture[i] = ResizeBitmap(detailTexture[i], 256, 256);
205  }
206  }
207  }
208 
209  #region Layer Map
210 
211  float[,] layermap = new float[256, 256];
212 
213  // Scale difference between actual region size and the 256 texture being created
214  int xFactor = terrain.Width / 256;
215  int yFactor = terrain.Height / 256;
216 
217  // Create 'layermap' where each value is the fractional layer number to place
218  // at that point. For instance, a value of 1.345 gives the blending of
219  // layer 1 and layer 2 for that point.
220  for (int y = 0; y < 256; y++)
221  {
222  for (int x = 0; x < 256; x++)
223  {
224  float height = (float)terrain[x * xFactor, y * yFactor];
225 
226  float pctX = (float)x / 255f;
227  float pctY = (float)y / 255f;
228 
229  // Use bilinear interpolation between the four corners of start height and
230  // height range to select the current values at this position
231  float startHeight = ImageUtils.Bilinear(
232  startHeights[0],
233  startHeights[2],
234  startHeights[1],
235  startHeights[3],
236  pctX, pctY);
237  startHeight = Utils.Clamp(startHeight, 0f, 255f);
238 
239  float heightRange = ImageUtils.Bilinear(
240  heightRanges[0],
241  heightRanges[2],
242  heightRanges[1],
243  heightRanges[3],
244  pctX, pctY);
245  heightRange = Utils.Clamp(heightRange, 0f, 255f);
246 
247  // Generate two frequencies of perlin noise based on our global position
248  // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
249  Vector3 vec = new Vector3
250  (
251  ((float)regionPosition.X + (x * xFactor)) * 0.20319f,
252  ((float)regionPosition.Y + (y * yFactor)) * 0.20319f,
253  height * 0.25f
254  );
255 
256  float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f;
257  float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f;
258  float noise = (lowFreq + highFreq) * 2f;
259 
260  // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
261  float layer = ((height + noise - startHeight) / heightRange) * 4f;
262  if (Single.IsNaN(layer))
263  layer = 0f;
264  layermap[x, y] = Utils.Clamp(layer, 0f, 3f);
265  }
266  }
267 
268  #endregion Layer Map
269 
270  #region Texture Compositing
271 
272  Bitmap output = new Bitmap(256, 256, PixelFormat.Format24bppRgb);
273  BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
274 
275  // Unsafe work as we lock down the source textures for quicker access and access the
276  // pixel data directly
277  unsafe
278  {
279  // Get handles to all of the texture data arrays
280  BitmapData[] datas = new BitmapData[]
281  {
282  detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
283  detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
284  detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
285  detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
286  };
287 
288  // Compute size of each pixel data (used to address into the pixel data array)
289  int[] comps = new int[]
290  {
291  (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
292  (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
293  (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
294  (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
295  };
296 
297  for (int y = 0; y < 256; y++)
298  {
299  for (int x = 0; x < 256; x++)
300  {
301  float layer = layermap[x, y];
302 
303  // Select two textures
304  int l0 = (int)Math.Floor(layer);
305  int l1 = Math.Min(l0 + 1, 3);
306 
307  byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0];
308  byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1];
309  byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3;
310 
311  float aB = *(ptrA + 0);
312  float aG = *(ptrA + 1);
313  float aR = *(ptrA + 2);
314 
315  float bB = *(ptrB + 0);
316  float bG = *(ptrB + 1);
317  float bR = *(ptrB + 2);
318 
319  float layerDiff = layer - l0;
320 
321  // Interpolate between the two selected textures
322  *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB));
323  *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG));
324  *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR));
325  }
326  }
327 
328  for (int i = 0; i < detailTexture.Length; i++)
329  detailTexture[i].UnlockBits(datas[i]);
330  }
331 
332  for (int i = 0; i < detailTexture.Length; i++)
333  if (detailTexture[i] != null)
334  detailTexture[i].Dispose();
335 
336  output.UnlockBits(outputData);
337 
338  // We generated the texture upside down, so flip it
339  output.RotateFlip(RotateFlipType.RotateNoneFlipY);
340 
341  #endregion Texture Compositing
342 
343  return output;
344  }
345 
346  public static Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
347  {
348  m_log.DebugFormat("{0} ResizeBitmap. From <{1},{2}> to <{3},{4}>",
349  LogHeader, b.Width, b.Height, nWidth, nHeight);
350  Bitmap result = new Bitmap(nWidth, nHeight);
351  using (Graphics g = Graphics.FromImage(result))
352  g.DrawImage(b, 0, 0, nWidth, nHeight);
353  b.Dispose();
354  return result;
355  }
356  public static Bitmap SplatSimple(float[] heightmap)
357  {
358  const float BASE_HSV_H = 93f / 360f;
359  const float BASE_HSV_S = 44f / 100f;
360  const float BASE_HSV_V = 34f / 100f;
361 
362  Bitmap img = new Bitmap(256, 256);
363  BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
364 
365  unsafe
366  {
367  for (int y = 255; y >= 0; y--)
368  {
369  for (int x = 0; x < 256; x++)
370  {
371  float normHeight = heightmap[y * 256 + x] / 255f;
372  normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
373 
374  Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
375 
376  byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3;
377  *(ptr + 0) = (byte)(color.B * 255f);
378  *(ptr + 1) = (byte)(color.G * 255f);
379  *(ptr + 2) = (byte)(color.R * 255f);
380  }
381  }
382  }
383 
384  img.UnlockBits(bitmapData);
385  return img;
386  }
387  }
388 }
Asset class. All Assets are reference by this class or a class derived from this class ...
Definition: AssetBase.cs:49