Ejemplo n.º 1
0
        protected override void SetCursorForHandle(MapViewport viewport, ResizeHandle handle)
        {
            var ct = ToolCursors.RotateCursor;

            viewport.Control.Cursor = ct;
        }
Ejemplo n.º 2
0
        public override void Render(Graphics g, MapViewport map)
        {
            try
            {
                _shapeFile.Open();
                var ds = new FeatureDataSet();
                _shapeFile.ExecuteIntersectionQuery(map.Envelope, ds);

                var dt = ds.Tables[0];
                foreach (FeatureDataRow fdr in dt.Rows)
                {
                    if (fdr.Geometry.EnvelopeInternal.Intersects(map.Envelope))
                    {
                        var file = fdr[_fieldName] as string;
                        if (!Path.IsPathRooted(file))
                        {
                            file = Path.Combine(Path.GetDirectoryName(_fileName), file);
                        }

                        if (file == null)
                        {
                            continue;
                        }

                        if (_logger.IsDebugEnabled)
                        {
                            _logger.Debug("Drawing " + file);
                        }

                        if (!_openDatasets.ContainsKey(file))
                        {
                            OpenDataset(file);
                            _openDatasets.Add(file, new CacheHolder()
                            {
                                Bands       = Bands,
                                Dataset     = _gdalDataset,
                                Envelope    = _envelope,
                                HistoBounds = HistoBounds,
                                ImageSize   = _imageSize,
                                Projection  = Projection
                            });
                        }
                        else
                        {
                            CacheHolder hld = _openDatasets[file];
                            Bands        = hld.Bands;
                            _gdalDataset = hld.Dataset;
                            _envelope    = hld.Envelope;
                            HistoBounds  = hld.HistoBounds;
                            _imageSize   = hld.ImageSize;
                            Projection   = hld.Projection;
                        }

                        //base.Render(g, map);
                        _envelope    = null;
                        _gdalDataset = null;
                    }
                }
            }
            catch (Exception)
            {
                _shapeFile.Close();
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Transforms a <see cref="ILineString"/> to an array of <see cref="PointF"/>s.
 /// </summary>
 /// <param name="self">The linestring</param>
 /// <param name="map">The map that defines the affine coordinate transformation</param>
 /// <returns>The array of <see cref="PointF"/>s</returns>
 public static PointF[] TransformToImage(this ILineString self, MapViewport map)
 {
     return(TransformToImage(self.Coordinates, map));
 }
Ejemplo n.º 4
0
 protected override void KeyDown(MapDocument document, MapViewport viewport, PerspectiveCamera camera, ViewportEvent e)
 {
     HandleKeyDown(e);
     base.KeyDown(document, viewport, camera, e);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Method to perform symbolization
 /// </summary>
 /// <param name="g">The graphics object to symbolize upon</param>
 /// <param name="map">The map</param>
 public override void Symbolize(Graphics g, MapViewport map)
 {
     Outline.Symbolize(g, map);
     base.Symbolize(g, map);
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Method to indicate that the symbolizer has to be prepared.
 /// </summary>
 /// <param name="g">The graphics object</param>
 /// <param name="map">The map</param>
 /// <param name="aproximateNumberOfGeometries">The approximate number of geometries</param>
 public void Begin(Graphics g, MapViewport map, int aproximateNumberOfGeometries)
 {
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Method to indicate that the symbolizers work is done and it can clean up.
 /// </summary>
 /// <param name="g">The graphics object</param>
 /// <param name="map">The map</param>
 public void End(Graphics g, MapViewport map)
 {
 }
 public override void Drag(MapDocument document, MapViewport viewport, OrthographicCamera camera,
                           ViewportEvent e,
                           Vector3 lastPosition, Vector3 position)
 {
     _skewEnd = position;
 }
 public override void EndDrag(MapDocument document, MapViewport viewport, OrthographicCamera camera,
                              ViewportEvent e, Vector3 position)
 {
     _skewStart = _skewEnd = null;
     base.EndDrag(document, viewport, camera, e, position);
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Method to indicate that the symbolizers work is done and it can clean up.
 /// </summary>
 /// <param name="g">The graphics object</param>
 /// <param name="map">The map</param>
 public void End(Graphics g, MapViewport map)
 {
     _polygonSymbolizer.End(g, map);
     _lineSymbolizer.End(g, map);
     _pointSymbolizer.End(g, map);
 }
Ejemplo n.º 11
0
        public static Coordinate MapToWorld(PointF p, MapViewport map)
        {
            var coords = MapToWorld(new [] { p }, map.Center, map.Zoom, map.MapHeight, map.PixelWidth, map.PixelHeight);

            return(coords[0]);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Method to indicate that the symbolizer has to be prepared.
 /// </summary>
 /// <param name="g">The graphics object</param>
 /// <param name="map">The map</param>
 /// <param name="aproximateNumberOfGeometries">The approximate number of geometries</param>
 public void Begin(Graphics g, MapViewport map, int aproximateNumberOfGeometries)
 {
     _lineSymbolizer.Begin(g, map, aproximateNumberOfGeometries);
     _pointSymbolizer.Begin(g, map, aproximateNumberOfGeometries);
     _polygonSymbolizer.Begin(g, map, aproximateNumberOfGeometries);
 }
Ejemplo n.º 13
0
 public override void EndDrag(MapViewport viewport, OrthographicCamera camera, ViewportEvent e, Vector3 position)
 {
     _rotateStart = _rotateEnd = null;
     base.EndDrag(viewport, camera, e, position);
 }
Ejemplo n.º 14
0
 public override void Drag(MapViewport viewport, OrthographicCamera camera, ViewportEvent e,
                           Vector3 lastPosition, Vector3 position)
 {
     _rotateEnd = position;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Renders the layer using the current viewport
 /// </summary>
 /// <param name="g">Graphics object reference</param>
 /// <param name="map">Map which is rendered</param>
 public virtual void Render(Graphics g, MapViewport map)
 {
     Render(g, map, out _);
 }
        public Matrix4x4?GetTransformationMatrix(MapViewport viewport, OrthographicCamera camera, BoxState state, MapDocument doc)
        {
            var shearUpDown   = Handle == ResizeHandle.Left || Handle == ResizeHandle.Right;
            var shearTopRight = Handle == ResizeHandle.Top || Handle == ResizeHandle.Right;

            if (!_skewStart.HasValue || !_skewEnd.HasValue)
            {
                return(null);
            }

            var nsmd      = _skewEnd.Value - _skewStart.Value;
            var mouseDiff = State.Tool.SnapIfNeeded(nsmd);

            if (KeyboardState.Shift && !KeyboardState.Alt)
            {
                // todo post-beta: this is hard-coded to only work on the square grid
                var gridData = doc.Map.Data.GetOne <GridData>();
                if (gridData?.Grid is SquareGrid sg && gridData?.SnapToGrid == true)
                {
                    mouseDiff = nsmd.Snap(sg.Step / 2);
                }
            }

            var relative    = camera.Flatten(state.OrigEnd - state.OrigStart);
            var shearOrigin = (shearTopRight) ? state.OrigStart : state.OrigEnd;

            var shearAmount = new Vector3(mouseDiff.X / relative.Y, mouseDiff.Y / relative.X, 0);

            if (!shearTopRight)
            {
                shearAmount *= -1;
            }

            var shearMatrix = Matrix4x4.Identity;
            var sax         = shearAmount.X;
            var say         = shearAmount.Y;

            switch (camera.ViewType)
            {
            case OrthographicCamera.OrthographicType.Top:
                if (shearUpDown)
                {
                    shearMatrix.M12 = say;
                }
                else
                {
                    shearMatrix.M21 = sax;
                }
                break;

            case OrthographicCamera.OrthographicType.Front:
                if (shearUpDown)
                {
                    shearMatrix.M23 = say;
                }
                else
                {
                    shearMatrix.M32 = sax;
                }
                break;

            case OrthographicCamera.OrthographicType.Side:
                if (shearUpDown)
                {
                    shearMatrix.M13 = say;
                }
                else
                {
                    shearMatrix.M31 = sax;
                }
                break;
            }

            var stran = Matrix4x4.CreateTranslation(-shearOrigin.X, -shearOrigin.Y, -shearOrigin.Z);
            var shear = Matrix4x4.Multiply(stran, shearMatrix);
            var inv   = Matrix4x4.Invert(stran, out var i) ? i : Matrix4x4.Identity;

            return(Matrix4x4.Multiply(shear, inv));
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Renders the layer using the current viewport
 /// </summary>
 /// <param name="g">Graphics object reference</param>
 /// <param name="map">Map which is rendered</param>
 /// <returns>Rectangle enclosing the actual area rendered on the graphics canvas</returns>
 Rectangle ILayerEx.Render(Graphics g, MapViewport map)
 {
     Render(g, map, out var canvasArea);
     return(canvasArea);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Method to render this layer to the map, applying <paramref name="theme"/>.
        /// </summary>
        /// <param name="g">The graphics object</param>
        /// <param name="map">The map object</param>
        /// <param name="envelope">The envelope to render</param>
        /// <param name="theme">The theme to apply</param>
        protected void RenderInternal(Graphics g, MapViewport map, Envelope envelope, ITheme theme)
        {
            var ds = new FeatureDataSet();

            lock (_dataSource)
            {
                DataSource.Open();
                DataSource.ExecuteIntersectionQuery(envelope, ds);
                DataSource.Close();
            }

            double scale = map.GetMapScale((int)g.DpiX);
            double zoom  = map.Zoom;

            foreach (FeatureDataTable features in ds.Tables)
            {
                // Transform geometries if necessary
                if (CoordinateTransformation != null)
                {
                    for (int i = 0; i < features.Count; i++)
                    {
                        features[i].Geometry = ToTarget(features[i].Geometry);
                    }
                }

                //Linestring outlines is drawn by drawing the layer once with a thicker line
                //before drawing the "inline" on top.
                if (Style.EnableOutline)
                {
                    for (int i = 0; i < features.Count; i++)
                    {
                        var feature      = features[i];
                        var outlineStyle = theme.GetStyle(feature) as VectorStyle;
                        if (outlineStyle == null)
                        {
                            continue;
                        }
                        if (!(outlineStyle.Enabled && outlineStyle.EnableOutline))
                        {
                            continue;
                        }

                        double compare = outlineStyle.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;

                        if (!(outlineStyle.MinVisible <= compare && compare <= outlineStyle.MaxVisible))
                        {
                            continue;
                        }

                        using (outlineStyle = outlineStyle.Clone())
                        {
                            if (outlineStyle != null)
                            {
                                //Draw background of all line-outlines first
                                if (feature.Geometry is ILineString)
                                {
                                    VectorRenderer.DrawLineString(g, feature.Geometry as ILineString, outlineStyle.Outline,
                                                                  map, outlineStyle.LineOffset);
                                }
                                else if (feature.Geometry is IMultiLineString)
                                {
                                    VectorRenderer.DrawMultiLineString(g, feature.Geometry as IMultiLineString,
                                                                       outlineStyle.Outline, map, outlineStyle.LineOffset);
                                }
                            }
                        }
                    }
                }


                for (int i = 0; i < features.Count; i++)
                {
                    var feature = features[i];
                    var style   = theme.GetStyle(feature);
                    if (style == null)
                    {
                        continue;
                    }
                    if (!style.Enabled)
                    {
                        continue;
                    }

                    double compare = style.VisibilityUnits == VisibilityUnits.ZoomLevel ? zoom : scale;

                    if (!(style.MinVisible <= compare && compare <= style.MaxVisible))
                    {
                        continue;
                    }


                    IEnumerable <IStyle> stylesToRender = GetStylesToRender(style);

                    if (stylesToRender == null)
                    {
                        return;
                    }

                    foreach (var vstyle in stylesToRender)
                    {
                        if (!(vstyle is VectorStyle) || !vstyle.Enabled)
                        {
                            continue;
                        }

                        using (var clone = (vstyle as VectorStyle).Clone())
                        {
                            if (clone != null)
                            {
                                RenderGeometry(g, map, feature.Geometry, clone);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Method to indicate that the symbolizer should do its symbolizer work.
 /// </summary>
 /// <param name="g">The graphics object</param>
 /// <param name="map">The map</param>
 public void Symbolize(Graphics g, MapViewport map)
 {
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Method to render this layer to the map, applying <see cref="Style"/>.
        /// </summary>
        /// <param name="g">The graphics object</param>
        /// <param name="map">The map object</param>
        /// <param name="envelope">The envelope to render</param>
        protected void RenderInternal(Graphics g, MapViewport map, Envelope envelope)
        {
            //if style is not enabled, we don't need to render anything
            if (!Style.Enabled)
            {
                return;
            }

            IEnumerable <IStyle> stylesToRender = GetStylesToRender(Style);

            if (stylesToRender == null)
            {
                return;
            }

            foreach (var style in stylesToRender)
            {
                if (!(style is VectorStyle) || !style.Enabled)
                {
                    continue;
                }
                using (var vStyle = (style as VectorStyle).Clone())
                {
                    if (vStyle != null)
                    {
                        Collection <IGeometry> geoms;
                        // Is datasource already open?
                        lock (_dataSource)
                        {
                            bool alreadyOpen = DataSource.IsOpen;

                            // If not open yet, open it
                            if (!alreadyOpen)
                            {
                                DataSource.Open();
                            }

                            // Read data
                            geoms = DataSource.GetGeometriesInView(envelope);

                            if (_logger.IsDebugEnabled)
                            {
                                _logger.DebugFormat("Layer {0}, NumGeometries {1}", LayerName, geoms.Count);
                            }

                            // If was not open, close it
                            if (!alreadyOpen)
                            {
                                DataSource.Close();
                            }
                        }

                        // Transform geometries if necessary
                        if (CoordinateTransformation != null)
                        {
                            for (int i = 0; i < geoms.Count; i++)
                            {
                                geoms[i] = ToTarget(geoms[i]);
                            }
                        }

                        if (vStyle.LineSymbolizer != null)
                        {
                            vStyle.LineSymbolizer.Begin(g, map, geoms.Count);
                        }
                        else
                        {
                            //Linestring outlines is drawn by drawing the layer once with a thicker line
                            //before drawing the "inline" on top.
                            if (vStyle.EnableOutline)
                            {
                                foreach (var geom in geoms)
                                {
                                    if (geom != null)
                                    {
                                        //Draw background of all line-outlines first
                                        if (geom is ILineString)
                                        {
                                            VectorRenderer.DrawLineString(g, geom as ILineString, vStyle.Outline, map, vStyle.LineOffset);
                                        }
                                        else if (geom is IMultiLineString)
                                        {
                                            VectorRenderer.DrawMultiLineString(g, geom as IMultiLineString, vStyle.Outline, map, vStyle.LineOffset);
                                        }
                                    }
                                }
                            }
                        }

                        foreach (IGeometry geom in geoms)
                        {
                            if (geom != null)
                            {
                                RenderGeometry(g, map, geom, vStyle);
                            }
                        }

                        if (vStyle.LineSymbolizer != null)
                        {
                            vStyle.LineSymbolizer.Symbolize(g, map);
                            vStyle.LineSymbolizer.End(g, map);
                        }
                    }
                }
            }
        }
Ejemplo n.º 21
0
 protected override void KeyDown(MapDocument document, MapViewport viewport, OrthographicCamera camera, ViewportEvent e)
 {
     HandleKeyDown(e);
     base.KeyDown(document, viewport, camera, e);
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Method to render <paramref name="feature"/> using <paramref name="style"/>
        /// </summary>
        /// <param name="g">The graphics object</param>
        /// <param name="map">The map</param>
        /// <param name="feature">The feature's geometry</param>
        /// <param name="style">The style to apply</param>
        protected void RenderGeometry(Graphics g, MapViewport map, IGeometry feature, VectorStyle style)
        {
            if (feature == null)
            {
                return;
            }

            var geometryType = feature.OgcGeometryType;

            switch (geometryType)
            {
            case OgcGeometryType.Polygon:
                if (style.EnableOutline)
                {
                    VectorRenderer.DrawPolygon(g, (IPolygon)feature, style.Fill, style.Outline, _clippingEnabled,
                                               map);
                }
                else
                {
                    VectorRenderer.DrawPolygon(g, (IPolygon)feature, style.Fill, null, _clippingEnabled, map);
                }
                break;

            case OgcGeometryType.MultiPolygon:
                if (style.EnableOutline)
                {
                    VectorRenderer.DrawMultiPolygon(g, (IMultiPolygon)feature, style.Fill, style.Outline,
                                                    _clippingEnabled, map);
                }
                else
                {
                    VectorRenderer.DrawMultiPolygon(g, (IMultiPolygon)feature, style.Fill, null, _clippingEnabled,
                                                    map);
                }
                break;

            case OgcGeometryType.LineString:
                if (style.LineSymbolizer != null)
                {
                    style.LineSymbolizer.Render(map, (ILineString)feature, g);
                    return;
                }
                VectorRenderer.DrawLineString(g, (ILineString)feature, style.Line, map, style.LineOffset);
                return;

            case OgcGeometryType.MultiLineString:
                if (style.LineSymbolizer != null)
                {
                    style.LineSymbolizer.Render(map, (IMultiLineString)feature, g);
                    return;
                }
                VectorRenderer.DrawMultiLineString(g, (IMultiLineString)feature, style.Line, map, style.LineOffset);
                break;

            case OgcGeometryType.Point:
                if (style.PointSymbolizer != null)
                {
                    VectorRenderer.DrawPoint(style.PointSymbolizer, g, (IPoint)feature, map);
                    return;
                }

                if (style.Symbol != null || style.PointColor == null)
                {
                    VectorRenderer.DrawPoint(g, (IPoint)feature, style.Symbol, style.SymbolScale, style.SymbolOffset,
                                             style.SymbolRotation, map);
                    return;
                }
                VectorRenderer.DrawPoint(g, (IPoint)feature, style.PointColor, style.PointSize, style.SymbolOffset, map);

                break;

            case OgcGeometryType.MultiPoint:
                if (style.PointSymbolizer != null)
                {
                    VectorRenderer.DrawMultiPoint(style.PointSymbolizer, g, (IMultiPoint)feature, map);
                }
                if (style.Symbol != null || style.PointColor == null)
                {
                    VectorRenderer.DrawMultiPoint(g, (IMultiPoint)feature, style.Symbol, style.SymbolScale,
                                                  style.SymbolOffset, style.SymbolRotation, map);
                }
                else
                {
                    VectorRenderer.DrawMultiPoint(g, (IMultiPoint)feature, style.PointColor, style.PointSize, style.SymbolOffset, map);
                }
                break;

            case OgcGeometryType.GeometryCollection:
                var coll = (IGeometryCollection)feature;
                for (var i = 0; i < coll.NumGeometries; i++)
                {
                    IGeometry geom = coll[i];
                    RenderGeometry(g, map, geom, style);
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Method to perform preparatory work for symbilizing.
 /// </summary>
 /// <param name="g">The graphics object to symbolize upon</param>
 /// <param name="map">The map</param>
 /// <param name="aproximateNumberOfGeometries">An approximate number of geometries to symbolize</param>
 public override void Begin(Graphics g, MapViewport map, int aproximateNumberOfGeometries)
 {
     Outline.Begin(g, map, aproximateNumberOfGeometries);
     base.Begin(g, map, aproximateNumberOfGeometries);
 }
Ejemplo n.º 24
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();
                    }
                }
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Method to restore the state of the graphics object and do cleanup work.
 /// </summary>
 /// <param name="g">The graphics object to symbolize upon</param>
 /// <param name="map">The map</param>
 public override void End(Graphics g, MapViewport map)
 {
     Outline.End(g, map);
     base.End(g, map);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Method to indicate that the symbolizer has to be prepared.
 /// </summary>
 public override void Begin(Graphics g, MapViewport map, int aproximateNumberOfGeometries)
 {
     _graphicsPaths = new List <GraphicsPath>(aproximateNumberOfGeometries);
     base.Begin(g, map, aproximateNumberOfGeometries);
 }
Ejemplo n.º 27
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)
        {
            if (!map.Size.IsEmpty && map.Size.Width > 0 && map.Size.Height > 0)
            {
                var bmp = new Bitmap(map.Size.Width, map.Size.Height, PixelFormat.Format32bppArgb);

                using (var g = Graphics.FromImage(bmp))
                {
                    g.InterpolationMode = InterpolationMode;
                    g.Transform         = graphics.Transform.Clone();

                    var extent = new Extent(map.Envelope.MinX, map.Envelope.MinY,
                                            map.Envelope.MaxX, map.Envelope.MaxY);
                    var level      = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, Math.Max(map.PixelWidth, map.PixelHeight));
                    var tiles      = new List <TileInfo>(_source.Schema.GetTileInfos(extent, level));
                    var tileWidth  = _source.Schema.GetTileWidth(level);
                    var tileHeight = _source.Schema.GetTileWidth(level);

                    IList <WaitHandle> waitHandles = new List <WaitHandle>();
                    var toRender       = new System.Collections.Concurrent.ConcurrentDictionary <TileIndex, Bitmap>();
                    var takenFromCache = new System.Collections.Concurrent.ConcurrentDictionary <TileIndex, bool>();
                    foreach (TileInfo info in tiles)
                    {
                        var image = _bitmaps.Find(info.Index);
                        if (image != null)
                        {
                            toRender.TryAdd(info.Index, image);
                            takenFromCache.TryAdd(info.Index, true);
                            continue;
                        }
                        if (_fileCache != null && _fileCache.Exists(info.Index))
                        {
                            var tileBitmap = GetImageFromFileCache(info) as Bitmap;
                            _bitmaps.Add(info.Index, tileBitmap);
                            toRender.TryAdd(info.Index, tileBitmap);
                            takenFromCache.TryAdd(info.Index, true);
                            continue;
                        }

                        var waitHandle = new AutoResetEvent(false);
                        waitHandles.Add(waitHandle);
                        ThreadPool.QueueUserWorkItem(GetTileOnThread,
                                                     new object[] { _source, info, toRender, waitHandle, true, takenFromCache });
                    }

                    foreach (var handle in waitHandles)
                    {
                        handle.WaitOne();
                    }

                    using (var ia = new ImageAttributes())
                    {
                        if (!_transparentColor.IsEmpty)
                        {
                            ia.SetColorKey(_transparentColor, _transparentColor);
                        }
#if !PocketPC
                        ia.SetWrapMode(WrapMode.TileFlipXY);
#endif

                        foreach (var info in tiles)
                        {
                            if (!toRender.ContainsKey(info.Index))
                            {
                                continue;
                            }

                            var bitmap = toRender[info.Index];//_bitmaps.Find(info.Index);
                            if (bitmap == null)
                            {
                                continue;
                            }

                            var min = map.WorldToImage(new Coordinate(info.Extent.MinX, info.Extent.MinY));
                            var max = map.WorldToImage(new Coordinate(info.Extent.MaxX, info.Extent.MaxY));

                            min = new PointF((float)Math.Round(min.X), (float)Math.Round(min.Y));
                            max = new PointF((float)Math.Round(max.X), (float)Math.Round(max.Y));

                            try
                            {
                                g.DrawImage(bitmap,
                                            new Rectangle((int)min.X, (int)max.Y, (int)(max.X - min.X),
                                                          (int)(min.Y - max.Y)),
                                            0, 0, tileWidth, tileHeight,
                                            GraphicsUnit.Pixel,
                                            ia);
                            }
                            catch (Exception ee)
                            {
                                Logger.Error(ee.Message);
                            }
                        }
                    }

                    //Add rendered tiles to cache
                    foreach (var kvp in toRender)
                    {
                        if (takenFromCache.ContainsKey(kvp.Key) && !takenFromCache[kvp.Key])
                        {
                            _bitmaps.Add(kvp.Key, kvp.Value);
                        }
                    }

                    graphics.Transform = new Matrix();
                    graphics.DrawImageUnscaled(bmp, 0, 0);
                    graphics.Transform = g.Transform;
                }
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Method to indicate that the symbolizer should do its symbolizer work.
 /// </summary>
 public override void Symbolize(Graphics g, MapViewport map)
 {
     Symbolize(g, map, Paths);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Renders the layer
        /// </summary>
        /// <param name="g">Graphics object reference</param>
        /// <param name="map">Map which is rendered</param>
        public override void Render(Graphics g, MapViewport map)
        {
            if (Logger.IsDebugEnabled)
            {
                Logger.Debug("Rendering wmslayer: " + LayerName);
            }

            Client.WmsOnlineResource resource = GetPreferredMethod();
            var myUri = new Uri(GetRequestUrl(map.Envelope, map.Size));

            if (Logger.IsDebugEnabled)
            {
                Logger.Debug("Url: " + myUri);
            }

            var myWebRequest = WebRequest.Create(myUri);

            myWebRequest.Method  = resource.Type;
            myWebRequest.Timeout = TimeOut;

            if (myWebRequest is HttpWebRequest)
            {
                (myWebRequest as HttpWebRequest).Accept    = _mimeType;
                (myWebRequest as HttpWebRequest).KeepAlive = false;
                (myWebRequest as HttpWebRequest).UserAgent = "SharpMap-WMSLayer";
            }

            if (Credentials != null)
            {
                myWebRequest.Credentials     = Credentials;
                myWebRequest.PreAuthenticate = true;
            }
            else
            {
                myWebRequest.Credentials = CredentialCache.DefaultCredentials;
            }

            if (Proxy != null)
            {
                myWebRequest.Proxy = Proxy;
            }

            try
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Beginning request");
                }

                using (var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse())
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("Got response");
                    }

                    using (var dataStream = myWebResponse.GetResponseStream())
                    {
                        if (dataStream != null && myWebResponse.ContentType.StartsWith("image"))
                        {
                            if (Logger.IsDebugEnabled)
                            {
                                Logger.Debug("Reading image from stream");
                            }

                            var cLength = (int)myWebResponse.ContentLength;

                            if (Logger.IsDebugEnabled)
                            {
                                Logger.Debug("Content-Length: " + cLength);
                            }

                            Image img;
                            using (var ms = new MemoryStream())
                            {
                                var      buf             = new byte[50000];
                                int      numRead         = 0;
                                DateTime lastTimeGotData = DateTime.Now;
                                var      moreToRead      = true;
                                do
                                {
                                    try
                                    {
                                        int nr = dataStream.Read(buf, 0, buf.Length);
                                        ms.Write(buf, 0, nr);
                                        numRead += nr;

                                        if (nr == 0)
                                        {
                                            int testByte = dataStream.ReadByte();
                                            if (testByte == -1)
                                            {
                                                //moreToRead = false;
                                                break;
                                            }

                                            if ((DateTime.Now - lastTimeGotData).TotalSeconds > TimeOut)
                                            {
                                                if (Logger.IsInfoEnabled)
                                                {
                                                    Logger.Info("Did not get any data for " + TimeOut +
                                                                " seconds, aborting");
                                                }
                                                return;
                                            }

                                            if (Logger.IsDebugEnabled)
                                            {
                                                Logger.Debug("No data to read. Have received: " +
                                                             numRead + " of " + cLength);
                                            }


                                            //Did not get data... sleep for a while to not spin
                                            System.Threading.Thread.Sleep(10);
                                        }
                                        else
                                        {
                                            lastTimeGotData = DateTime.Now;
                                        }
                                    }
                                    catch (IOException /*ee*/)
                                    {
                                        //This can be valid since in some cases .NET failed to parse 0-sized chunks in responses..
                                        //For now, just safely ignore the exception and assume we read all data...
                                        //Either way we will get an error later if we did not..
                                        moreToRead = false;
                                    }
                                    catch (Exception ee)
                                    {
                                        Logger.Error("Error reading from WMS-server..", ee);
                                        throw;
                                    }
                                } while (moreToRead);

                                if (Logger.IsDebugEnabled)
                                {
                                    Logger.Debug("Have received: " + numRead);
                                }

                                ms.Seek(0, SeekOrigin.Begin);
                                img = Image.FromStream(ms);
                            }


                            if (Logger.IsDebugEnabled)
                            {
                                Logger.Debug("Image read.. Drawing");
                            }

                            if (Opacity < 1f)
                            {
                                using (var ia = CreateImageAttributes(Opacity))
                                {
                                    g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0,
                                                img.Width, img.Height, GraphicsUnit.Pixel, ia);
                                }
                            }
                            else
                            {
                                g.DrawImage(img, Rectangle.FromLTRB(0, 0, map.Size.Width, map.Size.Height));
                            }

                            if (Logger.IsDebugEnabled)
                            {
                                Logger.Debug("Draw complete");
                            }

                            dataStream.Close();
                        }
                    }
                    myWebResponse.Close();
                }
            }
            catch (WebException webEx)
            {
                if (!_continueOnError)
                {
                    throw (new RenderException(
                               "There was a problem connecting to the WMS server when rendering layer '" + LayerName + "'",
                               webEx));
                }
                Logger.Error("There was a problem connecting to the WMS server when rendering layer '" + LayerName +
                             "'", webEx);
            }
            catch (Exception ex)
            {
                if (!_continueOnError)
                {
                    throw (new RenderException("There was a problem rendering layer '" + LayerName + "'", ex));
                }
                Logger.Error("There was a problem connecting to the WMS server when rendering layer '" + LayerName +
                             "'", ex);
            }
            // Obsolete (and will cause infinite loop)
            //base.Render(g, map);
        }
Ejemplo n.º 30
0
 private void Awake()
 {
     mView = Object.FindObjectOfType <MapViewport>();
 }