From 27340f616edfc2c6c199cb9d550b0ca3f67d2c6f Mon Sep 17 00:00:00 2001 From: Melanie Date: Sun, 3 Oct 2010 16:34:55 +0100 Subject: Addign the new / renamed files for previous commit --- .../World/LegacyMap/IMapTileTerrainRenderer.cs | 39 ++ .../CoreModules/World/LegacyMap/MapImageModule.cs | 549 ++++++++++++++++++ .../World/LegacyMap/ShadedMapTileRenderer.cs | 244 ++++++++ .../World/LegacyMap/TexturedMapTileRenderer.cs | 418 ++++++++++++++ .../CoreModules/World/Warp3DMap/MapImageModule.cs | 624 +++++++++++++++++++++ .../Region/CoreModules/World/Warp3DMap/Perlin.cs | 273 +++++++++ .../CoreModules/World/Warp3DMap/TerrainSplat.cs | 343 +++++++++++ .../Region/CoreModules/World/Warp3DMap/Viewport.cs | 165 ++++++ 8 files changed, 2655 insertions(+) create mode 100644 OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs create mode 100644 OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs create mode 100644 OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs create mode 100644 OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs create mode 100644 OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs create mode 100644 OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs create mode 100644 OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs create mode 100644 OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs (limited to 'OpenSim/Region') diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs new file mode 100644 index 0000000..e892b14 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/LegacyMap/IMapTileTerrainRenderer.cs @@ -0,0 +1,39 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Drawing; +using Nini.Config; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.LegacyMap +{ + public interface IMapTileTerrainRenderer + { + void Initialise(Scene scene, IConfigSource config); + void TerrainToBitmap(Bitmap mapbmp); + } +} diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs b/OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs new file mode 100644 index 0000000..9e6e366 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/LegacyMap/MapImageModule.cs @@ -0,0 +1,549 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Reflection; +using log4net; +using Nini.Config; +using OpenMetaverse; +using OpenMetaverse.Imaging; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.LegacyMap +{ + public enum DrawRoutine + { + Rectangle, + Polygon, + Ellipse + } + + public struct face + { + public Point[] pts; + } + + public struct DrawStruct + { + public DrawRoutine dr; + public Rectangle rect; + public SolidBrush brush; + public face[] trns; + } + + public class MapImageModule : IMapImageGenerator, IRegionModule + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene; + private IConfigSource m_config; + private IMapTileTerrainRenderer terrainRenderer; + + #region IMapImageGenerator Members + + public Bitmap CreateMapTile() + { + bool drawPrimVolume = true; + bool textureTerrain = false; + + try + { + IConfig startupConfig = m_config.Configs["Startup"]; + drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume); + textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain); + } + catch + { + m_log.Warn("[MAPTILE]: Failed to load StartupConfig"); + } + + if (textureTerrain) + { + terrainRenderer = new TexturedMapTileRenderer(); + } + else + { + terrainRenderer = new ShadedMapTileRenderer(); + } + terrainRenderer.Initialise(m_scene, m_config); + + Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb); + //long t = System.Environment.TickCount; + //for (int i = 0; i < 10; ++i) { + terrainRenderer.TerrainToBitmap(mapbmp); + //} + //t = System.Environment.TickCount - t; + //m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t); + + + if (drawPrimVolume) + { + DrawObjectVolume(m_scene, mapbmp); + } + + return mapbmp; + } + + public byte[] WriteJpeg2000Image() + { + try + { + using (Bitmap mapbmp = CreateMapTile()) + return OpenJPEG.EncodeFromImage(mapbmp, true); + } + catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke + { + m_log.Error("Failed generating terrain map: " + e); + } + + return null; + } + + #endregion + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource source) + { + m_scene = scene; + m_config = source; + + IConfig startupConfig = m_config.Configs["Startup"]; + if (startupConfig.GetString("MapImageModule", "MapImageModule") != + "MapImageModule") + return; + + m_scene.RegisterModuleInterface(this); + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "MapImageModule"; } + } + + public bool IsSharedModule + { + get { return false; } + } + + #endregion + +// TODO: unused: +// private void ShadeBuildings(Bitmap map) +// { +// lock (map) +// { +// lock (m_scene.Entities) +// { +// foreach (EntityBase entity in m_scene.Entities.Values) +// { +// if (entity is SceneObjectGroup) +// { +// SceneObjectGroup sog = (SceneObjectGroup) entity; +// +// foreach (SceneObjectPart primitive in sog.Children.Values) +// { +// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2)); +// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2)); +// int w = (int) primitive.Scale.X; +// int h = (int) primitive.Scale.Y; +// +// int dx; +// for (dx = x; dx < x + w; dx++) +// { +// int dy; +// for (dy = y; dy < y + h; dy++) +// { +// if (x < 0 || y < 0) +// continue; +// if (x >= map.Width || y >= map.Height) +// continue; +// +// map.SetPixel(dx, dy, Color.DarkGray); +// } +// } +// } +// } +// } +// } +// } +// } + + private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp) + { + int tc = 0; + double[,] hm = whichScene.Heightmap.GetDoubles(); + tc = Environment.TickCount; + m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile"); + EntityBase[] objs = whichScene.GetEntities(); + Dictionary z_sort = new Dictionary(); + //SortedList z_sort = new SortedList(); + List z_sortheights = new List(); + List z_localIDs = new List(); + + lock (objs) + { + foreach (EntityBase obj in objs) + { + // Only draw the contents of SceneObjectGroup + if (obj is SceneObjectGroup) + { + SceneObjectGroup mapdot = (SceneObjectGroup)obj; + Color mapdotspot = Color.Gray; // Default color when prim color is white + + // Loop over prim in group + foreach (SceneObjectPart part in mapdot.Parts) + { + if (part == null) + continue; + + // Draw if the object is at least 1 meter wide in any direction + if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f) + { + // Try to get the RGBA of the default texture entry.. + // + try + { + // get the null checks out of the way + // skip the ones that break + if (part == null) + continue; + + if (part.Shape == null) + continue; + + if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass) + continue; // eliminates trees from this since we don't really have a good tree representation + // if you want tree blocks on the map comment the above line and uncomment the below line + //mapdotspot = Color.PaleGreen; + + Primitive.TextureEntry textureEntry = part.Shape.Textures; + + if (textureEntry == null || textureEntry.DefaultTexture == null) + continue; + + Color4 texcolor = textureEntry.DefaultTexture.RGBA; + + // Not sure why some of these are null, oh well. + + int colorr = 255 - (int)(texcolor.R * 255f); + int colorg = 255 - (int)(texcolor.G * 255f); + int colorb = 255 - (int)(texcolor.B * 255f); + + if (!(colorr == 255 && colorg == 255 && colorb == 255)) + { + //Try to set the map spot color + try + { + // If the color gets goofy somehow, skip it *shakes fist at Color4 + mapdotspot = Color.FromArgb(colorr, colorg, colorb); + } + catch (ArgumentException) + { + } + } + } + catch (IndexOutOfRangeException) + { + // Windows Array + } + catch (ArgumentOutOfRangeException) + { + // Mono Array + } + + Vector3 pos = part.GetWorldPosition(); + + // skip prim outside of retion + if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f) + continue; + + // skip prim in non-finite position + if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || + Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y)) + continue; + + // Figure out if object is under 256m above the height of the terrain + bool isBelow256AboveTerrain = false; + + try + { + isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f)); + } + catch (Exception) + { + } + + if (isBelow256AboveTerrain) + { + // Translate scale by rotation so scale is represented properly when object is rotated + Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z); + Vector3 scale = new Vector3(); + Vector3 tScale = new Vector3(); + Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z); + + Quaternion llrot = part.GetWorldRotation(); + Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z); + scale = lscale * rot; + + // negative scales don't work in this situation + scale.X = Math.Abs(scale.X); + scale.Y = Math.Abs(scale.Y); + scale.Z = Math.Abs(scale.Z); + + // This scaling isn't very accurate and doesn't take into account the face rotation :P + int mapdrawstartX = (int)(pos.X - scale.X); + int mapdrawstartY = (int)(pos.Y - scale.Y); + int mapdrawendX = (int)(pos.X + scale.X); + int mapdrawendY = (int)(pos.Y + scale.Y); + + // If object is beyond the edge of the map, don't draw it to avoid errors + if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1) + || mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0 + || mapdrawendY > ((int)Constants.RegionSize - 1)) + continue; + +#region obb face reconstruction part duex + Vector3[] vertexes = new Vector3[8]; + + // float[] distance = new float[6]; + Vector3[] FaceA = new Vector3[6]; // vertex A for Facei + Vector3[] FaceB = new Vector3[6]; // vertex B for Facei + Vector3[] FaceC = new Vector3[6]; // vertex C for Facei + Vector3[] FaceD = new Vector3[6]; // vertex D for Facei + + tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z); + scale = ((tScale * rot)); + vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + // vertexes[0].x = pos.X + vertexes[0].x; + //vertexes[0].y = pos.Y + vertexes[0].y; + //vertexes[0].z = pos.Z + vertexes[0].z; + + FaceA[0] = vertexes[0]; + FaceB[3] = vertexes[0]; + FaceA[4] = vertexes[0]; + + tScale = lscale; + scale = ((tScale * rot)); + vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[1].x = pos.X + vertexes[1].x; + // vertexes[1].y = pos.Y + vertexes[1].y; + //vertexes[1].z = pos.Z + vertexes[1].z; + + FaceB[0] = vertexes[1]; + FaceA[1] = vertexes[1]; + FaceC[4] = vertexes[1]; + + tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + + vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + //vertexes[2].x = pos.X + vertexes[2].x; + //vertexes[2].y = pos.Y + vertexes[2].y; + //vertexes[2].z = pos.Z + vertexes[2].z; + + FaceC[0] = vertexes[2]; + FaceD[3] = vertexes[2]; + FaceC[5] = vertexes[2]; + + tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + //vertexes[3].x = pos.X + vertexes[3].x; + // vertexes[3].y = pos.Y + vertexes[3].y; + // vertexes[3].z = pos.Z + vertexes[3].z; + + FaceD[0] = vertexes[3]; + FaceC[1] = vertexes[3]; + FaceA[5] = vertexes[3]; + + tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z); + scale = ((tScale * rot)); + vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[4].x = pos.X + vertexes[4].x; + // vertexes[4].y = pos.Y + vertexes[4].y; + // vertexes[4].z = pos.Z + vertexes[4].z; + + FaceB[1] = vertexes[4]; + FaceA[2] = vertexes[4]; + FaceD[4] = vertexes[4]; + + tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[5].x = pos.X + vertexes[5].x; + // vertexes[5].y = pos.Y + vertexes[5].y; + // vertexes[5].z = pos.Z + vertexes[5].z; + + FaceD[1] = vertexes[5]; + FaceC[2] = vertexes[5]; + FaceB[5] = vertexes[5]; + + tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z); + scale = ((tScale * rot)); + vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[6].x = pos.X + vertexes[6].x; + // vertexes[6].y = pos.Y + vertexes[6].y; + // vertexes[6].z = pos.Z + vertexes[6].z; + + FaceB[2] = vertexes[6]; + FaceA[3] = vertexes[6]; + FaceB[4] = vertexes[6]; + + tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z); + scale = ((tScale * rot)); + vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z))); + + // vertexes[7].x = pos.X + vertexes[7].x; + // vertexes[7].y = pos.Y + vertexes[7].y; + // vertexes[7].z = pos.Z + vertexes[7].z; + + FaceD[2] = vertexes[7]; + FaceC[3] = vertexes[7]; + FaceD[5] = vertexes[7]; +#endregion + + //int wy = 0; + + //bool breakYN = false; // If we run into an error drawing, break out of the + // loop so we don't lag to death on error handling + DrawStruct ds = new DrawStruct(); + ds.brush = new SolidBrush(mapdotspot); + //ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY); + + ds.trns = new face[FaceA.Length]; + + for (int i = 0; i < FaceA.Length; i++) + { + Point[] working = new Point[5]; + working[0] = project(FaceA[i], axPos); + working[1] = project(FaceB[i], axPos); + working[2] = project(FaceD[i], axPos); + working[3] = project(FaceC[i], axPos); + working[4] = project(FaceA[i], axPos); + + face workingface = new face(); + workingface.pts = working; + + ds.trns[i] = workingface; + } + + z_sort.Add(part.LocalId, ds); + z_localIDs.Add(part.LocalId); + z_sortheights.Add(pos.Z); + + //for (int wx = mapdrawstartX; wx < mapdrawendX; wx++) + //{ + //for (wy = mapdrawstartY; wy < mapdrawendY; wy++) + //{ + //m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy); + //try + //{ + // Remember, flip the y! + // mapbmp.SetPixel(wx, (255 - wy), mapdotspot); + //} + //catch (ArgumentException) + //{ + // breakYN = true; + //} + + //if (breakYN) + // break; + //} + + //if (breakYN) + // break; + //} + } // Object is within 256m Z of terrain + } // object is at least a meter wide + } // loop over group children + } // entitybase is sceneobject group + } // foreach loop over entities + + float[] sortedZHeights = z_sortheights.ToArray(); + uint[] sortedlocalIds = z_localIDs.ToArray(); + + // Sort prim by Z position + Array.Sort(sortedZHeights, sortedlocalIds); + + Graphics g = Graphics.FromImage(mapbmp); + + for (int s = 0; s < sortedZHeights.Length; s++) + { + if (z_sort.ContainsKey(sortedlocalIds[s])) + { + DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]]; + for (int r = 0; r < rectDrawStruct.trns.Length; r++) + { + g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts); + } + //g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect); + } + } + + g.Dispose(); + } // lock entities objs + + m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms"); + return mapbmp; + } + + private Point project(Vector3 point3d, Vector3 originpos) + { + Point returnpt = new Point(); + //originpos = point3d; + //int d = (int)(256f / 1.5f); + + //Vector3 topos = new Vector3(0, 0, 0); + // float z = -point3d.z - topos.z; + + returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d); + returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d))); + + return returnpt; + } + } +} diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs new file mode 100644 index 0000000..eb1a27f --- /dev/null +++ b/OpenSim/Region/CoreModules/World/LegacyMap/ShadedMapTileRenderer.cs @@ -0,0 +1,244 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Drawing; +using System.Reflection; +using log4net; +using Nini.Config; +using OpenSim.Framework; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.LegacyMap +{ + public class ShadedMapTileRenderer : IMapTileTerrainRenderer + { + private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95); + + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene; + //private IConfigSource m_config; // not used currently + + public void Initialise(Scene scene, IConfigSource config) + { + m_scene = scene; + // m_config = config; // not used currently + } + + public void TerrainToBitmap(Bitmap mapbmp) + { + int tc = Environment.TickCount; + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain"); + + double[,] hm = m_scene.Heightmap.GetDoubles(); + bool ShadowDebugContinue = true; + + bool terraincorruptedwarningsaid = false; + + float low = 255; + float high = 0; + for (int x = 0; x < (int)Constants.RegionSize; x++) + { + for (int y = 0; y < (int)Constants.RegionSize; y++) + { + float hmval = (float)hm[x, y]; + if (hmval < low) + low = hmval; + if (hmval > high) + high = hmval; + } + } + + float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; + + for (int x = 0; x < (int)Constants.RegionSize; x++) + { + for (int y = 0; y < (int)Constants.RegionSize; y++) + { + // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left + int yr = ((int)Constants.RegionSize - 1) - y; + + float heightvalue = (float)hm[x, y]; + + if (heightvalue > waterHeight) + { + // scale height value + // No, that doesn't scale it: + // heightvalue = low + mid * (heightvalue - low) / mid; => low + (heightvalue - low) * mid / mid = low + (heightvalue - low) * 1 = low + heightvalue - low = heightvalue + + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0; + else if (heightvalue > 255f) + heightvalue = 255f; + else if (heightvalue < 0f) + heightvalue = 0f; + + Color color = Color.FromArgb((int)heightvalue, 100, (int)heightvalue); + + mapbmp.SetPixel(x, yr, color); + + try + { + //X + // . + // + // Shade the terrain for shadows + if (x < ((int)Constants.RegionSize - 1) && yr < ((int)Constants.RegionSize - 1)) + { + float hfvalue = (float)hm[x, y]; + float hfvaluecompare = 0f; + + if ((x + 1 < (int)Constants.RegionSize) && (y + 1 < (int)Constants.RegionSize)) + { + hfvaluecompare = (float)hm[x + 1, y + 1]; // light from north-east => look at land height there + } + if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue)) + hfvalue = 0f; + + if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare)) + hfvaluecompare = 0f; + + float hfdiff = hfvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower + + int hfdiffi = 0; + int hfdiffihighlight = 0; + float highlightfactor = 0.18f; + + try + { + // hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1; + hfdiffi = Math.Abs((int)(hfdiff * 4.5f)) + 1; + if (hfdiff % 1f != 0) + { + // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1); + hfdiffi = hfdiffi + Math.Abs((int)((hfdiff % 1f) * 5f) - 1); + } + + hfdiffihighlight = Math.Abs((int)((hfdiff * highlightfactor) * 4.5f)) + 1; + if (hfdiff % 1f != 0) + { + // hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1); + hfdiffihighlight = hfdiffihighlight + Math.Abs((int)(((hfdiff * highlightfactor) % 1f) * 5f) - 1); + } + } + catch (OverflowException) + { + m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString()); + ShadowDebugContinue = false; + } + + if (hfdiff > 0.3f) + { + // NE is lower than here + // We have to desaturate and lighten the land at the same time + // we use floats, colors use bytes, so shrink are space down to + // 0-255 + + if (ShadowDebugContinue) + { + int r = color.R; + int g = color.G; + int b = color.B; + color = Color.FromArgb((r + hfdiffihighlight < 255) ? r + hfdiffihighlight : 255, + (g + hfdiffihighlight < 255) ? g + hfdiffihighlight : 255, + (b + hfdiffihighlight < 255) ? b + hfdiffihighlight : 255); + } + } + else if (hfdiff < -0.3f) + { + // here is lower than NE: + // We have to desaturate and blacken the land at the same time + // we use floats, colors use bytes, so shrink are space down to + // 0-255 + + if (ShadowDebugContinue) + { + if ((x - 1 > 0) && (yr + 1 < (int)Constants.RegionSize)) + { + color = mapbmp.GetPixel(x - 1, yr + 1); + int r = color.R; + int g = color.G; + int b = color.B; + color = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0, + (g - hfdiffi > 0) ? g - hfdiffi : 0, + (b - hfdiffi > 0) ? b - hfdiffi : 0); + + mapbmp.SetPixel(x-1, yr+1, color); + } + } + } + } + } + catch (ArgumentException) + { + if (!terraincorruptedwarningsaid) + { + m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName); + terraincorruptedwarningsaid = true; + } + color = Color.Black; + mapbmp.SetPixel(x, yr, color); + } + } + else + { + // We're under the water level with the terrain, so paint water instead of land + + // Y flip the cordinates + heightvalue = waterHeight - heightvalue; + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0f; + else if (heightvalue > 19f) + heightvalue = 19f; + else if (heightvalue < 0f) + heightvalue = 0f; + + heightvalue = 100f - (heightvalue * 100f) / 19f; + + try + { + mapbmp.SetPixel(x, yr, WATER_COLOR); + } + catch (ArgumentException) + { + if (!terraincorruptedwarningsaid) + { + m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", m_scene.RegionInfo.RegionName); + terraincorruptedwarningsaid = true; + } + Color black = Color.Black; + mapbmp.SetPixel(x, ((int)Constants.RegionSize - y) - 1, black); + } + } + } + } + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms"); + } + } +} diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs new file mode 100644 index 0000000..071314a --- /dev/null +++ b/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs @@ -0,0 +1,418 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Reflection; +using log4net; +using Nini.Config; +using OpenMetaverse; +using OpenMetaverse.Imaging; +using OpenSim.Framework; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.LegacyMap +{ + // Hue, Saturation, Value; used for color-interpolation + struct HSV { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public float h; + public float s; + public float v; + + public HSV(float h, float s, float v) + { + this.h = h; + this.s = s; + this.v = v; + } + + // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV) + public HSV(Color c) + { + float r = c.R / 255f; + float g = c.G / 255f; + float b = c.B / 255f; + float max = Math.Max(Math.Max(r, g), b); + float min = Math.Min(Math.Min(r, g), b); + float diff = max - min; + + if (max == min) h = 0f; + else if (max == r) h = (g - b) / diff * 60f; + else if (max == g) h = (b - r) / diff * 60f + 120f; + else h = (r - g) / diff * 60f + 240f; + if (h < 0f) h += 360f; + + if (max == 0f) s = 0f; + else s = diff / max; + + v = max; + } + + // (for info about algorithm, see http://en.wikipedia.org/wiki/HSL_and_HSV) + public Color toColor() + { + if (s < 0f) m_log.Debug("S < 0: " + s); + else if (s > 1f) m_log.Debug("S > 1: " + s); + if (v < 0f) m_log.Debug("V < 0: " + v); + else if (v > 1f) m_log.Debug("V > 1: " + v); + + float f = h / 60f; + int sector = (int)f % 6; + f = f - (int)f; + int pi = (int)(v * (1f - s) * 255f); + int qi = (int)(v * (1f - s * f) * 255f); + int ti = (int)(v * (1f - (1f - f) * s) * 255f); + int vi = (int)(v * 255f); + + if (pi < 0) pi = 0; + if (pi > 255) pi = 255; + if (qi < 0) qi = 0; + if (qi > 255) qi = 255; + if (ti < 0) ti = 0; + if (ti > 255) ti = 255; + if (vi < 0) vi = 0; + if (vi > 255) vi = 255; + + switch (sector) + { + case 0: + return Color.FromArgb(vi, ti, pi); + case 1: + return Color.FromArgb(qi, vi, pi); + case 2: + return Color.FromArgb(pi, vi, ti); + case 3: + return Color.FromArgb(pi, qi, vi); + case 4: + return Color.FromArgb(ti, pi, vi); + default: + return Color.FromArgb(vi, pi, qi); + } + } + } + + public class TexturedMapTileRenderer : IMapTileTerrainRenderer + { + #region Constants + + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + // some hardcoded terrain UUIDs that work with SL 1.20 (the four default textures and "Blank"). + // The color-values were choosen because they "look right" (at least to me) ;-) + private static readonly UUID defaultTerrainTexture1 = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5"); + private static readonly Color defaultColor1 = Color.FromArgb(165, 137, 118); + private static readonly UUID defaultTerrainTexture2 = new UUID("63338ede-0037-c4fd-855b-015d77112fc8"); + private static readonly Color defaultColor2 = Color.FromArgb(69, 89, 49); + private static readonly UUID defaultTerrainTexture3 = new UUID("303cd381-8560-7579-23f1-f0a880799740"); + private static readonly Color defaultColor3 = Color.FromArgb(162, 154, 141); + private static readonly UUID defaultTerrainTexture4 = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c"); + private static readonly Color defaultColor4 = Color.FromArgb(200, 200, 200); + + private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95); + + #endregion + + + private Scene m_scene; + // private IConfigSource m_config; // not used currently + + // mapping from texture UUIDs to averaged color. This will contain 5-9 values, in general; new values are only + // added when the terrain textures are changed in the estate dialog and a new map is generated (and will stay in + // that map until the region-server restarts. This could be considered a memory-leak, but it's a *very* small one. + // TODO does it make sense to use a "real" cache and regenerate missing entries on fetch? + private Dictionary m_mapping; + + + public void Initialise(Scene scene, IConfigSource source) + { + m_scene = scene; + // m_config = source; // not used currently + m_mapping = new Dictionary(); + m_mapping.Add(defaultTerrainTexture1, defaultColor1); + m_mapping.Add(defaultTerrainTexture2, defaultColor2); + m_mapping.Add(defaultTerrainTexture3, defaultColor3); + m_mapping.Add(defaultTerrainTexture4, defaultColor4); + m_mapping.Add(Util.BLANK_TEXTURE_UUID, Color.White); + } + + #region Helpers + // This fetches the texture from the asset server synchroneously. That should be ok, as we + // call map-creation only in those places: + // - on start: We can wait here until the asset server returns the texture + // TODO (- on "map" command: We are in the command-line thread, we will wait for completion anyway) + // TODO (- on "automatic" update after some change: We are called from the mapUpdateTimer here and + // will wait anyway) + private Bitmap fetchTexture(UUID id) + { + AssetBase asset = m_scene.AssetService.Get(id.ToString()); + m_log.DebugFormat("Fetched texture {0}, found: {1}", id, asset != null); + if (asset == null) return null; + + ManagedImage managedImage; + Image image; + + try + { + if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image)) + return new Bitmap(image); + else + return null; + } + catch (DllNotFoundException) + { + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", id); + + } + catch (IndexOutOfRangeException) + { + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id); + + } + catch (Exception) + { + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id); + + } + return null; + + } + + // Compute the average color of a texture. + private Color computeAverageColor(Bitmap bmp) + { + // we have 256 x 256 pixel, each with 256 possible color-values per + // color-channel, so 2^24 is the maximum value we can get, adding everything. + // int is be big enough for that. + int r = 0, g = 0, b = 0; + for (int y = 0; y < bmp.Height; ++y) + { + for (int x = 0; x < bmp.Width; ++x) + { + Color c = bmp.GetPixel(x, y); + r += (int)c.R & 0xff; + g += (int)c.G & 0xff; + b += (int)c.B & 0xff; + } + } + + int pixels = bmp.Width * bmp.Height; + return Color.FromArgb(r / pixels, g / pixels, b / pixels); + } + + // return either the average color of the texture, or the defaultColor if the texturID is invalid + // or the texture couldn't be found + private Color computeAverageColor(UUID textureID, Color defaultColor) { + if (textureID == UUID.Zero) return defaultColor; // not set + if (m_mapping.ContainsKey(textureID)) return m_mapping[textureID]; // one of the predefined textures + + Bitmap bmp = fetchTexture(textureID); + Color color = bmp == null ? defaultColor : computeAverageColor(bmp); + // store it for future reference + m_mapping[textureID] = color; + + return color; + } + + // S-curve: f(x) = 3x² - 2x³: + // f(0) = 0, f(0.5) = 0.5, f(1) = 1, + // f'(x) = 0 at x = 0 and x = 1; f'(0.5) = 1.5, + // f''(0.5) = 0, f''(x) != 0 for x != 0.5 + private float S(float v) { + return (v * v * (3f - 2f * v)); + } + + // interpolate two colors in HSV space and return the resulting color + private HSV interpolateHSV(ref HSV c1, ref HSV c2, float ratio) { + if (ratio <= 0f) return c1; + if (ratio >= 1f) return c2; + + // make sure we are on the same side on the hue-circle for interpolation + // We change the hue of the parameters here, but we don't change the color + // represented by that value + if (c1.h - c2.h > 180f) c1.h -= 360f; + else if (c2.h - c1.h > 180f) c1.h += 360f; + + return new HSV(c1.h * (1f - ratio) + c2.h * ratio, + c1.s * (1f - ratio) + c2.s * ratio, + c1.v * (1f - ratio) + c2.v * ratio); + } + + // the heigthfield might have some jumps in values. Rendered land is smooth, though, + // as a slope is rendered at that place. So average 4 neighbour values to emulate that. + private float getHeight(double[,] hm, int x, int y) { + if (x < ((int)Constants.RegionSize - 1) && y < ((int)Constants.RegionSize - 1)) + return (float)(hm[x, y] * .444 + (hm[x + 1, y] + hm[x, y + 1]) * .222 + hm[x + 1, y +1] * .112); + else + return (float)hm[x, y]; + } + #endregion + + public void TerrainToBitmap(Bitmap mapbmp) + { + int tc = Environment.TickCount; + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain"); + + // These textures should be in the AssetCache anyway, as every client conneting to this + // region needs them. Except on start, when the map is recreated (before anyone connected), + // and on change of the estate settings (textures and terrain values), when the map should + // be recreated. + RegionSettings settings = m_scene.RegionInfo.RegionSettings; + + // the four terrain colors as HSVs for interpolation + HSV hsv1 = new HSV(computeAverageColor(settings.TerrainTexture1, defaultColor1)); + HSV hsv2 = new HSV(computeAverageColor(settings.TerrainTexture2, defaultColor2)); + HSV hsv3 = new HSV(computeAverageColor(settings.TerrainTexture3, defaultColor3)); + HSV hsv4 = new HSV(computeAverageColor(settings.TerrainTexture4, defaultColor4)); + + float levelNElow = (float)settings.Elevation1NE; + float levelNEhigh = (float)settings.Elevation2NE; + + float levelNWlow = (float)settings.Elevation1NW; + float levelNWhigh = (float)settings.Elevation2NW; + + float levelSElow = (float)settings.Elevation1SE; + float levelSEhigh = (float)settings.Elevation2SE; + + float levelSWlow = (float)settings.Elevation1SW; + float levelSWhigh = (float)settings.Elevation2SW; + + float waterHeight = (float)settings.WaterHeight; + + double[,] hm = m_scene.Heightmap.GetDoubles(); + + for (int x = 0; x < (int)Constants.RegionSize; x++) + { + float columnRatio = x / ((float)Constants.RegionSize - 1); // 0 - 1, for interpolation + for (int y = 0; y < (int)Constants.RegionSize; y++) + { + float rowRatio = y / ((float)Constants.RegionSize - 1); // 0 - 1, for interpolation + + // Y flip the cordinates for the bitmap: hf origin is lower left, bm origin is upper left + int yr = ((int)Constants.RegionSize - 1) - y; + + float heightvalue = getHeight(hm, x, y); + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0; + + if (heightvalue > waterHeight) + { + // add a bit noise for breaking up those flat colors: + // - a large-scale noise, for the "patches" (using an doubled s-curve for sharper contrast) + // - a small-scale noise, for bringing in some small scale variation + //float bigNoise = (float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f; // map to 0.0 - 1.0 + //float smallNoise = (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * .5f + .5f; + //float hmod = heightvalue + smallNoise * 3f + S(S(bigNoise)) * 10f; + float hmod = + heightvalue + + (float)TerrainUtil.InterpolatedNoise(x + 33, y + 43) * 1.5f + 1.5f + // 0 - 3 + S(S((float)TerrainUtil.InterpolatedNoise(x / 8.0, y / 8.0) * .5f + .5f)) * 10f; // 0 - 10 + + // find the low/high values for this point (interpolated bilinearily) + // (and remember, x=0,y=0 is SW) + float low = levelSWlow * (1f - rowRatio) * (1f - columnRatio) + + levelSElow * (1f - rowRatio) * columnRatio + + levelNWlow * rowRatio * (1f - columnRatio) + + levelNElow * rowRatio * columnRatio; + float high = levelSWhigh * (1f - rowRatio) * (1f - columnRatio) + + levelSEhigh * (1f - rowRatio) * columnRatio + + levelNWhigh * rowRatio * (1f - columnRatio) + + levelNEhigh * rowRatio * columnRatio; + if (high < low) + { + // someone tried to fool us. High value should be higher than low every time + float tmp = high; + high = low; + low = tmp; + } + + HSV hsv; + if (hmod <= low) hsv = hsv1; // too low + else if (hmod >= high) hsv = hsv4; // too high + else + { + // HSV-interpolate along the colors + // first, rescale h to 0.0 - 1.0 + hmod = (hmod - low) / (high - low); + // now we have to split: 0.00 => color1, 0.33 => color2, 0.67 => color3, 1.00 => color4 + if (hmod < 1f/3f) hsv = interpolateHSV(ref hsv1, ref hsv2, hmod * 3f); + else if (hmod < 2f/3f) hsv = interpolateHSV(ref hsv2, ref hsv3, (hmod * 3f) - 1f); + else hsv = interpolateHSV(ref hsv3, ref hsv4, (hmod * 3f) - 2f); + } + + // Shade the terrain for shadows + if (x < ((int)Constants.RegionSize - 1) && y < ((int)Constants.RegionSize - 1)) + { + float hfvaluecompare = getHeight(hm, x + 1, y + 1); // light from north-east => look at land height there + if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare)) + hfvaluecompare = 0f; + + float hfdiff = heightvalue - hfvaluecompare; // => positive if NE is lower, negative if here is lower + hfdiff *= 0.06f; // some random factor so "it looks good" + if (hfdiff > 0.02f) + { + float highlightfactor = 0.18f; + // NE is lower than here + // We have to desaturate and lighten the land at the same time + hsv.s = (hsv.s - (hfdiff * highlightfactor) > 0f) ? hsv.s - (hfdiff * highlightfactor) : 0f; + hsv.v = (hsv.v + (hfdiff * highlightfactor) < 1f) ? hsv.v + (hfdiff * highlightfactor) : 1f; + } + else if (hfdiff < -0.02f) + { + // here is lower than NE: + // We have to desaturate and blacken the land at the same time + hsv.s = (hsv.s + hfdiff > 0f) ? hsv.s + hfdiff : 0f; + hsv.v = (hsv.v + hfdiff > 0f) ? hsv.v + hfdiff : 0f; + } + } + mapbmp.SetPixel(x, yr, hsv.toColor()); + } + else + { + // We're under the water level with the terrain, so paint water instead of land + + heightvalue = waterHeight - heightvalue; + if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue)) + heightvalue = 0f; + else if (heightvalue > 19f) + heightvalue = 19f; + else if (heightvalue < 0f) + heightvalue = 0f; + + heightvalue = 100f - (heightvalue * 100f) / 19f; // 0 - 19 => 100 - 0 + + mapbmp.SetPixel(x, yr, WATER_COLOR); + } + } + } + m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (Environment.TickCount - tc) + " ms"); + } + } +} diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs new file mode 100644 index 0000000..47b1639 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Warp3DMap/MapImageModule.cs @@ -0,0 +1,624 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Reflection; +using CSJ2K; +using Nini.Config; +using log4net; +using Rednettle.Warp3D; +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 WarpRenderer = global::Warp3D.Warp3D; + +namespace OpenSim.Region.CoreModules.World.Warp3DMap +{ + public class Warp3DImageModule : IMapImageGenerator, IRegionModule + { + private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3"); + private static readonly Color4 WATER_COLOR = new Color4(29, 71, 95, 216); + + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene; + private IRendering m_primMesher; + private IConfigSource m_config; + private Dictionary m_colors = new Dictionary(); + private bool m_useAntiAliasing = true; // TODO: Make this a config option + + #region IRegionModule Members + + public void Initialise(Scene scene, IConfigSource source) + { + m_scene = scene; + m_config = source; + + IConfig startupConfig = m_config.Configs["Startup"]; + if (startupConfig.GetString("MapImageModule", "MapImageModule") != "Warp3DImageModule") + return; + + List renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory()); + if (renderers.Count > 0) + { + m_primMesher = RenderingLoader.LoadRenderer(renderers[0]); + m_log.Info("[MAPTILE]: Loaded prim mesher " + m_primMesher.ToString()); + } + else + { + m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled"); + } + + m_scene.RegisterModuleInterface(this); + } + + public void PostInitialise() + { + } + + public void Close() + { + } + + public string Name + { + get { return "Warp3DImageModule"; } + } + + public bool IsSharedModule + { + get { return false; } + } + + #endregion + + #region IMapImageGenerator Members + + public Bitmap CreateMapTile() + { + bool drawPrimVolume = true; + bool textureTerrain = true; + + try + { + IConfig startupConfig = m_config.Configs["Startup"]; + drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume); + textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain); + } + catch + { + m_log.Warn("[MAPTILE]: Failed to load StartupConfig"); + } + + m_colors.Clear(); + + Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f); + Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize); + + int width = viewport.Width; + int height = viewport.Height; + + if (m_useAntiAliasing) + { + width *= 2; + height *= 2; + } + + WarpRenderer renderer = new WarpRenderer(); + renderer.CreateScene(width, height); + renderer.Scene.autoCalcNormals = false; + + #region Camera + + warp_Vector pos = ConvertVector(viewport.Position); + pos.z -= 0.001f; // Works around an issue with the Warp3D camera + warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection)); + + renderer.Scene.defaultCamera.setPos(pos); + renderer.Scene.defaultCamera.lookAt(lookat); + + if (viewport.Orthographic) + { + renderer.Scene.defaultCamera.isOrthographic = true; + renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth; + renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight; + } + else + { + float fov = viewport.FieldOfView; + fov *= 1.75f; // FIXME: ??? + renderer.Scene.defaultCamera.setFov(fov); + } + + #endregion Camera + + renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(0.2f, 0.2f, 1f), 0xffffff, 320, 80)); + renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 100, 40)); + + CreateWater(renderer); + CreateTerrain(renderer, textureTerrain); + if (drawPrimVolume) + CreateAllPrims(renderer); + + renderer.Render(); + Bitmap bitmap = renderer.Scene.getImage(); + + if (m_useAntiAliasing) + bitmap = ImageUtils.ResizeImage(bitmap, viewport.Width, viewport.Height); + + return bitmap; + } + + public byte[] WriteJpeg2000Image() + { + try + { + using (Bitmap mapbmp = CreateMapTile()) + return OpenJPEG.EncodeFromImage(mapbmp, true); + } + catch (Exception e) + { + // JPEG2000 encoder failed + m_log.Error("[MAPTILE]: Failed generating terrain map: " + e); + } + + return null; + } + + #endregion + + #region Rendering Methods + + 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.AddMaterial("WaterColor", ConvertColor(WATER_COLOR)); + renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f)); + renderer.SetObjectMaterial("Water", "WaterColor"); + } + + private void CreateTerrain(WarpRenderer renderer, bool textureTerrain) + { + ITerrainChannel terrain = m_scene.Heightmap; + float[] heightmap = terrain.GetFloatsSerialised(); + + warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2); + + for (int y = 0; y < 256; y++) + { + for (int x = 0; x < 256; x++) + { + 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)); + } + } + + for (int y = 0; y < 256; y++) + { + for (int x = 0; x < 256; x++) + { + if (x < 255 && y < 255) + { + int v = y * 256 + x; + + // 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]); + warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3)); + norm = norm.reverse(); + obj.vertex(v).n = norm; + + // Triangle 1 + obj.addTriangle( + v, + v + 1, + v + 256); + + // Triangle 2 + obj.addTriangle( + v + 256 + 1, + v + 256, + v + 1); + } + } + } + + renderer.Scene.addObject("Terrain", obj); + + UUID[] textureIDs = new UUID[4]; + float[] startHeights = new float[4]; + float[] heightRanges = new float[4]; + + RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings; + + textureIDs[0] = regionInfo.TerrainTexture1; + textureIDs[1] = regionInfo.TerrainTexture2; + textureIDs[2] = regionInfo.TerrainTexture3; + textureIDs[3] = regionInfo.TerrainTexture4; + + startHeights[0] = (float)regionInfo.Elevation1SW; + startHeights[1] = (float)regionInfo.Elevation1NW; + startHeights[2] = (float)regionInfo.Elevation1SE; + startHeights[3] = (float)regionInfo.Elevation1NE; + + heightRanges[0] = (float)regionInfo.Elevation2SW; + heightRanges[1] = (float)regionInfo.Elevation2NW; + heightRanges[2] = (float)regionInfo.Elevation2SE; + heightRanges[3] = (float)regionInfo.Elevation2NE; + + uint globalX, globalY; + Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY); + + Bitmap image = TerrainSplat.Splat(heightmap, textureIDs, startHeights, heightRanges, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain); + warp_Texture texture = new warp_Texture(image); + warp_Material material = new warp_Material(texture); + material.setReflectivity(50); + renderer.Scene.addMaterial("TerrainColor", material); + renderer.SetObjectMaterial("Terrain", "TerrainColor"); + } + + private void CreateAllPrims(WarpRenderer renderer) + { + if (m_primMesher == null) + return; + + m_scene.ForEachSOG( + delegate(SceneObjectGroup group) + { + CreatePrim(renderer, group.RootPart); + foreach (SceneObjectPart child in group.Children.Values) + CreatePrim(renderer, child); + } + ); + } + + private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim) + { + const float MIN_SIZE = 2f; + + if ((PCode)prim.Shape.PCode != PCode.Prim) + return; + if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE) + return; + + Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset); + FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium); + if (renderMesh == null) + return; + + warp_Vector primPos = ConvertVector(prim.AbsolutePosition); + warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset); + + warp_Matrix m = warp_Matrix.quaternionMatrix(primRot); + + if (prim.ParentID != 0) + { + SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId); + if (group != null) + m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset))); + } + + warp_Vector primScale = ConvertVector(prim.Scale); + + string primID = prim.UUID.ToString(); + + // Create the prim faces + for (int i = 0; i < renderMesh.Faces.Count; i++) + { + Face face = renderMesh.Faces[i]; + string meshName = primID + "-Face-" + i.ToString(); + + warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3); + + for (int j = 0; j < face.Vertices.Count; j++) + { + Vertex v = face.Vertices[j]; + + warp_Vector pos = ConvertVector(v.Position); + warp_Vector norm = ConvertVector(v.Normal); + + if (prim.Shape.SculptTexture == UUID.Zero) + norm = norm.reverse(); + warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y); + + faceObj.addVertex(vert); + } + + for (int j = 0; j < face.Indices.Count; j += 3) + { + faceObj.addTriangle( + face.Indices[j + 0], + face.Indices[j + 1], + face.Indices[j + 2]); + } + + Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i); + Color4 faceColor = GetFaceColor(teFace); + string materialName = GetOrCreateMaterial(renderer, faceColor); + + faceObj.transform(m); + faceObj.setPos(primPos); + faceObj.scaleSelf(primScale.x, primScale.y, primScale.z); + + renderer.Scene.addObject(meshName, faceObj); + + renderer.SetObjectMaterial(meshName, materialName); + } + } + + private Color4 GetFaceColor(Primitive.TextureEntryFace face) + { + Color4 color; + + if (face.TextureID == UUID.Zero) + return face.RGBA; + + if (!m_colors.TryGetValue(face.TextureID, out color)) + { + bool fetched = false; + + // Attempt to fetch the texture metadata + UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC); + AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString()); + if (metadata != null) + { + OSDMap map = null; + try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { } + + if (map != null) + { + color = map["X-JPEG2000-RGBA"].AsColor4(); + fetched = true; + } + } + + if (!fetched) + { + // Fetch the texture, decode and get the average color, + // then save it to a temporary metadata asset + AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString()); + if (textureAsset != null) + { + int width, height; + color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height); + + OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } }; + metadata = new AssetBase + { + Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)), + Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(), + Flags = AssetFlags.Collectable, + FullID = metadataID, + ID = metadataID.ToString(), + Local = true, + Temporary = true, + Name = String.Empty, + Type = (sbyte)AssetType.Unknown + }; + m_scene.AssetService.Store(metadata); + } + else + { + color = new Color4(0.5f, 0.5f, 0.5f, 1.0f); + } + } + + m_colors[face.TextureID] = color; + } + + return color * face.RGBA; + } + + private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color) + { + string name = color.ToString(); + + warp_Material material = renderer.Scene.material(name); + if (material != null) + return name; + + renderer.AddMaterial(name, ConvertColor(color)); + if (color.A < 1f) + renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f)); + return name; + } + + #endregion Rendering Methods + + #region Static Helpers + + private static warp_Vector ConvertVector(Vector3 vector) + { + return new warp_Vector(vector.X, vector.Z, vector.Y); + } + + private static warp_Quaternion ConvertQuaternion(Quaternion quat) + { + return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W); + } + + private static int ConvertColor(Color4 color) + { + int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f)); + if (color.A < 1f) + c |= (byte)(color.A * 255f) << 24; + + return c; + } + + private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3) + { + Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z); + Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z); + + Vector3 normal = Vector3.Cross(edge1, edge2); + normal.Normalize(); + + return normal; + } + + public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height) + { + ulong r = 0; + ulong g = 0; + ulong b = 0; + ulong a = 0; + + using (MemoryStream stream = new MemoryStream(j2kData)) + { + try + { + Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream); + width = bitmap.Width; + height = bitmap.Height; + + BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat); + int pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4; + + // Sum up the individual channels + unsafe + { + if (pixelBytes == 4) + { + for (int y = 0; y < height; y++) + { + byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); + + for (int x = 0; x < width; x++) + { + b += row[x * pixelBytes + 0]; + g += row[x * pixelBytes + 1]; + r += row[x * pixelBytes + 2]; + a += row[x * pixelBytes + 3]; + } + } + } + else + { + for (int y = 0; y < height; y++) + { + byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride); + + for (int x = 0; x < width; x++) + { + b += row[x * pixelBytes + 0]; + g += row[x * pixelBytes + 1]; + r += row[x * pixelBytes + 2]; + } + } + } + } + + // Get the averages for each channel + const decimal OO_255 = 1m / 255m; + decimal totalPixels = (decimal)(width * height); + + decimal rm = ((decimal)r / totalPixels) * OO_255; + decimal gm = ((decimal)g / totalPixels) * OO_255; + decimal bm = ((decimal)b / totalPixels) * OO_255; + decimal am = ((decimal)a / totalPixels) * OO_255; + + if (pixelBytes == 3) + am = 1m; + + return new Color4((float)rm, (float)gm, (float)bm, (float)am); + } + catch (Exception ex) + { + m_log.WarnFormat("[MAPTILE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", textureID, j2kData.Length, ex.Message); + width = 0; + height = 0; + return new Color4(0.5f, 0.5f, 0.5f, 1.0f); + } + } + } + + #endregion Static Helpers + } + + public static class ImageUtils + { + /// + /// Performs bilinear interpolation between four values + /// + /// First, or top left value + /// Second, or top right value + /// Third, or bottom left value + /// Fourth, or bottom right value + /// Interpolation value on the X axis, between 0.0 and 1.0 + /// Interpolation value on fht Y axis, between 0.0 and 1.0 + /// The bilinearly interpolated result + public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent) + { + return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent); + } + + /// + /// Performs a high quality image resize + /// + /// Image to resize + /// New width + /// New height + /// Resized image + public static Bitmap ResizeImage(Image image, int width, int height) + { + Bitmap result = new Bitmap(width, height); + + using (Graphics graphics = Graphics.FromImage(result)) + { + graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; + graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; + + graphics.DrawImage(image, 0, 0, result.Width, result.Height); + } + + return result; + } + } +} diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs new file mode 100644 index 0000000..af59d7a --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Warp3DMap/Perlin.cs @@ -0,0 +1,273 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using OpenMetaverse; + +namespace OpenSim.Region.CoreModules.World.Warp3DMap +{ + public static class Perlin + { + // We use a hardcoded seed to keep the noise generation consistent between runs + private const int SEED = 42; + + private const int SAMPLE_SIZE = 1024; + private const int B = SAMPLE_SIZE; + private const int BM = SAMPLE_SIZE - 1; + private const int N = 0x1000; + + private static readonly int[] p = new int[SAMPLE_SIZE + SAMPLE_SIZE + 2]; + private static readonly float[,] g3 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2, 3]; + private static readonly float[,] g2 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2, 2]; + private static readonly float[] g1 = new float[SAMPLE_SIZE + SAMPLE_SIZE + 2]; + + static Perlin() + { + Random rng = new Random(SEED); + int i, j, k; + + for (i = 0; i < B; i++) + { + p[i] = i; + g1[i] = (float)((rng.Next() % (B + B)) - B) / B; + + for (j = 0; j < 2; j++) + g2[i, j] = (float)((rng.Next() % (B + B)) - B) / B; + normalize2(g2, i); + + for (j = 0; j < 3; j++) + g3[i, j] = (float)((rng.Next() % (B + B)) - B) / B; + normalize3(g3, i); + } + + while (--i > 0) + { + k = p[i]; + p[i] = p[j = rng.Next() % B]; + p[j] = k; + } + + for (i = 0; i < B + 2; i++) + { + p[B + i] = p[i]; + g1[B + i] = g1[i]; + for (j = 0; j < 2; j++) + g2[B + i, j] = g2[i, j]; + for (j = 0; j < 3; j++) + g3[B + i, j] = g3[i, j]; + } + } + + public static float noise1(float arg) + { + int bx0, bx1; + float rx0, rx1, sx, t, u, v, a; + + a = arg; + + t = arg + N; + bx0 = ((int)t) & BM; + bx1 = (bx0 + 1) & BM; + rx0 = t - (int)t; + rx1 = rx0 - 1f; + + sx = s_curve(rx0); + + u = rx0 * g1[p[bx0]]; + v = rx1 * g1[p[bx1]]; + + return Utils.Lerp(u, v, sx); + } + + public static float noise2(float x, float y) + { + int bx0, bx1, by0, by1, b00, b10, b01, b11; + float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v; + int i, j; + + t = x + N; + bx0 = ((int)t) & BM; + bx1 = (bx0 + 1) & BM; + rx0 = t - (int)t; + rx1 = rx0 - 1f; + + t = y + N; + by0 = ((int)t) & BM; + by1 = (by0 + 1) & BM; + ry0 = t - (int)t; + ry1 = ry0 - 1f; + + i = p[bx0]; + j = p[bx1]; + + b00 = p[i + by0]; + b10 = p[j + by0]; + b01 = p[i + by1]; + b11 = p[j + by1]; + + sx = s_curve(rx0); + sy = s_curve(ry0); + + u = rx0 * g2[b00, 0] + ry0 * g2[b00, 1]; + v = rx1 * g2[b10, 0] + ry0 * g2[b10, 1]; + a = Utils.Lerp(u, v, sx); + + u = rx0 * g2[b01, 0] + ry1 * g2[b01, 1]; + v = rx1 * g2[b11, 0] + ry1 * g2[b11, 1]; + b = Utils.Lerp(u, v, sx); + + return Utils.Lerp(a, b, sy); + } + + public static float noise3(float x, float y, float z) + { + int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; + float rx0, rx1, ry0, ry1, rz0, rz1, sy, sz, a, b, c, d, t, u, v; + int i, j; + + t = x + N; + bx0 = ((int)t) & BM; + bx1 = (bx0 + 1) & BM; + rx0 = t - (int)t; + rx1 = rx0 - 1f; + + t = y + N; + by0 = ((int)t) & BM; + by1 = (by0 + 1) & BM; + ry0 = t - (int)t; + ry1 = ry0 - 1f; + + t = z + N; + bz0 = ((int)t) & BM; + bz1 = (bz0 + 1) & BM; + rz0 = t - (int)t; + rz1 = rz0 - 1f; + + i = p[bx0]; + j = p[bx1]; + + b00 = p[i + by0]; + b10 = p[j + by0]; + b01 = p[i + by1]; + b11 = p[j + by1]; + + t = s_curve(rx0); + sy = s_curve(ry0); + sz = s_curve(rz0); + + u = rx0 * g3[b00 + bz0, 0] + ry0 * g3[b00 + bz0, 1] + rz0 * g3[b00 + bz0, 2]; + v = rx1 * g3[b10 + bz0, 0] + ry0 * g3[b10 + bz0, 1] + rz0 * g3[b10 + bz0, 2]; + a = Utils.Lerp(u, v, t); + + u = rx0 * g3[b01 + bz0, 0] + ry1 * g3[b01 + bz0, 1] + rz0 * g3[b01 + bz0, 2]; + v = rx1 * g3[b11 + bz0, 0] + ry1 * g3[b11 + bz0, 1] + rz0 * g3[b11 + bz0, 2]; + b = Utils.Lerp(u, v, t); + + c = Utils.Lerp(a, b, sy); + + u = rx0 * g3[b00 + bz1, 0] + ry0 * g3[b00 + bz1, 1] + rz1 * g3[b00 + bz1, 2]; + v = rx1 * g3[b10 + bz1, 0] + ry0 * g3[b10 + bz1, 1] + rz1 * g3[b10 + bz1, 2]; + a = Utils.Lerp(u, v, t); + + u = rx0 * g3[b01 + bz1, 0] + ry1 * g3[b01 + bz1, 1] + rz1 * g3[b01 + bz1, 2]; + v = rx1 * g3[b11 + bz1, 0] + ry1 * g3[b11 + bz1, 1] + rz1 * g3[b11 + bz1, 2]; + b = Utils.Lerp(u, v, t); + + d = Utils.Lerp(a, b, sy); + return Utils.Lerp(c, d, sz); + } + + public static float turbulence1(float x, float freq) + { + float t; + float v; + + for (t = 0f; freq >= 1f; freq *= 0.5f) + { + v = freq * x; + t += noise1(v) / freq; + } + return t; + } + + public static float turbulence2(float x, float y, float freq) + { + float t; + Vector2 vec; + + for (t = 0f; freq >= 1f; freq *= 0.5f) + { + vec.X = freq * x; + vec.Y = freq * y; + t += noise2(vec.X, vec.Y) / freq; + } + return t; + } + + public static float turbulence3(float x, float y, float z, float freq) + { + float t; + Vector3 vec; + + for (t = 0f; freq >= 1f; freq *= 0.5f) + { + vec.X = freq * x; + vec.Y = freq * y; + vec.Z = freq * z; + t += noise3(vec.X, vec.Y, vec.Z) / freq; + } + return t; + } + + private static void normalize2(float[,] v, int i) + { + float s; + + s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1]); + s = 1.0f / s; + v[i, 0] = v[i, 0] * s; + v[i, 1] = v[i, 1] * s; + } + + private static void normalize3(float[,] v, int i) + { + float s; + + s = (float)Math.Sqrt(v[i, 0] * v[i, 0] + v[i, 1] * v[i, 1] + v[i, 2] * v[i, 2]); + s = 1.0f / s; + + v[i, 0] = v[i, 0] * s; + v[i, 1] = v[i, 1] * s; + v[i, 2] = v[i, 2] * s; + } + + private static float s_curve(float t) + { + return t * t * (3f - 2f * t); + } + } +} diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs new file mode 100644 index 0000000..7bf675d --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Warp3DMap/TerrainSplat.cs @@ -0,0 +1,343 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Diagnostics; +using System.Drawing; +using System.Drawing.Imaging; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Services.Interfaces; + +namespace OpenSim.Region.CoreModules.World.Warp3DMap +{ + public static class TerrainSplat + { + #region Constants + + private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5"); + private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8"); + private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740"); + private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c"); + + private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new UUID[] + { + DIRT_DETAIL, + GRASS_DETAIL, + MOUNTAIN_DETAIL, + ROCK_DETAIL + }; + + private static readonly Color[] DEFAULT_TERRAIN_COLOR = new Color[] + { + Color.FromArgb(255, 164, 136, 117), + Color.FromArgb(255, 65, 87, 47), + Color.FromArgb(255, 157, 145, 131), + Color.FromArgb(255, 125, 128, 130) + }; + + private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b"); + + #endregion Constants + + private static readonly ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name); + + /// + /// Builds a composited terrain texture given the region texture + /// and heightmap settings + /// + /// Terrain heightmap + /// Region information including terrain texture parameters + /// A composited 256x256 RGB texture ready for rendering + /// Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting + /// + public static Bitmap Splat(float[] heightmap, 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]; + + if (textureTerrain) + { + // 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++) + { + 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) + { + 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) + { + 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) + { + Bitmap bitmap = detailTexture[i]; + + // Make sure this texture is the correct size, otherwise resize + if (bitmap.Width != 256 || bitmap.Height != 256) + bitmap = ImageUtils.ResizeImage(bitmap, 256, 256); + + // Save the decoded and resized texture to the cache + byte[] data; + using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) + { + bitmap.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) + { + // 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]; + + 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); + } + } + + #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 + { + // 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]); + } + + output.UnlockBits(outputData); + + // We generated the texture upside down, so flip it + output.RotateFlip(RotateFlipType.RotateNoneFlipY); + + #endregion Texture Compositing + + return output; + } + + public static Bitmap SplatSimple(float[] heightmap) + { + const float BASE_HSV_H = 93f / 360f; + const float BASE_HSV_S = 44f / 100f; + const float BASE_HSV_V = 34f / 100f; + + Bitmap img = new Bitmap(256, 256); + BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); + + unsafe + { + for (int y = 255; y >= 0; y--) + { + for (int x = 0; x < 256; x++) + { + float normHeight = heightmap[y * 256 + x] / 255f; + normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f); + + Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight); + + byte* ptr = (byte*)bitmapData.Scan0 + y * bitmapData.Stride + x * 3; + *(ptr + 0) = (byte)(color.B * 255f); + *(ptr + 1) = (byte)(color.G * 255f); + *(ptr + 2) = (byte)(color.R * 255f); + } + } + } + + img.UnlockBits(bitmapData); + return img; + } + } +} diff --git a/OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs b/OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs new file mode 100644 index 0000000..472f86e --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Warp3DMap/Viewport.cs @@ -0,0 +1,165 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Drawing; +using OpenMetaverse; + +namespace OpenSim.Region.CoreModules.World.Warp3DMap +{ + public class Viewport + { + private const float DEG_TO_RAD = (float)Math.PI / 180f; + private static readonly Vector3 UP_DIRECTION = Vector3.UnitZ; + + public Vector3 Position; + public Vector3 LookDirection; + public float FieldOfView; + public float NearPlaneDistance; + public float FarPlaneDistance; + public int Width; + public int Height; + public bool Orthographic; + public float OrthoWindowWidth; + public float OrthoWindowHeight; + + public Viewport(Vector3 position, Vector3 lookDirection, float fieldOfView, float farPlaneDist, float nearPlaneDist, int width, int height) + { + // Perspective projection mode + Position = position; + LookDirection = lookDirection; + FieldOfView = fieldOfView; + FarPlaneDistance = farPlaneDist; + NearPlaneDistance = nearPlaneDist; + Width = width; + Height = height; + } + + public Viewport(Vector3 position, Vector3 lookDirection, float farPlaneDist, float nearPlaneDist, int width, int height, float orthoWindowWidth, float orthoWindowHeight) + { + // Orthographic projection mode + Position = position; + LookDirection = lookDirection; + FarPlaneDistance = farPlaneDist; + NearPlaneDistance = nearPlaneDist; + Width = width; + Height = height; + OrthoWindowWidth = orthoWindowWidth; + OrthoWindowHeight = orthoWindowHeight; + Orthographic = true; + } + + public Point VectorToScreen(Vector3 v) + { + Matrix4 m = GetWorldToViewportMatrix(); + Vector3 screenPoint = v * m; + return new Point((int)screenPoint.X, (int)screenPoint.Y); + } + + public Matrix4 GetWorldToViewportMatrix() + { + Matrix4 result = GetViewMatrix(); + result *= GetPerspectiveProjectionMatrix(); + result *= GetViewportMatrix(); + + return result; + } + + public Matrix4 GetViewMatrix() + { + Vector3 zAxis = -LookDirection; + zAxis.Normalize(); + + Vector3 xAxis = Vector3.Cross(UP_DIRECTION, zAxis); + xAxis.Normalize(); + + Vector3 yAxis = Vector3.Cross(zAxis, xAxis); + + Vector3 position = Position; + float offsetX = -Vector3.Dot(xAxis, position); + float offsetY = -Vector3.Dot(yAxis, position); + float offsetZ = -Vector3.Dot(zAxis, position); + + return new Matrix4( + xAxis.X, yAxis.X, zAxis.X, 0f, + xAxis.Y, yAxis.Y, zAxis.Y, 0f, + xAxis.Z, yAxis.Z, zAxis.Z, 0f, + offsetX, offsetY, offsetZ, 1f); + } + + public Matrix4 GetPerspectiveProjectionMatrix() + { + float aspectRatio = (float)Width / (float)Height; + + float hFoV = FieldOfView * DEG_TO_RAD; + float zn = NearPlaneDistance; + float zf = FarPlaneDistance; + + float xScale = 1f / (float)Math.Tan(hFoV / 2f); + float yScale = aspectRatio * xScale; + float m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf)); + float m43 = zn * m33; + + return new Matrix4( + xScale, 0f, 0f, 0f, + 0f, yScale, 0f, 0f, + 0f, 0f, m33, -1f, + 0f, 0f, m43, 0f); + } + + public Matrix4 GetOrthographicProjectionMatrix(float aspectRatio) + { + float w = Width; + float h = Height; + float zn = NearPlaneDistance; + float zf = FarPlaneDistance; + + float m33 = 1 / (zn - zf); + float m43 = zn * m33; + + return new Matrix4( + 2f / w, 0f, 0f, 0f, + 0f, 2f / h, 0f, 0f, + 0f, 0f, m33, 0f, + 0f, 0f, m43, 1f); + } + + public Matrix4 GetViewportMatrix() + { + float scaleX = (float)Width * 0.5f; + float scaleY = (float)Height * 0.5f; + float offsetX = 0f + scaleX; + float offsetY = 0f + scaleY; + + return new Matrix4( + scaleX, 0f, 0f, 0f, + 0f, -scaleY, 0f, 0f, + 0f, 0f, 1f, 0f, + offsetX, offsetY, 0f, 1f); + } + } +} -- cgit v1.1