From 54a4b9eab4009711f574fe744e2dd82373c971c9 Mon Sep 17 00:00:00 2001 From: Robert Adams Date: Sun, 19 Jan 2014 07:33:56 -0800 Subject: [PATCH] varregion: Update Warp3D to properly handle varregions. This includes additions to Warp3D: Optional rendering of mesh and scupltie prims (INI parameter. Off by default) Texturing of large prims (INI parameter. On by default) Better garbage collection --- .../MapImage/MapImageServiceModule.cs | 8 +- .../World/Warp3DMap/TerrainSplat.cs | 448 +++++++++--------- .../World/Warp3DMap/Warp3DImageModule.cs | 241 +++++++--- bin/OpenSim.ini.example | 12 + bin/OpenSimDefaults.ini | 9 + 5 files changed, 447 insertions(+), 271 deletions(-) diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/MapImage/MapImageServiceModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/MapImage/MapImageServiceModule.cs index e4a875dc96..4d7538ce3e 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/MapImage/MapImageServiceModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/MapImage/MapImageServiceModule.cs @@ -207,9 +207,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage { if (mapTile != null) { - mapTile.Save( // DEBUG DEBUG - String.Format("maptiles/raw-{0}-{1}-{2}.jpg", regionName, scene.RegionInfo.RegionSizeX, scene.RegionInfo.RegionSizeY), - ImageFormat.Jpeg); + // mapTile.Save( // DEBUG DEBUG + // String.Format("maptiles/raw-{0}-{1}-{2}.jpg", regionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY), + // ImageFormat.Jpeg); // If the region/maptile is legacy sized, just upload the one tile like it has always been done if (mapTile.Width == Constants.RegionSize && mapTile.Height == Constants.RegionSize) { @@ -235,8 +235,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage (int)Constants.RegionSize, (int)Constants.RegionSize); using (Bitmap subMapTile = mapTile.Clone(rect, mapTile.PixelFormat)) { - m_log.DebugFormat("{0} ConvertAndUploadMaptile: {1}: rect={2}, xx,yy=<{3},{4}>", - LogHeader, regionName, rect, xx, yy); ConvertAndUploadMaptile(subMapTile, scene.RegionInfo.RegionLocX + (xx / Constants.RegionSize), scene.RegionInfo.RegionLocY + (yy / Constants.RegionSize), diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs index df5ac92bb4..9534ad3dab 100644 --- a/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs +++ b/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -32,6 +32,7 @@ using System.Drawing.Imaging; using log4net; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Warp3DMap @@ -66,261 +67,271 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap #endregion Constants private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name); + private static string LogHeader = "[WARP3D TERRAIN SPLAT]"; /// /// Builds a composited terrain texture given the region texture /// and heightmap settings /// - /// Terrain heightmap + /// Terrain heightmap /// Region information including terrain texture parameters - /// A composited 256x256 RGB texture ready for rendering + /// A 256x256 square RGB texture ready for rendering /// Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting + /// Note we create a 256x256 dimension texture even if the actual terrain is larger. /// - public static Bitmap Splat(float[] heightmap, UUID[] textureIDs, float[] startHeights, float[] heightRanges, Vector3d regionPosition, IAssetService assetService, bool textureTerrain) + public static Bitmap Splat(ITerrainChannel terrain, + UUID[] textureIDs, float[] startHeights, float[] heightRanges, + Vector3d regionPosition, IAssetService assetService, bool textureTerrain) { - Debug.Assert(heightmap.Length == 256 * 256); Debug.Assert(textureIDs.Length == 4); Debug.Assert(startHeights.Length == 4); Debug.Assert(heightRanges.Length == 4); Bitmap[] detailTexture = new Bitmap[4]; - Bitmap output = null; - BitmapData outputData = null; - try + if (textureTerrain) { - if (textureTerrain) + // Swap empty terrain textureIDs with default IDs + for (int i = 0; i < textureIDs.Length; i++) { - // Swap empty terrain textureIDs with default IDs - for (int i = 0; i < textureIDs.Length; i++) + if (textureIDs[i] == UUID.Zero) + textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i]; + } + + #region Texture Fetching + + if (assetService != null) + { + for (int i = 0; i < 4; i++) { - if (textureIDs[i] == UUID.Zero) - textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i]; - } - - #region Texture Fetching - - if (assetService != null) - { - for (int i = 0; i < 4; i++) + AssetBase asset; + UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]); + + // Try to fetch a cached copy of the decoded/resized version of this texture + asset = assetService.GetCached(cacheID.ToString()); + if (asset != null) { - AssetBase asset; - UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]); - - // Try to fetch a cached copy of the decoded/resized version of this texture - asset = assetService.GetCached(cacheID.ToString()); + try + { + using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data)) + detailTexture[i] = (Bitmap)Image.FromStream(stream); + } + catch (Exception ex) + { + m_log.Warn("Failed to decode cached terrain texture " + cacheID + + " (textureID: " + textureIDs[i] + "): " + ex.Message); + } + } + + if (detailTexture[i] == null) + { + // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG + asset = assetService.Get(textureIDs[i].ToString()); if (asset != null) { -// m_log.DebugFormat( -// "[TERRAIN SPLAT]: Got asset service cached terrain texture {0} {1}", i, asset.ID); - - try - { - using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data)) - detailTexture[i] = (Bitmap)Image.FromStream(stream); - } - catch (Exception ex) - { - m_log.Warn("Failed to decode cached terrain texture " + cacheID + - " (textureID: " + textureIDs[i] + "): " + ex.Message); - } - } - - if (detailTexture[i] == null) - { - // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG - asset = assetService.Get(textureIDs[i].ToString()); - if (asset != null) - { // m_log.DebugFormat( // "[TERRAIN SPLAT]: Got cached original JPEG2000 terrain texture {0} {1}", i, asset.ID); - try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); } - catch (Exception ex) + try { detailTexture[i] = (Bitmap)CSJ2K.J2kImage.FromBytes(asset.Data); } + catch (Exception ex) + { + m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message); + } + } + + if (detailTexture[i] != null) + { + // Make sure this texture is the correct size, otherwise resize + if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256) + { + using (Bitmap origBitmap = detailTexture[i]) { - m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message); + detailTexture[i] = ImageUtils.ResizeImage(origBitmap, 256, 256); } } - - if (detailTexture[i] != null) - { - // Make sure this texture is the correct size, otherwise resize - if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256) - { - using (Bitmap origBitmap = detailTexture[i]) - { - detailTexture[i] = ImageUtils.ResizeImage(origBitmap, 256, 256); - } - } - - // Save the decoded and resized texture to the cache - byte[] data; - using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) - { - detailTexture[i].Save(stream, ImageFormat.Png); - data = stream.ToArray(); - } - - // Cache a PNG copy of this terrain texture - AssetBase newAsset = new AssetBase - { - Data = data, - Description = "PNG", - Flags = AssetFlags.Collectable, - FullID = cacheID, - ID = cacheID.ToString(), - Local = true, - Name = String.Empty, - Temporary = true, - Type = (sbyte)AssetType.Unknown - }; - newAsset.Metadata.ContentType = "image/png"; - assetService.Store(newAsset); + + // Save the decoded and resized texture to the cache + byte[] data; + using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) + { + detailTexture[i].Save(stream, ImageFormat.Png); + data = stream.ToArray(); } + + // Cache a PNG copy of this terrain texture + AssetBase newAsset = new AssetBase + { + Data = data, + Description = "PNG", + Flags = AssetFlags.Collectable, + FullID = cacheID, + ID = cacheID.ToString(), + Local = true, + Name = String.Empty, + Temporary = true, + Type = (sbyte)AssetType.Unknown + }; + newAsset.Metadata.ContentType = "image/png"; + assetService.Store(newAsset); } } } - - #endregion Texture Fetching } - - // Fill in any missing textures with a solid color - for (int i = 0; i < 4; i++) - { - if (detailTexture[i] == null) - { -// m_log.DebugFormat( -// "[TERRAIN SPLAT]: Generating solid colour for missing texture {0}", i); - // Create a solid color texture for this layer - detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb); - using (Graphics gfx = Graphics.FromImage(detailTexture[i])) - { - using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i])) - gfx.FillRectangle(brush, 0, 0, 256, 256); - } + #endregion Texture Fetching + } + + // Fill in any missing textures with a solid color + for (int i = 0; i < 4; i++) + { + if (detailTexture[i] == null) + { + m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color", + LogHeader, i); + // Create a solid color texture for this layer + detailTexture[i] = new Bitmap(256, 256, PixelFormat.Format24bppRgb); + using (Graphics gfx = Graphics.FromImage(detailTexture[i])) + { + using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i])) + gfx.FillRectangle(brush, 0, 0, 256, 256); } } - - #region Layer Map - - float[] layermap = new float[256 * 256]; - + else + { + if (detailTexture[i].Width != 256 || detailTexture[i].Height != 256) + { + detailTexture[i] = ResizeBitmap(detailTexture[i], 256, 256); + } + } + } + + #region Layer Map + + float[,] layermap = new float[256, 256]; + + // Scale difference between actual region size and the 256 texture being created + int xFactor = terrain.Width / 256; + int yFactor = terrain.Height / 256; + + // Create 'layermap' where each value is the fractional layer number to place + // at that point. For instance, a value of 1.345 gives the blending of + // layer 1 and layer 2 for that point. + for (int y = 0; y < 256; y++) + { + for (int x = 0; x < 256; x++) + { + float height = (float)terrain[x * xFactor, y * yFactor]; + + float pctX = (float)x / 255f; + float pctY = (float)y / 255f; + + // Use bilinear interpolation between the four corners of start height and + // height range to select the current values at this position + float startHeight = ImageUtils.Bilinear( + startHeights[0], + startHeights[2], + startHeights[1], + startHeights[3], + pctX, pctY); + startHeight = Utils.Clamp(startHeight, 0f, 255f); + + float heightRange = ImageUtils.Bilinear( + heightRanges[0], + heightRanges[2], + heightRanges[1], + heightRanges[3], + pctX, pctY); + heightRange = Utils.Clamp(heightRange, 0f, 255f); + + // Generate two frequencies of perlin noise based on our global position + // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting + Vector3 vec = new Vector3 + ( + ((float)regionPosition.X + (x * xFactor)) * 0.20319f, + ((float)regionPosition.Y + (y * yFactor)) * 0.20319f, + height * 0.25f + ); + + float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f; + float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f; + float noise = (lowFreq + highFreq) * 2f; + + // Combine the current height, generated noise, start height, and height range parameters, then scale all of it + float layer = ((height + noise - startHeight) / heightRange) * 4f; + if (Single.IsNaN(layer)) + layer = 0f; + layermap[x, y] = Utils.Clamp(layer, 0f, 3f); + } + } + + #endregion Layer Map + + #region Texture Compositing + + Bitmap output = new Bitmap(256, 256, PixelFormat.Format24bppRgb); + BitmapData outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); + + // Unsafe work as we lock down the source textures for quicker access and access the + // pixel data directly + unsafe + { + // Get handles to all of the texture data arrays + BitmapData[] datas = new BitmapData[] + { + detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat), + detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat), + detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat), + detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat) + }; + + // Compute size of each pixel data (used to address into the pixel data array) + int[] comps = new int[] + { + (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, + (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, + (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, + (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3 + }; + for (int y = 0; y < 256; y++) { for (int x = 0; x < 256; x++) { - float height = heightmap[y * 256 + x]; - - float pctX = (float)x / 255f; - float pctY = (float)y / 255f; - - // Use bilinear interpolation between the four corners of start height and - // height range to select the current values at this position - float startHeight = ImageUtils.Bilinear( - startHeights[0], - startHeights[2], - startHeights[1], - startHeights[3], - pctX, pctY); - startHeight = Utils.Clamp(startHeight, 0f, 255f); - - float heightRange = ImageUtils.Bilinear( - heightRanges[0], - heightRanges[2], - heightRanges[1], - heightRanges[3], - pctX, pctY); - heightRange = Utils.Clamp(heightRange, 0f, 255f); - - // Generate two frequencies of perlin noise based on our global position - // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting - Vector3 vec = new Vector3 - ( - ((float)regionPosition.X + x) * 0.20319f, - ((float)regionPosition.Y + y) * 0.20319f, - height * 0.25f - ); - - float lowFreq = Perlin.noise2(vec.X * 0.222222f, vec.Y * 0.222222f) * 6.5f; - float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f) * 2.25f; - float noise = (lowFreq + highFreq) * 2f; - - // Combine the current height, generated noise, start height, and height range parameters, then scale all of it - float layer = ((height + noise - startHeight) / heightRange) * 4f; - if (Single.IsNaN(layer)) layer = 0f; - layermap[y * 256 + x] = Utils.Clamp(layer, 0f, 3f); + float layer = layermap[x, y]; + + // Select two textures + int l0 = (int)Math.Floor(layer); + int l1 = Math.Min(l0 + 1, 3); + + byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0]; + byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1]; + byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3; + + float aB = *(ptrA + 0); + float aG = *(ptrA + 1); + float aR = *(ptrA + 2); + + float bB = *(ptrB + 0); + float bG = *(ptrB + 1); + float bR = *(ptrB + 2); + + float layerDiff = layer - l0; + + // Interpolate between the two selected textures + *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB)); + *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG)); + *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR)); } } - - #endregion Layer Map - - #region Texture Compositing - - output = new Bitmap(256, 256, PixelFormat.Format24bppRgb); - outputData = output.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); - - unsafe - { - // Get handles to all of the texture data arrays - BitmapData[] datas = new BitmapData[] - { - detailTexture[0].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat), - detailTexture[1].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat), - detailTexture[2].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat), - detailTexture[3].LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat) - }; - - int[] comps = new int[] - { - (datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, - (datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, - (datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3, - (datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3 - }; - - for (int y = 0; y < 256; y++) - { - for (int x = 0; x < 256; x++) - { - float layer = layermap[y * 256 + x]; - - // Select two textures - int l0 = (int)Math.Floor(layer); - int l1 = Math.Min(l0 + 1, 3); - - byte* ptrA = (byte*)datas[l0].Scan0 + y * datas[l0].Stride + x * comps[l0]; - byte* ptrB = (byte*)datas[l1].Scan0 + y * datas[l1].Stride + x * comps[l1]; - byte* ptrO = (byte*)outputData.Scan0 + y * outputData.Stride + x * 3; - - float aB = *(ptrA + 0); - float aG = *(ptrA + 1); - float aR = *(ptrA + 2); - - float bB = *(ptrB + 0); - float bG = *(ptrB + 1); - float bR = *(ptrB + 2); - - float layerDiff = layer - l0; - - // Interpolate between the two selected textures - *(ptrO + 0) = (byte)Math.Floor(aB + layerDiff * (bB - aB)); - *(ptrO + 1) = (byte)Math.Floor(aG + layerDiff * (bG - aG)); - *(ptrO + 2) = (byte)Math.Floor(aR + layerDiff * (bR - aR)); - } - } - - for (int i = 0; i < 4; i++) - detailTexture[i].UnlockBits(datas[i]); - } - } - finally - { - for (int i = 0; i < 4; i++) - if (detailTexture[i] != null) - detailTexture[i].Dispose(); + + for (int i = 0; i < detailTexture.Length; i++) + detailTexture[i].UnlockBits(datas[i]); } + for (int i = 0; i < detailTexture.Length; i++) + if (detailTexture[i] != null) + detailTexture[i].Dispose(); + output.UnlockBits(outputData); // We generated the texture upside down, so flip it @@ -331,6 +342,17 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap return output; } + public static Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight) + { + m_log.DebugFormat("{0} ResizeBitmap. From <{1},{2}> to <{3},{4}>", + LogHeader, b.Width, b.Height, nWidth, nHeight); + Bitmap result = new Bitmap(nWidth, nHeight); + using (Graphics g = Graphics.FromImage(result)) + g.DrawImage(b, 0, 0, nWidth, nHeight); + b.Dispose(); + return result; + } + public static Bitmap SplatSimple(float[] heightmap) { const float BASE_HSV_H = 93f / 360f; diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/Warp3DImageModule.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/Warp3DImageModule.cs index 6d9e31b1c5..f072268f16 100644 --- a/OpenSim/Region/CoreModules/World/Warp3DMap/Warp3DImageModule.cs +++ b/OpenSim/Region/CoreModules/World/Warp3DMap/Warp3DImageModule.cs @@ -31,21 +31,25 @@ using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; + using CSJ2K; using Nini.Config; using log4net; using Rednettle.Warp3D; using Mono.Addins; -using OpenMetaverse; -using OpenMetaverse.Imaging; -using OpenMetaverse.Rendering; -using OpenMetaverse.StructuredData; + using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; using OpenSim.Services.Interfaces; +using OpenMetaverse; +using OpenMetaverse.Assets; +using OpenMetaverse.Imaging; +using OpenMetaverse.Rendering; +using OpenMetaverse.StructuredData; + using WarpRenderer = global::Warp3D.Warp3D; namespace OpenSim.Region.CoreModules.World.Warp3DMap @@ -57,12 +61,20 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static string LogHeader = "[WARP 3D IMAGE MODULE]"; private Scene m_scene; private IRendering m_primMesher; - private IConfigSource m_config; private Dictionary m_colors = new Dictionary(); - private bool m_useAntiAliasing = false; // TODO: Make this a config option + + private IConfigSource m_config; + private bool m_drawPrimVolume = true; // true if should render the prims on the tile + private bool m_textureTerrain = true; // true if to create terrain splatting texture + private bool m_texturePrims = true; // true if should texture the rendered prims + private float m_texturePrimSize = 48f; // size of prim before we consider texturing it + private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes + private bool m_useAntiAliasing = false; // true if to anti-alias the rendered image + private bool m_Enabled = false; #region Region Module interface @@ -71,11 +83,27 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap { m_config = source; + string[] configSections = new string[] { "Map", "Startup" }; + if (Util.GetConfigVarFromSections( - m_config, "MapImageModule", new string[] { "Startup", "Map" }, "MapImageModule") != "Warp3DImageModule") + m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule") return; m_Enabled = true; + + m_drawPrimVolume + = Util.GetConfigVarFromSections(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume); + m_textureTerrain + = Util.GetConfigVarFromSections(m_config, "TextureOnMapTile", configSections, m_textureTerrain); + m_texturePrims + = Util.GetConfigVarFromSections(m_config, "TexturePrims", configSections, m_texturePrims); + m_texturePrimSize + = Util.GetConfigVarFromSections(m_config, "TexturePrimSize", configSections, m_texturePrimSize); + m_renderMeshes + = Util.GetConfigVarFromSections(m_config, "RenderMeshes", configSections, m_renderMeshes); + m_useAntiAliasing + = Util.GetConfigVarFromSections(m_config, "UseAntiAliasing", configSections, m_useAntiAliasing); + } public void AddRegion(Scene scene) @@ -127,31 +155,28 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap public Bitmap CreateMapTile() { - Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f); + // Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f); + // Camera above the middle of the region + Vector3 camPos = new Vector3( + m_scene.RegionInfo.RegionSizeX/2 - 0.5f, + m_scene.RegionInfo.RegionSizeY/2 - 0.5f, + 221.7025033688163f); + // Viewport viewing down onto the region Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, - (int)Constants.RegionSize, (int)Constants.RegionSize, - (float)Constants.RegionSize, (float)Constants.RegionSize); + (int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY, + (float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY ); + // Fill the viewport and return the image return CreateMapTile(viewport, false); } public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures) { - Viewport viewport = new Viewport(camPos, camDir, fov, (float)Constants.RegionSize, 0.1f, width, height); + Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height); return CreateMapTile(viewport, useTextures); } public Bitmap CreateMapTile(Viewport viewport, bool useTextures) { - bool drawPrimVolume = true; - bool textureTerrain = true; - - string[] configSections = new string[] { "Map", "Startup" }; - - drawPrimVolume - = Util.GetConfigVarFromSections(m_config, "DrawPrimOnMapTile", configSections, drawPrimVolume); - textureTerrain - = Util.GetConfigVarFromSections(m_config, "TextureOnMapTile", configSections, textureTerrain); - m_colors.Clear(); int width = viewport.Width; @@ -195,8 +220,8 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40)); CreateWater(renderer); - CreateTerrain(renderer, textureTerrain); - if (drawPrimVolume) + CreateTerrain(renderer, m_textureTerrain); + if (m_drawPrimVolume) CreateAllPrims(renderer, useTextures); renderer.Render(); @@ -212,6 +237,16 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap // afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory // then this may be some issue with the Warp3D code itself, though it's also quite possible that generating // this map tile simply takes a lot of memory. + foreach (var o in renderer.Scene.objectData.Values) + { + warp_Object obj = (warp_Object)o; + obj.vertexData = null; + obj.triangleData = null; + } + renderer.Scene.removeAllObjects(); + renderer = null; + viewport = null; + m_colors.Clear(); GC.Collect(); m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()"); @@ -238,61 +273,74 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap #region Rendering Methods + // Add a water plane to the renderer. private void CreateWater(WarpRenderer renderer) { float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; - renderer.AddPlane("Water", 256f * 0.5f); - renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f); + renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f); + renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX/2 - 0.5f, + waterHeight, + m_scene.RegionInfo.RegionSizeY/2 - 0.5f ); - renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR)); - renderer.Scene.material("WaterColor").setReflectivity(0); // match water color with standard map module thanks lkalif - renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f)); + warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR)); + waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif + waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f)); + renderer.Scene.addMaterial("WaterColor", waterColorMaterial); renderer.SetObjectMaterial("Water", "WaterColor"); } + // Add a terrain to the renderer. + // Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for + // full resolution. This saves a lot of memory especially for very large regions. private void CreateTerrain(WarpRenderer renderer, bool textureTerrain) { ITerrainChannel terrain = m_scene.Heightmap; - float[] heightmap = terrain.GetFloatsSerialised(); + + // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding + float diff = (float)m_scene.RegionInfo.RegionSizeX / 256f; warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2); - for (int y = 0; y < 256; y++) + // Create all the vertices for the terrain + for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff) { - for (int x = 0; x < 256; x++) + for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff) { - int v = y * 256 + x; - float height = heightmap[v]; - - warp_Vector pos = ConvertVector(new Vector3(x, y, height)); - obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f)); + warp_Vector pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]); + obj.addVertex(new warp_Vertex(pos, + x / (float)m_scene.RegionInfo.RegionSizeX, + (((float)m_scene.RegionInfo.RegionSizeY) - y) / m_scene.RegionInfo.RegionSizeY) ); } } - for (int y = 0; y < 256; y++) + // Now that we have all the vertices, make another pass and create + // the normals for each of the surface triangles and + // create the list of triangle indices. + for (float y = 0; y < m_scene.RegionInfo.RegionSizeY; y += diff) { - for (int x = 0; x < 256; x++) + for (float x = 0; x < m_scene.RegionInfo.RegionSizeX; x += diff) { - if (x < 255 && y < 255) + float newX = x / diff; + float newY = y / diff; + if (newX < 255 && newY < 255) { - int v = y * 256 + x; + int v = (int)newY * 256 + (int)newX; - // Normal - Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]); - Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]); - Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]); + // Normal for a triangle made up of three adjacent vertices + Vector3 v1 = new Vector3(newX, newY, (float)terrain[(int)x, (int)y]); + Vector3 v2 = new Vector3(newX + 1, newY, (float)terrain[(int)(x + 1), (int)y]); + Vector3 v3 = new Vector3(newX, newY + 1, (float)terrain[(int)x, ((int)(y + 1))]); warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3)); norm = norm.reverse(); obj.vertex(v).n = norm; - // Triangle 1 + // Make two triangles for each of the squares in the grid of vertices obj.addTriangle( v, v + 1, v + 256); - // Triangle 2 obj.addTriangle( v + 256 + 1, v + 256, @@ -307,7 +355,7 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap float[] startHeights = new float[4]; float[] heightRanges = new float[4]; - RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings; + OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings; textureIDs[0] = regionInfo.TerrainTexture1; textureIDs[1] = regionInfo.TerrainTexture2; @@ -325,16 +373,18 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap heightRanges[3] = (float)regionInfo.Elevation2NE; uint globalX, globalY; - Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY); + Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY); warp_Texture texture; - using ( Bitmap image - = TerrainSplat.Splat( - heightmap, textureIDs, startHeights, heightRanges, + = TerrainSplat.Splat(terrain, textureIDs, startHeights, heightRanges, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain)) { + image.Save( // DEBUG DEBUG + String.Format("maptiles/splat-{0}-{1}-{2}.jpg", m_scene.RegionInfo.RegionName, + m_scene.RegionInfo.RegionLocX, m_scene.RegionInfo.RegionLocY), + ImageFormat.Jpeg); texture = new warp_Texture(image); } @@ -370,8 +420,48 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE) return; + FacetedMesh renderMesh = null; Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset); - FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium); + + if (m_renderMeshes) + { + if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero) + { + // Try fetchinng the asset + byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString()); + if (sculptAsset != null) + { + // Is it a mesh? + if (omvPrim.Sculpt.Type == SculptType.Mesh) + { + AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset); + FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh); + meshAsset = null; + } + else // It's sculptie + { + IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface(); + if (imgDecoder != null) + { + Image sculpt = imgDecoder.DecodeToImage(sculptAsset); + if (sculpt != null) + { + renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, + DetailLevel.Medium); + sculpt.Dispose(); + } + } + } + } + } + } + + // If not a mesh or sculptie, try the regular mesher + if (renderMesh == null) + { + renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium); + } + if (renderMesh == null) return; @@ -430,7 +520,11 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i); Color4 faceColor = GetFaceColor(teFace); - string materialName = GetOrCreateMaterial(renderer, faceColor); + string materialName = String.Empty; + if (m_texturePrims && prim.Scale.LengthSquared() > m_texturePrimSize*m_texturePrimSize) + materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID); + else + materialName = GetOrCreateMaterial(renderer, faceColor); faceObj.transform(m); faceObj.setPos(primPos); @@ -519,10 +613,51 @@ namespace OpenSim.Region.CoreModules.World.Warp3DMap return name; } + public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID) + { + string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString(); + + if (renderer.Scene.material(materialName) == null) + { + renderer.AddMaterial(materialName, ConvertColor(faceColor)); + if (faceColor.A < 1f) + { + renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f)); + } + warp_Texture texture = GetTexture(textureID); + if (texture != null) + renderer.Scene.material(materialName).setTexture(texture); + } + + return materialName; + } + + private warp_Texture GetTexture(UUID id) + { + warp_Texture ret = null; + byte[] asset = m_scene.AssetService.GetData(id.ToString()); + if (asset != null) + { + IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface(); + Bitmap img = (Bitmap) imgDecoder.DecodeToImage(asset); + if (img != null) + { + return new warp_Texture(img); + } + } + return ret; + } + #endregion Rendering Methods #region Static Helpers + // Note: axis change. + private static warp_Vector ConvertVector(float x, float y, float z) + { + return new warp_Vector(x, z, y); + } + private static warp_Vector ConvertVector(Vector3 vector) { return new warp_Vector(vector.X, vector.Z, vector.Y); diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 28c16cf5dc..d422c3395c 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -308,6 +308,18 @@ ;; got a large number of objects, so you can turn it off here if you'd like. ; DrawPrimOnMapTile = true + ;# {TexturePrims} {} {Texture prims on map tiles?} {true false} true + ;; Texture the faces of the prims that are rendered on the map tiles. + ; TexturePrims = true + + ;# {TexturePrimSize} {} {Size of prims to texture faces?} {} 48 + ;; Only texture prims that have a diagonal size greater than this number + ; TexturePrimSize = 48 + + ;# {RenderMeshes} {} {Render meshes and sculpties on map tiles?} {true false} false + ;; Attempt to render meshes and sculpties on the map + ; RenderMeshes = false; + [Permissions] ;# {permissionmodules} {} {Permission modules to use (may specify multiple modules, separated by comma} {} DefaultPermissionsModule diff --git a/bin/OpenSimDefaults.ini b/bin/OpenSimDefaults.ini index ae7b7947d8..d80f5bae2e 100644 --- a/bin/OpenSimDefaults.ini +++ b/bin/OpenSimDefaults.ini @@ -310,6 +310,15 @@ ; Use terrain texture for maptiles if true, use shaded green if false TextureOnMapTile = true + ; Texture prims + TexturePrims = true + + ; Only texture prims that have a diagonal size greater than this number + TexturePrimSize = 48 + + ; Attempt to render meshes and sculpties on the map + RenderMeshes = false; + [Permissions] ; ## ; ## PERMISSIONS