MapImageServiceModule.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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.Reflection;
  30. using System.Net;
  31. using System.IO;
  32. using System.Timers;
  33. using System.Drawing;
  34. using System.Drawing.Imaging;
  35. using log4net;
  36. using Mono.Addins;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Services.Interfaces;
  42. using OpenSim.Server.Base;
  43. using OpenMetaverse;
  44. using OpenMetaverse.StructuredData;
  45. namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage
  46. {
  47. /// <summary>
  48. /// </summary>
  49. /// <remarks>
  50. /// </remarks>
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageServiceModule")]
  52. public class MapImageServiceModule : IMapImageUploadModule, ISharedRegionModule
  53. {
  54. private static readonly ILog m_log =
  55. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. private static string LogHeader = "[MAP IMAGE SERVICE MODULE]:";
  57. private bool m_enabled = false;
  58. private IMapImageService m_MapService;
  59. private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
  60. private int m_refreshtime = 0;
  61. private int m_lastrefresh = 0;
  62. private System.Timers.Timer m_refreshTimer;
  63. #region ISharedRegionModule
  64. public Type ReplaceableInterface { get { return null; } }
  65. public string Name { get { return "MapImageServiceModule"; } }
  66. public void RegionLoaded(Scene scene) { }
  67. public void Close() { }
  68. public void PostInitialise() { }
  69. ///<summary>
  70. ///
  71. ///</summary>
  72. public void Initialise(IConfigSource source)
  73. {
  74. IConfig moduleConfig = source.Configs["Modules"];
  75. if (moduleConfig != null)
  76. {
  77. string name = moduleConfig.GetString("MapImageService", "");
  78. if (name != Name)
  79. return;
  80. }
  81. IConfig config = source.Configs["MapImageService"];
  82. if (config == null)
  83. return;
  84. int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime"));
  85. // if refresh is less than zero, disable the module
  86. if (refreshminutes < 0)
  87. {
  88. m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Negative refresh time given in config. Module disabled.");
  89. return;
  90. }
  91. string service = config.GetString("LocalServiceModule", string.Empty);
  92. if (service == string.Empty)
  93. {
  94. m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No service dll given in config. Unable to proceed.");
  95. return;
  96. }
  97. Object[] args = new Object[] { source };
  98. m_MapService = ServerUtils.LoadPlugin<IMapImageService>(service, args);
  99. if (m_MapService == null)
  100. {
  101. m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Unable to load LocalServiceModule from {0}. MapService module disabled. Please fix the configuration.", service);
  102. return;
  103. }
  104. // we don't want the timer if the interval is zero, but we still want this module enables
  105. if(refreshminutes > 0)
  106. {
  107. m_refreshtime = refreshminutes * 60 * 1000; // convert from minutes to ms
  108. m_refreshTimer = new System.Timers.Timer();
  109. m_refreshTimer.Enabled = true;
  110. m_refreshTimer.AutoReset = true;
  111. m_refreshTimer.Interval = m_refreshtime;
  112. m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh);
  113. m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0} min and service object {1}",
  114. refreshminutes, service);
  115. }
  116. else
  117. {
  118. m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with no refresh and service object {0}", service);
  119. }
  120. m_enabled = true;
  121. }
  122. ///<summary>
  123. ///
  124. ///</summary>
  125. public void AddRegion(Scene scene)
  126. {
  127. if (!m_enabled)
  128. return;
  129. // Every shared region module has to maintain an indepedent list of
  130. // currently running regions
  131. lock (m_scenes)
  132. m_scenes[scene.RegionInfo.RegionID] = scene;
  133. // v2 Map generation on startup is now handled by scene to allow bmp to be shared with
  134. // v1 service and not generate map tiles twice as was previous behavior
  135. //scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) UploadMapTile(s); };
  136. scene.RegisterModuleInterface<IMapImageUploadModule>(this);
  137. }
  138. ///<summary>
  139. ///
  140. ///</summary>
  141. public void RemoveRegion(Scene scene)
  142. {
  143. if (! m_enabled)
  144. return;
  145. lock (m_scenes)
  146. m_scenes.Remove(scene.RegionInfo.RegionID);
  147. }
  148. #endregion ISharedRegionModule
  149. ///<summary>
  150. ///
  151. ///</summary>
  152. private void HandleMaptileRefresh(object sender, EventArgs ea)
  153. {
  154. // this approach is a bit convoluted becase we want to wait for the
  155. // first upload to happen on startup but after all the objects are
  156. // loaded and initialized
  157. if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime)
  158. return;
  159. m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: map refresh!");
  160. lock (m_scenes)
  161. {
  162. foreach (IScene scene in m_scenes.Values)
  163. {
  164. try
  165. {
  166. UploadMapTile(scene);
  167. }
  168. catch (Exception ex)
  169. {
  170. m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: something bad happened {0}", ex.Message);
  171. }
  172. }
  173. }
  174. m_lastrefresh = Util.EnvironmentTickCount();
  175. }
  176. public void UploadMapTile(IScene scene, Bitmap mapTile)
  177. {
  178. if (mapTile == null)
  179. {
  180. m_log.WarnFormat("{0} Cannot upload null image", LogHeader);
  181. return;
  182. }
  183. m_log.DebugFormat("{0} Upload maptile for {1}", LogHeader, scene.Name);
  184. // mapTile.Save( // DEBUG DEBUG
  185. // String.Format("maptiles/raw-{0}-{1}-{2}.jpg", regionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY),
  186. // ImageFormat.Jpeg);
  187. // If the region/maptile is legacy sized, just upload the one tile like it has always been done
  188. if (mapTile.Width == Constants.RegionSize && mapTile.Height == Constants.RegionSize)
  189. {
  190. ConvertAndUploadMaptile(mapTile,
  191. scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY,
  192. scene.RegionInfo.RegionName);
  193. }
  194. else
  195. {
  196. // For larger regions (varregion) we must cut the region image into legacy sized
  197. // pieces since that is how the maptile system works.
  198. // Note the assumption that varregions are always a multiple of legacy size.
  199. for (uint xx = 0; xx < mapTile.Width; xx += Constants.RegionSize)
  200. {
  201. for (uint yy = 0; yy < mapTile.Height; yy += Constants.RegionSize)
  202. {
  203. // Images are addressed from the upper left corner so have to do funny
  204. // math to pick out the sub-tile since regions are numbered from
  205. // the lower left.
  206. Rectangle rect = new Rectangle(
  207. (int)xx,
  208. mapTile.Height - (int)yy - (int)Constants.RegionSize,
  209. (int)Constants.RegionSize, (int)Constants.RegionSize);
  210. using (Bitmap subMapTile = mapTile.Clone(rect, mapTile.PixelFormat))
  211. {
  212. ConvertAndUploadMaptile(subMapTile,
  213. scene.RegionInfo.RegionLocX + (xx / Constants.RegionSize),
  214. scene.RegionInfo.RegionLocY + (yy / Constants.RegionSize),
  215. scene.Name);
  216. }
  217. }
  218. }
  219. }
  220. }
  221. ///<summary>
  222. ///
  223. ///</summary>
  224. private void UploadMapTile(IScene scene)
  225. {
  226. // Create a JPG map tile and upload it to the AddMapTile API
  227. IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>();
  228. if (tileGenerator == null)
  229. {
  230. m_log.WarnFormat("{0} Cannot upload map tile without an ImageGenerator", LogHeader);
  231. return;
  232. }
  233. using (Bitmap mapTile = tileGenerator.CreateMapTile())
  234. {
  235. if (mapTile != null)
  236. {
  237. UploadMapTile(scene, mapTile);
  238. }
  239. else
  240. {
  241. m_log.WarnFormat("{0} Tile image generation failed", LogHeader);
  242. }
  243. }
  244. }
  245. private void ConvertAndUploadMaptile(Image tileImage, uint locX, uint locY, string regionName)
  246. {
  247. byte[] jpgData = Utils.EmptyBytes;
  248. using (MemoryStream stream = new MemoryStream())
  249. {
  250. tileImage.Save(stream, ImageFormat.Jpeg);
  251. jpgData = stream.ToArray();
  252. }
  253. if (jpgData != Utils.EmptyBytes)
  254. {
  255. string reason = string.Empty;
  256. if (!m_MapService.AddMapTile((int)locX, (int)locY, jpgData, out reason))
  257. {
  258. m_log.DebugFormat("{0} Unable to upload tile image for {1} at {2}-{3}: {4}", LogHeader,
  259. regionName, locX, locY, reason);
  260. }
  261. }
  262. else
  263. {
  264. m_log.WarnFormat("{0} Tile image generation failed for region {1}", LogHeader, regionName);
  265. }
  266. }
  267. }
  268. }