Example #1
0
        private static void GetRecursive(IDictionary<TileIndex, IFeature> resultTiles, ITileSchema schema,
            ITileCache<Feature> cache, Extent extent, IList<KeyValuePair<string, Resolution>> resolutions, int resolutionIndex)
        {
            if (resolutionIndex < 0 || resolutionIndex >= resolutions.Count)
                return;

            var tiles = schema.GetTileInfos(extent, resolutions[resolutionIndex].Key);

            foreach (var tileInfo in tiles)
            {
                var feature = cache.Find(tileInfo.Index);

                if (feature == null)
                {
                    // only continue the recursive search if this tile is within the extent
                    if (tileInfo.Extent.Intersects(extent))
                    {
                        GetRecursive(resultTiles, schema, cache, tileInfo.Extent.Intersect(extent), resolutions, resolutionIndex - 1);
                    }
                }
                else
                {
                    resultTiles[tileInfo.Index] = feature;
                }
            }
        }
        private static void RenderTile(WriteableBitmap bitmap, ITileSchema schema, IViewport viewport, MemoryCache<Feature> memoryCache)
        {
            int level = BruTile.Utilities.GetNearestLevel(schema.Resolutions, viewport.Resolution);
            var tiles = schema.GetTilesInView(viewport.Extent.ToExtent(), level);

            foreach (TileInfo tile in tiles)
            {
                var p = NativeCache.Find(tile.Index);
                if (p != null)
                {
                    bitmap.Render(p, null);
                    continue;
                }

                var image = memoryCache.Find(tile.Index);

                if (image != null)
                {
                    Rect dest = WorldToView(tile.Extent, viewport);
                    dest = GeometryRenderer.RoundToPixel(dest);

                    //See here the clumsy way to write a bitmap in SL/WPF
                    var path = new System.Windows.Shapes.Path();
                    path.Data = new RectangleGeometry { Rect = dest };
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(((IRaster)image.Geometry).Data);
                    path.Fill = new ImageBrush { ImageSource = bitmapImage };
                    path.CacheMode = new BitmapCache();
                    bitmap.Render(path, null);
                }
            }
        }
Example #3
0
        public BingLayer()
        {
            // Here we use a tile schema that is defined in code. There are a few predefined 
            // tile schemas in the BruTile.dll. In the usual case the schema should be parsed
            // from a tile service description.
            schema = new BingSchema();

            if (cache == null)
            {
                // Cache = new MemoryCache<byte[]>(1000, 100000);

                var localSettingsDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                
                var assembly = Assembly.GetEntryAssembly();
                if (assembly == null)
                {
                    cache = new MemoryCache<byte[]>(1000, 100000);
                }
                else
                {
                    var assemblyInfo = AssemblyUtils.GetAssemblyInfo(assembly);
                    var cacheDirectoryPath = Path.Combine(Path.Combine(Path.Combine(localSettingsDirectoryPath, assemblyInfo.Company), assemblyInfo.Product), "cache_bing");
                    cache = new FileCache(cacheDirectoryPath, "jpg");
                }
            }
        }
        private static void DrawRecursive(Graphics graphics, ITileSchema schema, IViewport viewport, 
            MemoryCache<Feature> cache, Extent extent, int level)
        {
            var tileInfos = schema.GetTilesInView(extent, level);

            foreach (TileInfo info in tileInfos)
            {
                var feature = cache.Find(info.Index);
                if (feature == null)
                {
                    if (level > 0) DrawRecursive(graphics, schema, viewport, cache, info.Extent.Intersect(extent), level - 1);
                }
                else
                {
                    var image = ((IRaster)feature.Geometry).Data;
                    RectangleF dest = WorldToView(info.Extent, viewport);
                    dest = RoundToPixel(dest);
                    RectangleF clip = WorldToView(extent, viewport);
                    clip = RoundToPixel(clip);

                    if (!Contains(clip, dest))
                    {
                        clip = Intersect(clip, dest);
                        if (clip.IsEmpty) continue;
                        DrawImage(graphics, new Bitmap(image), dest, clip);
                    }
                    else
                    {
                        //Not using a clip at all sometimes performs better than using screenwide clip.
                        DrawImage(graphics, new Bitmap(image), dest);
                    }
                }
            }
        }
 public HttpTileSource(ITileSchema tileSchema, IRequest request, string name = null, 
     IPersistentCache<byte[]> persistentCache = null, Func<Uri, byte[]> tileFetcher = null)
 {
     _provider = new HttpTileProvider(request, persistentCache, tileFetcher);
     _tileSchema = tileSchema;
     Name = name ?? string.Empty;
 }
 private static WmscRequest CreateWmsRequest(ITileSchema schema)
 {
     const string url = "http://geoserver.nl/world/mapserv.cgi?map=world/world.map&VERSION=1.1.1";
     return new WmscRequest(new Uri(url), schema,
                                   new List<string>(new[] {"world"}), new List<string>(),
                                   new Dictionary<string, string>());
 }
Example #7
0
 public IList<IFeature> GetFeatures(BoundingBox box, double resolution, ITileSchema schema, ITileCache<Feature> memoryCache)
 {
     var dictionary = new Dictionary<TileIndex, IFeature>();
     var levelId = BruTile.Utilities.GetNearestLevel(schema.Resolutions, resolution);
     GetRecursive(dictionary, schema, memoryCache, box.ToExtent(), levelId);
     var sortedFeatures = dictionary.OrderByDescending(t => schema.Resolutions[t.Key.Level].UnitsPerPixel);
     return sortedFeatures.ToDictionary(pair => pair.Key, pair => pair.Value).Values.ToList();
 }
 private static IRequest GetRequestBuilder(ITileSchema schema)
 {
     const string url = "http://geoserver.nl/tiles/tilecache.aspx?";
     var parameters = new Dictionary<string, string>();
     var request = new WmscRequest(new Uri(url), schema,
       new List<string>(new[] { "world_GM" }), new List<string>(), parameters);
     return request;
 }
Example #9
0
 public WmscRequest(Uri baseUrl, ITileSchema schema, IList<string> layers, IList<string> styles, IDictionary<string, string> customParameters, string version = null)
 {
     _baseUrl = baseUrl;
     _customParameters = customParameters;
     _layers = layers;
     _schema = schema;
     _styles = styles;
     _version = version;
 }
Example #10
0
 private static TileRange WorldToTileInvertedY(Extent extent, int level, ITileSchema schema)
 {
     var resolution = schema.Resolutions[level];
     var tileWorldUnits = resolution.UnitsPerPixel * schema.Width;
     var firstCol = (int)Math.Floor((extent.MinX - schema.OriginX) / tileWorldUnits);
     var firstRow = (int)Math.Floor((-extent.MaxY + schema.OriginY) / tileWorldUnits);
     var lastCol = (int)Math.Ceiling((extent.MaxX - schema.OriginX) / tileWorldUnits);
     var lastRow = (int)Math.Ceiling((-extent.MinY + schema.OriginY) / tileWorldUnits);
     return new TileRange(firstCol, firstRow, lastCol - firstCol, lastRow - firstRow);
 }
Example #11
0
 private static Extent TileToWorldInvertedY(TileRange range, int level, ITileSchema schema)
 {
     var resolution = schema.Resolutions[level];
     var tileWorldUnits = resolution.UnitsPerPixel * schema.Width;
     var minX = range.FirstCol * tileWorldUnits + schema.OriginX;
     var minY = -(range.FirstRow + range.RowCount) * tileWorldUnits + schema.OriginY;
     var maxX = (range.FirstCol + range.ColCount) * tileWorldUnits + schema.OriginX;
     var maxY = -(range.FirstRow) * tileWorldUnits + schema.OriginY;
     return new Extent(minX, minY, maxX, maxY);
 }
Example #12
0
 private static Extent TileToWorldNormal(TileRange range, string levelId, ITileSchema schema)
 {
     var resolution = schema.Resolutions[levelId];
     var tileWorldUnits = resolution.UnitsPerPixel * schema.GetTileWidth(levelId);
     var minX = range.FirstCol * tileWorldUnits + schema.GetOriginX(levelId);
     var minY = range.FirstRow * tileWorldUnits + schema.GetOriginY(levelId);
     var maxX = (range.FirstCol + range.ColCount) * tileWorldUnits + schema.GetOriginX(levelId);
     var maxY = (range.FirstRow + range.RowCount) * tileWorldUnits + schema.GetOriginY(levelId);
     return new Extent(minX, minY, maxX, maxY);
 }
Example #13
0
 private static TileRange WorldToTileNormal(Extent extent, string levelId, ITileSchema schema)
 {
     var resolution = schema.Resolutions[levelId];
     var tileWorldUnits = resolution.UnitsPerPixel * schema.GetTileWidth(levelId);
     var firstCol = (int)Math.Floor((extent.MinX - schema.GetOriginX(levelId)) / tileWorldUnits);
     var firstRow = (int)Math.Floor((extent.MinY - schema.GetOriginY(levelId)) / tileWorldUnits);
     var lastCol = (int)Math.Ceiling((extent.MaxX - schema.GetOriginX(levelId)) / tileWorldUnits);
     var lastRow = (int)Math.Ceiling((extent.MaxY - schema.GetOriginY(levelId)) / tileWorldUnits);
     return new TileRange(firstCol, firstRow, lastCol - firstCol, lastRow - firstRow);
 }
 public ArcGisTileSource(
         string baseUrl, 
         ITileSchema schema, 
         IPersistentCache<byte[]> persistentCache = null,
         Func<Uri, byte[]> fetchTile = null)
     : base(new WebTileProvider(CreateArcGISRequest(baseUrl), persistentCache, fetchTile), 
         schema)
 {
     BaseUrl = baseUrl;
 }
Example #15
0
        public int GetTileCount(ITileSchema schema)
        {
            var result = 0;

            foreach (var resolution in schema.Resolutions)
            {
                result += resolution.Value.MatrixHeight*resolution.Value.MatrixWidth;
            }

            return result;
        }
Example #16
0
 public ArcGisTileSource(
         string baseUrl, 
         ITileSchema schema, 
         IPersistentCache<byte[]> persistentCache = null,
         Func<Uri, HttpWebRequest> webRequestFactory = null)
     : base(
         new WebTileProvider(CreateArcGISRequest(baseUrl), persistentCache, webRequestFactory), 
         schema)
 {
     BaseUrl = baseUrl;
 }
Example #17
0
 public static Extent TileToWorld(TileRange range, int level, ITileSchema schema)
 {
     switch (schema.Axis)
     {
         case AxisDirection.Normal:
             return TileToWorldNormal(range, level, schema);
         case AxisDirection.InvertedY:
             return TileToWorldInvertedY(range, level, schema);
         default:
             throw new Exception("Axis type was not found");
     }
 }
Example #18
0
 public static Extent TileToWorld(TileRange range, string levelId, ITileSchema schema)
 {
     switch (schema.YAxis)
     {
         case YAxis.TMS:
             return TileToWorldNormal(range, levelId, schema);
         case YAxis.OSM:
             return TileToWorldInvertedY(range, levelId, schema);
         default:
             throw new Exception("YAxis type was not found");
     }
 }
Example #19
0
 public static TileRange WorldToTile(Extent extent, int level, ITileSchema schema)
 {
     switch (schema.Axis)
     {
         case AxisDirection.Normal:
             return WorldToTileNormal(extent, level, schema);
         case AxisDirection.InvertedY:
             return WorldToTileInvertedY(extent, level, schema);
         default:
             throw new Exception("Axis type was not found");
     }
 }
Example #20
0
 public static TileRange WorldToTile(Extent extent, string levelId, ITileSchema schema)
 {
     switch (schema.YAxis)
     {
         case YAxis.TMS:
             return WorldToTileNormal(extent, levelId, schema);
         case YAxis.OSM:
             return WorldToTileInvertedY(extent, levelId, schema);
         default:
             throw new Exception("YAxis type was not found");
     }
 }
        public IList<IFeature> GetFeatures(BoundingBox box, double resolution, ITileSchema schema, ITileCache<Feature> memoryCache)
        {
            var tiles = schema.GetTileInfos(box.ToExtent(), resolution);
            var result = new List<IFeature>();
            foreach (var tileInfo in tiles)
            {
                var feature = memoryCache.Find(tileInfo.Index);

                if (feature != null)
                {
                    result.Add(feature);
                }
            }
            return result;
        }
Example #22
0
        private static RectangleF DrawTile(ITileSchema schema, Graphics graphics, Bitmap bitmap, RectangleF extent)
        {
            // For drawing on WinForms there are two things to take into account
            // to prevent seams between tiles.
            // 1) The WrapMode should be set to TileFlipXY. This is related
            //    to how pixels are rounded by GDI+
            ImageAttributes imageAttributes = new ImageAttributes();

            imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
            // 2) The rectangle should be rounded to actual pixels.
            Rectangle roundedExtent = RoundToPixel(extent);

            graphics.DrawImage(bitmap, roundedExtent, 0, 0, schema.Width, schema.Height, GraphicsUnit.Pixel, imageAttributes);
            return(extent);
        }
Example #23
0
 public static void WriteWorldFile(string f, Extent extent, ITileSchema schema)
 {
     using (var sw = new StreamWriter(f))
     {
         var resX = (extent.MaxX - extent.MinX) / schema.GetTileWidth("0");
         var resY = (extent.MaxY - extent.MinY) / schema.GetTileHeight("0");
         sw.WriteLine(resX.ToString(CultureInfo.InvariantCulture));
         sw.WriteLine("0");
         sw.WriteLine("0");
         sw.WriteLine((resY * -1).ToString(CultureInfo.InvariantCulture));
         sw.WriteLine(extent.MinX.ToString(CultureInfo.InvariantCulture));
         sw.WriteLine(extent.MaxY.ToString(CultureInfo.InvariantCulture));
         sw.Close();
     }
 }
Example #24
0
 public static void GetRecursive(IDictionary<TileIndex, IFeature> resultTiles, ITileSchema schema,
     ITileCache<Feature> cache, Extent extent, string levelId)
 {
     // to improve performance, convert the resolutions to a list so they can be walked up by
     // simply decrementing an index when the level index needs to change
     var resolutions = schema.Resolutions.OrderByDescending(pair => pair.Value.UnitsPerPixel).ToList();
     for (int i = 0; i < resolutions.Count; i++)
     {
         if (levelId == resolutions[i].Key)
         {
             GetRecursive(resultTiles, schema, cache, extent, resolutions, i);
             break;
         }
     }
 }
Example #25
0
        public MbTilesTileSource(SQLiteConnectionString connectionString, ITileSchema schema = null, MbTilesType type = MbTilesType.None)
        {
            _connectionString = connectionString;
            var connection = new SQLiteConnectionWithLock(connectionString, SQLiteOpenFlags.ReadOnly);

            using (connection.Lock())
            {
                Type = type == MbTilesType.None ? ReadType(connection) : type;
                var schemaFromDatabase = ReadSchemaFromDatabase(connection);
                Schema = schema ?? schemaFromDatabase;

                // the tile range should be based on the tiles actually present.
                var zoomLevelsFromDatabase = schemaFromDatabase.Resolutions.Select(r => r.Key);
                _tileRange = ReadZoomLevelsFromTilesTable(connection, zoomLevelsFromDatabase);
            }
        }
        public IList <IFeature> GetFeatures(BoundingBox extent, double resolution, ITileSchema schema, ITileCache <Feature> memoryCache)
        {
            var tiles  = schema.GetTileInfos(extent.ToExtent(), resolution);
            var result = new List <IFeature>();

            foreach (var tileInfo in tiles)
            {
                var feature = memoryCache.Find(tileInfo.Index);

                if (feature != null)
                {
                    result.Add(feature);
                }
            }
            return(result);
        }
Example #27
0
        internal MbTilesCache(SQLiteConnectionString connectionString, ITileSchema schema = null, MbTilesType type = MbTilesType.None)
        {
            if (_connectionPool == null)
            {
                throw new InvalidOperationException("You must assign a platform prior to using MbTilesCache by calling MbTilesTileSource.SetPlatform()");
            }

            _connectionString = connectionString;
            var connection = _connectionPool.GetConnection(connectionString);

            using (connection.Lock())
            {
                _type = type == MbTilesType.None ? ReadType(connection) : type;

                if (schema == null)
                {
                    // Format (if defined)
                    _format = ReadFormat(connection);

                    // Extent
                    _extent = ReadExtent(connection);


                    if (HasMapTable(connection))
                    {
                        // it is possible to override the schema by definining it in a 'map' table.
                        // This method depends on reading tiles from an 'images' table, which
                        // is not part of the MBTiles spec

                        // Declared zoom levels
                        var declaredZoomLevels = ReadZoomLevels(connection, out _tileRange);

                        // Create schema
                        _schema = new GlobalMercator(_format.ToString(), declaredZoomLevels);
                    }
                    else
                    {
                        // this is actually the most regular case:
                        _schema = new GlobalSphericalMercator();
                    }
                }
                else
                {
                    _schema = schema;
                }
            }
        }
Example #28
0
        public IList <TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, string levelId)
        {
            var tileInfos = new List <TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not available the renderer can fall back on higher level tiles.
            var resolution = schema.Resolutions[levelId].UnitsPerPixel;
            var levels     = schema.Resolutions.Where(k => k.Value.UnitsPerPixel >= resolution).OrderBy(x => x.Value.UnitsPerPixel).ToList();

            foreach (var level in levels)
            {
                var tileInfosForLevel = schema.GetTileInfos(extent, level.Key).OrderBy(
                    t => Algorithms.Distance(extent.CenterX, extent.CenterY, t.Extent.CenterX, t.Extent.CenterY));

                tileInfos.AddRange(tileInfosForLevel);
            }

            return(tileInfos);
        }
 private void SafeSchema(ITileSchema schema)
 {
     _axis        = schema.YAxis;
     _minX        = schema.Extent.MinX;
     _maxX        = schema.Extent.MaxX;
     _minY        = schema.Extent.MinY;
     _maxY        = schema.Extent.MaxY;
     _format      = schema.Format;
     _height      = schema.GetTileHeight(String.Empty);
     _width       = schema.GetTileWidth(String.Empty);
     _schemaName  = schema.Name;
     _originX     = schema.GetOriginX(String.Empty);
     _originY     = schema.GetOriginY(String.Empty);
     _srs         = schema.Srs;
     _resolutions = new Dictionary <string, Resolution>();
     foreach (var resolution in schema.Resolutions)
     {
         _resolutions.Add(resolution.Key, resolution.Value);
     }
 }
Example #30
0
        public IList<TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, int level)
        {
            IList<TileInfo> infos = new List<TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not availeble the renderer can fall back on higher level tiles. 
            var levels = schema.Resolutions.Keys.Where(k => k <= level).OrderByDescending(x => x);

            foreach (var lvl in levels)
            {
                var infosOfLevel = schema.GetTilesInView(extent, lvl);
                infosOfLevel = SortByPriority(infosOfLevel, extent.CenterX, extent.CenterY);

                foreach (TileInfo info in infosOfLevel)
                {
                    if ((info.Index.Row >= 0) && (info.Index.Col >= 0)) infos.Add(info);
                }
            }

            return infos;
        }
Example #31
0
        public BingLayer()
        {
            // Here we use a tile schema that is defined in code. There are a few predefined
            // tile schemas in the BruTile.dll. In the usual case the schema should be parsed
            // from a tile service description.
            schema = new BingSchema();

            if (cache == null)
            {
                //no cache so mem
                if (CacheLocation == null)
                {
                    cache = new MemoryCache <byte[]>(1000, 100000);
                }
                else
                {
                    cache = new FileCache(CacheLocation, "jpg");
                }
            }
        }
Example #32
0
        public BingLayer()
        {
            // Here we use a tile schema that is defined in code. There are a few predefined 
            // tile schemas in the BruTile.dll. In the usual case the schema should be parsed
            // from a tile service description.
            schema = new BingSchema();

            if (cache == null)
            {
                //no cache so mem
                if (CacheLocation == null)
                {
                    cache = new MemoryCache<byte[]>(1000, 100000);
                }
                else
                {
                    cache = new FileCache(CacheLocation, "jpg");
                }
            }
        }
Example #33
0
        public OpenStreetMapLayer()
        {
            // Here we use a tile schema that is defined in code. There are a few predefined
            // tile schemas in the BruTile.dll. In the usual case the schema should be parsed
            // from a tile service description.
            schema = CreateTileSchema();

            if (cache == null)
            {
                if (CacheLocation == null)
                {
                    cache = new MemoryCache <byte[]>(1000, 100000);
                }
                else
                {
                    var cacheDirectoryPath = CacheLocation;
                    cache = new FileCache(cacheDirectoryPath, "png");
                }
            }
        }
Example #34
0
        private void button2_Click(object sender, EventArgs e)
        {
            var tile = comboBox1.SelectedItem;

            if (tile == null)
            {
                MessageBox.Show("请选择至少一种地图");
                return;
            }
            EnumBruTileLayer enumBruTileLayer = (EnumBruTileLayer)Enum.Parse(typeof(EnumBruTileLayer), tile.ToString());
            IConfig          config           = ConfigHelper.GetConfig(enumBruTileLayer);

            tileSource = config.CreateTileSource();
            schema     = tileSource.Schema;
            var env = Projector.ProjectEnvelope(view.Extent, schema.Srs);

            textBox3.Text = env.XMin.ToString();
            textBox4.Text = env.XMax.ToString();
            textBox5.Text = env.YMin.ToString();
            textBox2.Text = env.YMax.ToString();
        }
Example #35
0
        public IList<TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, string levelId)
        {
            var infos = new List<TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not available the renderer can fall back on higher level tiles.
            var resolution = schema.Resolutions[levelId].UnitsPerPixel;
            var levels = schema.Resolutions.Where(k => k.Value.UnitsPerPixel >= resolution).OrderBy(x => x.Value.UnitsPerPixel).ToList();

            foreach (var level in levels)
            {
                var tileInfos = schema.GetTileInfos(extent, level.Key).OrderBy(
                    t => Algorithms.Distance(extent.CenterX, extent.CenterY, t.Extent.CenterX, t.Extent.CenterY));

                foreach (TileInfo info in tileInfos.Where(info => (info.Index.Row >= 0) && (info.Index.Col >= 0)))
                {
                    infos.Add(info);
                }
            }

            return infos;
        }
Example #36
0
        private static void DrawRecursive(Graphics graphics, ITileSchema schema, IViewport viewport,
                                          MemoryCache <Feature> cache, Extent extent, int level)
        {
            var tileInfos = schema.GetTilesInView(extent, level);

            foreach (TileInfo info in tileInfos)
            {
                var feature = cache.Find(info.Index);
                if (feature == null)
                {
                    if (level > 0)
                    {
                        DrawRecursive(graphics, schema, viewport, cache, info.Extent.Intersect(extent), level - 1);
                    }
                }
                else
                {
                    var        image = ((IRaster)feature.Geometry).Data;
                    RectangleF dest  = WorldToView(info.Extent, viewport);
                    dest = RoundToPixel(dest);
                    RectangleF clip = WorldToView(extent, viewport);
                    clip = RoundToPixel(clip);

                    if (!Contains(clip, dest))
                    {
                        clip = Intersect(clip, dest);
                        if (clip.IsEmpty)
                        {
                            continue;
                        }
                        DrawImage(graphics, new Bitmap(image), dest, clip);
                    }
                    else
                    {
                        //Not using a clip at all sometimes performs better than using screenwide clip.
                        DrawImage(graphics, new Bitmap(image), dest);
                    }
                }
            }
        }
Example #37
0
        public SharpMapTileProvider(ITileSchema schema, ITileCache <byte[]> cache, params ILayer[] layers)
        {
            if (schema == null)
            {
                throw new ArgumentNullException("schema");
            }
            if (layers == null)
            {
                throw new ArgumentNullException("layers");
            }

            this.Schema = schema;
            this.cache  = cache ?? new NullCache();

            LayerCollection collection = new LayerCollection();

            foreach (ILayer layer in layers)
            {
                collection.Add(layer);
            }
            this.layers = collection;
        }
Example #38
0
        public IList<TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, string levelId)
        {
            IList<TileInfo> infos = new List<TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not availeble the renderer can fall back on higher level tiles. 
            var unitsPerPixel = schema.Resolutions[levelId].UnitsPerPixel;
            var levels = schema.Resolutions.Where(k => unitsPerPixel <= k.Value.UnitsPerPixel).OrderByDescending(x => x.Value.UnitsPerPixel);
            
            //var levelCount = levels.Count();
            foreach (var level in levels)
            {
                var tileInfos = schema.GetTileInfos(extent, level.Key);
                tileInfos = SortByPriority(tileInfos, extent.CenterX, extent.CenterY);

                //var count = infosOfLevel.Count();
                foreach (var info in tileInfos)
                {
                    if ((info.Index.Row >= 0) && (info.Index.Col >= 0)) infos.Add(info);
                }
            }

            return infos;
        }
Example #39
0
        public IList<TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, int level)
        {
            //line below only works properly of this instance is always called with the the resolutions. Think of something better
            if (preFetchLayers == null) preFetchLayers = GetPreFetchLevels(0, schema.Resolutions.Count - 1);

            IList<TileInfo> infos = new List<TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not availeble the renderer can fall back on higher level tiles. 
            while (level >= 0)
            {
                ////////if (!preFetchLayers.Contains(level)) continue;
                var infosOfLevel = schema.GetTilesInView(extent, level);
                infosOfLevel = PrioritizeTiles(infosOfLevel, extent.CenterX, extent.CenterY);

                foreach (TileInfo info in infosOfLevel)
                {
                    if ((info.Index.Row >= 0) && (info.Index.Col >= 0)) infos.Add(info);
                }
                level--;
            }

            return infos;
        }
Example #40
0
        public IList<TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, string levelId)
        {
            IList<TileInfo> infos = new List<TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not availeble the renderer can fall back on higher level tiles.
            var resolution = schema.Resolutions[levelId].UnitsPerPixel;
            var levels = schema.Resolutions.Where(k => resolution <= k.Value.UnitsPerPixel).OrderByDescending(x => x.Value.UnitsPerPixel);

            //var levelCount = levels.Count();
            foreach (var level in levels)
            {
                var tileInfos = schema.GetTilesInView(extent, level.Key);
                tileInfos = SortByPriority(tileInfos, extent.CenterX, extent.CenterY);

                //var count = infosOfLevel.Count();
                foreach (var info in tileInfos)
                {
                    if ((info.Index.Row >= 0) && (info.Index.Col >= 0)) infos.Add(info);
                }
            }

            return infos;
        }
Example #41
0
        public IList <TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, int level)
        {
            IList <TileInfo> infos = new List <TileInfo>();
            // Iterating through all levels from current to zero. If lower levels are
            // not availeble the renderer can fall back on higher level tiles.
            var levels = schema.Resolutions.Keys.Where(k => k <= level).OrderByDescending(x => x);

            foreach (var lvl in levels)
            {
                var infosOfLevel = schema.GetTilesInView(extent, lvl);
                infosOfLevel = SortByPriority(infosOfLevel, extent.CenterX, extent.CenterY);

                foreach (TileInfo info in infosOfLevel)
                {
                    if ((info.Index.Row >= 0) && (info.Index.Col >= 0))
                    {
                        infos.Add(info);
                    }
                }
            }

            return(infos);
        }
Example #42
0
        internal static IEnumerable <TileInfo> GetTileInfos(ITileSchema schema, Extent extent, string levelId)
        {
            // todo: move this method elsewhere.
            var range = TileTransform.WorldToTile(extent, levelId, schema);

            // todo: use a method to get tilerange for full schema and intersect with requested tilerange.
            var startX = Math.Max(range.FirstCol, schema.GetMatrixFirstCol(levelId));
            var stopX  = Math.Min(range.FirstCol + range.ColCount, schema.GetMatrixFirstCol(levelId) + schema.GetMatrixWidth(levelId));
            var startY = Math.Max(range.FirstRow, schema.GetMatrixFirstRow(levelId));
            var stopY  = Math.Min(range.FirstRow + range.RowCount, schema.GetMatrixFirstRow(levelId) + schema.GetMatrixHeight(levelId));

            for (var x = startX; x < stopX; x++)
            {
                for (var y = startY; y < stopY; y++)
                {
                    yield return(new TileInfo
                    {
                        Extent = TileTransform.TileToWorld(new TileRange(x, y), levelId, schema),
                        Index = new TileIndex(x, y, levelId)
                    });
                }
            }
        }
Example #43
0
        public MbTilesTileSource(SQLiteConnectionString connectionString, ITileSchema schema = null, MbTilesType type = MbTilesType.None, bool tileRangeOptimization = true)
        {
            _connectionString = connectionString;
            if (tileRangeOptimization || schema == null)
            {
                using (var connection = new SQLiteConnectionWithLock(connectionString))
                    using (connection.Lock())
                    {
                        Type = type == MbTilesType.None ? ReadType(connection) : type;
                        var schemaFromDatabase = ReadSchemaFromDatabase(connection);
                        Schema = schema ?? schemaFromDatabase;

                        // Read other stuff
                        Version     = ReadString(connection, "version");
                        Attribution = new Attribution(ReadString(connection, "attribution"));
                        Description = ReadString(connection, "description");
                        Name        = ReadString(connection, "name");
                        Json        = ReadString(connection, "json");
                        Compression = ReadString(connection, "compression");

                        var zoomMin = ReadInt(connection, "minzoom");
                        ZoomMin = zoomMin < 0 ? 0 : zoomMin;

                        var zoomMax = ReadInt(connection, "maxzoom");
                        ZoomMax = zoomMax < 0 ? int.MaxValue : zoomMax;

                        // the tile range should be based on the tiles actually present.
                        var zoomLevelsFromDatabase = schemaFromDatabase.Resolutions.Select(r => r.Key);
                        _tileRange = ReadZoomLevelsFromTilesTable(connection, zoomLevelsFromDatabase);
                    }
            }
            else
            {
                Schema     = schema;
                _tileRange = null;
            }
        }
Example #44
0
        public OpenStreetMapLayer()
        {
            // Here we use a tile schema that is defined in code. There are a few predefined
            // tile schemas in the BruTile.dll. In the usual case the schema should be parsed
            // from a tile service description.
            schema = CreateTileSchema();

            if (cache == null)
            {
                var localSettingsDirectoryPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var assembly = Assembly.GetEntryAssembly();
                if (assembly == null)
                {
                    cache = new MemoryCache <byte[]>(1000, 100000);
                }
                else
                {
                    var assemblyInfo       = AssemblyUtils.GetAssemblyInfo(assembly);
                    var cacheDirectoryPath = Path.Combine(Path.Combine(Path.Combine(
                                                                           localSettingsDirectoryPath, assemblyInfo.Company), assemblyInfo.Product), "cache_open_street_map");
                    cache = new FileCache(cacheDirectoryPath, "png");
                }
            }
        }
Example #45
0
        private static void RenderTile(WriteableBitmap bitmap, ITileSchema schema, IViewport viewport, MemoryCache <Feature> memoryCache)
        {
            int level = BruTile.Utilities.GetNearestLevel(schema.Resolutions, viewport.Resolution);
            var tiles = schema.GetTilesInView(viewport.Extent.ToExtent(), level);

            foreach (TileInfo tile in tiles)
            {
                var p = NativeCache.Find(tile.Index);
                if (p != null)
                {
                    bitmap.Render(p, null);
                    continue;
                }

                var image = memoryCache.Find(tile.Index);

                if (image != null)
                {
                    Rect dest = WorldToView(tile.Extent, viewport);
                    dest = GeometryRenderer.RoundToPixel(dest);

                    //See here the clumsy way to write a bitmap in SL/WPF
                    var path = new System.Windows.Shapes.Path();
                    path.Data = new RectangleGeometry {
                        Rect = dest
                    };
                    var bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(((IRaster)image.Geometry).Data);
                    path.Fill = new ImageBrush {
                        ImageSource = bitmapImage
                    };
                    path.CacheMode = new BitmapCache();
                    bitmap.Render(path, null);
                }
            }
        }
Example #46
0
        private static bool EqualTileProviders(ITileSchema schema, ITileProvider tp1, ITileProvider tp2, out string message)
        {
            if (!ReferenceEquals(tp1, tp2))
            {
                if (tp1 == null)
                {
                    message = "The reference tile provider is null!";
                    return(false);
                }
                if (tp2 == null)
                {
                    message = "One of the tile providers is null, and the other not";
                    return(false);
                }

                if (tp1.GetType() != tp2.GetType())
                {
                    message = "Tile providers are of different type";
                    return(false);
                }

                var keys   = schema.Resolutions.Keys.ToArray();
                var minkey = GetIndex(keys[0]);
                var maxKey = GetIndex(keys[keys.Length - 1]);
                var prefix = GetPrefix(keys[0]);
                for (var i = 0; i < 3; i++)
                {
                    TileInfo ti = null;
                    try
                    {
                        ti = RandomTileInfo(prefix + "{0}", minkey, Math.Min(maxKey, 12));
                        var req1 = tp1 as IRequest;
                        var req2 = tp2 as IRequest;
                        if (req1 != null && req2 != null)
                        {
                            if (req1.GetUri(ti) != req2.GetUri(ti))
                            {
                                message = "Request builders produce different uris for the same request";
                                return(false);
                            }
                        }
                        else
                        {
                            var t1 = tp1.GetTile(ti);
                            var t2 = tp2.GetTile(ti);
                            if (!TilesEqual(t1, t2))
                            {
                                message = "Request builders produce different results for same tile request";
                                return(false);
                            }
                        }
                    }
                    catch (TimeoutException ex)
                    {
                        System.Diagnostics.Trace.WriteLine(string.Format(
                                                               "TileInfo({4}): {0}, {1}, {2}\n{3}",
                                                               ti.Index.Level, ti.Index.Col, ti.Index.Row, ex.Message, i));
                    }
                    catch (WebException ex)
                    {
                        if (ti == null)
                        {
                            System.Diagnostics.Trace.WriteLine("No tile info!");
                        }
                        else
                        {
                            System.Diagnostics.Trace.WriteLine(string.Format(
                                                                   "TileInfo({5}): {0}, {1}, {2}\n{3}\n{4}",
                                                                   ti.Index.Level, ti.Index.Col, ti.Index.Row,
                                                                   ex.Message, ex.Response.ResponseUri, i));
                        }
                    }
                }
            }

            message = "Tile providers appear to be equal";
            return(true);
        }
Example #47
0
 public HttpTileSourceTDT(ITileSchema tileSchema, string urlFormatter, IEnumerable <string> serverNodes = null,
                          string apiKey = null, string name = null, IPersistentCache <byte[]> persistentCache = null,
                          Func <Uri, byte[]> tileFetcher = null, Attribution attribution = null)
     : this(tileSchema, new BasicRequestTDT(urlFormatter, serverNodes, apiKey), name, persistentCache, tileFetcher, attribution)
 {
 }
Example #48
0
 public MbTilesProvider(SQLiteConnection connection, ITileSchema schema = null, MbTilesType type = MbTilesType.None)
 {
     _cache = new MbTilesCache(connection, schema, type);
 }
 private WmscTileSource(ITileSchema tileSchema, ITileProvider tileProvider)
     : base(tileProvider, tileSchema)
 {
 }
Example #50
0
        public OpenStreetMapLayer()
        {
            // Here we use a tile schema that is defined in code. There are a few predefined 
            // tile schemas in the BruTile.dll. In the usual case the schema should be parsed
            // from a tile service description.
            schema = CreateTileSchema();

            if (cache == null)
            {
                if (CacheLocation == null)
                {
                    cache = new MemoryCache<byte[]>(1000, 100000);
                }
                else
                {
                    var cacheDirectoryPath = CacheLocation;
                    cache = new FileCache(cacheDirectoryPath, "png");
                }
            }
        }
Example #51
0
 public IList <TileInfo> Get(ITileSchema schema, Extent extent, int level)
 {
     return(schema.GetTileInfos(extent, level).OrderBy(
                t => Algorithms.Distance(extent.CenterX, extent.CenterY, t.Extent.CenterX, t.Extent.CenterY)).ToList());
 }
Example #52
0
        private static void GetRecursive(IDictionary <TileIndex, IFeature> resultTiles, ITileSchema schema,
                                         ITileCache <Feature> cache, Extent extent, IList <KeyValuePair <string, Resolution> > resolutions, int resolutionIndex)
        {
            if (resolutionIndex < 0 || resolutionIndex >= resolutions.Count)
            {
                return;
            }

            var tiles = schema.GetTileInfos(extent, resolutions[resolutionIndex].Key);

            foreach (var tileInfo in tiles)
            {
                var feature = cache.Find(tileInfo.Index);

                if (feature == null)
                {
                    // only continue the recursive search if this tile is within the extent
                    if (tileInfo.Extent.Intersects(extent))
                    {
                        GetRecursive(resultTiles, schema, cache, tileInfo.Extent.Intersect(extent), resolutions, resolutionIndex - 1);
                    }
                }
                else
                {
                    resultTiles[tileInfo.Index] = feature;
                }
            }
        }
Example #53
0
        public static void GetRecursive(IDictionary <TileIndex, IFeature> resultTiles, ITileSchema schema,
                                        ITileCache <Feature> cache, Extent extent, string levelId)
        {
            // to improve performance, convert the resolutions to a list so they can be walked up by
            // simply decrementing an index when the level index needs to change
            var resolutions = schema.Resolutions.OrderByDescending(pair => pair.Value.UnitsPerPixel).ToList();

            for (int i = 0; i < resolutions.Count; i++)
            {
                if (levelId == resolutions[i].Key)
                {
                    GetRecursive(resultTiles, schema, cache, extent, resolutions, i);
                    break;
                }
            }
        }
Example #54
0
        private static bool TryInitializeViewport(ref Viewport viewport, double actualWidth, double actualHeight, ITileSchema schema)
        {
            if (double.IsNaN(actualWidth))
            {
                return(false);
            }
            if (actualWidth <= 0)
            {
                return(false);
            }

            var nearestLevel = Utilities.GetNearestLevel(schema.Resolutions, schema.Extent.Width / actualWidth);

            viewport = new Viewport
            {
                Width         = actualWidth,
                Height        = actualHeight,
                UnitsPerPixel = schema.Resolutions[nearestLevel].UnitsPerPixel,
                Center        = new Samples.Common.Geometries.Point(schema.Extent.CenterX, schema.Extent.CenterY)
            };
            return(true);
        }
Example #55
0
        private static WmscRequest CreateWmsRequest(ITileSchema schema)
        {
            const string url = "http://geoserver.nl/world/mapserv.cgi?map=world/world.map&VERSION=1.1.1";

            return(new WmscRequest(new Uri(url), schema, new[] { "world" }.ToList(), new string[0].ToList()));
        }
Example #56
0
 public TmsTileSource(Uri serviceUri, ITileSchema tileSchema, IPersistentCache <byte[]> persistentCache = null,
                      Func <Uri, byte[]> fetchTile = null) :
     base(new WebTileProvider(new TmsRequest(serviceUri, tileSchema.Format), persistentCache,
                              fetchTile), tileSchema)
 {
 }
Example #57
0
 public TmsTileSource(string serviceUrl, ITileSchema tileSchema)
     : this(new Uri(serviceUrl), tileSchema)
 {
 }
Example #58
0
        private static bool EqualTileSchemas(ITileSchema ts1, ITileSchema ts2, out string message)
        {
            if (ts1.Name != ts2.Name)
            {
                message = "Names don't match";
                return(false);
            }

            if (ts1.Srs != ts2.Srs)
            {
                message = "Srs' don't match";
                return(false);
            }

            if (ts1.Format != ts2.Format)
            {
                message = "Formats don't match";
                return(false);
            }

            if (ts1.Extent != ts2.Extent)
            {
                message = "Extents don't match";
                return(false);
            }

            var tts1 = ts1 as TileSchema;
            var tts2 = ts2 as TileSchema;

            if (tts1 != null && tts2 != null)
            {
                if (tts1.Resolutions.Count != tts2.Resolutions.Count)
                {
                    message = "Number of resolutions don't match";
                    return(false);
                }

                if (tts1.OriginX != tts2.OriginX)
                {
                    message = "OriginX' don't match";
                    return(false);
                }

                if (tts1.OriginY != tts2.OriginY)
                {
                    message = "OriginYs don't match";
                    return(false);
                }

                foreach (var res1 in tts1.Resolutions.Values)
                {
                    var res2 = tts2.Resolutions[res1.Id];
                    if (tts1.GetTileHeight(res1.Id) != tts2.GetTileHeight(res2.Id))
                    {
                        message = "Heights don't match";
                        return(false);
                    }

                    if (tts1.GetTileWidth(res1.Id) != tts2.GetTileWidth(res2.Id))
                    {
                        message = "Widths don't match";
                        return(false);
                    }
                }
            }

            var wts1 = ts1 as WmtsTileSchema;
            var wts2 = ts2 as WmtsTileSchema;

            if (wts1 != null && wts2 != null)
            {
                if (wts1.Abstract != wts2.Abstract)
                {
                    message = "Abstracts don't match";
                    return(false);
                }
                if (wts1.Style != wts2.Style)
                {
                    message = "Styles don't match";
                    return(false);
                }
                if (wts1.Identifier != wts2.Identifier)
                {
                    message = "Identifiers don't match";
                    return(false);
                }
                if (wts1.SupportedSRS.ToString() != wts2.SupportedSRS.ToString())
                {
                    message = "SupportedSRS' don't match";
                    return(false);
                }
            }

            if (ts1.Resolutions.Count != ts2.Resolutions.Count)
            {
                message = "Number of resolutions doesn't match";
                return(false);
            }

            foreach (var key in ts1.Resolutions.Keys)
            {
                var r1 = ts1.Resolutions[key];
                var r2 = ts2.Resolutions[key];

                //!!! compare other resultion parameters.

                if (r1.Id != r2.Id || r1.UnitsPerPixel != r2.UnitsPerPixel)
                {
                    message = string.Format("Resolution doesn't match at index {0}", key);
                    return(false);
                }
            }

            message = "Schemas are equal!";
            return(true);
        }
Example #59
0
 /// <summary>
 /// Creates an instance of this class
 /// </summary>
 /// <param name="tileProvider">The tile provider</param>
 /// <param name="tileSchema">The tile schema</param>
 public TileSource(ITileProvider tileProvider, ITileSchema tileSchema)
 {
     _provider = tileProvider;
     Schema    = tileSchema;
 }
Example #60
0
 private static RectangleF DrawTile(ITileSchema schema, Graphics graphics, Bitmap bitmap, RectangleF extent)
 {
     // For drawing on WinForms there are two things to take into account 
     // to prevent seams between tiles.
     // 1) The WrapMode should be set to TileFlipXY. This is related 
     //    to how pixels are rounded by GDI+
     ImageAttributes imageAttributes = new ImageAttributes();
     imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
     // 2) The rectangle should be rounded to actual pixels. 
     Rectangle roundedExtent = RoundToPixel(extent);
     graphics.DrawImage(bitmap, roundedExtent, 0, 0, schema.Width, schema.Height, GraphicsUnit.Pixel, imageAttributes);
     return extent;
 }