From 2940f325436f5b07dcfbac03545b3eb96e20ffcf Mon Sep 17 00:00:00 2001
From: onefang
Date: Thu, 10 Sep 2020 21:20:23 +1000
Subject: Warp3DCachedImageModule from Christopher Latza.
From -
https://clatza.dev/OpenSim/OpenSim.Modules.Warp3DCachedImageModule.git
Commit ad0aa59f53ae77c85a7c745d9af5aa70187568ba on 17/5/20 1:37 AM
---
.../.gitignore | 287 ++++++
.../LICENSE | 25 +
.../prebuild.xml | 41 +
.../src/Perlin.cs | 264 +++++
.../src/TerrainSplat.cs | 470 +++++++++
.../src/Warp3DImageModule.cs | 1073 ++++++++++++++++++++
6 files changed, 2160 insertions(+)
create mode 100644 addon-modules/OpenSim.Modules.Warp3DCachedImageModule/.gitignore
create mode 100644 addon-modules/OpenSim.Modules.Warp3DCachedImageModule/LICENSE
create mode 100644 addon-modules/OpenSim.Modules.Warp3DCachedImageModule/prebuild.xml
create mode 100644 addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Perlin.cs
create mode 100644 addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/TerrainSplat.cs
create mode 100644 addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Warp3DImageModule.cs
(limited to 'addon-modules')
diff --git a/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/.gitignore b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/.gitignore
new file mode 100644
index 0000000..a752eac
--- /dev/null
+++ b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/.gitignore
@@ -0,0 +1,287 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+
+# Visual Studio 2015 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUNIT
+*.VisualState.xml
+TestResult.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+**/Properties/launchSettings.json
+
+*_i.c
+*_p.c
+*_i.h
+*.ilk
+*.meta
+*.obj
+*.pch
+*.pdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# JustCode is a .NET coding add-in
+.JustCode
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# TODO: Comment the next line if you want to checkin your web deploy settings
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# The packages folder can be ignored because of Package Restore
+**/packages/*
+# except build/, which is used as an MSBuild target.
+!**/packages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/packages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+
+# SQL Server files
+*.mdf
+*.ldf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Typescript v1 declaration files
+typings/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# JetBrains Rider
+.idea/
+*.sln.iml
+
+# CodeRush
+.cr/
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
\ No newline at end of file
diff --git a/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/LICENSE b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/LICENSE
new file mode 100644
index 0000000..570f732
--- /dev/null
+++ b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/LICENSE
@@ -0,0 +1,25 @@
+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.
diff --git a/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/prebuild.xml b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/prebuild.xml
new file mode 100644
index 0000000..df5b460
--- /dev/null
+++ b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/prebuild.xml
@@ -0,0 +1,41 @@
+
+
+
+ ../../../bin
+
+
+
+
+ ../../../bin
+
+
+
+ ../../../bin
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Perlin.cs b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Perlin.cs
new file mode 100644
index 0000000..2279b76
--- /dev/null
+++ b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Perlin.cs
@@ -0,0 +1,264 @@
+/*
+ * 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;
+
+ 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 bx, by, b00, b10, b01, b11;
+ float rx0, rx1, ry0, ry1, sx, sy, a, b, t, u, v;
+ int i, j;
+
+ t = x + N;
+ rx0 = t - (int)t;
+ bx = ((int)t) & BM;
+ i = p[bx];
+ bx = (bx + 1) & BM;
+ j = p[bx];
+
+ t = y + N;
+ ry0 = t - (int)t;
+ by = ((int)t) & BM;
+ b00 = p[i + by];
+ b10 = p[j + by];
+
+ by = (by + 1) & BM;
+ b01 = p[i + by];
+ b11 = p[j + by];
+
+ sx = s_curve(rx0);
+ u = rx0 * g2[b00, 0] + ry0 * g2[b00, 1];
+ rx1 = rx0 - 1f;
+ v = rx1 * g2[b10, 0] + ry0 * g2[b10, 1];
+ a = Utils.Lerp(u, v, sx);
+
+ ry1 = ry0 - 1f;
+ u = rx0 * g2[b01, 0] + ry1 * g2[b01, 1];
+ v = rx1 * g2[b11, 0] + ry1 * g2[b11, 1];
+ b = Utils.Lerp(u, v, sx);
+
+ sy = s_curve(ry0);
+ 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;
+
+ for (t = 0f; freq >= 1f; freq *= 0.5f)
+ {
+ t += noise1(freq * x) / freq;
+ }
+ return t;
+ }
+
+ public static float turbulence2(float x, float y, float freq)
+ {
+ float t;
+
+ for (t = 0f; freq >= 1f; freq *= 0.5f)
+ t += noise2(freq * x, freq * y) / freq;
+
+ return t;
+ }
+
+ public static float turbulence3(float x, float y, float z, float freq)
+ {
+ float t;
+
+ for (t = 0f; freq >= 1f; freq *= 0.5f)
+ {
+ t += noise3(freq * x, freq * y, freq * z) / freq;
+ }
+ return t;
+ }
+
+ private static void normalize2(float[,] v, int i)
+ {
+ float s;
+ float a = v[i, 0];
+ float b = v[i, 1];
+
+ s = (float)Math.Sqrt(a * a + b * b);
+ s = 1.0f / s;
+ v[i, 0] = a * s;
+ v[i, 1] = b * s;
+ }
+
+ private static void normalize3(float[,] v, int i)
+ {
+ float s;
+ float a = v[i, 0];
+ float b = v[i, 1];
+ float c = v[i, 2];
+
+ s = (float)Math.Sqrt(a * a + b * b + c * c);
+ s = 1.0f / s;
+
+ v[i, 0] = a * s;
+ v[i, 1] = b * s;
+ v[i, 2] = c * s;
+ }
+
+ private static float s_curve(float t)
+ {
+ return t * t * (3f - 2f * t);
+ }
+ }
+}
diff --git a/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/TerrainSplat.cs b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/TerrainSplat.cs
new file mode 100644
index 0000000..f60beaf
--- /dev/null
+++ b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/TerrainSplat.cs
@@ -0,0 +1,470 @@
+/*
+ * 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.Region.Framework.Interfaces;
+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);
+ private static string LogHeader = "[WARP3D TERRAIN SPLAT]";
+
+ ///
+ /// Builds a composited terrain texture given the region texture
+ /// and heightmap settings
+ ///
+ /// Terrain heightmap
+ /// Region information including terrain texture parameters
+ /// 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(ITerrainChannel terrain, UUID[] textureIDs,
+ float[] startHeights, float[] heightRanges,
+ uint regionPositionX, uint regionPositionY,
+ IAssetService assetService, IJ2KDecoder decoder,
+ bool textureTerrain, bool averagetextureTerrain,
+ int twidth, int theight)
+ {
+ Debug.Assert(textureIDs.Length == 4);
+ Debug.Assert(startHeights.Length == 4);
+ Debug.Assert(heightRanges.Length == 4);
+
+ Bitmap[] detailTexture = new Bitmap[4];
+
+ byte[] mapColorsRed = new byte[4];
+ byte[] mapColorsGreen = new byte[4];
+ byte[] mapColorsBlue = new byte[4];
+
+ bool usecolors = false;
+
+ 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 = null;
+
+ // asset cache indexes are strings
+ string cacheName ="MAP-Patch" + textureIDs[i].ToString();
+
+ // Try to fetch a cached copy of the decoded/resized version of this texture
+ asset = assetService.GetCached(cacheName);
+ if(asset != null)
+ {
+ try
+ {
+ using(System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
+ detailTexture[i] = (Bitmap)Image.FromStream(stream);
+
+ if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
+ detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
+ {
+ detailTexture[i].Dispose();
+ detailTexture[i] = null;
+ }
+ }
+ catch(Exception ex)
+ {
+ m_log.Warn("Failed to decode cached terrain patch texture" + 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)decoder.DecodeToImage(asset.Data);
+ }
+ catch(Exception ex)
+ {
+ m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
+ }
+ }
+
+ if(detailTexture[i] != null)
+ {
+ if(detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
+ detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
+ using(Bitmap origBitmap = detailTexture[i])
+ detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
+
+ // 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 = UUID.Zero,
+ ID = cacheName,
+ Local = true,
+ Name = String.Empty,
+ Temporary = true,
+ Type = (sbyte)AssetType.Unknown
+ };
+ newAsset.Metadata.ContentType = "image/png";
+ assetService.Store(newAsset);
+ }
+ }
+ }
+ }
+
+ #endregion Texture Fetching
+ if(averagetextureTerrain)
+ {
+ for(int t = 0; t < 4; t++)
+ {
+ usecolors = true;
+ if(detailTexture[t] == null)
+ {
+ mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
+ mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
+ mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
+ continue;
+ }
+
+ int npixeis = 0;
+ int cR = 0;
+ int cG = 0;
+ int cB = 0;
+
+ BitmapData bmdata = detailTexture[t].LockBits(new Rectangle(0, 0, 16, 16),
+ ImageLockMode.ReadOnly, detailTexture[t].PixelFormat);
+
+ npixeis = bmdata.Height * bmdata.Width;
+ int ylen = bmdata.Height * bmdata.Stride;
+
+ unsafe
+ {
+ for(int y = 0; y < ylen; y += bmdata.Stride)
+ {
+ byte* ptrc = (byte*)bmdata.Scan0 + y;
+ for(int x = 0 ; x < bmdata.Width; ++x)
+ {
+ cR += *(ptrc++);
+ cG += *(ptrc++);
+ cB += *(ptrc++);
+ }
+ }
+
+ }
+ detailTexture[t].UnlockBits(bmdata);
+ detailTexture[t].Dispose();
+
+ mapColorsRed[t] = (byte)Util.Clamp(cR / npixeis, 0 , 255);
+ mapColorsGreen[t] = (byte)Util.Clamp(cG / npixeis, 0 , 255);
+ mapColorsBlue[t] = (byte)Util.Clamp(cB / npixeis, 0 , 255);
+ }
+ }
+ else
+ {
+ // 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(16, 16, PixelFormat.Format24bppRgb);
+ using(Graphics gfx = Graphics.FromImage(detailTexture[i]))
+ {
+ using(SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
+ gfx.FillRectangle(brush, 0, 0, 16, 16);
+ }
+ }
+ else
+ {
+ if(detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
+ {
+ using(Bitmap origBitmap = detailTexture[i])
+ detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ usecolors = true;
+ for(int t = 0; t < 4; t++)
+ {
+ mapColorsRed[t] = DEFAULT_TERRAIN_COLOR[t].R;
+ mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
+ mapColorsBlue[t] = DEFAULT_TERRAIN_COLOR[t].B;
+ }
+ }
+
+ #region Layer Map
+
+ float xFactor = terrain.Width / twidth;
+ float yFactor = terrain.Height / theight;
+
+ #endregion Layer Map
+
+ #region Texture Compositing
+
+ Bitmap output = new Bitmap(twidth, theight, PixelFormat.Format24bppRgb);
+ BitmapData outputData = output.LockBits(new Rectangle(0, 0, twidth, theight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
+
+ // Unsafe work as we lock down the source textures for quicker access and access the
+ // pixel data directly
+ float invtwitdthMinus1 = 1.0f / (twidth - 1);
+ float invtheightMinus1 = 1.0f / (theight - 1);
+ int ty;
+ int tx;
+ float pctx;
+ float pcty;
+ float height;
+ float layer;
+ float layerDiff;
+ int l0;
+ int l1;
+ uint yglobalpos;
+
+ if(usecolors)
+ {
+ float a;
+ float b;
+ unsafe
+ {
+ byte* ptrO;
+ for(int y = 0; y < theight; ++y)
+ {
+ pcty = y * invtheightMinus1;
+ ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
+ ty = (int)(y * yFactor);
+ yglobalpos = (uint)ty + regionPositionY;
+
+ for(int x = 0; x < twidth; ++x)
+ {
+ tx = (int)(x * xFactor);
+ pctx = x * invtwitdthMinus1;
+ height = (float)terrain[tx, ty];
+ layer = getLayerTex(height, pctx, pcty,
+ (uint)tx + regionPositionX, yglobalpos,
+ startHeights, heightRanges);
+
+ // Select two textures
+ l0 = (int)layer;
+ l1 = Math.Min(l0 + 1, 3);
+
+ layerDiff = layer - l0;
+
+ a = mapColorsRed[l0];
+ b = mapColorsRed[l1];
+ *(ptrO++) = (byte)(a + layerDiff * (b - a));
+
+ a = mapColorsGreen[l0];
+ b = mapColorsGreen[l1];
+ *(ptrO++) = (byte)(a + layerDiff * (b - a));
+
+ a = mapColorsBlue[l0];
+ b = mapColorsBlue[l1];
+ *(ptrO++) = (byte)(a + layerDiff * (b - a));
+ }
+ }
+ }
+ }
+ else
+ {
+ float aB;
+ float aG;
+ float aR;
+ float bB;
+ float bG;
+ float bR;
+
+ unsafe
+ {
+ // Get handles to all of the texture data arrays
+ BitmapData[] datas = new BitmapData[]
+ {
+ detailTexture[0].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
+ detailTexture[1].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
+ detailTexture[2].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
+ detailTexture[3].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
+ };
+
+ byte* ptr;
+ byte* ptrO;
+ for(int y = 0; y < theight; y++)
+ {
+ pcty = y * invtheightMinus1;
+ int ypatch = ((int)(y * yFactor) & 0x0f) * datas[0].Stride;
+ ptrO = (byte*)outputData.Scan0 + y * outputData.Stride;
+ ty = (int)(y * yFactor);
+ yglobalpos = (uint)ty + regionPositionY;
+
+ for(int x = 0; x < twidth; x++)
+ {
+ tx = (int)(x * xFactor);
+ pctx = x * invtwitdthMinus1;
+ height = (float)terrain[tx, ty];
+ layer = getLayerTex(height, pctx, pcty,
+ (uint)tx + regionPositionX, yglobalpos,
+ startHeights, heightRanges);
+
+ // Select two textures
+ l0 = (int)layer;
+ layerDiff = layer - l0;
+
+ int patchOffset = (tx & 0x0f) * 3 + ypatch;
+
+ ptr = (byte*)datas[l0].Scan0 + patchOffset;
+ aB = *(ptr++);
+ aG = *(ptr++);
+ aR = *(ptr);
+
+ l1 = Math.Min(l0 + 1, 3);
+ ptr = (byte*)datas[l1].Scan0 + patchOffset;
+ bB = *(ptr++);
+ bG = *(ptr++);
+ bR = *(ptr);
+
+
+ // Interpolate between the two selected textures
+ *(ptrO++) = (byte)(aB + layerDiff * (bB - aB));
+ *(ptrO++) = (byte)(aG + layerDiff * (bG - aG));
+ *(ptrO++) = (byte)(aR + layerDiff * (bR - aR));
+ }
+ }
+
+ 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);
+
+//output.Save("terr.png",ImageFormat.Png);
+
+ #endregion Texture Compositing
+
+ return output;
+ }
+
+ [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
+ private static float getLayerTex(float height, float pctX, float pctY, uint X, uint Y,
+ float[] startHeights, float[] heightRanges)
+ {
+ // 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);
+ if (float.IsNaN(startHeight))
+ return 0;
+
+ 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);
+ if(heightRange == 0f || float.IsNaN(heightRange))
+ return 0;
+
+ // Generate two frequencies of perlin noise based on our global position
+ // The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
+ float sX = X * 0.20319f;
+ float sY = Y * 0.20319f;
+
+ float noise = Perlin.noise2(sX * 0.222222f, sY * 0.222222f) * 13.0f;
+ noise += Perlin.turbulence2(sX, sY, 2f) * 4.5f;
+
+ // Combine the current height, generated noise, start height, and height range parameters, then scale all of it
+ float layer = ((height + noise - startHeight) / heightRange) * 4f;
+ return Utils.Clamp(layer, 0f, 3f);
+ }
+ }
+}
diff --git a/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Warp3DImageModule.cs b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Warp3DImageModule.cs
new file mode 100644
index 0000000..8e50a16
--- /dev/null
+++ b/addon-modules/OpenSim.Modules.Warp3DCachedImageModule/src/Warp3DImageModule.cs
@@ -0,0 +1,1073 @@
+/*
+ * 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 System.Runtime;
+
+using CSJ2K;
+using Nini.Config;
+using log4net;
+using Warp3D;
+using Mono.Addins;
+
+using OpenSim.Framework;
+using OpenSim.Region.Framework.Interfaces;
+using OpenSim.Region.Framework.Scenes;
+using OpenSim.Region.PhysicsModules.SharedBase;
+using OpenSim.Services.Interfaces;
+
+using OpenMetaverse;
+using OpenMetaverse.Assets;
+using OpenMetaverse.Imaging;
+using OpenMetaverse.Rendering;
+using OpenMetaverse.StructuredData;
+
+using WarpRenderer = Warp3D.Warp3D;
+using System.Drawing.Drawing2D;
+
+[assembly: Addin("Warp3DCachedImageModule", "1.1")]
+[assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
+namespace OpenSim.Region.CoreModules.World.Warp3DMap
+{
+ [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DCachedImageModule")]
+ public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
+ {
+ private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
+ // private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 128);
+
+ private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+#pragma warning disable 414
+ private static string LogHeader = "[WARP 3D CACHED IMAGE MODULE]";
+#pragma warning restore 414
+ private const float m_cameraHeight = 4096f;
+
+ internal Scene m_scene;
+ private IRendering m_primMesher;
+ internal IJ2KDecoder m_imgDecoder;
+
+ // caches per rendering
+ private Dictionary m_warpTextures = new Dictionary();
+ private Dictionary m_colors = new Dictionary();
+
+ 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_textureAverageTerrain = false; // replace terrain textures by their average color
+ 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 float m_renderMinHeight = -100f;
+ private float m_renderMaxHeight = 4096f;
+
+ private String m_cacheDirectory = "";
+ private bool m_enable_date = false;
+ private bool m_enable_regionName = false;
+ private bool m_enable_regionPosition = false;
+ private bool m_enable_refreshEveryMonth = false;
+ private bool m_enable_HostedBy = false;
+ private String m_enable_HostedByText = "";
+
+ private bool m_Enabled = false;
+
+ // private Bitmap lastImage = null;
+ private DateTime lastImageTime = DateTime.MinValue;
+
+ #region Region Module interface
+
+ public void Initialise(IConfigSource source)
+ {
+ m_config = source;
+
+ string[] configSections = new string[] { "Map", "Startup" };
+
+ if (Util.GetConfigVarFromSections(
+ m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DCachedImageModule")
+ 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_textureAverageTerrain =
+ Util.GetConfigVarFromSections(m_config, "AverageTextureColorOnMapTile", configSections, m_textureAverageTerrain);
+ if (m_textureAverageTerrain)
+ m_textureTerrain = true;
+ 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_cacheDirectory =
+ Util.GetConfigVarFromSections(m_config, "CacheDirectory", configSections, System.IO.Path.Combine(new DirectoryInfo(".").FullName, "MapImageCache"));
+
+
+ m_enable_date = Util.GetConfigVarFromSections(m_config, "enableDate", configSections, false);
+ m_enable_regionName = Util.GetConfigVarFromSections(m_config, "enableName", configSections, false);
+ m_enable_regionPosition = Util.GetConfigVarFromSections(m_config, "enablePosition", configSections, false);
+ m_enable_refreshEveryMonth = Util.GetConfigVarFromSections(m_config, "RefreshEveryMonth", configSections, true);
+ m_enable_HostedBy = Util.GetConfigVarFromSections(m_config, "enableHostedBy", configSections, false);
+ m_enable_HostedByText = Util.GetConfigVarFromSections(m_config, "HosterText", configSections, String.Empty);
+
+ m_renderMaxHeight = Util.GetConfigVarFromSections(m_config, "RenderMaxHeight", configSections, m_renderMaxHeight);
+ m_renderMinHeight = Util.GetConfigVarFromSections(m_config, "RenderMinHeight", configSections, m_renderMinHeight);
+
+ if (!Directory.Exists(m_cacheDirectory))
+ Directory.CreateDirectory(m_cacheDirectory);
+
+ if (m_renderMaxHeight < 100f)
+ m_renderMaxHeight = 100f;
+ else if (m_renderMaxHeight > m_cameraHeight - 10f)
+ m_renderMaxHeight = m_cameraHeight - 10f;
+
+ if (m_renderMinHeight < -100f)
+ m_renderMinHeight = -100f;
+ else if (m_renderMinHeight > m_renderMaxHeight - 10f)
+ m_renderMinHeight = m_renderMaxHeight - 10f;
+ }
+
+ public void AddRegion(Scene scene)
+ {
+ if (!m_Enabled)
+ return;
+
+ m_scene = scene;
+
+ List renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
+ if (renderers.Count > 0)
+ m_log.Info("[MAPTILE]: Loaded prim mesher " + renderers[0]);
+ else
+ m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
+
+ m_scene.RegisterModuleInterface(this);
+ }
+
+ public void RegionLoaded(Scene scene)
+ {
+ if (!m_Enabled)
+ return;
+
+ m_imgDecoder = m_scene.RequestModuleInterface();
+ }
+
+ public void RemoveRegion(Scene scene)
+ {
+ }
+
+ public void Close()
+ {
+ }
+
+ public string Name
+ {
+ get { return "Warp3DImageModule"; }
+ }
+
+ public Type ReplaceableInterface
+ {
+ get { return null; }
+ }
+
+ #endregion
+
+ #region IMapImageGenerator Members
+
+ private Vector3 cameraPos;
+ private Vector3 cameraDir;
+ private int viewWitdh = 256;
+ private int viewHeight = 256;
+ private float fov;
+ private bool orto;
+
+ public static string fillInt(int _i, int _l)
+ {
+ String _return = _i.ToString();
+
+ while (_return.Length < _l)
+ {
+ _return = 0 + _return;
+ }
+
+ return _return;
+ }
+
+ public static int getCurrentUnixTime()
+ {
+ return (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
+ }
+
+ public static String unixTimeToDateString(int unixTime)
+ {
+ DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
+ long unixTimeStampInTicks = (long)(unixTime * TimeSpan.TicksPerSecond);
+ DateTime _date = new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
+
+ return fillInt(_date.Day, 2) + "." + fillInt(_date.Month, 2) + "." + fillInt(_date.Year, 4) + " " + fillInt(_date.Hour, 2) + ":" + fillInt(_date.Minute, 2);
+ }
+
+ private void writeDateOnMap(ref Bitmap _map)
+ {
+ RectangleF rectf = new RectangleF(2, 1, 200, 25);
+
+ Graphics g = Graphics.FromImage(_map);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ g.DrawString(unixTimeToDateString(getCurrentUnixTime()), new Font("Arial", 8), Brushes.White, rectf);
+ g.Flush();
+ }
+
+ private void writeNameOnMap(ref Bitmap _map)
+ {
+ RectangleF rectf = new RectangleF(2, m_scene.RegionInfo.RegionSizeX - 15, 200, 25);
+
+ Graphics g = Graphics.FromImage(_map);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ g.DrawString(m_scene.Name, new Font("Arial", 8), Brushes.White, rectf);
+ g.Flush();
+ }
+
+ private void writePositionOnMap(ref Bitmap _map)
+ {
+ RectangleF rectf = new RectangleF(m_scene.RegionInfo.RegionSizeY - 85, m_scene.RegionInfo.RegionSizeX - 15, 80, 25);
+
+ Graphics g = Graphics.FromImage(_map);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ g.DrawString(m_scene.RegionInfo.RegionLocX + ", " + m_scene.RegionInfo.RegionLocY, new Font("Arial", 8), Brushes.White, rectf);
+ g.Flush();
+ }
+
+ private void writeHostedByOnMap(ref Bitmap _map)
+ {
+ RectangleF rectf = new RectangleF(2, m_scene.RegionInfo.RegionSizeX - 15, 200, 25);
+
+ Graphics g = Graphics.FromImage(_map);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PixelOffsetMode = PixelOffsetMode.HighQuality;
+ g.DrawString(m_enable_HostedByText, new Font("Arial", 8), Brushes.Gray, rectf);
+ g.Flush();
+ }
+
+
+ public Bitmap CreateMapTile()
+ {
+ if ((File.GetCreationTime(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")).Month != DateTime.Now.Month) && m_enable_refreshEveryMonth == true)
+ File.Delete(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
+
+ if (File.Exists(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp")))
+ {
+ return new Bitmap(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
+ }
+ else
+ {
+ List renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
+ if (renderers.Count > 0)
+ {
+ m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
+ }
+
+ cameraPos = new Vector3(
+ (m_scene.RegionInfo.RegionSizeX) * 0.5f,
+ (m_scene.RegionInfo.RegionSizeY) * 0.5f,
+ m_cameraHeight);
+
+ cameraDir = -Vector3.UnitZ;
+ viewWitdh = (int)m_scene.RegionInfo.RegionSizeX;
+ viewHeight = (int)m_scene.RegionInfo.RegionSizeY;
+ orto = true;
+
+ // fov = warp_Math.rad2deg(2f * (float)Math.Atan2(viewWitdh, 4096f));
+ // orto = false;
+
+ Bitmap tile = GenImage();
+
+ if (m_enable_date)
+ writeDateOnMap(ref tile);
+
+ if (m_enable_regionName)
+ writeNameOnMap(ref tile);
+
+ if (m_enable_regionPosition)
+ writePositionOnMap(ref tile);
+
+ if (m_enable_HostedBy)
+ writeHostedByOnMap(ref tile);
+
+ tile.Save(System.IO.Path.Combine(m_cacheDirectory, m_scene.RegionInfo.RegionID + ".bmp"));
+
+ // image may be reloaded elsewhere, so no compression format
+ string filename = "MAP-" + m_scene.RegionInfo.RegionID.ToString() + ".png";
+ tile.Save(filename, ImageFormat.Png);
+ m_primMesher = null;
+ return tile;
+ }
+ }
+
+ public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float pfov, int width, int height, bool useTextures)
+ {
+ List renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
+ if (renderers.Count > 0)
+ {
+ m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
+ }
+
+ cameraPos = camPos;
+ cameraDir = camDir;
+ viewWitdh = width;
+ viewHeight = height;
+ fov = pfov;
+ orto = false;
+
+ Bitmap tile = GenImage();
+ m_primMesher = null;
+ return tile;
+ }
+
+ private Bitmap GenImage()
+ {
+ m_colors.Clear();
+ m_warpTextures.Clear();
+
+ WarpRenderer renderer = new WarpRenderer();
+
+ if (!renderer.CreateScene(viewWitdh, viewHeight))
+ return new Bitmap(viewWitdh, viewHeight);
+
+ #region Camera
+
+ warp_Vector pos = ConvertVector(cameraPos);
+ warp_Vector lookat = warp_Vector.add(pos, ConvertVector(cameraDir));
+
+ if (orto)
+ renderer.Scene.defaultCamera.setOrthographic(true, viewWitdh, viewHeight);
+ else
+ renderer.Scene.defaultCamera.setFov(fov);
+
+ renderer.Scene.defaultCamera.setPos(pos);
+ renderer.Scene.defaultCamera.lookAt(lookat);
+ #endregion Camera
+
+ renderer.Scene.setAmbient(warp_Color.getColor(192, 191, 173));
+ renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(0f, 1f, 8f), warp_Color.White, 0, 320, 40));
+
+ CreateWater(renderer);
+ CreateTerrain(renderer);
+ if (m_drawPrimVolume)
+ CreateAllPrims(renderer);
+
+ renderer.Render();
+ Bitmap bitmap = renderer.Scene.getImage();
+
+ renderer.Scene.destroy();
+ renderer.Reset();
+ renderer = null;
+
+ m_colors.Clear();
+ m_warpTextures.Clear();
+
+ GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
+ return bitmap;
+ }
+
+ public byte[] WriteJpeg2000Image()
+ {
+ try
+ {
+ using (Bitmap mapbmp = CreateMapTile())
+ return OpenJPEG.EncodeFromImage(mapbmp, false);
+ }
+ catch (Exception e)
+ {
+ // JPEG2000 encoder failed
+ m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
+ }
+
+ return null;
+ }
+
+ #endregion
+
+ #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", m_scene.RegionInfo.RegionSizeX * 0.5f);
+ renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX * 0.5f,
+ waterHeight,
+ m_scene.RegionInfo.RegionSizeY * 0.5f);
+
+ warp_Material waterMaterial = new warp_Material(ConvertColor(WATER_COLOR));
+ renderer.Scene.addMaterial("WaterMat", waterMaterial);
+ renderer.SetObjectMaterial("Water", "WaterMat");
+ }
+
+ // Add a terrain to the renderer.
+ // Note that we create a 'low resolution' 257x257 vertex terrain rather than trying for
+ // full resolution. This saves a lot of memory especially for very large regions.
+ private void CreateTerrain(WarpRenderer renderer)
+ {
+ ITerrainChannel terrain = m_scene.Heightmap;
+
+ float regionsx = m_scene.RegionInfo.RegionSizeX;
+ float regionsy = m_scene.RegionInfo.RegionSizeY;
+
+ // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
+
+ int bitWidth;
+ int bitHeight;
+
+ const double log2inv = 1.4426950408889634073599246810019;
+ bitWidth = (int)Math.Ceiling((Math.Log(terrain.Width) * log2inv));
+ bitHeight = (int)Math.Ceiling((Math.Log(terrain.Height) * log2inv));
+
+ if (bitWidth > 8) // more than 256 is very heavy :(
+ bitWidth = 8;
+ if (bitHeight > 8)
+ bitHeight = 8;
+
+ int twidth = (int)Math.Pow(2, bitWidth);
+ int theight = (int)Math.Pow(2, bitHeight);
+
+ float diff = regionsx / twidth;
+
+ int npointsx = (int)(regionsx / diff);
+ int npointsy = (int)(regionsy / diff);
+
+ float invsx = 1.0f / (npointsx * diff);
+ float invsy = 1.0f / (npointsy * diff);
+
+ npointsx++;
+ npointsy++;
+
+ // Create all the vertices for the terrain
+ warp_Object obj = new warp_Object();
+ warp_Vector pos;
+ float x, y;
+ float tv;
+ for (y = 0; y < regionsy; y += diff)
+ {
+ tv = y * invsy;
+ for (x = 0; x < regionsx; x += diff)
+ {
+ pos = ConvertVector(x, y, (float)terrain[(int)x, (int)y]);
+ obj.addVertex(new warp_Vertex(pos, x * invsx, tv));
+ }
+ pos = ConvertVector(x, y, (float)terrain[(int)(x - diff), (int)y]);
+ obj.addVertex(new warp_Vertex(pos, 1.0f, tv));
+ }
+
+ int lastY = (int)(y - diff);
+ for (x = 0; x < regionsx; x += diff)
+ {
+ pos = ConvertVector(x, y, (float)terrain[(int)x, lastY]);
+ obj.addVertex(new warp_Vertex(pos, x * invsx, 1.0f));
+ }
+ pos = ConvertVector(x, y, (float)terrain[(int)(x - diff), lastY]);
+ obj.addVertex(new warp_Vertex(pos, 1.0f, 1.0f));
+
+ // create triangles.
+ int limx = npointsx - 1;
+ int limy = npointsy - 1;
+ for (int j = 0; j < limy; j++)
+ {
+ for (int i = 0; i < limx; i++)
+ {
+ int v = j * npointsx + i;
+
+ // Make two triangles for each of the squares in the grid of vertices
+ obj.addTriangle(
+ v,
+ v + 1,
+ v + npointsx);
+
+ obj.addTriangle(
+ v + npointsx + 1,
+ v + npointsx,
+ v + 1);
+ }
+ }
+
+ renderer.Scene.addObject("Terrain", obj);
+
+ UUID[] textureIDs = new UUID[4];
+ float[] startHeights = new float[4];
+ float[] heightRanges = new float[4];
+
+ OpenSim.Framework.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;
+
+ warp_Texture texture;
+ using (Bitmap image = TerrainSplat.Splat(terrain, textureIDs, startHeights, heightRanges,
+ m_scene.RegionInfo.WorldLocX, m_scene.RegionInfo.WorldLocY,
+ m_scene.AssetService, m_imgDecoder, m_textureTerrain, m_textureAverageTerrain,
+ twidth, twidth))
+ texture = new warp_Texture(image);
+
+ warp_Material material = new warp_Material(texture);
+ renderer.Scene.addMaterial("TerrainMat", material);
+ renderer.SetObjectMaterial("Terrain", "TerrainMat");
+ }
+
+ private void CreateAllPrims(WarpRenderer renderer)
+ {
+ if (m_primMesher == null)
+ return;
+
+ m_scene.ForEachSOG(
+ delegate (SceneObjectGroup group)
+ {
+ foreach (SceneObjectPart child in group.Parts)
+ CreatePrim(renderer, child);
+ }
+ );
+ }
+
+ private void UVPlanarMap(Vertex v, Vector3 scale, out float tu, out float tv)
+ {
+ Vector3 scaledPos = v.Position * scale;
+ float d = v.Normal.X;
+ if (d >= 0.5f)
+ {
+ tu = 2f * scaledPos.Y;
+ tv = scaledPos.X * v.Normal.Z - scaledPos.Z * v.Normal.X;
+ }
+ else if (d <= -0.5f)
+ {
+ tu = -2f * scaledPos.Y;
+ tv = -scaledPos.X * v.Normal.Z + scaledPos.Z * v.Normal.X;
+ }
+ else if (v.Normal.Y > 0f)
+ {
+ tu = -2f * scaledPos.X;
+ tv = scaledPos.Y * v.Normal.Z - scaledPos.Z * v.Normal.Y;
+ }
+ else
+ {
+ tu = 2f * scaledPos.X;
+ tv = -scaledPos.Y * v.Normal.Z + scaledPos.Z * v.Normal.Y;
+ }
+
+ tv *= 2f;
+ }
+
+ private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim)
+ {
+ if ((PCode)prim.Shape.PCode != PCode.Prim)
+ return;
+
+ Vector3 ppos = prim.GetWorldPosition();
+ if (ppos.Z < m_renderMinHeight || ppos.Z > m_renderMaxHeight)
+ return;
+
+ warp_Vector primPos = ConvertVector(ppos);
+ warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
+ warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
+
+ float screenFactor = renderer.Scene.EstimateBoxProjectedArea(primPos, ConvertVector(prim.Scale), m);
+ if (screenFactor < 0)
+ return;
+
+ int p2 = (int)(-(float)Math.Log(screenFactor) * 1.442695f * 0.5 - 1);
+
+ if (p2 < 0)
+ p2 = 0;
+ else if (p2 > 3)
+ p2 = 3;
+
+ DetailLevel lod = (DetailLevel)(3 - p2);
+
+ FacetedMesh renderMesh = null;
+ Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
+
+ 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, lod, out renderMesh);
+ meshAsset = null;
+ }
+ else // It's sculptie
+ {
+ if (m_imgDecoder != null)
+ {
+ Image sculpt = m_imgDecoder.DecodeToImage(sculptAsset);
+ if (sculpt != null)
+ {
+ renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt, lod);
+ sculpt.Dispose();
+ }
+ }
+ }
+ }
+ else
+ {
+ m_log.WarnFormat("[Warp3D] failed to get mesh or sculpt asset {0} of prim {1} at {2}",
+ omvPrim.Sculpt.SculptTexture.ToString(), prim.Name, prim.GetWorldPosition().ToString());
+ }
+ }
+ }
+
+ // If not a mesh or sculptie, try the regular mesher
+ if (renderMesh == null)
+ {
+ renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, lod);
+ }
+
+ if (renderMesh == null)
+ return;
+
+ string primID = prim.UUID.ToString();
+
+ // Create the prim faces
+ // TODO: Implement the useTextures flag behavior
+ for (int i = 0; i < renderMesh.Faces.Count; i++)
+ {
+ Face face = renderMesh.Faces[i];
+ string meshName = primID + i.ToString();
+
+ // Avoid adding duplicate meshes to the scene
+ if (renderer.Scene.objectData.ContainsKey(meshName))
+ continue;
+
+ warp_Object faceObj = new warp_Object();
+
+ Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
+ Color4 faceColor = teFace.RGBA;
+ if (faceColor.A == 0)
+ continue;
+
+ string materialName = String.Empty;
+ if (m_texturePrims)
+ {
+ // if(lod > DetailLevel.Low)
+ {
+ // materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, lod == DetailLevel.Low);
+ materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID, false, prim);
+ if (String.IsNullOrEmpty(materialName))
+ continue;
+ int c = renderer.Scene.material(materialName).getColor();
+ if ((c & warp_Color.MASKALPHA) == 0)
+ continue;
+ }
+ }
+ else
+ materialName = GetOrCreateMaterial(renderer, faceColor);
+
+ if (renderer.Scene.material(materialName).getTexture() == null)
+ {
+ // uv map details dont not matter for color;
+ for (int j = 0; j < face.Vertices.Count; j++)
+ {
+ Vertex v = face.Vertices[j];
+ warp_Vector pos = ConvertVector(v.Position);
+ warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
+ faceObj.addVertex(vert);
+ }
+ }
+ else
+ {
+ float tu;
+ float tv;
+ float offsetu = teFace.OffsetU + 0.5f;
+ float offsetv = teFace.OffsetV + 0.5f;
+ float scaleu = teFace.RepeatU;
+ float scalev = teFace.RepeatV;
+ float rotation = teFace.Rotation;
+ float rc = 0;
+ float rs = 0;
+ if (rotation != 0)
+ {
+ rc = (float)Math.Cos(rotation);
+ rs = (float)Math.Sin(rotation);
+ }
+
+ for (int j = 0; j < face.Vertices.Count; j++)
+ {
+ warp_Vertex vert;
+ Vertex v = face.Vertices[j];
+ warp_Vector pos = ConvertVector(v.Position);
+ if (teFace.TexMapType == MappingType.Planar)
+ UVPlanarMap(v, prim.Scale, out tu, out tv);
+ else
+ {
+ tu = v.TexCoord.X - 0.5f;
+ tv = 0.5f - v.TexCoord.Y;
+ }
+ if (rotation != 0)
+ {
+ float tur = tu * rc - tv * rs;
+ float tvr = tu * rs + tv * rc;
+ tur *= scaleu;
+ tur += offsetu;
+
+ tvr *= scalev;
+ tvr += offsetv;
+ vert = new warp_Vertex(pos, tur, tvr);
+ }
+ else
+ {
+ tu *= scaleu;
+ tu += offsetu;
+ tv *= scalev;
+ tv += offsetv;
+ vert = new warp_Vertex(pos, tu, tv);
+ }
+
+ 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]);
+ }
+
+ faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);
+ faceObj.transform(m);
+ faceObj.setPos(primPos);
+
+ renderer.Scene.addObject(meshName, faceObj);
+ renderer.SetObjectMaterial(meshName, materialName);
+ }
+ }
+
+ private int GetFaceColor(Primitive.TextureEntryFace face)
+ {
+ int color;
+ Color4 ctmp = Color4.White;
+
+ if (face.TextureID == UUID.Zero)
+ return warp_Color.White;
+
+ if (!m_colors.TryGetValue(face.TextureID, out color))
+ {
+ bool fetched = false;
+
+ // Attempt to fetch the texture metadata
+ string cacheName = "MAPCLR" + face.TextureID.ToString();
+ AssetBase metadata = m_scene.AssetService.GetCached(cacheName);
+ if (metadata != null)
+ {
+ OSDMap map = null;
+ try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
+
+ if (map != null)
+ {
+ ctmp = map["X-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;
+ ctmp = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
+
+ OSDMap data = new OSDMap { { "X-RGBA", OSD.FromColor4(ctmp) } };
+ metadata = new AssetBase
+ {
+ Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
+ Description = "Metadata for texture color" + face.TextureID.ToString(),
+ Flags = AssetFlags.Collectable,
+ FullID = UUID.Zero,
+ ID = cacheName,
+ Local = true,
+ Temporary = true,
+ Name = String.Empty,
+ Type = (sbyte)AssetType.Unknown
+ };
+ m_scene.AssetService.Store(metadata);
+ }
+ else
+ {
+ ctmp = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
+ }
+ }
+ color = ConvertColor(ctmp);
+ m_colors[face.TextureID] = color;
+ }
+
+ return color;
+ }
+
+ 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));
+ return name;
+ }
+
+ public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID, bool useAverageTextureColor, SceneObjectPart sop)
+ {
+ int color = ConvertColor(faceColor);
+ string idstr = textureID.ToString() + color.ToString();
+ string materialName = "MAPMAT" + idstr;
+
+ if (renderer.Scene.material(materialName) != null)
+ return materialName;
+
+ warp_Material mat = new warp_Material();
+ warp_Texture texture = GetTexture(textureID, sop);
+ if (texture != null)
+ {
+ if (useAverageTextureColor)
+ color = warp_Color.multiply(color, texture.averageColor);
+ else
+ mat.setTexture(texture);
+ }
+ else
+ color = warp_Color.multiply(color, warp_Color.Grey);
+
+ mat.setColor(color);
+ renderer.Scene.addMaterial(materialName, mat);
+
+ return materialName;
+ }
+
+ private warp_Texture GetTexture(UUID id, SceneObjectPart sop)
+ {
+ warp_Texture ret = null;
+ if (id == UUID.Zero)
+ return ret;
+
+ if (m_warpTextures.TryGetValue(id.ToString(), out ret))
+ return ret;
+
+ byte[] asset = m_scene.AssetService.GetData(id.ToString());
+
+ if (asset != null)
+ {
+ try
+ {
+ using (Bitmap img = (Bitmap)m_imgDecoder.DecodeToImage(asset))
+ ret = new warp_Texture(img, 8); // reduce textures size to 256x256
+ }
+ catch (Exception e)
+ {
+ m_log.WarnFormat("[Warp3D]: Failed to decode texture {0} for prim {1} at {2}, exception {3}", id.ToString(), sop.Name, sop.GetWorldPosition().ToString(), e.Message);
+ }
+ }
+ else
+ m_log.WarnFormat("[Warp3D]: missing texture {0} data for prim {1} at {2}",
+ id.ToString(), sop.Name, sop.GetWorldPosition().ToString());
+
+ m_warpTextures[id.ToString()] = ret;
+ 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);
+ }
+
+ 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), (byte)(color.A * 255f));
+ 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 Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
+ {
+ ulong r = 0;
+ ulong g = 0;
+ ulong b = 0;
+ ulong a = 0;
+ int pixelBytes;
+
+ try
+ {
+ using (MemoryStream stream = new MemoryStream(j2kData))
+ using (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);
+ 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(
+ "[WARP 3D IMAGE MODULE]: 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);
+ }
+ }
+}
--
cgit v1.1