MapImageService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. * The design of this map service is based on SimianGrid's PHP-based
  28. * map service. See this URL for the original PHP version:
  29. * https://github.com/openmetaversefoundation/simiangrid/
  30. */
  31. using System;
  32. using System.Collections.Generic;
  33. using System.Drawing;
  34. using System.Drawing.Imaging;
  35. using System.IO;
  36. using System.Net;
  37. using System.Reflection;
  38. using Nini.Config;
  39. using log4net;
  40. using OpenMetaverse;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Console;
  43. using OpenSim.Services.Interfaces;
  44. namespace OpenSim.Services.MapImageService
  45. {
  46. public class MapImageService : IMapImageService
  47. {
  48. private static readonly ILog m_log =
  49. LogManager.GetLogger(
  50. MethodBase.GetCurrentMethod().DeclaringType);
  51. private const int ZOOM_LEVELS = 8;
  52. private const int IMAGE_WIDTH = 256;
  53. private const int HALF_WIDTH = 128;
  54. private const int JPEG_QUALITY = 80;
  55. private static string m_TilesStoragePath = "maptiles";
  56. private static object m_Sync = new object();
  57. private static bool m_Initialized = false;
  58. private static string m_WaterTileFile = string.Empty;
  59. private static Color m_Watercolor = Color.FromArgb(29, 71, 95);
  60. public MapImageService(IConfigSource config)
  61. {
  62. if (!m_Initialized)
  63. {
  64. m_Initialized = true;
  65. m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service");
  66. IConfig serviceConfig = config.Configs["MapImageService"];
  67. if (serviceConfig != null)
  68. {
  69. m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath);
  70. if (!Directory.Exists(m_TilesStoragePath))
  71. Directory.CreateDirectory(m_TilesStoragePath);
  72. m_WaterTileFile = Path.Combine(m_TilesStoragePath, "water.jpg");
  73. if (!File.Exists(m_WaterTileFile))
  74. {
  75. Bitmap waterTile = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH);
  76. FillImage(waterTile, m_Watercolor);
  77. waterTile.Save(m_WaterTileFile, ImageFormat.Jpeg);
  78. }
  79. }
  80. }
  81. }
  82. #region IMapImageService
  83. public bool AddMapTile(int x, int y, byte[] imageData, out string reason)
  84. {
  85. reason = string.Empty;
  86. string fileName = GetFileName(1, x, y);
  87. lock (m_Sync)
  88. {
  89. try
  90. {
  91. using (FileStream f = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write))
  92. f.Write(imageData, 0, imageData.Length);
  93. }
  94. catch (Exception e)
  95. {
  96. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save image file {0}: {1}", fileName, e);
  97. reason = e.Message;
  98. return false;
  99. }
  100. }
  101. return UpdateMultiResolutionFiles(x, y, out reason);
  102. }
  103. public bool RemoveMapTile(int x, int y, out string reason)
  104. {
  105. reason = String.Empty;
  106. string fileName = GetFileName(1, x, y);
  107. lock (m_Sync)
  108. {
  109. try
  110. {
  111. File.Delete(fileName);
  112. }
  113. catch (Exception e)
  114. {
  115. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save delete file {0}: {1}", fileName, e);
  116. reason = e.Message;
  117. return false;
  118. }
  119. }
  120. return UpdateMultiResolutionFiles(x, y, out reason);
  121. }
  122. private bool UpdateMultiResolutionFiles(int x, int y, out string reason)
  123. {
  124. reason = String.Empty;
  125. lock (m_Sync)
  126. {
  127. // Stitch seven more aggregate tiles together
  128. for (uint zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++)
  129. {
  130. // Calculate the width (in full resolution tiles) and bottom-left
  131. // corner of the current zoom level
  132. int width = (int)Math.Pow(2, (double)(zoomLevel - 1));
  133. int x1 = x - (x % width);
  134. int y1 = y - (y % width);
  135. if (!CreateTile(zoomLevel, x1, y1))
  136. {
  137. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0},{1} at zoom level {1}", x, y, zoomLevel);
  138. reason = string.Format("Map tile at zoom level {0} failed", zoomLevel);
  139. return false;
  140. }
  141. }
  142. }
  143. return true;
  144. }
  145. public byte[] GetMapTile(string fileName, out string format)
  146. {
  147. // m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName);
  148. format = ".jpg";
  149. string fullName = Path.Combine(m_TilesStoragePath, fileName);
  150. if (File.Exists(fullName))
  151. {
  152. format = Path.GetExtension(fileName).ToLower();
  153. //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
  154. return File.ReadAllBytes(fullName);
  155. }
  156. else if (File.Exists(m_WaterTileFile))
  157. {
  158. return File.ReadAllBytes(m_WaterTileFile);
  159. }
  160. else
  161. {
  162. m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName);
  163. return new byte[0];
  164. }
  165. }
  166. #endregion
  167. private string GetFileName(uint zoomLevel, int x, int y)
  168. {
  169. string extension = "jpg";
  170. return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension));
  171. }
  172. private Bitmap GetInputTileImage(string fileName)
  173. {
  174. try
  175. {
  176. if (File.Exists(fileName))
  177. return new Bitmap(fileName);
  178. }
  179. catch (Exception e)
  180. {
  181. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  182. }
  183. return null;
  184. }
  185. private Bitmap GetOutputTileImage(string fileName)
  186. {
  187. try
  188. {
  189. if (File.Exists(fileName))
  190. return new Bitmap(fileName);
  191. else
  192. {
  193. // Create a new output tile with a transparent background
  194. Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
  195. bm.MakeTransparent();
  196. return bm;
  197. }
  198. }
  199. catch (Exception e)
  200. {
  201. m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
  202. }
  203. return null;
  204. }
  205. private bool CreateTile(uint zoomLevel, int x, int y)
  206. {
  207. // m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel);
  208. int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2);
  209. int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1);
  210. // Convert x and y to the bottom left tile for this zoom level
  211. int xIn = x - (x % prevWidth);
  212. int yIn = y - (y % prevWidth);
  213. // Convert x and y to the bottom left tile for the next zoom level
  214. int xOut = x - (x % thisWidth);
  215. int yOut = y - (y % thisWidth);
  216. // Try to open the four input tiles from the previous zoom level
  217. Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn));
  218. Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn));
  219. Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth));
  220. Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth));
  221. // Open the output tile (current zoom level)
  222. string outputFile = GetFileName(zoomLevel, xOut, yOut);
  223. Bitmap output = GetOutputTileImage(outputFile);
  224. if (output == null)
  225. return false;
  226. FillImage(output, m_Watercolor);
  227. if (inputBL != null)
  228. {
  229. ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0);
  230. inputBL.Dispose();
  231. }
  232. if (inputBR != null)
  233. {
  234. ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0);
  235. inputBR.Dispose();
  236. }
  237. if (inputTL != null)
  238. {
  239. ImageCopyResampled(output, inputTL, 0, 0, 0, 0);
  240. inputTL.Dispose();
  241. }
  242. if (inputTR != null)
  243. {
  244. ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0);
  245. inputTR.Dispose();
  246. }
  247. // Write the modified output
  248. try
  249. {
  250. using (Bitmap final = new Bitmap(output))
  251. {
  252. output.Dispose();
  253. final.Save(outputFile, ImageFormat.Jpeg);
  254. }
  255. }
  256. catch (Exception e)
  257. {
  258. m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e);
  259. }
  260. // Save also as png?
  261. return true;
  262. }
  263. #region Image utilities
  264. private void FillImage(Bitmap bm, Color c)
  265. {
  266. for (int x = 0; x < bm.Width; x++)
  267. for (int y = 0; y < bm.Height; y++)
  268. bm.SetPixel(x, y, c);
  269. }
  270. private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY)
  271. {
  272. int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX);
  273. int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY);
  274. for (int x = destX; x < destX + HALF_WIDTH; x++)
  275. for (int y = destY; y < destY + HALF_WIDTH; y++)
  276. {
  277. Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY);
  278. output.SetPixel(x, y, p);
  279. }
  280. }
  281. #endregion
  282. }
  283. }