clockwerk-opensim – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 vero 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  
32 using System;
33 using System.Collections.Generic;
34 using System.Drawing;
35 using System.Drawing.Imaging;
36 using System.IO;
37 using System.Net;
38 using System.Reflection;
39 using System.Threading;
40  
41 using Nini.Config;
42 using log4net;
43 using OpenMetaverse;
44  
45 using OpenSim.Framework;
46 using OpenSim.Framework.Console;
47 using OpenSim.Services.Interfaces;
48  
49  
50 namespace OpenSim.Services.MapImageService
51 {
52 public class MapImageService : IMapImageService
53 {
54 private static readonly ILog m_log =
55 LogManager.GetLogger(
56 MethodBase.GetCurrentMethod().DeclaringType);
57 #pragma warning disable 414
58 private string LogHeader = "[MAP IMAGE SERVICE]";
59 #pragma warning restore 414
60  
61 private const int ZOOM_LEVELS = 8;
62 private const int IMAGE_WIDTH = 256;
63 private const int HALF_WIDTH = 128;
64 private const int JPEG_QUALITY = 80;
65  
66 private static string m_TilesStoragePath = "maptiles";
67  
68 private static object m_Sync = new object();
69 private static bool m_Initialized = false;
70 private static string m_WaterTileFile = string.Empty;
71 private static Color m_Watercolor = Color.FromArgb(29, 71, 95);
72  
73 public MapImageService(IConfigSource config)
74 {
75 if (!m_Initialized)
76 {
77 m_Initialized = true;
78 m_log.Debug("[MAP IMAGE SERVICE]: Starting MapImage service");
79  
80 IConfig serviceConfig = config.Configs["MapImageService"];
81 if (serviceConfig != null)
82 {
83 m_TilesStoragePath = serviceConfig.GetString("TilesStoragePath", m_TilesStoragePath);
84 if (!Directory.Exists(m_TilesStoragePath))
85 Directory.CreateDirectory(m_TilesStoragePath);
86  
87  
88 m_WaterTileFile = Path.Combine(m_TilesStoragePath, "water.jpg");
89 if (!File.Exists(m_WaterTileFile))
90 {
91 Bitmap waterTile = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH);
92 FillImage(waterTile, m_Watercolor);
93 waterTile.Save(m_WaterTileFile, ImageFormat.Jpeg);
94 }
95 }
96 }
97 }
98  
99 #region IMapImageService
100  
101 public bool AddMapTile(int x, int y, byte[] imageData, out string reason)
102 {
103 reason = string.Empty;
104 string fileName = GetFileName(1, x, y);
105  
106 lock (m_Sync)
107 {
108 try
109 {
110 using (FileStream f = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write))
111 f.Write(imageData, 0, imageData.Length);
112 }
113 catch (Exception e)
114 {
115 m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save image file {0}: {1}", fileName, e);
116 reason = e.Message;
117 return false;
118 }
119 }
120  
121 return UpdateMultiResolutionFilesAsync(x, y, out reason);
122 }
123  
124 public bool RemoveMapTile(int x, int y, out string reason)
125 {
126 reason = String.Empty;
127 string fileName = GetFileName(1, x, y);
128  
129 lock (m_Sync)
130 {
131 try
132 {
133 File.Delete(fileName);
134 }
135 catch (Exception e)
136 {
137 m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to save delete file {0}: {1}", fileName, e);
138 reason = e.Message;
139 return false;
140 }
141 }
142  
143 return UpdateMultiResolutionFilesAsync(x, y, out reason);
144 }
145  
146 // When large varregions start up, they can send piles of new map tiles. This causes
147 // this multi-resolution routine to be called a zillion times an causes much CPU
148 // time to be spent creating multi-resolution tiles that will be replaced when
149 // the next maptile arrives.
150 private class mapToMultiRez
151 {
152 public int xx;
153 public int yy;
154 public mapToMultiRez(int pX, int pY)
155 {
156 xx = pX;
157 yy = pY;
158 }
159 };
160 private Queue<mapToMultiRez> multiRezToBuild = new Queue<mapToMultiRez>();
161 private bool UpdateMultiResolutionFilesAsync(int x, int y, out string reason)
162 {
163 reason = String.Empty;
164 lock (multiRezToBuild)
165 {
166 // m_log.DebugFormat("{0} UpdateMultiResolutionFilesAsync: scheduling update for <{1},{2}>", LogHeader, x, y);
167 multiRezToBuild.Enqueue(new mapToMultiRez(x, y));
168 if (multiRezToBuild.Count == 1)
169 Util.FireAndForget(DoUpdateMultiResolutionFilesAsync);
170 }
171  
172 return true;
173 }
174  
175 private void DoUpdateMultiResolutionFilesAsync(object o)
176 {
177 // This sleep causes the FireAndForget thread to be different than the invocation thread.
178 // It also allows other tiles to be uploaded so the multi-rez images are more likely
179 // to be correct.
180 Thread.Sleep(1 * 1000);
181  
182 while (multiRezToBuild.Count > 0)
183 {
184 mapToMultiRez toMultiRez = null;
185 lock (multiRezToBuild)
186 {
187 if (multiRezToBuild.Count > 0)
188 toMultiRez = multiRezToBuild.Dequeue();
189 }
190 if (toMultiRez != null)
191 {
192 int x = toMultiRez.xx;
193 int y = toMultiRez.yy;
194 // m_log.DebugFormat("{0} DoUpdateMultiResolutionFilesAsync: doing build for <{1},{2}>", LogHeader, x, y);
195  
196 // Stitch seven more aggregate tiles together
197 for (uint zoomLevel = 2; zoomLevel <= ZOOM_LEVELS; zoomLevel++)
198 {
199 // Calculate the width (in full resolution tiles) and bottom-left
200 // corner of the current zoom level
201 int width = (int)Math.Pow(2, (double)(zoomLevel - 1));
202 int x1 = x - (x % width);
203 int y1 = y - (y % width);
204  
205 lock (m_Sync) // must lock the reading and writing of the maptile files
206 {
207 if (!CreateTile(zoomLevel, x1, y1))
208 {
209 m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to create tile for {0},{1} at zoom level {1}", x, y, zoomLevel);
210 return;
211 }
212 }
213 }
214 }
215 }
216  
217 return;
218 }
219  
220 public byte[] GetMapTile(string fileName, out string format)
221 {
222 // m_log.DebugFormat("[MAP IMAGE SERVICE]: Getting map tile {0}", fileName);
223  
224 format = ".jpg";
225 string fullName = Path.Combine(m_TilesStoragePath, fileName);
226 if (File.Exists(fullName))
227 {
228 format = Path.GetExtension(fileName).ToLower();
229 //m_log.DebugFormat("[MAP IMAGE SERVICE]: Found file {0}, extension {1}", fileName, format);
230 return File.ReadAllBytes(fullName);
231 }
232 else if (File.Exists(m_WaterTileFile))
233 {
234 return File.ReadAllBytes(m_WaterTileFile);
235 }
236 else
237 {
238 m_log.DebugFormat("[MAP IMAGE SERVICE]: unable to get file {0}", fileName);
239 return new byte[0];
240 }
241 }
242  
243 #endregion
244  
245  
246 private string GetFileName(uint zoomLevel, int x, int y)
247 {
248 string extension = "jpg";
249 return Path.Combine(m_TilesStoragePath, string.Format("map-{0}-{1}-{2}-objects.{3}", zoomLevel, x, y, extension));
250 }
251  
252 private Bitmap GetInputTileImage(string fileName)
253 {
254 try
255 {
256 if (File.Exists(fileName))
257 return new Bitmap(fileName);
258 }
259 catch (Exception e)
260 {
261 m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
262 }
263  
264 return null;
265 }
266  
267 private Bitmap GetOutputTileImage(string fileName)
268 {
269 try
270 {
271 if (File.Exists(fileName))
272 return new Bitmap(fileName);
273  
274 else
275 {
276 // Create a new output tile with a transparent background
277 Bitmap bm = new Bitmap(IMAGE_WIDTH, IMAGE_WIDTH, PixelFormat.Format24bppRgb);
278 bm.MakeTransparent();
279 return bm;
280 }
281 }
282 catch (Exception e)
283 {
284 m_log.WarnFormat("[MAP IMAGE SERVICE]: Unable to read image data from {0}: {1}", fileName, e);
285 }
286  
287 return null;
288 }
289  
290 private bool CreateTile(uint zoomLevel, int x, int y)
291 {
292 // m_log.DebugFormat("[MAP IMAGE SERVICE]: Create tile for {0} {1}, zoom {2}", x, y, zoomLevel);
293 int prevWidth = (int)Math.Pow(2, (double)zoomLevel - 2);
294 int thisWidth = (int)Math.Pow(2, (double)zoomLevel - 1);
295  
296 // Convert x and y to the bottom left tile for this zoom level
297 int xIn = x - (x % prevWidth);
298 int yIn = y - (y % prevWidth);
299  
300 // Convert x and y to the bottom left tile for the next zoom level
301 int xOut = x - (x % thisWidth);
302 int yOut = y - (y % thisWidth);
303  
304 // Try to open the four input tiles from the previous zoom level
305 Bitmap inputBL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn));
306 Bitmap inputBR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn));
307 Bitmap inputTL = GetInputTileImage(GetFileName(zoomLevel - 1, xIn, yIn + prevWidth));
308 Bitmap inputTR = GetInputTileImage(GetFileName(zoomLevel - 1, xIn + prevWidth, yIn + prevWidth));
309  
310 // Open the output tile (current zoom level)
311 string outputFile = GetFileName(zoomLevel, xOut, yOut);
312 Bitmap output = GetOutputTileImage(outputFile);
313 if (output == null)
314 return false;
315 FillImage(output, m_Watercolor);
316  
317 if (inputBL != null)
318 {
319 ImageCopyResampled(output, inputBL, 0, HALF_WIDTH, 0, 0);
320 inputBL.Dispose();
321 }
322 if (inputBR != null)
323 {
324 ImageCopyResampled(output, inputBR, HALF_WIDTH, HALF_WIDTH, 0, 0);
325 inputBR.Dispose();
326 }
327 if (inputTL != null)
328 {
329 ImageCopyResampled(output, inputTL, 0, 0, 0, 0);
330 inputTL.Dispose();
331 }
332 if (inputTR != null)
333 {
334 ImageCopyResampled(output, inputTR, HALF_WIDTH, 0, 0, 0);
335 inputTR.Dispose();
336 }
337  
338 // Write the modified output
339 try
340 {
341 using (Bitmap final = new Bitmap(output))
342 {
343 output.Dispose();
344 final.Save(outputFile, ImageFormat.Jpeg);
345 }
346 }
347 catch (Exception e)
348 {
349 m_log.WarnFormat("[MAP IMAGE SERVICE]: Oops on saving {0} {1}", outputFile, e);
350 }
351  
352 // Save also as png?
353  
354 return true;
355 }
356  
357 #region Image utilities
358  
359 private void FillImage(Bitmap bm, Color c)
360 {
361 for (int x = 0; x < bm.Width; x++)
362 for (int y = 0; y < bm.Height; y++)
363 bm.SetPixel(x, y, c);
364 }
365  
366 private void ImageCopyResampled(Bitmap output, Bitmap input, int destX, int destY, int srcX, int srcY)
367 {
368 int resamplingRateX = 2; // (input.Width - srcX) / (output.Width - destX);
369 int resamplingRateY = 2; // (input.Height - srcY) / (output.Height - destY);
370  
371 for (int x = destX; x < destX + HALF_WIDTH; x++)
372 for (int y = destY; y < destY + HALF_WIDTH; y++)
373 {
374 Color p = input.GetPixel(srcX + (x - destX) * resamplingRateX, srcY + (y - destY) * resamplingRateY);
375 output.SetPixel(x, y, p);
376 }
377 }
378  
379 #endregion
380 }
381 }