-
Notifications
You must be signed in to change notification settings - Fork 305
Expand file tree
/
Copy pathTileLayer.cs
More file actions
412 lines (356 loc) · 16.5 KB
/
TileLayer.cs
File metadata and controls
412 lines (356 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Threading;
using BruTile;
using BruTile.Cache;
using BruTile.Web;
using Common.Logging;
using GeoAPI.Geometries;
using SharpMap.Base;
namespace SharpMap.Layers
{
//ReSharper disable InconsistentNaming
///<summary>
/// Tile layer class
///</summary>
[Serializable]
public class TileLayer : Layer, IDeserializationCallback
{
private static readonly ILog Logger = LogManager.GetLogger<TileLayer>();
#region Fields
//string layerName;
///// <summary>
///// The <see cref="ImageAttributes"/> used when rendering the tiles
///// </summary>
//protected readonly ImageAttributes _imageAttributes = new ImageAttributes();
/// <summary>
/// The tile source for this layer
/// </summary>
protected readonly ITileSource _source;
/// <summary>
/// An in-memory tile cache
/// </summary>
[NonSerialized]
protected MemoryCache<Bitmap> _bitmaps = new MemoryCache<Bitmap>(100, 200);
/// <summary>
/// A file cache
/// </summary>
protected FileCache _fileCache;
/// <summary>
/// The format of the images
/// </summary>
protected ImageFormat _ImageFormat;
/// <summary>
/// Value indicating if "error" tiles should be generated or not.
/// </summary>
protected readonly bool _showErrorInTile;
InterpolationMode _interpolationMode = InterpolationMode.HighQualityBicubic;
/// <summary>
/// Color that is treated as a placeholder for transparency
/// </summary>
protected Color _transparentColor;
//System.Collections.Hashtable _cacheTiles = new System.Collections.Hashtable();
#endregion
#region Properties
/// <summary>
/// Gets the boundingbox of the entire layer
/// </summary>
public override Envelope Envelope
{
get
{
var extent = _source.Schema.Extent;
return new Envelope(
extent.MinX, extent.MaxX,
extent.MinY, extent.MaxY);
}
}
/// <summary>
/// The algorithm used when images are scaled or rotated
/// </summary>
public InterpolationMode InterpolationMode
{
get { return _interpolationMode; }
set { _interpolationMode = value; }
}
#endregion
#region Constructors
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="tileSource">the source to get the tiles from</param>
/// <param name="layerName">name of the layer</param>
public TileLayer(ITileSource tileSource, string layerName)
: this(tileSource, layerName, new Color(), true, null)
{
}
/// <summary>
///
/// </summary>
/// <param name="tileSource">The source to get the tiles from</param>
/// <param name="layerName">The name of the layer</param>
/// <param name="transparentColor">The color to be treated as transparent color</param>
/// <param name="showErrorInTile">Flag indicating that an error tile should be generated for <see cref="WebException"/>s</param>
public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile)
: this(tileSource,layerName, transparentColor, showErrorInTile,null)
{
}
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="tileSource">the source to get the tiles from</param>
/// <param name="layerName">name of the layer</param>
/// <param name="transparentColor">transparent color off</param>
/// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
/// <param name="fileCacheDir">If the layer should use a file-cache so store tiles, set this to that directory. Set to null to avoid filecache</param>
/// <remarks>If <paramref name="showErrorInTile"/> is set to false, tile source keeps trying to get the tile in every request</remarks>
public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, string fileCacheDir)
{
_source = tileSource;
LayerName = layerName;
_transparentColor = transparentColor;
_showErrorInTile = showErrorInTile;
if (!string.IsNullOrEmpty(fileCacheDir))
{
_fileCache = new FileCache(fileCacheDir, "png");
}
else
{
_fileCache = (tileSource as HttpTileProvider)?.PersistentCache as FileCache;
}
if (_fileCache != null)
_ImageFormat = ImageFormat.Png;
}
/// <summary>
/// Creates an instance of this class
/// </summary>
/// <param name="tileSource">the source to get the tiles from</param>
/// <param name="layerName">name of the layer</param>
/// <param name="transparentColor">transparent color off</param>
/// <param name="showErrorInTile">generate an error tile if it could not be retrieved from source</param>
/// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param>
/// <param name="imgFormat">Set the format of the tiles to be used</param>
public TileLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat)
{
_source = tileSource;
LayerName = layerName;
_transparentColor = transparentColor;
_showErrorInTile = showErrorInTile;
_fileCache = fileCache;
_ImageFormat = imgFormat;
}
#endregion
#region Public methods
/// <summary>
/// Renders the layer
/// </summary>
/// <param name="graphics">Graphics object reference</param>
/// <param name="map">Map which is rendered</param>
public override void Render(Graphics graphics, MapViewport map)
{
if (!map.Size.IsEmpty && map.Size.Width > 0 && map.Size.Height > 0)
{
var bmp = new Bitmap(map.Size.Width, map.Size.Height, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(bmp))
{
g.InterpolationMode = InterpolationMode;
g.Transform = graphics.Transform.Clone();
var extent = new Extent(map.Envelope.MinX, map.Envelope.MinY,
map.Envelope.MaxX, map.Envelope.MaxY);
var level = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, Math.Max(map.PixelWidth, map.PixelHeight));
var tiles = new List<TileInfo>(_source.Schema.GetTileInfos(extent, level));
var tileWidth = _source.Schema.GetTileWidth(level);
var tileHeight = _source.Schema.GetTileWidth(level);
IList<WaitHandle> waitHandles = new List<WaitHandle>();
var toRender = new System.Collections.Concurrent.ConcurrentDictionary<TileIndex, Bitmap>();
var takenFromCache = new System.Collections.Concurrent.ConcurrentDictionary<TileIndex,bool>();
foreach (TileInfo info in tiles)
{
var image = _bitmaps.Find(info.Index);
if (image != null)
{
toRender.TryAdd(info.Index, image);
takenFromCache.TryAdd(info.Index,true);
continue;
}
if (_fileCache != null && _fileCache.Exists(info.Index))
{
var tileBitmap = GetImageFromFileCache(info) as Bitmap;
_bitmaps.Add(info.Index, tileBitmap);
toRender.TryAdd(info.Index, tileBitmap);
takenFromCache.TryAdd(info.Index, true);
continue;
}
var waitHandle = new AutoResetEvent(false);
waitHandles.Add(waitHandle);
ThreadPool.QueueUserWorkItem(GetTileOnThread,
new object[] { _source, info, toRender, waitHandle, true, takenFromCache });
}
foreach (var handle in waitHandles)
handle.WaitOne();
using (var ia = new ImageAttributes())
{
if (!_transparentColor.IsEmpty)
ia.SetColorKey(_transparentColor, _transparentColor);
#if !PocketPC
ia.SetWrapMode(WrapMode.TileFlipXY);
#endif
foreach (var info in tiles)
{
if (!toRender.ContainsKey(info.Index))
continue;
var bitmap = toRender[info.Index];//_bitmaps.Find(info.Index);
if (bitmap == null) continue;
var min = map.WorldToImage(new Coordinate(info.Extent.MinX, info.Extent.MinY));
var max = map.WorldToImage(new Coordinate(info.Extent.MaxX, info.Extent.MaxY));
min = new PointF((float) Math.Round(min.X), (float) Math.Round(min.Y));
max = new PointF((float) Math.Round(max.X), (float) Math.Round(max.Y));
try
{
g.DrawImage(bitmap,
new Rectangle((int) min.X, (int) max.Y, (int) (max.X - min.X),
(int) (min.Y - max.Y)),
0, 0, tileWidth, tileHeight,
GraphicsUnit.Pixel,
ia);
}
catch (Exception ee)
{
Logger.Error(ee.Message);
}
}
}
//Add rendered tiles to cache
foreach (var kvp in toRender)
{
if (takenFromCache.ContainsKey(kvp.Key) && !takenFromCache[kvp.Key])
{
_bitmaps.Add(kvp.Key, kvp.Value);
}
}
graphics.Transform = new Matrix();
graphics.DrawImageUnscaled(bmp, 0, 0);
graphics.Transform = g.Transform;
}
}
}
#endregion
#region Private methods
private void GetTileOnThread(object parameter)
{
object[] parameters = (object[])parameter;
if (parameters.Length != 6) throw new ArgumentException("Six parameters expected");
ITileProvider tileProvider = (ITileProvider)parameters[0];
TileInfo tileInfo = (TileInfo)parameters[1];
//MemoryCache<Bitmap> bitmaps = (MemoryCache<Bitmap>)parameters[2];
var bitmaps = (ConcurrentDictionary<TileIndex, Bitmap>)parameters[2];
AutoResetEvent autoResetEvent = (AutoResetEvent)parameters[3];
bool retry = (bool) parameters[4];
var takenFromCache = (IDictionary<TileIndex, bool>) parameters[5];
var setEvent = true;
try
{
byte[] bytes = tileProvider.GetTile(tileInfo);
Bitmap bitmap = new Bitmap(new MemoryStream(bytes));
bitmaps.TryAdd(tileInfo.Index, bitmap);
// this bitmap will later be memory cached
takenFromCache.Add(tileInfo.Index, false);
// add to persistent cache if enabled
if (_fileCache != null)
{
AddImageToFileCache(tileInfo, bitmap);
}
}
catch (WebException ex)
{
if (retry)
{
GetTileOnThread(new object[] { tileProvider, tileInfo, bitmaps, autoResetEvent, false, takenFromCache });
setEvent = false;
return;
}
if (_showErrorInTile)
{
try
{
//an issue with this method is that one an error tile is in the memory cache it will stay even
//if the error is resolved. PDD.
var tileWidth = _source.Schema.GetTileWidth(tileInfo.Index.Level);
var tileHeight = _source.Schema.GetTileHeight(tileInfo.Index.Level);
var bitmap = new Bitmap(tileWidth, tileHeight);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.DrawString(ex.Message, new Font(FontFamily.GenericSansSerif, 12),
new SolidBrush(Color.Black),
new RectangleF(0, 0, tileWidth, tileHeight));
}
bitmaps.TryAdd(tileInfo.Index, bitmap);
}
catch (Exception e)
{
// we don't want fatal exceptions here!
Logger.Error(e);
}
}
}
catch(Exception ex)
{
Logger.Error(ex.Message);
}
finally
{
if (setEvent) autoResetEvent.Set();
}
}
/// <summary>
/// Method to add a tile image to the <see cref="FileCache"/>
/// </summary>
/// <param name="tileInfo">The tile info</param>
/// <param name="bitmap">The tile image</param>
protected void AddImageToFileCache(TileInfo tileInfo, Bitmap bitmap)
{
using (var ms = new MemoryStream())
{
bitmap.Save(ms, _ImageFormat);
ms.Seek(0, SeekOrigin.Begin);
var data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
_fileCache.Add(tileInfo.Index, data);
}
}
/// <summary>
/// Function to get a tile image from the <see cref="FileCache"/>.
/// </summary>
/// <param name="info">The tile info</param>
/// <returns>The tile-image, if already cached</returns>
protected Image GetImageFromFileCache(TileInfo info)
{
using (var ms = new MemoryStream(_fileCache.Find(info.Index)))
{
return Image.FromStream(ms);
}
}
#endregion
/// <inheritdoc cref="IDeserializationCallback.OnDeserialization"/>
public void OnDeserialization(object sender)
{
if (_bitmaps == null)
_bitmaps = new MemoryCache<Bitmap>(100, 200);
}
/// <inheritdoc cref="DisposableObject.ReleaseManagedResources"/>
protected override void ReleaseManagedResources()
{
base.ReleaseManagedResources();
if (_source is IDisposable disposable)
disposable.Dispose();
_bitmaps.Dispose();
}
}
}