public static Extent ConvertToMercatore(Extent extent)
        {
            NetTopologySuite.Geometries.PrecisionModel precisionModel = new NetTopologySuite.Geometries.PrecisionModel(GeoAPI.Geometries.PrecisionModels.Floating);

            CoordinateSystem wgs84 = GeographicCoordinateSystem.WGS84 as CoordinateSystem;
            CoordinateSystem mercatore = ProjectedCoordinateSystem.WebMercator as CoordinateSystem;
            ICoordinateSystemFactory cFac = new  CoordinateSystemFactory();

            int SRID_wgs84 = Convert.ToInt32(wgs84.AuthorityCode);    //WGS84 SRID
            int SRID_mercatore = Convert.ToInt32(mercatore.AuthorityCode); //Mercatore SRID

            ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory ctFact = new ProjNet.CoordinateSystems.Transformations.CoordinateTransformationFactory();
            GeoAPI.CoordinateSystems.Transformations.ICoordinateTransformation transformation = ctFact.CreateFromCoordinateSystems(wgs84, mercatore);

            NetTopologySuite.Geometries.GeometryFactory factory_wgs84 = new NetTopologySuite.Geometries.GeometryFactory(precisionModel, SRID_wgs84);

            var bottomLeft = factory_wgs84.CreatePoint(new GeoAPI.Geometries.Coordinate(extent.Left, extent.Bottom, 0));
            var topRight = factory_wgs84.CreatePoint(new GeoAPI.Geometries.Coordinate(extent.Right, extent.Top, 0));

            double[] coords_bl = transformation.MathTransform.Transform(new double[] { bottomLeft.X, bottomLeft.Y });
            double[] coords_tr = transformation.MathTransform.Transform(new double[] { topRight.X, topRight.Y });

            NetTopologySuite.Geometries.GeometryFactory factory_mercatore = new NetTopologySuite.Geometries.GeometryFactory(precisionModel, SRID_mercatore);

            var p1_bl = factory_mercatore.CreatePoint(new GeoAPI.Geometries.Coordinate(coords_bl[0], coords_bl[1]));
            var p2_tr = factory_mercatore.CreatePoint(new GeoAPI.Geometries.Coordinate(coords_tr[0], coords_tr[1]));

            return new Extent(p1_bl.X, p1_bl.Y, p2_tr.X, p2_tr.Y);
        }
Example #2
0
        static void Main()
        {
            // 1) Create a tile source

            //This is an example of the open street map tile source:
            var tileSource = new HttpTileSource(new GlobalSphericalMercator(0, 18),
                "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                new[] { "a", "b", "c" }, "OSM");

            // 2) Calculate which tiles you need

            // the extent of the visible map changes but lets start with the whole world
            var extent = new Extent(-20037508, -20037508, 20037508, 20037508);
            const int screenWidthInPixels = 400; // The width of the map on screen in pixels
            var unitsPerPixel = extent.Width / screenWidthInPixels;
            var tileInfos = tileSource.Schema.GetTileInfos(extent, unitsPerPixel);

            // 3) Fetch the tiles from the service

            var tiles = new Dictionary<TileInfo, byte[]>();
            foreach (var tileInfo in tileInfos)
            {
                tiles[tileInfo] = tileSource.GetTile(tileInfo);
            }

            // Show that something actually happended:

            foreach (var tile in tiles)
            {
                System.Console.WriteLine("Column: {0}, Row: {1}, level: {2}, bytes: {3}",
                    tile.Key.Index.Col, tile.Key.Index.Row, tile.Key.Index.Level, tile.Value.Length);
            }

            System.Console.ReadKey();
        }
        public SphericalMercatorWorldSchema()
        {
            var resolutions = new[] { 
                156543.033900000, 78271.516950000, 39135.758475000, 19567.879237500, 
                9783.939618750, 4891.969809375, 2445.984904688, 1222.992452344, 
                611.496226172, 305.748113086, 152.874056543, 76.437028271, 
                38.218514136, 19.109257068, 9.554628534, 4.777314267, 
                2.388657133, 1.194328567, 0.597164283};

            var count = 0;
            foreach (var resolution in resolutions)
            {
                Resolutions[count] = new Resolution {Id = count.ToString(CultureInfo.InvariantCulture), UnitsPerPixel = resolution};
                count++;
            }
            Height = 256;
            Width = 256;
            Extent = new Extent(-20037508.342789, -20037508.342789, 20037508.342789, 20037508.342789);
            OriginX = -20037508.342789;
            OriginY = -20037508.342789;
            Name = "WorldSphericalMercator";
            Format = "png";
            Axis = AxisDirection.Normal;
            Srs = "EPSG:3857";
        }
 private double[] ToGeoJSONArray(Extent extent)
 {
     // GeoJSON.NET has no class for bounding boxes. It just holds them in a double array.
     // The spec says it should first the lowest and then all the highest values for all axes:
     // http://geojson.org/geojson-spec.html#bounding-boxes
     return new [] {extent.MinX, extent.MinY, extent.MaxX, extent.MaxY };
 }
 public MapServerDownloader(Extent downloadExtent, int minDownloadZoom, int maxDownloadZoom)
     : this()
 {
     this.downloadExtent = downloadExtent;
     this.minDownloadZoom = minDownloadZoom;
     this.maxDownloadZoom = maxDownloadZoom;
 }
Example #6
0
        public static Extent ToExtent(Envelope envelope)
        {
            if (envelope == null)
                throw new ArgumentNullException("envelope");

            var result = new Extent(envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY);
            return result;
        }
Example #7
0
 public bool Intersects(Extent o)
 {
     if (xmin > o.xmax) return false;
     if (xmax < o.xmin) return false;
     if (ymin > o.ymax) return false;
     if (ymax < o.ymin) return false;
     return true;
 }
Example #8
0
 /// <summary>
 /// Creates a new instance of <see cref="IndexNode"/> (called when an
 /// instance of <see cref="DataNode"/> reaches its split threshold).
 /// </summary>
 /// <param name="w">The spatial extent of the node</param>
 /// <param name="points">The points that need to be indexed</param>
 /// <param name="depth">The 0-based depth of this node (0 for root)</param>
 internal IndexNode(Extent w, List<IPoint> points, int depth)
     : base(w)
 {
     Debug.Assert(depth>=0 && depth<=Node.MAX_DEPTH);
     m_Children = new List<Node>(1);
     foreach(IPoint p in points)
         this.Add(p, depth);
 }
Example #9
0
        public static Envelope ToEnvelope(Extent extent)
        {
            if (extent == null)
                throw new ArgumentNullException("extent");

            var result = new Envelope(extent.Left, extent.Right, extent.Bottom, extent.Top);
            return result;
        }
Example #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SpatialIndex"/> class
        /// with nothing in it.
        /// </summary>
        public SpatialIndex()
        {
            Extent all = new Extent();

            m_Points = new PointIndex();
            m_Lines = new RectangleIndex(all);
            m_Text = new RectangleIndex(all);
            m_Polygons = new RectangleIndex(all);
        }
Example #11
0
 public PolygonCollection()
     : base()
 {
     _patternName = string.Empty;
     _patternType = PatternType.NONE;
     _items = new ObservableCollection<Polygon>();
     _items.CollectionChanged += _items_CollectionChanged;
     _extent = new Extent();
 }
Example #12
0
        public static void PositionImage(Image image, Extent extent, Viewport viewport)
        {
            var min = viewport.WorldToScreen(extent.MinX, extent.MinY);
            var max = viewport.WorldToScreen(extent.MaxX, extent.MaxY);

            Canvas.SetLeft(image, min.X);
            Canvas.SetTop(image, max.Y);
            image.Width = max.X - min.X;
            image.Height = min.Y - max.Y;
        }
Example #13
0
        public void TileSchemaWithExtentThatDoesNotStartInOriginShouldReturnNoTiles()
        {
            // arrange
            var schema = new WkstNederlandSchema { Extent = new Extent(187036, 331205, 187202, 331291) };
            var mapExtent = new Extent(187256.999043765, 331197.712996388, 187437.576002535, 331303.350517269);

            // act
            var tileInfos = schema.GetTileInfos(mapExtent, "14");

            // assert
            Assert.AreEqual(tileInfos.Count(), 0);
        }
Example #14
0
        public void WorldToTileShouldReturnCorrectTileRange()
        {
            // arrange
            var expectedRange = new TileRange(1, 2);
            var schema = new SphericalMercatorWorldSchema();
            var extent = new Extent(-15028130, -10018753, -10018755, -5009378);
            
            // act
            var range = TileTransform.WorldToTile(extent, 3, schema);

            // assert
            Assert.AreEqual(range, expectedRange);
        }
Example #15
0
    public bool ContainsExtent(ref Extent extent)
    {
        if (minX <= extent.MinX &&
           maxX >= extent.MaxX &&
           minY <= extent.MinY &&
           maxY >= extent.MaxY &&
           minZ <= extent.MinZ &&
           maxZ >= extent.MaxZ)
        {
            return true;
        }

        return false;
    }
Example #16
0
        public void TileSchemaWithExtentThatDoesOriginateInOriginShouldReturnCorrectNumberOfTiles()
        {
            // arrange
            var schemaExtent = new Extent(187009, 331184, 187189, 331290);
            var schema = new WkstNederlandSchema { Extent = schemaExtent, OriginY = -100000 };
            var requestExtent = GrowExtent(schemaExtent, schemaExtent.Width);

            // act
            var tileInfos = schema.GetTileInfos(requestExtent, "14").ToList();

            // assert
            Assert.True(TilesWithinEnvelope(tileInfos, schemaExtent));
            Assert.True(Math.Abs(TileAreaWithinEnvelope(tileInfos, schemaExtent) - schemaExtent.Area) < Epsilon);
        }
Example #17
0
        public ExtentOperation(Session session, Extent firstOperand,  Extent secondOperand,  ExtentOperationType operationType)
            : base(session)
        {
            if (!firstOperand.ObjectType.Equals(secondOperand.ObjectType))
            {
                throw new ArgumentException("Both extents in a Union, Intersect or Except must be from the same type");
            }

            this.operationType = operationType;

            this.firstOperand = firstOperand;
            this.secondOperand = secondOperand;

            firstOperand.Parent = this;
            secondOperand.Parent = this;
        }
Example #18
0
        public void TileToWorldShouldReturnCorrectExtent()
        {
            // arrange
            var range = new TileRange(1, 2);
            var schema = new SphericalMercatorWorldSchema();
            var expectedExtent = new Extent(-15028131.257989,-10018754.173189,-10018754.173189,-5009377.088389);
              
            // act
            var extent = TileTransform.TileToWorld(range, 3, schema);

            // assert
            Assert.AreEqual(extent.MinX, expectedExtent.MinX, 0.0001);
            Assert.AreEqual(extent.MinY, expectedExtent.MinY, 0.0001);
            Assert.AreEqual(extent.MaxX, expectedExtent.MaxX, 0.0001);
            Assert.AreEqual(extent.MaxY, expectedExtent.MaxY, 0.0001);
        }
Example #19
0
        public void SmallRasterTest()
        {
            string path = FileTools.GetTempFileName(".BGD");

            const double xllcorner = 3267132.224761;
            const double yllcorner = 5326939.203029;
            const int ncols = 1098;
            const int nrows = 725;
            const double cellsize = 500;
            double x2 = xllcorner + (cellsize * ncols);
            double y2 = yllcorner + (cellsize * nrows);
            Extent myExtent = new Extent(xllcorner, yllcorner, x2, y2);
            IRaster output;
            output = Raster.Create(path, String.Empty, ncols, nrows, 1, typeof(double), new[] { String.Empty });
            output.Bounds = new RasterBounds(nrows, ncols, myExtent);
            output.NoDataValue = -9999;
            int mRow = output.Bounds.NumRows;
            int mCol = output.Bounds.NumColumns;

            // fill all cells to value=2 only for testing
            for (int row = 0; row < mRow; row++)
            {
                for (int col = 0; col < mCol; col++)
                {
                    output.Value[row, col] = 2d;
                }
            }
            output.Save();

            IRaster testRaster = Raster.Open(path);
            try
            {
                for (int row = 0; row < mRow; row++)
                {
                    for (int col = 0; col < mCol; col++)
                    {
                        Assert.AreEqual(output.Value[row, col], testRaster.Value[row, col]);
                    }
                }
            }
            finally
            {
                System.IO.File.Delete(path);    
            }
            
        }
Example #20
0
        public void TestEquals()
        {
            // arrange
            var extent = new Extent(-180, -90, 180, 90);
            var extentSame = new Extent(-180, -90, 180, 90);
            var extentDiffMinX = new Extent(-181, -90, 180, 90);
            var extentDiffMinY = new Extent(-180, -91, 180, 90);
            var extentDiffMaxX = new Extent(-180, -90, 181, 90);
            var extentDiffMaxy = new Extent(-180, -90, 180, 91);

            // act + assert
            Assert.True(extent == extentSame);
            Assert.False(extent != extentSame);
            Assert.False(extent == extentDiffMinX);
            Assert.False(extent == extentDiffMinY);
            Assert.False(extent == extentDiffMaxX);
            Assert.False(extent == extentDiffMaxy);
        }
Example #21
0
        public WkstNederlandSchema()
        {
            var unitsPerPixelArray = new[] {
                3440.64,
                1720.32,
                860.16,
                430.08,
                215.04,
                107.52,
                53.76,
                26.88,
                13.44,
                6.72,
                3.36,
                1.68,
                0.84,
                0.42,
                0.21
            };

            var count = 0;
            foreach (var unitsPerPixel in unitsPerPixelArray)
            {
                var levelId = count.ToString(CultureInfo.InvariantCulture);
                Resolutions[levelId] = new Resolution
                (
                    levelId,
                    unitsPerPixel,
                    TileSize,
                    TileSize,
                    _originX,
                    _originY
                );
                count++;
            }

            Extent = new Extent(-285401.920, 22598.080, 595401.92, 903401.920);
            OriginX = _originX;
            OriginY = _originY;
            Name = "urn:ogc:def:wkss:OGC:1.0:NLDEPSG28992Scale";
            Format = "png";
            YAxis = YAxis.TMS;
            Srs = "EPSG:28992";
        }
Example #22
0
        public void GetNoDataCellCountTest()
        {
            var path = FileTools.GetTempFileName(".bgd");
            const double xllcorner = 3267132.224761;
            const double yllcorner = 5326939.203029;
            const int ncols = 512;
            const int nrows = 128;
            const int frequencyOfNoValue = 5;

            const double cellsize = 500;
            var x2 = xllcorner + (cellsize * ncols);
            var y2 = yllcorner + (cellsize * nrows);
            var myExtent = new Extent(xllcorner, yllcorner, x2, y2);
            var target = (Raster)Raster.Create(path, String.Empty, ncols, nrows, 1, typeof(double), new[] { String.Empty });
            target.Bounds = new RasterBounds(nrows, ncols, myExtent);
            target.NoDataValue = -9999;
            var mRow = target.Bounds.NumRows;
            var mCol = target.Bounds.NumColumns;

            for (var row = 0; row < mRow; row++)
            {
                for (var col = 0; col < mCol; col++)
                {
                    if (row % frequencyOfNoValue == 0)
                        target.Value[row, col] = -9999d;
                    else
                        target.Value[row, col] = 2d;
                }
            }
            target.Save();

            const long expected = (nrows / frequencyOfNoValue) * ncols + ncols;
            var actual = target.GetNoDataCellCount();
            Assert.AreEqual(expected, actual);

            try
            {
                File.Delete(path);
            }
            catch (Exception)
            {
            }
        }
Example #23
0
        private void Initialize(WmsProjectInfo wmsInfo)
        {
            _wmsInfo = wmsInfo;
            _boundingBox = wmsInfo.LatLonBoundingBox;
            name = _wmsInfo.Name;
            Abstract = _wmsInfo.Abstract;
            Title = _wmsInfo.Title;

            if (!string.IsNullOrEmpty(_wmsInfo.MercatorEpsg))
                _mercatorEpsg = Convert.ToInt32(_wmsInfo.MercatorEpsg);

            if (!_wmsInfo.GetMapInfo.Formats.Contains("image/png") &&
                !_wmsInfo.GetMapInfo.Formats.Contains("image/png8"))
                throw new FormatException("Only PNG support is available at this time");

            if (!_wmsInfo.GetMapInfo.Formats.Contains("image/png"))
                _imageFormat = "image/png8";

            Layers = _wmsInfo.Layers;
        }
Example #24
0
        internal GlobalSphericalMercator(IEnumerable<KeyValuePair<string, Resolution>> resolutions, string format = DefaultFormat,
            YAxis yAxis = YAxis.OSM, string name = null)
        {
            Name = name ?? "GlobalSphericalMercator";
            Format = format;
            YAxis = yAxis;
            Srs = "EPSG:3857";

            foreach (var resolution in resolutions)
            {
                Resolutions[resolution.Value.Id] = resolution.Value;
            }

            OriginX = -ScaleFactor * TileSize;
            OriginY = -ScaleFactor * TileSize;

            Extent = new Extent(OriginX, OriginY, -OriginX, -OriginY);

            if (yAxis == YAxis.OSM) OriginY = -OriginY; // OSM has an inverted Y-axis
        }
        internal GlobalSphericalMercator(IEnumerable<KeyValuePair<int, Resolution>> resolutions, string format = DefaultFormat,
                                         bool invertedYAxis = DefaultInvertedYAxis, string name = null)
        {
            Name = name ?? "GlobalSphericalMercator";
            Format = format;
            Axis = invertedYAxis ? AxisDirection.InvertedY : AxisDirection.Normal;
            Srs = "EPSG:3857";
            Height = 256;
            Width = 256;

            foreach (var resolution in resolutions)
            {
                Resolutions[resolution.Key] = resolution.Value;
            }

            OriginX = -ScaleFactor * Width;
            OriginY = -ScaleFactor * Height;

            Extent = new Extent(OriginX, OriginY, -OriginX, -OriginY);

            if (invertedYAxis) OriginY = -OriginY;
        }
Example #26
0
        internal GlobalMercator(string format, IEnumerable<Resolution> resolutions)
        {
            Name = "GlobalMercator";

            Format = format;
            Axis = AxisDirection.Normal;
            Srs = "OSGEO:41001";
            Height = 256;
            Width = 256;

            var count = 0;
            foreach (var resolution in resolutions)
            {
                Resolutions[count] = resolution;
                count++;
            }

            OriginX = -ScaleFactor*Width;
            OriginY = -ScaleFactor*Height;

            Extent = new Extent(OriginX, OriginY, -OriginX, -OriginY);
        }
Example #27
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;
        }
        // Well known scale set: urn:ogc:def:wkss:OGC:1.0:NLDEPSG28992Scale
        // see: http://www.geonovum.nl/sites/default/files/Nederlandse_richtlijn_tiling_-_versie_1.0.pdf
        public WkstNederlandSchema()
        {
            var resolutions = new[] {
                3440.64,
                1720.32,
                860.16,
                430.08,
                215.04,
                107.52,
                53.76,
                26.88,
                13.44,
                6.72,
                3.36,
                1.68,
                0.84,
                0.42,
                0.21
            };

            var count = 0;
            foreach (var resolution in resolutions)
            {
                var levelId = count.ToString(CultureInfo.InvariantCulture);
                Resolutions[levelId] = new Resolution {Id = levelId, UnitsPerPixel = resolution};
                count++;
            }
            Height = 256;
            Width = 256;
            Extent = new Extent(-285401.920, 22598.080, 595401.92, 903401.920);
            OriginX = -285401.920;
            OriginY = 22598.080;
            Name = "urn:ogc:def:wkss:OGC:1.0:NLDEPSG28992Scale";
            Format = "png";
            YAxis = YAxis.TMS;
            Srs = "EPSG:28992";
        }
        public SphericalMercatorWorldSchema()
        {
            var unitsPerPixelArray = new[] {
                156543.033900000, 78271.516950000, 39135.758475000, 19567.879237500,
                9783.939618750, 4891.969809375, 2445.984904688, 1222.992452344,
                611.496226172, 305.748113086, 152.874056543, 76.437028271,
                38.218514136, 19.109257068, 9.554628534, 4.777314267,
                2.388657133, 1.194328567, 0.597164283};

            var count = 0;
            foreach (var unitsPerPixel in unitsPerPixelArray)
            {
                var levelId = count.ToString(CultureInfo.InvariantCulture);
                var ms = (int) Math.Pow(count, 2) / 2;

                Resolutions[levelId] = new Resolution(
                    levelId,
                    unitsPerPixel,
                    TileSize,
                    TileSize,
                    -20037508.342789,
                    20037508.342789,
                    ms,
                    ms);

                count++;
            }

            Extent = new Extent(-20037508.342789, -20037508.342789, 20037508.342789, 20037508.342789);
            OriginX = -20037508.342789;
            OriginY = -20037508.342789;
            Name = "WorldSphericalMercator";
            Format = "png";
            YAxis = YAxis.TMS;
            Srs = "EPSG:3857";
        }
        /// <summary>
        /// Before a shape is selected, moving the mouse over a shape will highlight that shape by changing
        /// its appearance. This tests features to determine the first feature to qualify as the highlight.
        /// </summary>
        /// <param name="e">The GeoMouseArgs parameter contains information about the mouse location and geographic coordinates.</param>
        /// <returns>A value indicating whether the shape was successfully highlighted.</returns>
        private bool ShapeHighlight(GeoMouseArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException(nameof(e), "e is null.");
            }

            Rectangle mouseRect          = new Rectangle(_mousePosition.X - 3, _mousePosition.Y - 3, 6, 6);
            Extent    ext                = Map.PixelToProj(mouseRect);
            IPolygon  env                = ext.ToEnvelope().ToPolygon();
            bool      requiresInvalidate = false;

            foreach (IFeature feature in _featureSet.Features)
            {
                if (_featureSet.FeatureType == FeatureType.Point || _featureSet.FeatureType == FeatureType.MultiPoint)
                {
                    MapPointLayer mpl = _layer as MapPointLayer;
                    if (mpl != null)
                    {
                        int           w  = 3;
                        int           h  = 3;
                        PointCategory pc = mpl.GetCategory(feature) as PointCategory;
                        if (pc != null)
                        {
                            if (pc.Symbolizer.ScaleMode != ScaleMode.Geographic)
                            {
                                Size2D size = pc.Symbolizer.GetSize();
                                w = (int)size.Width;
                                h = (int)size.Height;
                            }
                        }

                        _imageRect = new Rectangle(e.Location.X - (w / 2), e.Location.Y - (h / 2), w, h);
                        if (_imageRect.Contains(Map.ProjToPixel(feature.Geometry.Coordinates[0])))
                        {
                            _activeFeature = feature;
                            _oldCategory   = mpl.GetCategory(feature);
                            if (_selectedCategory == null)
                            {
                                _selectedCategory = _oldCategory.Copy();
                                _selectedCategory.SetColor(Color.Red);
                                _selectedCategory.LegendItemVisible = false;
                            }

                            mpl.SetCategory(_activeFeature, _selectedCategory);
                        }
                    }

                    requiresInvalidate = true;
                }
                else
                {
                    if (feature.Geometry.Intersects(env))
                    {
                        _activeFeature = feature;
                        _oldCategory   = _layer.GetCategory(_activeFeature);

                        if (_featureSet.FeatureType == FeatureType.Polygon)
                        {
                            IPolygonCategory pc = _activeCategory as IPolygonCategory;
                            if (pc == null)
                            {
                                _activeCategory = new PolygonCategory(Color.FromArgb(55, 255, 0, 0), Color.Red, 1)
                                {
                                    LegendItemVisible = false
                                };
                            }
                        }

                        if (_featureSet.FeatureType == FeatureType.Line)
                        {
                            ILineCategory pc = _activeCategory as ILineCategory;
                            if (pc == null)
                            {
                                _activeCategory = new LineCategory(Color.Red, 3)
                                {
                                    LegendItemVisible = false
                                };
                            }
                        }

                        _layer.SetCategory(_activeFeature, _activeCategory);
                        requiresInvalidate = true;
                    }
                }
            }

            return(requiresInvalidate);
        }
Example #31
0
        /// <summary>
        /// This draws to the back buffer. If the Backbuffer doesn't exist, this will create one.
        /// This will not flip the back buffer to the front.
        /// </summary>
        /// <param name="args">The map args.</param>
        /// <param name="regions">The regions.</param>
        /// <param name="clipRectangles">The clip rectangles.</param>
        private void DrawWindows(MapArgs args, IList <Extent> regions, IList <Rectangle> clipRectangles)
        {
            Graphics g;

            if (args.Device != null)
            {
                g = args.Device; // A device on the MapArgs is optional, but overrides the normal buffering behaviors.
            }
            else
            {
                if (BackBuffer == null)
                {
                    BackBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height);
                }
                g = Graphics.FromImage(BackBuffer);
            }

            int numBounds = Math.Min(regions.Count, clipRectangles.Count);

            for (int i = 0; i < numBounds; i++)
            {
                // For panning tiles, the region needs to be expanded.
                // This is not always 1 pixel. When very zoomed in, this could be many pixels,
                // but should correspond to 1 pixel in the source image.
                int dx = (int)Math.Ceiling(DataSet.Bounds.AffineCoefficients[1] * clipRectangles[i].Width / regions[i].Width);
                int dy = (int)Math.Ceiling(-DataSet.Bounds.AffineCoefficients[5] * clipRectangles[i].Height / regions[i].Height);

                Rectangle r = clipRectangles[i].ExpandBy(dx * 2, dy * 2);
                if (r.X < 0)
                {
                    r.X = 0;
                }
                if (r.Y < 0)
                {
                    r.Y = 0;
                }
                if (r.Width > 2 * clipRectangles[i].Width)
                {
                    r.Width = 2 * clipRectangles[i].Width;
                }
                if (r.Height > 2 * clipRectangles[i].Height)
                {
                    r.Height = 2 * clipRectangles[i].Height;
                }
                Extent env = regions[i].Reproportion(clipRectangles[i], r);
                Bitmap bmp = null;
                try
                {
                    bmp = DataSet.GetBitmap(env, r);
                    if (!_transparent.Name.Equals("0"))
                    {
                        bmp.MakeTransparent(_transparent);
                    }
                }
                catch
                {
                    bmp?.Dispose();
                    continue;
                }

                if (bmp == null)
                {
                    continue;
                }

                if (Symbolizer != null && Symbolizer.Opacity < 1)
                {
                    ColorMatrix matrix = new ColorMatrix
                    {
                        Matrix33 = Symbolizer.Opacity // draws the image not completely opaque
                    };
                    using (var attributes = new ImageAttributes())
                    {
                        attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                        g.DrawImage(bmp, new Rectangle(0, 0, r.Width, r.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attributes);
                    }
                }
                else
                {
                    g.DrawImage(bmp, new Rectangle(0, 0, r.Width, r.Height));
                }

                bmp.Dispose();
            }

            if (args.Device == null)
            {
                g.Dispose();
            }
        }
Example #32
0
        private void BuildPaths(MapArgs e, IEnumerable <int> indices, out List <GraphicsPath> paths)
        {
            paths = new List <GraphicsPath>();
            Extent             drawExtents = e.GeographicExtents;
            Rectangle          clipRect    = e.ProjToPixel(e.GeographicExtents);
            SoutherlandHodgman shClip      = new SoutherlandHodgman(clipRect);

            List <GraphicsPath> graphPaths = new List <GraphicsPath>();
            Dictionary <FastDrawnState, GraphicsPath> borders = new Dictionary <FastDrawnState, GraphicsPath>();

            for (int selectState = 0; selectState < 2; selectState++)
            {
                foreach (IPolygonCategory category in Symbology.Categories)
                {
                    FastDrawnState state = new FastDrawnState(selectState == 1, category);

                    GraphicsPath border = new GraphicsPath();
                    borders.Add(state, border);
                    graphPaths.Add(border);
                }
            }

            paths.AddRange(graphPaths);

            List <ShapeRange> shapes = DataSet.ShapeIndices;

            double[] vertices = DataSet.Vertex;

            var indiceList = indices as IList <int> ?? indices.ToList();

            if (ProgressReportingEnabled)
            {
                ProgressMeter = new ProgressMeter(ProgressHandler, "Building Paths", indiceList.Count);
            }

            if (!DrawnStatesNeeded)
            {
                FastDrawnState state = new FastDrawnState(false, Symbology.Categories[0]);

                foreach (int shp in indiceList)
                {
                    if (ProgressReportingEnabled)
                    {
                        ProgressMeter.Next();
                    }
                    ShapeRange shape = shapes[shp];
                    if (!shape.Extent.Intersects(e.GeographicExtents))
                    {
                        return;
                    }
                    if (shp >= shapes.Count)
                    {
                        return;
                    }
                    if (!borders.ContainsKey(state))
                    {
                        return;
                    }

                    BuildPolygon(vertices, shapes[shp], borders[state], e, drawExtents.Contains(shape.Extent) ? null : shClip);
                }
            }
            else
            {
                FastDrawnState[] states = DrawnStates;
                foreach (GraphicsPath borderPath in borders.Values)
                {
                    if (borderPath != null)
                    {
                        borderPath.FillMode = FillMode.Winding;
                    }
                }

                foreach (int shp in indiceList)
                {
                    if (ProgressReportingEnabled)
                    {
                        ProgressMeter.Next();
                    }
                    if (shp >= shapes.Count)
                    {
                        return;
                    }
                    if (shp >= states.Length)
                    {
                        AssignFastDrawnStates();
                        states = DrawnStates;
                    }

                    if (states[shp].Visible == false)
                    {
                        continue;
                    }
                    ShapeRange shape = shapes[shp];
                    if (!shape.Extent.Intersects(e.GeographicExtents))
                    {
                        continue;
                    }
                    if (drawExtents.Contains(shape.Extent))
                    {
                        FastDrawnState state = states[shp];
                        if (!borders.ContainsKey(state))
                        {
                            continue;
                        }
                        BuildPolygon(vertices, shapes[shp], borders[state], e, null);
                    }
                    else
                    {
                        FastDrawnState state = states[shp];
                        if (!borders.ContainsKey(state))
                        {
                            continue;
                        }
                        BuildPolygon(vertices, shapes[shp], borders[state], e, shClip);
                    }
                }
            }

            if (ProgressReportingEnabled)
            {
                ProgressMeter.Reset();
            }
        }
Example #33
0
 private void ZoomToGroupClick(object sender, EventArgs e)
 {
     OnZoomToLayer(Extent.ToEnvelope());
 }
Example #34
0
 /// <summary>
 /// Converts a single geographic envelope into an equivalent Rectangle
 /// as it would be drawn on the screen.
 /// </summary>
 /// <param name="env">The geographic IEnvelope</param>
 /// <returns>A Rectangle</returns>
 public Rectangle ProjToPixel(Extent env)
 {
     return(_gdiMapFrame.ProjToPixel(env));
 }
Example #35
0
 public void Read(AssetReader reader)
 {
     Center.Read(reader);
     Extent.Read(reader);
 }
Example #36
0
        /// <summary>
        /// Executes the ReSample Opaeration tool programmatically
        /// Ping deleted the static property for external testing.
        /// </summary>
        /// <param name="input1">The input raster.</param>
        /// <param name="newCellHeight">The size of the cell's hight.</param>
        /// <param name="newCellWidth">The size of the cell's width.</param>
        /// <param name="output">The output raster.</param>
        /// <param name="cancelProgressHandler">The progress handler.</param>
        /// <returns>Boolean, true if the method was successful.</returns>
        public bool Execute(IRaster input1, double newCellHeight, double newCellWidth, IRaster output, ICancelProgressHandler cancelProgressHandler)
        {
            // Validates the input and output data
            if (input1 == null || newCellWidth == 0 || output == null)
            {
                return(false);
            }

            Extent envelope = input1.Bounds.Extent;

            // Calculate new number of columns and rows
            int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / newCellWidth));
            int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / newCellHeight));

            int previous = 0;

            // create output raster
            output = Raster.CreateRaster(output.Filename, string.Empty, noOfCol, noOfRow, 1, input1.DataType, new[] { string.Empty });
            RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope);

            output.Bounds = bound;

            output.NoDataValue = input1.NoDataValue;

            // Loop throug every cell for new value
            int max = output.Bounds.NumRows + 1;

            for (int i = 0; i < output.Bounds.NumRows; i++)
            {
                for (int j = 0; j < output.Bounds.NumColumns; j++)
                {
                    // Projet the cell position to Map
                    Coordinate cellCenter = output.CellToProj(i, j);
                    var        index1     = input1.ProjToCell(cellCenter);

                    double val;
                    if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1)
                    {
                        val = input1.Value[index1.Row, index1.Column] == input1.NoDataValue ? output.NoDataValue : input1.Value[index1.Row, index1.Column];
                    }
                    else
                    {
                        val = output.NoDataValue;
                    }

                    output.Value[i, j] = val;

                    if (cancelProgressHandler.Cancel)
                    {
                        return(false);
                    }
                }

                int current = Convert.ToInt32(Math.Round(i * 100D / max));

                // only update when increment in persentage
                if (current > previous)
                {
                    cancelProgressHandler.Progress(current, current + TextStrings.progresscompleted);
                }

                previous = current;
            }

            output.Save();
            return(true);
        }
Example #37
0
        public void NormalizeDoesNotChokeOnStupidArea()
        {
            var ext = new Extent(-1e38, -90, -1.0001e38, 90);

            Assert.Throws <ArgumentException>(() => ext.Normalised());
        }
Example #38
0
 /// <summary>
 /// This adjusts the extents when ZoomToLayer is called in one of the internal layers.
 /// </summary>
 /// <param name="sender">Sender that raised the event.</param>
 /// <param name="e">The event args.</param>
 protected virtual void LayersZoomToLayer(object sender, EnvelopeArgs e)
 {
     ViewExtents = e.Envelope.ToExtent();
 }
Example #39
0
        /// <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, Map 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, map.PixelSize);
                    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;
                }
            }
        }
Example #40
0
 public IList <TileInfo> GetTilesWanted(ITileSchema schema, Extent extent, string levelId)
 {
     return(schema.GetTilesInView(extent, (levelId)).ToList());
 }
Example #41
0
        /// <summary>
        /// The Voronoi Graph calculation creates the lines that form a voronoi diagram.
        /// </summary>
        /// <param name="points">The points to use for creating the tesselation.</param>
        /// <param name="result">The output featureset.</param>
        /// <param name="cropToExtent">The normal polygons have sharp angles that extend like stars.
        /// Cropping will ensure that the original featureset extent plus a small extra buffer amount
        /// is the outer extent of the polygons.  Errors seem to occur if the exact extent is used.</param>
        public static void VoronoiPolygons(IFeatureSet points, IFeatureSet result, bool cropToExtent)
        {
            double[]     vertices = points.Vertex;
            VoronoiGraph gp       = Fortune.ComputeVoronoiGraph(vertices);

            Extent ext = points.Extent;

            ext.ExpandBy(ext.Width / 100, ext.Height / 100);
            Envelope env    = ext.ToEnvelope();
            IPolygon bounds = env.ToPolygon();

            // Convert undefined coordinates to a defined coordinate.
            HandleBoundaries(gp, env);
            for (int i = 0; i < vertices.Length / 2; i++)
            {
                List <VoronoiEdge> myEdges = new List <VoronoiEdge>();
                Vector2            v       = new Vector2(vertices, i * 2);
                foreach (VoronoiEdge edge in gp.Edges)
                {
                    if (!v.Equals(edge.RightData) && !v.Equals(edge.LeftData))
                    {
                        continue;
                    }
                    myEdges.Add(edge);
                }
                List <Coordinate> coords    = new List <Coordinate>();
                VoronoiEdge       firstEdge = myEdges[0];
                coords.Add(firstEdge.VVertexA.ToCoordinate());
                coords.Add(firstEdge.VVertexB.ToCoordinate());
                Vector2 previous = firstEdge.VVertexB;
                myEdges.Remove(myEdges[0]);
                Vector2 start = firstEdge.VVertexA;
                while (myEdges.Count > 0)
                {
                    for (int j = 0; j < myEdges.Count; j++)
                    {
                        VoronoiEdge edge = myEdges[j];
                        if (edge.VVertexA.Equals(previous))
                        {
                            previous = edge.VVertexB;
                            Coordinate c = previous.ToCoordinate();
                            coords.Add(c);
                            myEdges.Remove(edge);
                            break;
                        }

                        // couldn't match by adding to the end, so try adding to the beginning
                        if (edge.VVertexB.Equals(start))
                        {
                            start = edge.VVertexA;
                            coords.Insert(0, start.ToCoordinate());
                            myEdges.Remove(edge);
                            break;
                        }

                        // I don't like the reverse situation, but it seems necessary.
                        if (edge.VVertexB.Equals(previous))
                        {
                            previous = edge.VVertexA;
                            Coordinate c = previous.ToCoordinate();
                            coords.Add(c);
                            myEdges.Remove(edge);
                            break;
                        }

                        if (edge.VVertexA.Equals(start))
                        {
                            start = edge.VVertexB;
                            coords.Insert(0, start.ToCoordinate());
                            myEdges.Remove(edge);
                            break;
                        }
                    }
                }
                for (int j = 0; j < coords.Count; j++)
                {
                    Coordinate cA = coords[j];

                    // Remove NAN values
                    if (double.IsNaN(cA.X) || double.IsNaN(cA.Y))
                    {
                        coords.Remove(cA);
                    }

                    // Remove duplicate coordinates
                    for (int k = j + 1; k < coords.Count; k++)
                    {
                        Coordinate cB = coords[k];
                        if (cA.Equals2D(cB))
                        {
                            coords.Remove(cB);
                        }
                    }
                }
                foreach (Coordinate coord in coords)
                {
                    if (double.IsNaN(coord.X) || double.IsNaN(coord.Y))
                    {
                        coords.Remove(coord);
                    }
                }
                if (coords.Count <= 2)
                {
                    continue;
                }

                Polygon pg = new Polygon(new LinearRing(coords.ToArray()));

                if (cropToExtent)
                {
                    try
                    {
                        IGeometry g = pg.Intersection(bounds);
                        IPolygon  p = g as IPolygon;
                        if (p != null)
                        {
                            Feature f = new Feature(p, result);
                            f.CopyAttributes(points.Features[i]);
                        }
                    }
                    catch (Exception)
                    {
                        Feature f = new Feature(pg, result);
                        f.CopyAttributes(points.Features[i]);
                    }
                }
                else
                {
                    Feature f = new Feature(pg, result);
                    f.CopyAttributes(points.Features[i]);
                }
            }
            return;
        }
Example #42
0
 public Line(string content, Extent extent)
 {
     this.Content = content;
     this.Extent  = extent;
 }
Example #43
0
 public Extent GetExtentOfTilesInView(Extent extent, string levelId)
 {
     return(TileSchema.GetExtentOfTilesInView(this, extent, levelId));
 }
Example #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MapArgs"/> class.
 /// </summary>
 /// <param name="bufferRectangle">The buffer rectangle.</param>
 /// <param name="bufferEnvelope">The buffer envelope.</param>
 public MapArgs(Rectangle bufferRectangle, Extent bufferEnvelope)
 {
     _bufferRectangle = bufferRectangle;
     _bufferEnvelope  = bufferEnvelope;
 }
 public void ViewChanged(Extent extent, double resolution)
 {
     tileFetcher.ViewChanged(extent, resolution);
 }
Example #46
0
 /// <summary>
 /// Creates a new MapArgs, where the device is also specified, overriding the default buffering behavior.
 /// </summary>
 /// <param name="bufferRectangle"></param>
 /// <param name="bufferEnvelope"></param>
 /// <param name="g"></param>
 public MapArgs(Rectangle bufferRectangle, Extent bufferEnvelope, Graphics g)
 {
     _bufferRectangle = bufferRectangle;
     _bufferEnvelope  = bufferEnvelope;
     _graphics        = g;
 }
Example #47
0
        /// <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)
        {
            var bbox   = map.Envelope;
            var extent = new Extent(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);

#pragma warning disable CS0618 // Type or member is obsolete
            var level = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, map.PixelSize);
#pragma warning restore CS0618 // Type or member is obsolete
            var tiles = _source.Schema.GetTileInfos(extent, level);

            //Abort previous running Threads
            Cancel();

            using (var ia = new ImageAttributes())
            {
                if (!_transparentColor.IsEmpty)
                {
                    ia.SetColorKey(_transparentColor, _transparentColor);
                }
                ia.SetColorMatrix(new ColorMatrix {
                    Matrix33 = _opacity
                }, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
#if !PocketPC
                ia.SetWrapMode(WrapMode.TileFlipXY);
#endif
                var tileWidth  = _source.Schema.GetTileWidth(level);
                var tileHeight = _source.Schema.GetTileHeight(level);

                foreach (TileInfo info in tiles)
                {
                    if (_bitmaps.Find(info.Index) != null)
                    {
                        //draws directly the bitmap
                        var bb = new Envelope(new Coordinate(info.Extent.MinX, info.Extent.MinY),
                                              new Coordinate(info.Extent.MaxX, info.Extent.MaxY));
                        HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index),
                                                  tileWidth, tileHeight, ia);
                    }
                    else if (_fileCache != null && _fileCache.Exists(info.Index))
                    {
                        Bitmap img = GetImageFromFileCache(info) as Bitmap;
                        _bitmaps.Add(info.Index, img);

                        //draws directly the bitmap
                        var btExtent = info.Extent;
                        var bb       = new Envelope(new Coordinate(btExtent.MinX, btExtent.MinY),
                                                    new Coordinate(btExtent.MaxX, btExtent.MaxY));
                        HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index),
                                                  tileWidth, tileHeight, ia);
                    }
                    else
                    {
                        var cancelToken = new CancellationTokenSource();
                        var token       = cancelToken.Token;
                        var l_info      = info;
                        if (Logger.IsDebugEnabled)
                        {
                            Logger.DebugFormat("Starting new Task to download tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row);
                        }
                        var t = new System.Threading.Tasks.Task(delegate
                        {
                            if (token.IsCancellationRequested)
                            {
                                token.ThrowIfCancellationRequested();
                            }

                            if (Logger.IsDebugEnabled)
                            {
                                Logger.DebugFormat("Task started for download of tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row);
                            }

                            var res = GetTileOnThread(token, _source, l_info, _bitmaps, true);
                            if (res)
                            {
                                Interlocked.Decrement(ref _numPendingDownloads);
                                DownloadProgressChanged?.Invoke(_numPendingDownloads);
                            }
                        }, token);
                        var dt = new DownloadTask()
                        {
                            CancellationToken = cancelToken, Task = t
                        };
                        lock (_currentTasks)
                        {
                            _currentTasks.Add(dt);
                            _numPendingDownloads++;
                        }
                        t.Start();
                    }
                }
            }
        }
Example #48
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LiDarDataSet"/> class.
        /// </summary>
        /// <param name="filename">Name of the file that is used in this dataset.</param>
        public LiDarDataSet(string filename)
        {
            // here read the maxX, maxY from the las file header
            // and change the Extent property
            LasReader reader = new LasReader(filename);

            reader.initialize();
            ulong pointNum    = reader.getNumPoints();
            int   arrayLength = (int)pointNum;

            Schema      schema = reader.getSchema();
            PointBuffer data   = new PointBuffer(schema, (uint)pointNum);

            // get the dimensions (fields) of the point record for the X, Y, and Z values
            int       offsetX    = schema.getDimensionIndex(DimensionId.Id.X_i32);
            int       offsetY    = schema.getDimensionIndex(DimensionId.Id.Y_i32);
            int       offsetZ    = schema.getDimensionIndex(DimensionId.Id.Z_i32);
            Dimension dimensionX = schema.getDimension((uint)offsetX);
            Dimension dimensionY = schema.getDimension((uint)offsetY);

            schema.getDimension((uint)offsetZ);

            // make the iterator to read from the file
            StageSequentialIterator iter = reader.createSequentialIterator();

            iter.read(data);

            int xraw = data.getField_Int32(0, offsetX);
            int yraw = data.getField_Int32(0, offsetY);

            // LAS stores the data in scaled integer form: undo the scaling
            // so we can see the real values as doubles
            double maxX, maxY;
            var    minX = maxX = dimensionX.applyScaling_Int32(xraw);
            var    minY = maxY = dimensionY.applyScaling_Int32(yraw);

            for (int i = 1; i < arrayLength; i++)
            {
                xraw = data.getField_Int32((uint)i, offsetX);
                yraw = data.getField_Int32((uint)i, offsetY);

                // LAS stores the data in scaled integer form: undo the scaling
                // so we can see the real values as doubles
                double x = dimensionX.applyScaling_Int32(xraw);
                double y = dimensionY.applyScaling_Int32(yraw);

                if (x < minX)
                {
                    minX = x;
                }
                if (x > maxX)
                {
                    maxX = x;
                }
                if (y < minY)
                {
                    minY = y;
                }
                if (y > maxY)
                {
                    maxY = y;
                }
            }

            _setupExtent = new Extent(minX, minY, maxX, maxY);
        }
Example #49
0
 public void Write(AssetWriter writer)
 {
     Center.Write(writer);
     Extent.Write(writer);
 }
Example #50
0
        private List <SeriesDataCart> GetSeriesListForExtent(Extent extent, string[] keywords, double tileWidth, double tileHeight,
                                                             DateTime startDate, DateTime endDate, WebServiceNode[] serviceIDs,
                                                             IProgressHandler bgWorker, Func <SeriesDataCart, bool> seriesFilter)
        {
            var servicesToSearch = new List <Tuple <WebServiceNode[], Extent> >();

            if (serviceIDs.Length > 0)
            {
                foreach (var webService in serviceIDs)
                {
                    if (webService.ServiceBoundingBox == null)
                    {
                        servicesToSearch.Add(new Tuple <WebServiceNode[], Extent>(new[] { webService }, extent));
                        continue;
                    }
                    const double eps      = 0.05; //tolerance (0.05 deg) used for services whose bounding box is one point
                    var          wsBox    = webService.ServiceBoundingBox;
                    var          wsExtent = new Extent(wsBox.XMin - eps, wsBox.YMin - eps, wsBox.XMax + eps, wsBox.YMax + eps);
                    if (wsExtent.Intersects(extent))
                    {
                        servicesToSearch.Add(new Tuple <WebServiceNode[], Extent>(new[] { webService }, wsExtent.Intersection(extent)));
                    }
                }
            }
            else
            {
                servicesToSearch.Add(new Tuple <WebServiceNode[], Extent>(new WebServiceNode[] { }, extent));
            }

            var servicesWithExtents = new List <Tuple <WebServiceNode[], List <Extent> > >(servicesToSearch.Count);
            int totalTilesCount     = 0;

            foreach (var wsInfo in servicesToSearch)
            {
                var tiles = SearchHelper.CreateTiles(wsInfo.Item2, tileWidth, tileHeight);
                servicesWithExtents.Add(new Tuple <WebServiceNode[], List <Extent> >(wsInfo.Item1, tiles));
                totalTilesCount += tiles.Count;
            }

            var fullSeriesList   = new List <SeriesDataCart>();
            int currentTileIndex = 0;

            foreach (var wsInfo in servicesWithExtents)
            {
                var webServices = wsInfo.Item1;
                var tiles       = wsInfo.Item2;

                for (int i = 0; i < tiles.Count; i++, currentTileIndex++)
                {
                    var tile = tiles[i];

                    bgWorker.CheckForCancel();

                    // Do the web service call
                    var tileSeriesList = new List <SeriesDataCart>();
                    foreach (var keyword in keywords)
                    {
                        bgWorker.ReportMessage(
                            string.Format("Retrieving series from server. Keyword: {0}. Tile: {1} of {2}", keyword,
                                          currentTileIndex + 1, totalTilesCount));
                        bgWorker.CheckForCancel();
                        tileSeriesList.AddRange(GetSeriesCatalogForBox(tile.MinX, tile.MaxX, tile.MinY, tile.MaxY,
                                                                       keyword, startDate, endDate,
                                                                       webServices.Select(item => item.ServiceID).ToArray()));
                    }

                    fullSeriesList.AddRange(tileSeriesList.Where(seriesFilter));

                    // Report progress
                    var message         = string.Format("{0} Series found", fullSeriesList.Count);
                    var percentProgress = (currentTileIndex * 100) / totalTilesCount + 1;
                    bgWorker.ReportProgress(percentProgress, message);
                }
            }

            return(fullSeriesList);
        }
Example #51
0
        /// <summary>
        /// Draws the GraphicsPaths. Before we were effectively "re-creating" the same geometric.
        /// </summary>
        /// <param name="e">The map arguments.</param>
        /// <param name="paths">The graphics path.</param>
        private void DrawPaths(MapArgs e, IList <GraphicsPath> paths)
        {
            Graphics g             = e.Device ?? Graphics.FromImage(BackBuffer);
            int      numCategories = Symbology.Categories.Count;

            if (!DrawnStatesNeeded && !EditMode)
            {
                IPolygonSymbolizer ps = Symbolizer;

                g.SmoothingMode = ps.Smoothing ? SmoothingMode.AntiAlias : SmoothingMode.None;
                Extent catBounds = DataSet.Extent;
                var    bounds    = new RectangleF
                {
                    X = Convert.ToSingle((catBounds.MinX - e.MinX) * e.Dx),
                    Y = Convert.ToSingle((e.MaxY - catBounds.MaxY) * e.Dy)
                };
                float r = Convert.ToSingle((catBounds.MaxX - e.MinX) * e.Dx);
                bounds.Width = r - bounds.X;
                float b = Convert.ToSingle((e.MaxY - catBounds.MinY) * e.Dy);
                bounds.Height = b - bounds.Y;

                foreach (IPattern pattern in ps.Patterns)
                {
                    IGradientPattern gp = pattern as IGradientPattern;
                    if (gp != null)
                    {
                        gp.Bounds = bounds;
                    }

                    pattern.FillPath(g, paths[0]);
                }

                double scale = 1;
                if (ps.ScaleMode == ScaleMode.Geographic)
                {
                    scale = e.ImageRectangle.Width / e.GeographicExtents.Width;
                }

                foreach (IPattern pattern in ps.Patterns)
                {
                    if (pattern.UseOutline)
                    {
                        pattern.DrawPath(g, paths[0], scale);
                    }
                }
            }
            else
            {
                for (int selectState = 0; selectState < 2; selectState++)
                {
                    int iCategory = 0;
                    foreach (IPolygonCategory category in Symbology.Categories)
                    {
                        Extent catBounds = (CategoryExtents.Keys.Contains(category) ? CategoryExtents[category] : CalculateCategoryExtent(category)) ?? Extent;
                        var    bounds    = new RectangleF
                        {
                            X = Convert.ToSingle((catBounds.MinX - e.MinX) * e.Dx),
                            Y = Convert.ToSingle((e.MaxY - catBounds.MaxY) * e.Dy)
                        };
                        float r = Convert.ToSingle((catBounds.MaxX - e.MinX) * e.Dx);
                        bounds.Width = r - bounds.X;
                        float b = Convert.ToSingle((e.MaxY - catBounds.MinY) * e.Dy);
                        bounds.Height = b - bounds.Y;

                        int index = (selectState * numCategories) + iCategory;

                        // Define the symbology based on the category and selection state
                        IPolygonSymbolizer ps = category.Symbolizer;
                        if (selectState == Selected)
                        {
                            ps = category.SelectionSymbolizer;
                        }

                        g.SmoothingMode = ps.Smoothing ? SmoothingMode.AntiAlias : SmoothingMode.None;

                        foreach (IPattern pattern in ps.Patterns)
                        {
                            IGradientPattern gp = pattern as IGradientPattern;
                            if (gp != null)
                            {
                                gp.Bounds = bounds;
                            }

                            if (paths[index] != null)
                            {
                                paths[index].FillMode = FillMode.Winding;
                                pattern.FillPath(g, paths[index]);
                            }
                        }

                        double scale = 1;
                        if (ps.ScaleMode == ScaleMode.Geographic)
                        {
                            scale = e.ImageRectangle.Width / e.GeographicExtents.Width;
                        }

                        foreach (IPattern pattern in ps.Patterns)
                        {
                            if (pattern.UseOutline)
                            {
                                pattern.DrawPath(g, paths[index], scale);
                            }
                        }

                        iCategory++;
                    }
                }
            }

            if (e.Device == null)
            {
                g.Dispose();
            }
        }
Example #52
0
 /// <summary>
 /// Queries the specified search extent.
 /// </summary>
 /// <param name="searchExtent">The search extent.</param>
 /// <param name="itemHandler">The method that should be called for each query hit (any
 /// node with an extent that overlaps the query window)</param>
 internal abstract void Query(Extent searchExtent, ProcessItem itemHandler);
Example #53
0
        public void RaiseCallbackEvent(String eventArgument)
        {
            returnCommand = "REFRESH";

            string Nm = SessionName;

            GDIMap m = (GDIMap)System.Web.HttpContext.Current.Session[(string)ViewState[ClientID]];

            if (m == null)
            {
                return;
            }


            string[] arg = eventArgument.Split('|');

            string cmd = arg[0].ToUpper();

            switch (cmd)
            {
            case "ZOOMALL":
            {
                ZoomAll(ref m);
                returnCommand = "REFRESHANDHIDEBUFFER";
            }
            break;

            case "SELECT":
            {
                if (m.Layers.SelectedLayer != null)
                {
                    System.Drawing.Point pt1 = new System.Drawing.Point(Convert.ToInt32(arg[1]), Convert.ToInt32(arg[2]));
                    System.Drawing.Point pt2 = new System.Drawing.Point(Convert.ToInt32(arg[3]), Convert.ToInt32(arg[4]));

                    Coordinate pm1 = m.PixelToProj(pt1);
                    Coordinate pm2 = m.PixelToProj(pt2);

                    Extent ex = new Extent(Math.Min(pm1.X, pm2.X), Math.Min(pm1.Y, pm2.Y),
                                           Math.Max(pm1.X, pm2.X), Math.Max(pm1.Y, pm2.Y));

                    IEnvelope MapEnv = m.Extent.ToEnvelope();

                    m.Layers.SelectedLayer.ClearSelection(out MapEnv);


                    m.Layers.SelectedLayer.ClearSelection();

                    IEnvelope affectedarea = null;

                    m.Layers.SelectedLayer.Select(m.ViewExtents.ToEnvelope(), ex.ToEnvelope(), Symbology.SelectionMode.IntersectsExtent, out affectedarea);

                    returnCommand = "STRUCTURE";
                }
                else
                {
                    returnValue   = "<table><tr><td> Choose a layer! </td></tr><table>";
                    returnCommand = "POPUP";
                }
            }
            break;

            case "INFO":
            {
                System.Drawing.Point pt = new System.Drawing.Point(Convert.ToInt32(arg[2]), Convert.ToInt32(arg[3]));
                Coordinate           pm = m.PixelToProj(pt);

                Extent ex = new Extent(pm.X, pm.Y, pm.X, pm.Y);

                if (m.Layers.SelectedLayer != null)
                {
                    FeatureSet fs = m.Layers.SelectedLayer.DataSet as FeatureSet;

                    List <IFeature> flist = fs.Select(ex);

                    int n = flist.Count;

                    returnValue = "<table>";

                    if (n > 0)
                    {
                        for (int i = 0; i < fs.DataTable.Columns.Count; i++)
                        {
                            returnValue += "<tr><td>" + fs.DataTable.Columns[i].ColumnName + "</td><td>" + flist[0].DataRow[i].ToString() + "</td></tr>";
                        }

                        returnValue  += "</table>";
                        returnCommand = "POPUP";
                    }
                }
                else
                {
                    returnValue   = "<table><tr><td> Select a layer before info !</td></tr><table>";
                    returnCommand = "POPUP";
                }
            }
            break;


            case "RESIZE":
            {
                Size NewSz    = new Size(Convert.ToInt32(arg[2]), Convert.ToInt32(arg[3]));
                Size ActualSz = ControlSize;

                if (ActualSz.Width == 0 || ActualSz.Height == 0)
                {
                    ControlSize = NewSz;

                    ZoomAll(ref m);

                    returnCommand = "STRUCTURE";
                }
                else
                {
                    if (NewSz != ActualSz)
                    {
                        ControlSize = NewSz;

                        returnCommand = "STRUCTURE";
                    }
                    else
                    {
                        returnCommand = "NOTHING";
                    }
                }
            }
            break;

            case "ZOOMRECT":
            {
                System.Drawing.Point pt1 = new System.Drawing.Point(Convert.ToInt32(arg[1]), Convert.ToInt32(arg[2]));
                System.Drawing.Point pt2 = new System.Drawing.Point(Convert.ToInt32(arg[3]), Convert.ToInt32(arg[4]));

                Coordinate pm1 = m.PixelToProj(pt1);
                Coordinate pm2 = m.PixelToProj(pt2);

                Extent x = new Extent(Math.Min(pm1.X, pm2.X),
                                      Math.Min(pm1.Y, pm2.Y),
                                      Math.Max(pm1.X, pm2.X),
                                      Math.Max(pm1.Y, pm2.Y));

                m.ViewExtents = x;
                returnCommand = "REFRESHANDHIDEBUFFER";
            }
            break;

            case "ZOOMIN":
            {
                int x = Convert.ToInt32(arg[1]);
                int y = Convert.ToInt32(arg[2]);

                System.Drawing.Point pntZoomAndCenter = new System.Drawing.Point((x - m.Size.Width / 2), (y - m.Size.Height / 2));
                m.MapFrame.Pan(pntZoomAndCenter);
                m.ZoomIn();
                returnCommand = "REFRESHANDHIDEBUFFER";
            }
            break;

            case "ZOOMOUT":
            {
                int x = Convert.ToInt32(arg[1]);
                int y = Convert.ToInt32(arg[2]);

                System.Drawing.Point pnt = new System.Drawing.Point((x - m.Size.Width / 2), (y - m.Size.Height / 2));

                m.MapFrame.Pan(pnt);
                m.ZoomOut();
                returnCommand = "REFRESHANDHIDEBUFFER";
            }
            break;

            case "PAN":
            {
                int x = Convert.ToInt32(arg[1]);
                int y = Convert.ToInt32(arg[2]);

                System.Drawing.Point pnt = new System.Drawing.Point((x - m.Size.Width / 2), (y - m.Size.Height / 2));

                m.MapFrame.Pan(new System.Drawing.Point(x, y));
            }
            break;

            case "WHEELIN":
            {
                m.ZoomIn();
                returnCommand = "REFRESHANDHIDEBUFFER";
            }
            break;

            case "WHEELOUT":
            {
                m.ZoomOut();
                returnCommand = "REFRESHANDHIDEBUFFER";
            }
            break;
            }



            //ControlMap = m;
            System.Web.HttpContext.Current.Session[(string)ViewState[ClientID]] = m;


            if (returnCommand == "STRUCTURE")
            {
                returnValue = redraw(ref m);

                if (OnRedraw != null)
                {
                    OnRedraw(this);
                }
            }

            if (returnCommand == "REFRESH" | returnCommand == "REFRESHANDHIDEBUFFER")
            {
                returnValue = refresh(ref m);

                if (OnRedraw != null)
                {
                    OnRedraw(this);
                }
            }
        }
Example #54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Node"/> class.
 /// </summary>
 /// <param name="w">The covering rectangle of the node</param>
 protected Node(Extent w)
 {
     m_Window = w;
 }
Example #55
0
 public ActorAddvertisment(Actor actor, Addvertisment addvert, decimal salary)
 {
     (Actor, Addvertisment, Salary) = (actor, addvert, salary);
     Extent.Add(this);
 }
        public List <Path> GetPaths(Transform toScreen, BoundingBox mapBoundingBox, Action mouseDownAction = null)
        {
            if (_symbol == null)
            {
                return(new List <Path>());
            }

            var pathGeometry = GetPathGeometry(toScreen);

            var firstScreen  = toScreen.Transform(mapBoundingBox.TopLeft.AsWpfPoint());
            var secondScreen = toScreen.Transform(mapBoundingBox.BottomRight.AsWpfPoint());
            var screenLimit  = new BoundingBox(firstScreen.X, firstScreen.Y, secondScreen.X, secondScreen.Y);

            var size = toScreen.TransformBounds(Extent.AsRect());

            var size2 = pathGeometry.Bounds;

            var distance = Math.Max(size2.Width, size2.Height);

            var unitSize = Math.Max(_symbol.Bounds.Height, _symbol.Bounds.Width);

            var tolerance = distance / unitSize;

            List <Path> result = new List <Path>();

            var bound = _symbol.Bounds;

            for (int i = 0; i <= tolerance; i++)
            {
                double fraction = (i) / tolerance;

                System.Windows.Point location, direction;

                pathGeometry.GetPointAtFractionLength(fraction, out location, out direction);

                if (!screenLimit.Intersects(new Point(location.X, location.Y)))
                {
                    continue;
                }

                Path tempPath = new Path()
                {
                    Fill = this.VisualParameters.Fill, Data = _symbol
                };

                if (CanEdit && mouseDownAction != null)
                {
                    tempPath.MouseLeftButtonDown += (sender, e) =>
                    {
                        if (e.ClickCount > 1)
                        {
                            mouseDownAction();
                        }
                    };
                }

                Matrix matrix = Matrix.Identity;

                var rotation = Math.Atan2(direction.Y, direction.X) * 180 / Math.PI;

                matrix.RotateAt(rotation, (bound.Width + bound.X) / 2.0, (bound.Height + bound.Y) / 2.0);

                matrix.Translate(location.X - bound.Width / 2.0 - bound.X / 2.0, location.Y - bound.Height / 2.0 - bound.Y / 2.0);

                TransformGroup group = new TransformGroup();

                group.Children.Add(new MatrixTransform(matrix));

                tempPath.RenderTransform = group;

                //tempPath.Tag = new LayerTag(-1) { IsTiled = false, LayerType = LayerType.AnimatingItem };

                result.Add(tempPath);
            }

            return(result);
        }
        /// <summary>
        /// This method checks the various overviews available and attempts to create an image that will work
        /// best.
        /// </summary>
        /// <param name="envelope"></param>
        /// <param name="window"></param>
        /// <returns></returns>
        public override Bitmap GetBitmap(Extent envelope, Rectangle window)
        {
            //if (window.Width == 0 || window.Height == 0) return null;

            //Rectangle expWindow = window.ExpandBy(1);
            //IEnvelope expEnvelope = envelope.Reproportion(window, expWindow);

            //IEnvelope env = expEnvelope.Intersection(Bounds.Envelope);
            //if (env == null || env.IsNull || env.Height == 0 || env.Width == 0) return null;

            //Size[] he = _header.ImageHeaders[0];
            //int scale;

            //double cwa = expWindow.Width / expEnvelope.Width;
            //double cha = expWindow.Height / expEnvelope.Height;

            //for (scale = 0; scale < _header.ImageHeaders.Length; scale++)
            //{
            //    PyramidImageHeader ph = _header.ImageHeaders[scale];

            //    if (cwa > ph.NumColumns / Bounds.Width || cha > ph.NumRows / Bounds.Height)
            //    {
            //        if (scale > 0) scale -= 1;
            //        break;
            //    }
            //    he = ph;
            //}

            //// Get the cell coordinates of the part of the source bitmap to read
            //int x = (int)((he.NumColumns / Bounds.Width) * (env.X - he.Affine[0]));
            //int y = (int)((he.NumRows / Bounds.Height) * (he.Affine[3] - env.Y));
            //int w = (int)((he.NumColumns / Bounds.Width) * env.Width);
            //int h = (int)((he.NumRows / Bounds.Height) * env.Height);
            //if (w == 0 || h == 0) return null;
            //byte[] vals = ReadWindow(y, x, h, w, scale);
            //Bitmap bmp = new Bitmap(w, h);
            //BitmapData bData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            //Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            //bmp.UnlockBits(bData);

            //// Use the cell coordinates to determine the affine coefficients for the cells retrieved.
            //double[] affine = new double[6];
            //Array.Copy(he.Affine, affine, 6);
            //affine[0] = affine[0] + x * affine[1] + y * affine[2];
            //affine[3] = affine[3] + x * affine[4] + y * affine[5];

            //Bitmap result = new Bitmap(window.Width, window.Height);
            //Graphics g = Graphics.FromImage(result);

            //double imageToWorldW = affine[1];
            //double imageToWorldH = affine[5];

            //float cw = (float)(imageToWorldW * (window.Width / envelope.Width)); // cell width
            //float ch = -(float)(imageToWorldH * (window.Height / envelope.Height)); // cell height
            ////float sx = cw * (float)(_worldFile.Affine[2] / _worldFile.Affine[1]);
            ////float sy = ch * (float)(_worldFile.Affine[4] / _worldFile.Affine[5]);
            //const float sx = 0;
            //const float sy = 0;
            //float l = (float)(affine[0]);
            //float t = (float)(affine[3]);
            //float dx = (float)((l - envelope.Minimum.X) * (window.Width / envelope.Width));
            //float dy = (float)((envelope.Maximum.Y - t) * (window.Height / envelope.Height));
            //g.Transform = new Matrix(cw, sx, sy, ch, dx, dy);
            //g.PixelOffsetMode = PixelOffsetMode.Half;
            //if (cw > 1 || ch > 1) g.InterpolationMode = InterpolationMode.NearestNeighbor;
            //g.DrawImage(bmp, new PointF(0, 0));
            //bmp.Dispose();
            //g.Dispose();
            //return result;
            return null;
        }
Example #58
0
        public IEnumerable <TileInfo> GetTileInfos(Extent extent, double resolution)
        {
            var level = BruTile.Utilities.GetNearestLevel(_resolutions, resolution);

            return(GetTileInfos(extent, level));
        }
Example #59
0
        }//end method

        /// <summary>
        /// 処理実行
        /// </summary>
        /// <param name="opts">引数</param>
        private static void runProcess(CmdOptions opts)
        {
            try
            {
                //ファイルの存在確認
                if (!File.Exists(opts.InputCsv))
                {
                    Console.WriteLine($"File Not Found:{opts.InputCsv}");
                    Environment.Exit(1);
                }//end if

                //ディレクトリの存在確認
                if (!Directory.Exists(opts.OutDir))
                {
                    Console.WriteLine($"Directory Not Found:{opts.OutDir}");
                    Environment.Exit(1);
                }

                opts.ImageFormat = opts.ImageFormat.Trim().ToLower();
                if (opts.Bit8 && opts.ImageFormat != ".png")
                {
                    opts.Bit8 = false;
                    Console.WriteLine($"8 bit Index option cannot enable. :{opts.ImageFormat}");
                }

                //4隅座標カラムの件数確認
                var extCols = opts.ExtentColumn.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                              .Select(s => s.Trim()).ToList();

                if (extCols.Count < 4)
                {
                    Console.WriteLine("extent-column needs 4:ex minx,miny,maxx,maxy");
                    Console.WriteLine($"input:{opts.ExtentColumn}");
                    Environment.Exit(1);
                }

                //タイル関連準備
                var tileUrl = new TileUrl(opts.PreUrl, opts.PostUrl);
                tileUrl.NeedsColRow = true;
                var tileUtil = new TileUtil(tileUrl);
                var imgUtil  = new ImgUtil(tileUtil);

                var level = (int)opts.Level;


                bool checkHeader = false;

                //カラーファイルがあれば読み込み
                var          colorFile = Path.Combine(opts.OutDir, "colors.clr");
                List <Color> colors    = null;
                if (File.Exists(colorFile))
                {
                    colors = Program.readColors(colorFile);
                }
                imgUtil.Colors = colors;


                using (var fs = new FileStream(opts.InputCsv, FileMode.Open, FileAccess.Read))
                    using (var wfs = new FileStream(Path.Combine(opts.OutDir, "list.csv"), FileMode.Create, FileAccess.Write))
                        using (var sw = new StreamWriter(wfs))
                        {
                            sw.WriteLine($"{opts.UniqueColumn},img");

                            foreach (var line in CsvReader.ReadFromStream(fs))
                            {
                                //ヘッダのチェック
                                if (!checkHeader)
                                {
                                    if (!line.Headers.Contains(opts.UniqueColumn))
                                    {
                                        Console.WriteLine($"Unique Column Not Found:{opts.UniqueColumn}");
                                        Environment.Exit(1);
                                    }
                                    if (!line.Headers.Contains(extCols[0]) ||
                                        !line.Headers.Contains(extCols[1]) ||
                                        !line.Headers.Contains(extCols[2]) ||
                                        !line.Headers.Contains(extCols[3]))
                                    {
                                        Console.WriteLine($"extent-column Not Found:{opts.ExtentColumn}");
                                        Environment.Exit(1);
                                    }

                                    checkHeader = true;
                                }//end if

                                var    uniqueId = line[opts.UniqueColumn];
                                double minx, miny, maxx, maxy;
                                if (!double.TryParse(line[extCols[0]], out minx) ||
                                    !double.TryParse(line[extCols[1]], out miny) ||
                                    !double.TryParse(line[extCols[2]], out maxx) ||
                                    !double.TryParse(line[extCols[3]], out maxy))
                                {
                                    Console.WriteLine($"unique id:{uniqueId} extent cannot read.");
                                    continue;
                                }

                                var outFile = Path.Combine(opts.OutDir, $"img{uniqueId}{opts.ImageFormat}");
                                sw.WriteLine($"{uniqueId},{outFile}");//とりあえずリスト出力

                                //ファイルあれば戻す
                                if (File.Exists(outFile))
                                {
                                    continue;
                                }

                                var imgFormat = ImageFormat.Png;
                                if (outFile.ToLower().EndsWith("jpg"))
                                {
                                    imgFormat = ImageFormat.Jpeg;
                                }

                                //範囲
                                var ext = new Extent(minx, miny, maxx, maxy);

                                ExportResult ret = null;
                                try
                                {
                                    if (!opts.Bit8)
                                    {
                                        ret = imgUtil.Export(ext, level);
                                    }
                                    else
                                    {
                                        ret = imgUtil.Export8bppIndexed(ext, level);
                                    }
                                    ret.ExportImage.Save(outFile, imgFormat);
                                    File.WriteAllText(outFile + "w", ret.EsriWorldfile);
                                    if (imgUtil.Colors != null)
                                    {
                                        Program.writeColors(colorFile, imgUtil.Colors);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine($"unique id:{uniqueId} err.");
                                    Console.WriteLine(ex.Message);
                                    Console.WriteLine(ex.StackTrace);
                                }
                                finally
                                {
                                    if (ret != null && ret.ExportImage != null)
                                    {
                                        ret.ExportImage.Dispose();
                                    }
                                }
                            }//end csv loop
                        }//end file
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
                Environment.Exit(99);
            } //end try
        }     //end method
Example #60
0
 /// <summary>
 /// Creates a new instance of the ImageGraphics class for assisting with drawing.
 /// </summary>
 /// <param name="inExtent"></param>
 /// <param name="inDestRectangle"></param>
 public ImageProjection(Extent inExtent, Rectangle inDestRectangle)
 {
     _extents       = inExtent;
     _destRectangle = inDestRectangle;
 }