Warp3DImageModule.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Reflection;
  33. using CSJ2K;
  34. using Nini.Config;
  35. using log4net;
  36. using Rednettle.Warp3D;
  37. using Mono.Addins;
  38. using OpenMetaverse;
  39. using OpenMetaverse.Imaging;
  40. using OpenMetaverse.Rendering;
  41. using OpenMetaverse.StructuredData;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Physics.Manager;
  46. using OpenSim.Services.Interfaces;
  47. using WarpRenderer = global::Warp3D.Warp3D;
  48. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  49. {
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")]
  51. public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
  52. {
  53. private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
  54. private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. private Scene m_scene;
  57. private IRendering m_primMesher;
  58. private IConfigSource m_config;
  59. private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
  60. private bool m_useAntiAliasing = false; // TODO: Make this a config option
  61. private bool m_Enabled = false;
  62. #region Region Module interface
  63. public void Initialise(IConfigSource source)
  64. {
  65. m_config = source;
  66. if (Util.GetConfigVarFromSections<string>(
  67. m_config, "MapImageModule", new string[] { "Startup", "Map" }, "MapImageModule") != "Warp3DImageModule")
  68. return;
  69. m_Enabled = true;
  70. }
  71. public void AddRegion(Scene scene)
  72. {
  73. if (!m_Enabled)
  74. return;
  75. m_scene = scene;
  76. List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
  77. if (renderers.Count > 0)
  78. {
  79. m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
  80. m_log.DebugFormat("[WARP 3D IMAGE MODULE]: Loaded prim mesher {0}", m_primMesher);
  81. }
  82. else
  83. {
  84. m_log.Debug("[WARP 3D IMAGE MODULE]: No prim mesher loaded, prim rendering will be disabled");
  85. }
  86. m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
  87. }
  88. public void RegionLoaded(Scene scene)
  89. {
  90. }
  91. public void RemoveRegion(Scene scene)
  92. {
  93. }
  94. public void Close()
  95. {
  96. }
  97. public string Name
  98. {
  99. get { return "Warp3DImageModule"; }
  100. }
  101. public Type ReplaceableInterface
  102. {
  103. get { return null; }
  104. }
  105. #endregion
  106. #region IMapImageGenerator Members
  107. public Bitmap CreateMapTile()
  108. {
  109. Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
  110. Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize);
  111. return CreateMapTile(viewport, false);
  112. }
  113. public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
  114. {
  115. Viewport viewport = new Viewport(camPos, camDir, fov, (float)Constants.RegionSize, 0.1f, width, height);
  116. return CreateMapTile(viewport, useTextures);
  117. }
  118. public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
  119. {
  120. bool drawPrimVolume = true;
  121. bool textureTerrain = true;
  122. string[] configSections = new string[] { "Map", "Startup" };
  123. drawPrimVolume
  124. = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, drawPrimVolume);
  125. textureTerrain
  126. = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, textureTerrain);
  127. m_colors.Clear();
  128. int width = viewport.Width;
  129. int height = viewport.Height;
  130. if (m_useAntiAliasing)
  131. {
  132. width *= 2;
  133. height *= 2;
  134. }
  135. WarpRenderer renderer = new WarpRenderer();
  136. renderer.CreateScene(width, height);
  137. renderer.Scene.autoCalcNormals = false;
  138. #region Camera
  139. warp_Vector pos = ConvertVector(viewport.Position);
  140. pos.z -= 0.001f; // Works around an issue with the Warp3D camera
  141. warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
  142. renderer.Scene.defaultCamera.setPos(pos);
  143. renderer.Scene.defaultCamera.lookAt(lookat);
  144. if (viewport.Orthographic)
  145. {
  146. renderer.Scene.defaultCamera.isOrthographic = true;
  147. renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
  148. renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
  149. }
  150. else
  151. {
  152. float fov = viewport.FieldOfView;
  153. fov *= 1.75f; // FIXME: ???
  154. renderer.Scene.defaultCamera.setFov(fov);
  155. }
  156. #endregion Camera
  157. renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
  158. renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
  159. CreateWater(renderer);
  160. CreateTerrain(renderer, textureTerrain);
  161. if (drawPrimVolume)
  162. CreateAllPrims(renderer, useTextures);
  163. renderer.Render();
  164. Bitmap bitmap = renderer.Scene.getImage();
  165. if (m_useAntiAliasing)
  166. {
  167. using (Bitmap origBitmap = bitmap)
  168. bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height);
  169. }
  170. // XXX: It shouldn't really be necesary to force a GC here as one should occur anyway pretty shortly
  171. // afterwards. It's generally regarded as a bad idea to manually GC. If Warp3D is using lots of memory
  172. // then this may be some issue with the Warp3D code itself, though it's also quite possible that generating
  173. // this map tile simply takes a lot of memory.
  174. GC.Collect();
  175. m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
  176. return bitmap;
  177. }
  178. public byte[] WriteJpeg2000Image()
  179. {
  180. try
  181. {
  182. using (Bitmap mapbmp = CreateMapTile())
  183. return OpenJPEG.EncodeFromImage(mapbmp, true);
  184. }
  185. catch (Exception e)
  186. {
  187. // JPEG2000 encoder failed
  188. m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
  189. }
  190. return null;
  191. }
  192. #endregion
  193. #region Rendering Methods
  194. private void CreateWater(WarpRenderer renderer)
  195. {
  196. float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
  197. renderer.AddPlane("Water", 256f * 0.5f);
  198. renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f);
  199. renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR));
  200. renderer.Scene.material("WaterColor").setReflectivity(0); // match water color with standard map module thanks lkalif
  201. renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
  202. renderer.SetObjectMaterial("Water", "WaterColor");
  203. }
  204. private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
  205. {
  206. ITerrainChannel terrain = m_scene.Heightmap;
  207. float[] heightmap = terrain.GetFloatsSerialised();
  208. warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
  209. for (int y = 0; y < 256; y++)
  210. {
  211. for (int x = 0; x < 256; x++)
  212. {
  213. int v = y * 256 + x;
  214. float height = heightmap[v];
  215. warp_Vector pos = ConvertVector(new Vector3(x, y, height));
  216. obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f));
  217. }
  218. }
  219. for (int y = 0; y < 256; y++)
  220. {
  221. for (int x = 0; x < 256; x++)
  222. {
  223. if (x < 255 && y < 255)
  224. {
  225. int v = y * 256 + x;
  226. // Normal
  227. Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]);
  228. Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]);
  229. Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]);
  230. warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
  231. norm = norm.reverse();
  232. obj.vertex(v).n = norm;
  233. // Triangle 1
  234. obj.addTriangle(
  235. v,
  236. v + 1,
  237. v + 256);
  238. // Triangle 2
  239. obj.addTriangle(
  240. v + 256 + 1,
  241. v + 256,
  242. v + 1);
  243. }
  244. }
  245. }
  246. renderer.Scene.addObject("Terrain", obj);
  247. UUID[] textureIDs = new UUID[4];
  248. float[] startHeights = new float[4];
  249. float[] heightRanges = new float[4];
  250. RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
  251. textureIDs[0] = regionInfo.TerrainTexture1;
  252. textureIDs[1] = regionInfo.TerrainTexture2;
  253. textureIDs[2] = regionInfo.TerrainTexture3;
  254. textureIDs[3] = regionInfo.TerrainTexture4;
  255. startHeights[0] = (float)regionInfo.Elevation1SW;
  256. startHeights[1] = (float)regionInfo.Elevation1NW;
  257. startHeights[2] = (float)regionInfo.Elevation1SE;
  258. startHeights[3] = (float)regionInfo.Elevation1NE;
  259. heightRanges[0] = (float)regionInfo.Elevation2SW;
  260. heightRanges[1] = (float)regionInfo.Elevation2NW;
  261. heightRanges[2] = (float)regionInfo.Elevation2SE;
  262. heightRanges[3] = (float)regionInfo.Elevation2NE;
  263. uint globalX, globalY;
  264. Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
  265. warp_Texture texture;
  266. using (
  267. Bitmap image
  268. = TerrainSplat.Splat(
  269. heightmap, textureIDs, startHeights, heightRanges,
  270. new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
  271. {
  272. texture = new warp_Texture(image);
  273. }
  274. warp_Material material = new warp_Material(texture);
  275. material.setReflectivity(50);
  276. renderer.Scene.addMaterial("TerrainColor", material);
  277. renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
  278. renderer.SetObjectMaterial("Terrain", "TerrainColor");
  279. }
  280. private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
  281. {
  282. if (m_primMesher == null)
  283. return;
  284. m_scene.ForEachSOG(
  285. delegate(SceneObjectGroup group)
  286. {
  287. CreatePrim(renderer, group.RootPart, useTextures);
  288. foreach (SceneObjectPart child in group.Parts)
  289. CreatePrim(renderer, child, useTextures);
  290. }
  291. );
  292. }
  293. private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
  294. bool useTextures)
  295. {
  296. const float MIN_SIZE = 2f;
  297. if ((PCode)prim.Shape.PCode != PCode.Prim)
  298. return;
  299. if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
  300. return;
  301. Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
  302. FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
  303. if (renderMesh == null)
  304. return;
  305. warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
  306. warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
  307. warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
  308. if (prim.ParentID != 0)
  309. {
  310. SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
  311. if (group != null)
  312. m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
  313. }
  314. warp_Vector primScale = ConvertVector(prim.Scale);
  315. string primID = prim.UUID.ToString();
  316. // Create the prim faces
  317. // TODO: Implement the useTextures flag behavior
  318. for (int i = 0; i < renderMesh.Faces.Count; i++)
  319. {
  320. Face face = renderMesh.Faces[i];
  321. string meshName = primID + "-Face-" + i.ToString();
  322. // Avoid adding duplicate meshes to the scene
  323. if (renderer.Scene.objectData.ContainsKey(meshName))
  324. {
  325. continue;
  326. }
  327. warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
  328. for (int j = 0; j < face.Vertices.Count; j++)
  329. {
  330. Vertex v = face.Vertices[j];
  331. warp_Vector pos = ConvertVector(v.Position);
  332. warp_Vector norm = ConvertVector(v.Normal);
  333. if (prim.Shape.SculptTexture == UUID.Zero)
  334. norm = norm.reverse();
  335. warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
  336. faceObj.addVertex(vert);
  337. }
  338. for (int j = 0; j < face.Indices.Count; j += 3)
  339. {
  340. faceObj.addTriangle(
  341. face.Indices[j + 0],
  342. face.Indices[j + 1],
  343. face.Indices[j + 2]);
  344. }
  345. Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
  346. Color4 faceColor = GetFaceColor(teFace);
  347. string materialName = GetOrCreateMaterial(renderer, faceColor);
  348. faceObj.transform(m);
  349. faceObj.setPos(primPos);
  350. faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
  351. renderer.Scene.addObject(meshName, faceObj);
  352. renderer.SetObjectMaterial(meshName, materialName);
  353. }
  354. }
  355. private Color4 GetFaceColor(Primitive.TextureEntryFace face)
  356. {
  357. Color4 color;
  358. if (face.TextureID == UUID.Zero)
  359. return face.RGBA;
  360. if (!m_colors.TryGetValue(face.TextureID, out color))
  361. {
  362. bool fetched = false;
  363. // Attempt to fetch the texture metadata
  364. UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
  365. AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
  366. if (metadata != null)
  367. {
  368. OSDMap map = null;
  369. try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
  370. if (map != null)
  371. {
  372. color = map["X-JPEG2000-RGBA"].AsColor4();
  373. fetched = true;
  374. }
  375. }
  376. if (!fetched)
  377. {
  378. // Fetch the texture, decode and get the average color,
  379. // then save it to a temporary metadata asset
  380. AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
  381. if (textureAsset != null)
  382. {
  383. int width, height;
  384. color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
  385. OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
  386. metadata = new AssetBase
  387. {
  388. Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
  389. Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
  390. Flags = AssetFlags.Collectable,
  391. FullID = metadataID,
  392. ID = metadataID.ToString(),
  393. Local = true,
  394. Temporary = true,
  395. Name = String.Empty,
  396. Type = (sbyte)AssetType.Unknown
  397. };
  398. m_scene.AssetService.Store(metadata);
  399. }
  400. else
  401. {
  402. color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  403. }
  404. }
  405. m_colors[face.TextureID] = color;
  406. }
  407. return color * face.RGBA;
  408. }
  409. private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
  410. {
  411. string name = color.ToString();
  412. warp_Material material = renderer.Scene.material(name);
  413. if (material != null)
  414. return name;
  415. renderer.AddMaterial(name, ConvertColor(color));
  416. if (color.A < 1f)
  417. renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
  418. return name;
  419. }
  420. #endregion Rendering Methods
  421. #region Static Helpers
  422. private static warp_Vector ConvertVector(Vector3 vector)
  423. {
  424. return new warp_Vector(vector.X, vector.Z, vector.Y);
  425. }
  426. private static warp_Quaternion ConvertQuaternion(Quaternion quat)
  427. {
  428. return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
  429. }
  430. private static int ConvertColor(Color4 color)
  431. {
  432. int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
  433. if (color.A < 1f)
  434. c |= (byte)(color.A * 255f) << 24;
  435. return c;
  436. }
  437. private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
  438. {
  439. Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
  440. Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
  441. Vector3 normal = Vector3.Cross(edge1, edge2);
  442. normal.Normalize();
  443. return normal;
  444. }
  445. public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
  446. {
  447. ulong r = 0;
  448. ulong g = 0;
  449. ulong b = 0;
  450. ulong a = 0;
  451. using (MemoryStream stream = new MemoryStream(j2kData))
  452. {
  453. try
  454. {
  455. int pixelBytes;
  456. using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
  457. {
  458. width = bitmap.Width;
  459. height = bitmap.Height;
  460. BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
  461. pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
  462. // Sum up the individual channels
  463. unsafe
  464. {
  465. if (pixelBytes == 4)
  466. {
  467. for (int y = 0; y < height; y++)
  468. {
  469. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  470. for (int x = 0; x < width; x++)
  471. {
  472. b += row[x * pixelBytes + 0];
  473. g += row[x * pixelBytes + 1];
  474. r += row[x * pixelBytes + 2];
  475. a += row[x * pixelBytes + 3];
  476. }
  477. }
  478. }
  479. else
  480. {
  481. for (int y = 0; y < height; y++)
  482. {
  483. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  484. for (int x = 0; x < width; x++)
  485. {
  486. b += row[x * pixelBytes + 0];
  487. g += row[x * pixelBytes + 1];
  488. r += row[x * pixelBytes + 2];
  489. }
  490. }
  491. }
  492. }
  493. }
  494. // Get the averages for each channel
  495. const decimal OO_255 = 1m / 255m;
  496. decimal totalPixels = (decimal)(width * height);
  497. decimal rm = ((decimal)r / totalPixels) * OO_255;
  498. decimal gm = ((decimal)g / totalPixels) * OO_255;
  499. decimal bm = ((decimal)b / totalPixels) * OO_255;
  500. decimal am = ((decimal)a / totalPixels) * OO_255;
  501. if (pixelBytes == 3)
  502. am = 1m;
  503. return new Color4((float)rm, (float)gm, (float)bm, (float)am);
  504. }
  505. catch (Exception ex)
  506. {
  507. m_log.WarnFormat(
  508. "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
  509. textureID, j2kData.Length, ex.Message);
  510. width = 0;
  511. height = 0;
  512. return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  513. }
  514. }
  515. }
  516. #endregion Static Helpers
  517. }
  518. public static class ImageUtils
  519. {
  520. /// <summary>
  521. /// Performs bilinear interpolation between four values
  522. /// </summary>
  523. /// <param name="v00">First, or top left value</param>
  524. /// <param name="v01">Second, or top right value</param>
  525. /// <param name="v10">Third, or bottom left value</param>
  526. /// <param name="v11">Fourth, or bottom right value</param>
  527. /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
  528. /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
  529. /// <returns>The bilinearly interpolated result</returns>
  530. public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
  531. {
  532. return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
  533. }
  534. /// <summary>
  535. /// Performs a high quality image resize
  536. /// </summary>
  537. /// <param name="image">Image to resize</param>
  538. /// <param name="width">New width</param>
  539. /// <param name="height">New height</param>
  540. /// <returns>Resized image</returns>
  541. public static Bitmap ResizeImage(Image image, int width, int height)
  542. {
  543. Bitmap result = new Bitmap(width, height);
  544. using (Graphics graphics = Graphics.FromImage(result))
  545. {
  546. graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  547. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  548. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  549. graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  550. graphics.DrawImage(image, 0, 0, result.Width, result.Height);
  551. }
  552. return result;
  553. }
  554. }
  555. }