MapImageModule.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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 OpenMetaverse;
  38. using OpenMetaverse.Imaging;
  39. using OpenMetaverse.Rendering;
  40. using OpenMetaverse.StructuredData;
  41. using OpenSim.Framework;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes;
  44. using OpenSim.Region.Physics.Manager;
  45. using OpenSim.Services.Interfaces;
  46. using WarpRenderer = global::Warp3D.Warp3D;
  47. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  48. {
  49. public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
  50. {
  51. private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
  52. private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
  53. private static readonly ILog m_log =
  54. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  55. private Scene m_scene;
  56. private IRendering m_primMesher;
  57. private IConfigSource m_config;
  58. private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
  59. private bool m_useAntiAliasing = false; // TODO: Make this a config option
  60. private bool m_Enabled = false;
  61. #region IRegionModule Members
  62. public void Initialise(IConfigSource source)
  63. {
  64. m_config = source;
  65. IConfig startupConfig = m_config.Configs["Startup"];
  66. if (startupConfig.GetString("MapImageModule", "MapImageModule") != "Warp3DImageModule")
  67. return;
  68. m_Enabled = true;
  69. }
  70. public void AddRegion(Scene scene)
  71. {
  72. if (!m_Enabled)
  73. return;
  74. m_scene = scene;
  75. List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
  76. if (renderers.Count > 0)
  77. {
  78. m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
  79. m_log.Info("[MAPTILE]: Loaded prim mesher " + m_primMesher.ToString());
  80. }
  81. else
  82. {
  83. m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
  84. }
  85. m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
  86. }
  87. public void RegionLoaded(Scene scene)
  88. {
  89. }
  90. public void RemoveRegion(Scene scene)
  91. {
  92. }
  93. public void Close()
  94. {
  95. }
  96. public string Name
  97. {
  98. get { return "Warp3DImageModule"; }
  99. }
  100. public Type ReplaceableInterface
  101. {
  102. get { return null; }
  103. }
  104. #endregion
  105. #region IMapImageGenerator Members
  106. public Bitmap CreateMapTile()
  107. {
  108. Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
  109. Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize);
  110. return CreateMapTile(viewport, false);
  111. }
  112. public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
  113. {
  114. Viewport viewport = new Viewport(camPos, camDir, fov, (float)Constants.RegionSize, 0.1f, width, height);
  115. return CreateMapTile(viewport, useTextures);
  116. }
  117. public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
  118. {
  119. bool drawPrimVolume = true;
  120. bool textureTerrain = true;
  121. try
  122. {
  123. IConfig startupConfig = m_config.Configs["Startup"];
  124. drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
  125. textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
  126. }
  127. catch
  128. {
  129. m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
  130. }
  131. m_colors.Clear();
  132. int width = viewport.Width;
  133. int height = viewport.Height;
  134. if (m_useAntiAliasing)
  135. {
  136. width *= 2;
  137. height *= 2;
  138. }
  139. WarpRenderer renderer = new WarpRenderer();
  140. renderer.CreateScene(width, height);
  141. renderer.Scene.autoCalcNormals = false;
  142. #region Camera
  143. warp_Vector pos = ConvertVector(viewport.Position);
  144. pos.z -= 0.001f; // Works around an issue with the Warp3D camera
  145. warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
  146. renderer.Scene.defaultCamera.setPos(pos);
  147. renderer.Scene.defaultCamera.lookAt(lookat);
  148. if (viewport.Orthographic)
  149. {
  150. renderer.Scene.defaultCamera.isOrthographic = true;
  151. renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
  152. renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
  153. }
  154. else
  155. {
  156. float fov = viewport.FieldOfView;
  157. fov *= 1.75f; // FIXME: ???
  158. renderer.Scene.defaultCamera.setFov(fov);
  159. }
  160. #endregion Camera
  161. renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
  162. renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
  163. CreateWater(renderer);
  164. CreateTerrain(renderer, textureTerrain);
  165. if (drawPrimVolume)
  166. CreateAllPrims(renderer, useTextures);
  167. renderer.Render();
  168. Bitmap bitmap = renderer.Scene.getImage();
  169. if (m_useAntiAliasing)
  170. bitmap = ImageUtils.ResizeImage(bitmap, viewport.Width, viewport.Height);
  171. return bitmap;
  172. }
  173. public byte[] WriteJpeg2000Image()
  174. {
  175. try
  176. {
  177. using (Bitmap mapbmp = CreateMapTile())
  178. return OpenJPEG.EncodeFromImage(mapbmp, true);
  179. }
  180. catch (Exception e)
  181. {
  182. // JPEG2000 encoder failed
  183. m_log.Error("[MAPTILE]: Failed generating terrain map: " + e);
  184. }
  185. return null;
  186. }
  187. #endregion
  188. #region Rendering Methods
  189. private void CreateWater(WarpRenderer renderer)
  190. {
  191. float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
  192. renderer.AddPlane("Water", 256f * 0.5f);
  193. renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f);
  194. renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR));
  195. renderer.Scene.material("WaterColor").setReflectivity(0); // match water color with standard map module thanks lkalif
  196. renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
  197. renderer.SetObjectMaterial("Water", "WaterColor");
  198. }
  199. private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
  200. {
  201. ITerrainChannel terrain = m_scene.Heightmap;
  202. float[] heightmap = terrain.GetFloatsSerialised();
  203. warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
  204. for (int y = 0; y < 256; y++)
  205. {
  206. for (int x = 0; x < 256; x++)
  207. {
  208. int v = y * 256 + x;
  209. float height = heightmap[v];
  210. warp_Vector pos = ConvertVector(new Vector3(x, y, height));
  211. obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f));
  212. }
  213. }
  214. for (int y = 0; y < 256; y++)
  215. {
  216. for (int x = 0; x < 256; x++)
  217. {
  218. if (x < 255 && y < 255)
  219. {
  220. int v = y * 256 + x;
  221. // Normal
  222. Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]);
  223. Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]);
  224. Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]);
  225. warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
  226. norm = norm.reverse();
  227. obj.vertex(v).n = norm;
  228. // Triangle 1
  229. obj.addTriangle(
  230. v,
  231. v + 1,
  232. v + 256);
  233. // Triangle 2
  234. obj.addTriangle(
  235. v + 256 + 1,
  236. v + 256,
  237. v + 1);
  238. }
  239. }
  240. }
  241. renderer.Scene.addObject("Terrain", obj);
  242. UUID[] textureIDs = new UUID[4];
  243. float[] startHeights = new float[4];
  244. float[] heightRanges = new float[4];
  245. RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
  246. textureIDs[0] = regionInfo.TerrainTexture1;
  247. textureIDs[1] = regionInfo.TerrainTexture2;
  248. textureIDs[2] = regionInfo.TerrainTexture3;
  249. textureIDs[3] = regionInfo.TerrainTexture4;
  250. startHeights[0] = (float)regionInfo.Elevation1SW;
  251. startHeights[1] = (float)regionInfo.Elevation1NW;
  252. startHeights[2] = (float)regionInfo.Elevation1SE;
  253. startHeights[3] = (float)regionInfo.Elevation1NE;
  254. heightRanges[0] = (float)regionInfo.Elevation2SW;
  255. heightRanges[1] = (float)regionInfo.Elevation2NW;
  256. heightRanges[2] = (float)regionInfo.Elevation2SE;
  257. heightRanges[3] = (float)regionInfo.Elevation2NE;
  258. uint globalX, globalY;
  259. Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
  260. Bitmap image = TerrainSplat.Splat(heightmap, textureIDs, startHeights, heightRanges, new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain);
  261. warp_Texture texture = new warp_Texture(image);
  262. warp_Material material = new warp_Material(texture);
  263. material.setReflectivity(50);
  264. renderer.Scene.addMaterial("TerrainColor", material);
  265. renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
  266. renderer.SetObjectMaterial("Terrain", "TerrainColor");
  267. }
  268. private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
  269. {
  270. if (m_primMesher == null)
  271. return;
  272. m_scene.ForEachSOG(
  273. delegate(SceneObjectGroup group)
  274. {
  275. CreatePrim(renderer, group.RootPart, useTextures);
  276. foreach (SceneObjectPart child in group.Parts)
  277. CreatePrim(renderer, child, useTextures);
  278. }
  279. );
  280. }
  281. private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
  282. bool useTextures)
  283. {
  284. const float MIN_SIZE = 2f;
  285. if ((PCode)prim.Shape.PCode != PCode.Prim)
  286. return;
  287. if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
  288. return;
  289. Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
  290. FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
  291. if (renderMesh == null)
  292. return;
  293. warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
  294. warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
  295. warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
  296. if (prim.ParentID != 0)
  297. {
  298. SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
  299. if (group != null)
  300. m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
  301. }
  302. warp_Vector primScale = ConvertVector(prim.Scale);
  303. string primID = prim.UUID.ToString();
  304. // Create the prim faces
  305. // TODO: Implement the useTextures flag behavior
  306. for (int i = 0; i < renderMesh.Faces.Count; i++)
  307. {
  308. Face face = renderMesh.Faces[i];
  309. string meshName = primID + "-Face-" + i.ToString();
  310. // Avoid adding duplicate meshes to the scene
  311. if (renderer.Scene.objectData.ContainsKey(meshName))
  312. {
  313. continue;
  314. }
  315. warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
  316. for (int j = 0; j < face.Vertices.Count; j++)
  317. {
  318. Vertex v = face.Vertices[j];
  319. warp_Vector pos = ConvertVector(v.Position);
  320. warp_Vector norm = ConvertVector(v.Normal);
  321. if (prim.Shape.SculptTexture == UUID.Zero)
  322. norm = norm.reverse();
  323. warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
  324. faceObj.addVertex(vert);
  325. }
  326. for (int j = 0; j < face.Indices.Count; j += 3)
  327. {
  328. faceObj.addTriangle(
  329. face.Indices[j + 0],
  330. face.Indices[j + 1],
  331. face.Indices[j + 2]);
  332. }
  333. Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
  334. Color4 faceColor = GetFaceColor(teFace);
  335. string materialName = GetOrCreateMaterial(renderer, faceColor);
  336. faceObj.transform(m);
  337. faceObj.setPos(primPos);
  338. faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
  339. renderer.Scene.addObject(meshName, faceObj);
  340. renderer.SetObjectMaterial(meshName, materialName);
  341. }
  342. }
  343. private Color4 GetFaceColor(Primitive.TextureEntryFace face)
  344. {
  345. Color4 color;
  346. if (face.TextureID == UUID.Zero)
  347. return face.RGBA;
  348. if (!m_colors.TryGetValue(face.TextureID, out color))
  349. {
  350. bool fetched = false;
  351. // Attempt to fetch the texture metadata
  352. UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
  353. AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
  354. if (metadata != null)
  355. {
  356. OSDMap map = null;
  357. try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
  358. if (map != null)
  359. {
  360. color = map["X-JPEG2000-RGBA"].AsColor4();
  361. fetched = true;
  362. }
  363. }
  364. if (!fetched)
  365. {
  366. // Fetch the texture, decode and get the average color,
  367. // then save it to a temporary metadata asset
  368. AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
  369. if (textureAsset != null)
  370. {
  371. int width, height;
  372. color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
  373. OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
  374. metadata = new AssetBase
  375. {
  376. Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
  377. Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
  378. Flags = AssetFlags.Collectable,
  379. FullID = metadataID,
  380. ID = metadataID.ToString(),
  381. Local = true,
  382. Temporary = true,
  383. Name = String.Empty,
  384. Type = (sbyte)AssetType.Unknown
  385. };
  386. m_scene.AssetService.Store(metadata);
  387. }
  388. else
  389. {
  390. color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  391. }
  392. }
  393. m_colors[face.TextureID] = color;
  394. }
  395. return color * face.RGBA;
  396. }
  397. private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
  398. {
  399. string name = color.ToString();
  400. warp_Material material = renderer.Scene.material(name);
  401. if (material != null)
  402. return name;
  403. renderer.AddMaterial(name, ConvertColor(color));
  404. if (color.A < 1f)
  405. renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
  406. return name;
  407. }
  408. #endregion Rendering Methods
  409. #region Static Helpers
  410. private static warp_Vector ConvertVector(Vector3 vector)
  411. {
  412. return new warp_Vector(vector.X, vector.Z, vector.Y);
  413. }
  414. private static warp_Quaternion ConvertQuaternion(Quaternion quat)
  415. {
  416. return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
  417. }
  418. private static int ConvertColor(Color4 color)
  419. {
  420. int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
  421. if (color.A < 1f)
  422. c |= (byte)(color.A * 255f) << 24;
  423. return c;
  424. }
  425. private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
  426. {
  427. Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
  428. Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
  429. Vector3 normal = Vector3.Cross(edge1, edge2);
  430. normal.Normalize();
  431. return normal;
  432. }
  433. public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
  434. {
  435. ulong r = 0;
  436. ulong g = 0;
  437. ulong b = 0;
  438. ulong a = 0;
  439. using (MemoryStream stream = new MemoryStream(j2kData))
  440. {
  441. try
  442. {
  443. Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream);
  444. width = bitmap.Width;
  445. height = bitmap.Height;
  446. BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
  447. int pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
  448. // Sum up the individual channels
  449. unsafe
  450. {
  451. if (pixelBytes == 4)
  452. {
  453. for (int y = 0; y < height; y++)
  454. {
  455. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  456. for (int x = 0; x < width; x++)
  457. {
  458. b += row[x * pixelBytes + 0];
  459. g += row[x * pixelBytes + 1];
  460. r += row[x * pixelBytes + 2];
  461. a += row[x * pixelBytes + 3];
  462. }
  463. }
  464. }
  465. else
  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. }
  476. }
  477. }
  478. }
  479. // Get the averages for each channel
  480. const decimal OO_255 = 1m / 255m;
  481. decimal totalPixels = (decimal)(width * height);
  482. decimal rm = ((decimal)r / totalPixels) * OO_255;
  483. decimal gm = ((decimal)g / totalPixels) * OO_255;
  484. decimal bm = ((decimal)b / totalPixels) * OO_255;
  485. decimal am = ((decimal)a / totalPixels) * OO_255;
  486. if (pixelBytes == 3)
  487. am = 1m;
  488. return new Color4((float)rm, (float)gm, (float)bm, (float)am);
  489. }
  490. catch (Exception ex)
  491. {
  492. m_log.WarnFormat("[MAPTILE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}", textureID, j2kData.Length, ex.Message);
  493. width = 0;
  494. height = 0;
  495. return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  496. }
  497. }
  498. }
  499. #endregion Static Helpers
  500. }
  501. public static class ImageUtils
  502. {
  503. /// <summary>
  504. /// Performs bilinear interpolation between four values
  505. /// </summary>
  506. /// <param name="v00">First, or top left value</param>
  507. /// <param name="v01">Second, or top right value</param>
  508. /// <param name="v10">Third, or bottom left value</param>
  509. /// <param name="v11">Fourth, or bottom right value</param>
  510. /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
  511. /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
  512. /// <returns>The bilinearly interpolated result</returns>
  513. public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
  514. {
  515. return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
  516. }
  517. /// <summary>
  518. /// Performs a high quality image resize
  519. /// </summary>
  520. /// <param name="image">Image to resize</param>
  521. /// <param name="width">New width</param>
  522. /// <param name="height">New height</param>
  523. /// <returns>Resized image</returns>
  524. public static Bitmap ResizeImage(Image image, int width, int height)
  525. {
  526. Bitmap result = new Bitmap(width, height);
  527. using (Graphics graphics = Graphics.FromImage(result))
  528. {
  529. graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  530. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  531. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  532. graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  533. graphics.DrawImage(image, 0, 0, result.Width, result.Height);
  534. }
  535. return result;
  536. }
  537. }
  538. }