Example #1
0
        public void DoStuff(float dT)
        {
            this.Description = "Idle";
            if (GameScenes.MainGame.DebugKeyDown)
            {
                this.Description = "Idle";
            }


            if (this.Tasks.Count > 0)
            {
                DoTasks(dT);
            }
            else
            {
                if (CurrentTask != null)
                {
                    DoTasks(dT);
                    return;
                }
                ITask t = ParentMap.GetTask(this);
                if (t != null)
                {
                    t.Actor = this;
                    this.Tasks.Enqueue(t);
                }
                else
                {
                    Console.Write(this.Name + " is idling");
                    DoRandomShit(dT);
                }
            }
        }
Example #2
0
        public List <Interfaces.ITask> GenerateTasks()
        {
            List <Interfaces.ITask> result = new List <Interfaces.ITask>();

            Point v;

            List <MapItem> items = ParentMap.GetObjects <MapItem>();

            foreach (MapItem Item in items)
            {
                if (!Item.Reserved && ParentMap.FindStockpile(Item) == null)
                {
                    v = GetFreeSpot();
                    if (v == new Point(-1, -1))
                    {
                        return(result);
                    }
                    Components.Tasks.Haul h = new Tasks.Haul(Item, v);
                    Item.Reserved = true;
                    Reserved.Add(v);
                    result.Add(h);
                }
            }

            return(result);
        }
Example #3
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (ParentMap != null)
            {
                var bounds     = ParentMap.ViewportTransform.Inverse.TransformBounds(new Rect(ParentMap.RenderSize));
                var start      = ParentMap.MapTransform.Transform(new Point(bounds.X, bounds.Y));
                var end        = ParentMap.MapTransform.Transform(new Point(bounds.X + bounds.Width, bounds.Y + bounds.Height));
                var minSpacing = MinLineSpacing * 360d / (Math.Pow(2d, ParentMap.ZoomLevel) * TileSource.TileSize);
                var spacing    = LineSpacings[LineSpacings.Length - 1];

                if (spacing >= minSpacing)
                {
                    spacing = LineSpacings.FirstOrDefault(s => s >= minSpacing);
                }

                var latLabelStart = Math.Ceiling(start.Latitude / spacing) * spacing;
                var lonLabelStart = Math.Ceiling(start.Longitude / spacing) * spacing;
                var latLabels     = new List <Label>((int)((end.Latitude - latLabelStart) / spacing) + 1);
                var lonLabels     = new List <Label>((int)((end.Longitude - lonLabelStart) / spacing) + 1);
                var labelFormat   = spacing < 1d ? "{0} {1}°{2:00}'" : "{0} {1}°";

                for (var lat = latLabelStart; lat <= end.Latitude; lat += spacing)
                {
                    latLabels.Add(new Label(lat, new FormattedText(
                                                CoordinateString(lat, labelFormat, "NS"),
                                                CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Typeface, FontSize, Foreground)));

                    drawingContext.DrawLine(Pen,
                                            ParentMap.LocationToViewportPoint(new Location(lat, start.Longitude)),
                                            ParentMap.LocationToViewportPoint(new Location(lat, end.Longitude)));
                }

                for (var lon = lonLabelStart; lon <= end.Longitude; lon += spacing)
                {
                    lonLabels.Add(new Label(lon, new FormattedText(
                                                CoordinateString(Location.NormalizeLongitude(lon), labelFormat, "EW"),
                                                CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Typeface, FontSize, Foreground)));

                    drawingContext.DrawLine(Pen,
                                            ParentMap.LocationToViewportPoint(new Location(start.Latitude, lon)),
                                            ParentMap.LocationToViewportPoint(new Location(end.Latitude, lon)));
                }

                foreach (var latLabel in latLabels)
                {
                    foreach (var lonLabel in lonLabels)
                    {
                        var position = ParentMap.LocationToViewportPoint(new Location(latLabel.Position, lonLabel.Position));

                        drawingContext.PushTransform(new RotateTransform(ParentMap.Heading, position.X, position.Y));
                        drawingContext.DrawText(latLabel.Text,
                                                new Point(position.X + StrokeThickness / 2d + 2d, position.Y - StrokeThickness / 2d - latLabel.Text.Height));
                        drawingContext.DrawText(lonLabel.Text,
                                                new Point(position.X + StrokeThickness / 2d + 2d, position.Y + StrokeThickness / 2d));
                        drawingContext.Pop();
                    }
                }
            }
        }
Example #4
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (ParentMap != null)
            {
                //ERROR HERE
                var bounds        = ParentMap.ViewportTransform.Inverse.TransformBounds(new Rect(ParentMap.RenderSize));
                var start         = ParentMap.MapTransform.Transform(new Point(bounds.X, bounds.Y));
                var end           = ParentMap.MapTransform.Transform(new Point(bounds.X + bounds.Width, bounds.Y + bounds.Height));
                var lineDistance  = GetLineDistance();
                var labelFormat   = GetLabelFormat(lineDistance);
                var latLabelStart = Math.Ceiling(start.Latitude / lineDistance) * lineDistance;
                var lonLabelStart = Math.Ceiling(start.Longitude / lineDistance) * lineDistance;

                //ERROR HERE
                if (Double.IsNaN(end.Latitude) || Double.IsNaN(end.Longitude))
                {
                    return;
                }
                var latLabels = new List <Label>((int)((end.Latitude - latLabelStart) / lineDistance) + 1);
                var lonLabels = new List <Label>((int)((end.Longitude - lonLabelStart) / lineDistance) + 1);

                for (var lat = latLabelStart; lat <= end.Latitude; lat += lineDistance)
                {
                    latLabels.Add(new Label(lat, new FormattedText(
                                                GetLabelText(lat, labelFormat, "NS"),
                                                CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Typeface, FontSize, Foreground)));

                    drawingContext.DrawLine(Pen,
                                            ParentMap.LocationToViewportPoint(new Location(lat, start.Longitude)),
                                            ParentMap.LocationToViewportPoint(new Location(lat, end.Longitude)));
                }

                for (var lon = lonLabelStart; lon <= end.Longitude; lon += lineDistance)
                {
                    lonLabels.Add(new Label(lon, new FormattedText(
                                                GetLabelText(Location.NormalizeLongitude(lon), labelFormat, "EW"),
                                                CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Typeface, FontSize, Foreground)));

                    drawingContext.DrawLine(Pen,
                                            ParentMap.LocationToViewportPoint(new Location(start.Latitude, lon)),
                                            ParentMap.LocationToViewportPoint(new Location(end.Latitude, lon)));
                }

                foreach (var latLabel in latLabels)
                {
                    foreach (var lonLabel in lonLabels)
                    {
                        var position = ParentMap.LocationToViewportPoint(new Location(latLabel.Position, lonLabel.Position));

                        drawingContext.PushTransform(new RotateTransform(ParentMap.Heading, position.X, position.Y));
                        drawingContext.DrawText(latLabel.Text,
                                                new Point(position.X + StrokeThickness / 2d + 2d, position.Y - StrokeThickness / 2d - latLabel.Text.Height));
                        drawingContext.DrawText(lonLabel.Text,
                                                new Point(position.X + StrokeThickness / 2d + 2d, position.Y + StrokeThickness / 2d));
                        drawingContext.Pop();
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Returns the block which lies next to this block in given direction.
        /// If such block doesn't exist null is returned.
        /// Uses parent map to determine next block and if the parent map is null, null is returned.
        /// </summary>
        /// <param name="direction">Direction of next block.</param>
        /// <returns>Adjacent block or null.</returns>
        public MapBlock NextBlock(Direction direction)
        {
            if (ParentMap == null)
            {
                return(null);
            }

            return(ParentMap.AdjacentBlock(x, y, direction));
        }
Example #6
0
        // TODO: Call this after serializing this from disk.
        public void Reconstitute()
        {
            List <Guid> tileGuids = TileGuids;

            foreach (Guid guid in tileGuids)
            {
                AddTile(ParentMap.GetFlyweight <Tile>(guid));
            }
        }
Example #7
0
        private Feature FindFeatureByPoint(double x, double y)
        {
            Feature result = null;

            IEnumerable <FeatureLayer> allFeatureLayers = null;
            string currentProj4 = String.Empty;

            if (ParentMap != null)
            {
                allFeatureLayers = ParentMap.GetFeatureLayers(true).Reverse();
                currentProj4     = ParentMap.DisplayProjectionParameters;
            }
            else
            {
                allFeatureLayers = new Collection <FeatureLayer>();
            }

            GeographyUnit currentUnit = GeographyUnit.DecimalDegree;

            if (!string.IsNullOrEmpty(currentProj4))
            {
                currentUnit = GisEditorWpfMap.GetGeographyUnit(currentProj4);
            }

            foreach (var featureLayer in allFeatureLayers)
            {
                Collection <Feature> featuresInDistance = null;
                featureLayer.SafeProcess(() =>
                {
                    featuresInDistance = AscendingSearch(x, y, currentUnit, featureLayer, 1, 20);
                });
                //featureLayer.Open();
                //var featuresInDistance = AscendingSearch(x, y, currentUnit, featureLayer, 1, 20);
                //featureLayer.Close();

                if (featuresInDistance != null && featuresInDistance.Count > 0)
                {
                    if (featuresInDistance.Count > 1)
                    {
                        result = featuresInDistance[0];
                        for (int i = 0; i < featuresInDistance.Count - 1; i++)
                        {
                            result = result.GetIntersection(featuresInDistance[i + 1]);
                        }
                    }
                    else
                    {
                        result = featuresInDistance[0];
                    }
                    result.Tag = Convert.ToBase64String(result.GetWellKnownBinary());
                    break;
                }
            }

            return(result);
        }
Example #8
0
        protected void UpdateImage()
        {
            updateTimer.Stop();

            if (updateInProgress)
            {
                updateTimer.Start(); // update image on next timer tick
            }
            else if (ParentMap != null && ParentMap.RenderSize.Width > 0 && ParentMap.RenderSize.Height > 0)
            {
                updateInProgress = true;

                var relativeSize = Math.Max(RelativeImageSize, 1d);
                var width        = ParentMap.RenderSize.Width * relativeSize;
                var height       = ParentMap.RenderSize.Height * relativeSize;
                var dx           = (ParentMap.RenderSize.Width - width) / 2d;
                var dy           = (ParentMap.RenderSize.Height - height) / 2d;

                var loc1 = ParentMap.ViewportPointToLocation(new Point(dx, dy));
                var loc2 = ParentMap.ViewportPointToLocation(new Point(dx + width, dy));
                var loc3 = ParentMap.ViewportPointToLocation(new Point(dx, dy + height));
                var loc4 = ParentMap.ViewportPointToLocation(new Point(dx + width, dy + height));

                var west  = Math.Min(loc1.Longitude, Math.Min(loc2.Longitude, Math.Min(loc3.Longitude, loc4.Longitude)));
                var east  = Math.Max(loc1.Longitude, Math.Max(loc2.Longitude, Math.Max(loc3.Longitude, loc4.Longitude)));
                var south = Math.Min(loc1.Latitude, Math.Min(loc2.Latitude, Math.Min(loc3.Latitude, loc4.Latitude)));
                var north = Math.Max(loc1.Latitude, Math.Max(loc2.Latitude, Math.Max(loc3.Latitude, loc4.Latitude)));

                if (!double.IsNaN(MinLongitude) && west < MinLongitude)
                {
                    west = MinLongitude;
                }

                if (!double.IsNaN(MaxLongitude) && east > MaxLongitude)
                {
                    east = MaxLongitude;
                }

                if (!double.IsNaN(MinLatitude) && south < MinLatitude)
                {
                    south = MinLatitude;
                }

                if (!double.IsNaN(MaxLatitude) && north > MaxLatitude)
                {
                    north = MaxLatitude;
                }

                var p1 = ParentMap.MapTransform.Transform(new Location(south, west));
                var p2 = ParentMap.MapTransform.Transform(new Location(north, east));

                UpdateImage(new BoundingBox(west, east, south, north),
                            (int)Math.Round((p2.X - p1.X) * ParentMap.ViewportScale),
                            (int)Math.Round((p2.Y - p1.Y) * ParentMap.ViewportScale));
            }
        }
Example #9
0
 private void InsertTileItem_Click(object sender, EventArgs e)
 {
     InsertTile(Selection);
     if (ParentMap != null)
     {
         ParentMap.DoAllLayerAdjustment(Selection, 1);
     }
     Selection = Selection;
     Refresh();
 }
Example #10
0
        public void GetChildMapWhenParentIsMappedBeforeIt()
        {
            var parentMap = new ParentMap();
            var childMap  = new ChildMap();
            var c         = new ClassMapCollection(new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture));

            c.Add(parentMap);
            c.Add(childMap);

            var map = c[typeof(Child)];

            Assert.AreEqual(childMap, map);
        }
        public void GetChildMapWhenParentIsMappedBeforeIt()
        {
            var parentMap = new ParentMap();
            var childMap  = new ChildMap();
            var c         = new CsvClassMapCollection();

            c.Add(parentMap);
            c.Add(childMap);

            var map = c[typeof(Child)];

            Assert.AreEqual(childMap, map);
        }
        public bool CanFind(int startingVertex, int goalVertex)
        {
            if (startingVertex > GraphToSearch.NumberOfVertices || goalVertex > GraphToSearch.NumberOfVertices)
            {
                throw new InvalidOperationException();
            }

            StartingVertex = startingVertex;
            Goal           = goalVertex;

            //ideally this should be a priority queue
            var priorityQueue = new List <Tuple <int, int> >();

            //list of visited
            var dictionaryOfVisited = new Dictionary <int, int>();

            var cummulativeDistance = 0;

            //Initially start with 0 weight - sorted dictionary sorts the values based on keys
            priorityQueue.Add(new Tuple <int, int>(startingVertex, cummulativeDistance));

            while (priorityQueue.Count != 0)
            {
                var node = priorityQueue.OrderBy(n => n.Item2).First();
                priorityQueue.Remove(node);

                if (node.Item1 == goalVertex)
                {
                    return(true);
                }

                //Have we seen this node before, if so unwind the stack as we do not want to explore this node again
                if (dictionaryOfVisited.ContainsKey(node.Item1))
                {
                    continue;
                }

                //Otherwise update distance and add to visited
                cummulativeDistance = cummulativeDistance + node.Item2;
                dictionaryOfVisited.Add(node.Item1, node.Item1);
                //search for neighbours
                var listOfNeighbours = GraphToSearch.GetNeighbours(node.Item1);
                foreach (var neighbour in listOfNeighbours.Where(n => !dictionaryOfVisited.ContainsKey(n)))
                {
                    priorityQueue.Add(new Tuple <int, int>(neighbour, GraphToSearch.GetEdgeWeight(node.Item1, neighbour) + cummulativeDistance));
                    ParentMap.AddOrUpdate(neighbour, node.Item1);
                }
            }

            return(false);
        }
Example #13
0
 public void ForceCheck()
 {
     foreach (MapItem i in ParentMap.GetObjects <MapItem>())
     {
         if (this.Items.Contains(i) && !this.HasItem(i))
         {
             this.Items.Remove(i);
         }
         if (!this.Items.Contains(i) && this.HasItem(i))
         {
             this.Items.Add(i);
         }
     }
 }
Example #14
0
        protected override Size MeasureOverride(Size availableSize)
        {
            var size = new Size();

            if (ParentMap != null)
            {
                var scale     = ParentMap.GetScale(ParentMap.Center).X;
                var length    = MinWidth / scale;
                var magnitude = Math.Pow(10d, Math.Floor(Math.Log10(length)));

                if (length / magnitude < 2d)
                {
                    length = 2d * magnitude;
                }
                else if (length / magnitude < 5d)
                {
                    length = 5d * magnitude;
                }
                else
                {
                    length = 10d * magnitude;
                }

                size.Width  = length * scale + StrokeThickness + Padding.Left + Padding.Right;
                size.Height = 1.25 * FontSize + StrokeThickness + Padding.Top + Padding.Bottom;

                var x1 = Padding.Left + StrokeThickness / 2d;
                var x2 = size.Width - Padding.Right - StrokeThickness / 2d;
                var y1 = size.Height / 2d;
                var y2 = size.Height - Padding.Bottom - StrokeThickness / 2d;

                line.Points = new PointCollection
                {
                    new Point(x1, y1),
                    new Point(x1, y2),
                    new Point(x2, y2),
                    new Point(x2, y1)
                };
                line.Measure(size);

                label.Text   = length >= 1000d ? string.Format("{0:0} km", length / 1000d) : string.Format("{0:0} m", length);
                label.Width  = size.Width;
                label.Height = size.Height;
                label.Measure(size);
            }

            return(size);
        }
        private void DrawCylindricalGraticule(DrawingContext drawingContext, double lineDistance, string labelFormat)
        {
            var boundingBox   = ParentMap.ViewRectToBoundingBox(new Rect(ParentMap.RenderSize));
            var latLabelStart = Math.Ceiling(boundingBox.South / lineDistance) * lineDistance;
            var lonLabelStart = Math.Ceiling(boundingBox.West / lineDistance) * lineDistance;
            var latLabels     = new List <Label>((int)((boundingBox.North - latLabelStart) / lineDistance) + 1);
            var lonLabels     = new List <Label>((int)((boundingBox.East - lonLabelStart) / lineDistance) + 1);
            var typeface      = new Typeface(FontFamily, FontStyle, FontWeight, FontStretch);
            var pixelsPerDip  = VisualTreeHelper.GetDpi(this).PixelsPerDip;
            var pen           = CreatePen();

            for (var lat = latLabelStart; lat <= boundingBox.North; lat += lineDistance)
            {
                latLabels.Add(new Label(lat, new FormattedText(
                                            GetLabelText(lat, labelFormat, "NS"),
                                            CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, FontSize, Foreground, pixelsPerDip)));

                drawingContext.DrawLine(pen,
                                        ParentMap.LocationToView(new Location(lat, boundingBox.West)),
                                        ParentMap.LocationToView(new Location(lat, boundingBox.East)));
            }

            for (var lon = lonLabelStart; lon <= boundingBox.East; lon += lineDistance)
            {
                lonLabels.Add(new Label(lon, new FormattedText(
                                            GetLabelText(Location.NormalizeLongitude(lon), labelFormat, "EW"),
                                            CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, FontSize, Foreground, pixelsPerDip)));

                drawingContext.DrawLine(pen,
                                        ParentMap.LocationToView(new Location(boundingBox.South, lon)),
                                        ParentMap.LocationToView(new Location(boundingBox.North, lon)));
            }

            foreach (var latLabel in latLabels)
            {
                foreach (var lonLabel in lonLabels)
                {
                    var position = ParentMap.LocationToView(new Location(latLabel.Position, lonLabel.Position));

                    drawingContext.PushTransform(new RotateTransform(ParentMap.ViewTransform.Rotation, position.X, position.Y));
                    drawingContext.DrawText(latLabel.Text,
                                            new Point(position.X + StrokeThickness / 2d + 2d, position.Y - StrokeThickness / 2d - latLabel.Text.Height));
                    drawingContext.DrawText(lonLabel.Text,
                                            new Point(position.X + StrokeThickness / 2d + 2d, position.Y + StrokeThickness / 2d));
                    drawingContext.Pop();
                }
            }
        }
Example #16
0
        private void DuplicateTile_Click(object sender, EventArgs e)
        {
            Tile NewTile = tiles[Selection].Clone();

            if (Selection < tiles.Count)
            {
                InsertTile(Selection + 1);
            }
            else
            {
                AddTile();
            }
            tiles[Selection + 1] = NewTile;
            ParentMap.DoAllLayerAdjustment(Selection, 1);
            Refresh();
        }
Example #17
0
 public void ParseTemplateGroupXml(XElement xml)
 {
     Name           = TmxHelper.GetAttributeAsString(xml, "name");
     NextTemplateId = TmxHelper.GetAttributeAsUInt(xml, "nexttemplateid");
     TemplateMap    = ParentMap.MakeTemplate(Name);
     foreach (XElement item in xml.Descendants("tileset"))
     {
         TsxTileset.FromXml(item, TemplateMap);
     }
     foreach (XElement item2 in xml.Descendants("template"))
     {
         TgxTemplate tgxTemplate = TgxTemplate.FromXml(item2, FirstTemplateId, TemplateMap);
         if (tgxTemplate != null)
         {
             Templates.Add(tgxTemplate);
         }
     }
 }
Example #18
0
        private string GetBackupPath(string categoryId, string pageId)
        {
            pageId = PathUtil.SafePath(pageId);

            string path;

            if (Categories.ContainsKey(categoryId))
            {
                if (ParentMap.ContainsKey(categoryId))
                {
                    string parentId = ParentMap[categoryId];

                    if (Categories.ContainsKey(parentId))
                    {
                        path = Path.Combine(Root,
                                            Categories[parentId], Categories[categoryId],
                                            pageId);
                    }
                    else
                    {
                        path = Path.Combine(Root,
                                            "ts_고아", Categories[categoryId],
                                            pageId);
                    }
                }
                else
                {
                    path = Path.Combine(Root, Categories[categoryId], pageId);
                }
            }
            else
            {
                path = Path.Combine(Root, "ts_미분류", pageId);
            }

            if (Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }

            return(path);
        }
Example #19
0
        protected void UpdateImage()
        {
            if (updateInProgress)
            {
                updateTimer.Start(); // update image on next timer tick
            }
            else
            {
                updateTimer.Stop();

                if (ParentMap != null && RenderSize.Width > 0 && RenderSize.Height > 0)
                {
                    updateInProgress = true;

                    var relativeSize = Math.Max(RelativeImageSize, 1d);
                    var width        = RenderSize.Width * relativeSize;
                    var height       = RenderSize.Height * relativeSize;
                    var dx           = (RenderSize.Width - width) / 2d;
                    var dy           = (RenderSize.Height - height) / 2d;

                    var loc1 = ParentMap.ViewportPointToLocation(new Point(dx, dy));
                    var loc2 = ParentMap.ViewportPointToLocation(new Point(dx + width, dy));
                    var loc3 = ParentMap.ViewportPointToLocation(new Point(dx, dy + height));
                    var loc4 = ParentMap.ViewportPointToLocation(new Point(dx + width, dy + height));

                    var west  = Math.Min(loc1.Longitude, Math.Min(loc2.Longitude, Math.Min(loc3.Longitude, loc4.Longitude)));
                    var east  = Math.Max(loc1.Longitude, Math.Max(loc2.Longitude, Math.Max(loc3.Longitude, loc4.Longitude)));
                    var south = Math.Min(loc1.Latitude, Math.Min(loc2.Latitude, Math.Min(loc3.Latitude, loc4.Latitude)));
                    var north = Math.Max(loc1.Latitude, Math.Max(loc2.Latitude, Math.Max(loc3.Latitude, loc4.Latitude)));

                    var p1 = ParentMap.MapTransform.Transform(new Location(south, west));
                    var p2 = ParentMap.MapTransform.Transform(new Location(north, east));

                    width  = Math.Round((p2.X - p1.X) * ParentMap.ViewportScale);
                    height = Math.Round((p2.Y - p1.Y) * ParentMap.ViewportScale);

                    var image = GetBitmap(west, east, south, north, (int)width, (int)height);

                    UpdateImage(west, east, south, north, image);
                }
            }
        }
Example #20
0
        private void UpdateBoundingBox()
        {
            var width  = ParentMap.RenderSize.Width * RelativeImageSize;
            var height = ParentMap.RenderSize.Height * RelativeImageSize;
            var x      = (ParentMap.RenderSize.Width - width) / 2d;
            var y      = (ParentMap.RenderSize.Height - height) / 2d;
            var rect   = new Rect(x, y, width, height);

            BoundingBox = ParentMap.ViewRectToBoundingBox(rect);

            if (BoundingBox != null)
            {
                if (!double.IsNaN(MinLatitude) && BoundingBox.South < MinLatitude)
                {
                    BoundingBox.South = MinLatitude;
                }

                if (!double.IsNaN(MinLongitude) && BoundingBox.West < MinLongitude)
                {
                    BoundingBox.West = MinLongitude;
                }

                if (!double.IsNaN(MaxLatitude) && BoundingBox.North > MaxLatitude)
                {
                    BoundingBox.North = MaxLatitude;
                }

                if (!double.IsNaN(MaxLongitude) && BoundingBox.East > MaxLongitude)
                {
                    BoundingBox.East = MaxLongitude;
                }

                if (!double.IsNaN(MaxBoundingBoxWidth) && BoundingBox.Width > MaxBoundingBoxWidth)
                {
                    var d = (BoundingBox.Width - MaxBoundingBoxWidth) / 2d;
                    BoundingBox.West += d;
                    BoundingBox.East -= d;
                }
            }
        }
        public GisEditorEditInteractiveOverlay()
            : base()
        {
            newFeatureIds  = new Collection <string>();
            snappingLayers = new ObservableCollection <FeatureLayer>();
            snappingLayers.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add && ParentMap != null)
                {
                    ParentMap.Refresh(this);
                }
            };
            editSnapshots = new Collection <EditSnapshot>();
            OverlayCanvas.SetValue(Canvas.ZIndexProperty, editOverlayZIndex);

            editShapesLayer               = new InMemoryFeatureLayer();
            associateControlPointsLayer   = new InMemoryFeatureLayer();
            reshapeControlPointsLayer     = new InMemoryFeatureLayer();
            snappingPointsLayer           = new InMemoryFeatureLayer();
            snappingToleranceLayer        = new InMemoryFeatureLayer();
            editsInProcessSimpleCandidate = new Collection <SimpleCandidate>();
            editCandidatesLayer           = new InMemoryFeatureLayer();

            translateTransform            = new TranslateTransform();
            OverlayCanvas.RenderTransform = translateTransform;
            RenderMode = RenderMode.DrawingVisual;
            CanRotate  = true;
            CanResize  = true;

            SetDefaultStyle();
            tile = GetLayerTile();
            OverlayCanvas.Children.Add(tile);
            SnappingDistance     = 10;
            SnappingDistanceUnit = SnappingDistanceUnit.Pixel;
            if (Application.Current != null && Application.Current.MainWindow != null)
            {
                Application.Current.MainWindow.KeyDown += new System.Windows.Input.KeyEventHandler(MainWindow_KeyDown);
            }
            TakeSnapshot();
        }
Example #22
0
        private void DeleteTileMenuItem_Click(object sender, EventArgs e)
        {
            DeleteTile(Selection);
            if (ParentMap != null)
            {
                ParentMap.DoAllLayerAdjustment(Selection, -1);
            }
            if (Sprite != null)
            {
                Sprite.RemoveBadReference(Selection);
            }

            if (Selection == tiles.Count)
            {
                Selection--;
            }
            else
            {
                Selection = Selection;  // this is just to refresh the on_selection event.
            }
            Refresh();
        }
Example #23
0
    protected override string MonsterUpdate(GameTime gameTime)
    {
        if (SeenCount == 0)
        {
            return("");
        }

        if (NextMove != "")
        {
            ProcessMove(NextMove);
        }
        var myCell = GetCell();
        var path   = ParentMap.FindCellPath(myCell, game.Player.GetCell());

        if (!path.Any())
        {
            return("");
        }
        var cell = path.FirstOrDefault();

        return(DirectionFrom(myCell - cell) !);
    }
Example #24
0
        private void UpdateImage(object sender, EventArgs e)
        {
            if (updateInProgress)
            {
                return; // update image on next timer tick
            }

            updateTimer.Stop();

            if (ParentMap != null && ActualWidth > 0 && ActualHeight > 0)
            {
                updateInProgress = true;

                var relativeSize = Math.Max(RelativeImageSize, 1d);
                var width        = ActualWidth * relativeSize;
                var height       = ActualHeight * relativeSize;
                var dx           = (ActualWidth - width) / 2d;
                var dy           = (ActualHeight - height) / 2d;
                var loc1         = ParentMap.ViewportPointToLocation(new Point(dx, dy));
                var loc2         = ParentMap.ViewportPointToLocation(new Point(width, dy));
                var loc3         = ParentMap.ViewportPointToLocation(new Point(dx, height));
                var loc4         = ParentMap.ViewportPointToLocation(new Point(width, height));

                ThreadPool.QueueUserWorkItem(o =>
                {
                    var west  = Math.Min(loc1.Longitude, Math.Min(loc2.Longitude, Math.Min(loc3.Longitude, loc4.Longitude)));
                    var east  = Math.Max(loc1.Longitude, Math.Max(loc2.Longitude, Math.Max(loc3.Longitude, loc4.Longitude)));
                    var south = Math.Min(loc1.Latitude, Math.Min(loc2.Latitude, Math.Min(loc3.Latitude, loc4.Latitude)));
                    var north = Math.Max(loc1.Latitude, Math.Max(loc2.Latitude, Math.Max(loc3.Latitude, loc4.Latitude)));
                    var image = GetImage(west, east, south, north, (int)Math.Round(width), (int)Math.Round(height));

                    Dispatcher.BeginInvoke((Action)(() => UpdateImage(west, east, south, north, image)));

                    updateInProgress = false;
                });
            }
        }
Example #25
0
        protected override void OnViewportChanged(ViewportChangedEventArgs e)
        {
            if (path == null)
            {
                path = new Path
                {
                    Data = new PathGeometry()
                };

                path.SetBinding(Shape.StrokeProperty,
                                GetBindingExpression(StrokeProperty)?.ParentBinding ??
                                new Binding
                {
                    Source = this,
                    Path   = new PropertyPath("Stroke")
                });

                path.SetBinding(Shape.StrokeThicknessProperty,
                                GetBindingExpression(StrokeThicknessProperty)?.ParentBinding ??
                                new Binding
                {
                    Source = this,
                    Path   = new PropertyPath("StrokeThickness")
                });

                Children.Add(path);
            }

            var bounds       = ParentMap.ViewportTransform.Inverse.TransformBounds(new Rect(new Point(), ParentMap.RenderSize));
            var start        = ParentMap.MapTransform.Transform(new Point(bounds.X, bounds.Y));
            var end          = ParentMap.MapTransform.Transform(new Point(bounds.X + bounds.Width, bounds.Y + bounds.Height));
            var lineDistance = GetLineDistance();

            var labelStart = new Location(
                Math.Ceiling(start.Latitude / lineDistance) * lineDistance,
                Math.Ceiling(start.Longitude / lineDistance) * lineDistance);

            var labelEnd = new Location(
                Math.Floor(end.Latitude / lineDistance) * lineDistance,
                Math.Floor(end.Longitude / lineDistance) * lineDistance);

            var lineStart = new Location(
                Math.Min(Math.Max(labelStart.Latitude - lineDistance, -ParentMap.MapTransform.MaxLatitude), ParentMap.MapTransform.MaxLatitude),
                labelStart.Longitude - lineDistance);

            var lineEnd = new Location(
                Math.Min(Math.Max(labelEnd.Latitude + lineDistance, -ParentMap.MapTransform.MaxLatitude), ParentMap.MapTransform.MaxLatitude),
                labelEnd.Longitude + lineDistance);

            if (!lineStart.Equals(graticuleStart) || !lineEnd.Equals(graticuleEnd))
            {
                graticuleStart = lineStart;
                graticuleEnd   = lineEnd;

                var geometry = (PathGeometry)path.Data;
                geometry.Figures.Clear();
                geometry.Transform = ParentMap.ViewportTransform;

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += lineDistance)
                {
                    var figure = new PathFigure
                    {
                        StartPoint = ParentMap.MapTransform.Transform(new Location(lat, lineStart.Longitude)),
                        IsClosed   = false,
                        IsFilled   = false
                    };

                    figure.Segments.Add(new LineSegment
                    {
                        Point = ParentMap.MapTransform.Transform(new Location(lat, lineEnd.Longitude)),
                    });

                    geometry.Figures.Add(figure);
                }

                for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += lineDistance)
                {
                    var figure = new PathFigure
                    {
                        StartPoint = ParentMap.MapTransform.Transform(new Location(lineStart.Latitude, lon)),
                        IsClosed   = false,
                        IsFilled   = false
                    };

                    figure.Segments.Add(new LineSegment
                    {
                        Point = ParentMap.MapTransform.Transform(new Location(lineEnd.Latitude, lon)),
                    });

                    geometry.Figures.Add(figure);
                }

                var labelFormat = GetLabelFormat(lineDistance);
                var childIndex  = 1; // 0 for Path

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += lineDistance)
                {
                    for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += lineDistance)
                    {
                        TextBlock label;

                        if (childIndex < Children.Count)
                        {
                            label = (TextBlock)Children[childIndex];
                        }
                        else
                        {
                            var renderTransform = new TransformGroup();
                            renderTransform.Children.Add(new TranslateTransform());
                            renderTransform.Children.Add(ParentMap.RotateTransform);
                            renderTransform.Children.Add(new TranslateTransform());

                            label = new TextBlock
                            {
                                RenderTransform = renderTransform
                            };

                            label.SetBinding(TextBlock.ForegroundProperty,
                                             GetBindingExpression(ForegroundProperty)?.ParentBinding ??
                                             new Binding
                            {
                                Source = this,
                                Path   = new PropertyPath("Foreground")
                            });

                            Children.Add(label);
                        }

                        childIndex++;

                        if (FontFamily != null)
                        {
                            label.FontFamily = FontFamily;
                        }

                        label.FontSize    = FontSize;
                        label.FontStyle   = FontStyle;
                        label.FontStretch = FontStretch;
                        label.FontWeight  = FontWeight;
                        label.Text        = GetLabelText(lat, labelFormat, "NS") + "\n" + GetLabelText(Location.NormalizeLongitude(lon), labelFormat, "EW");
                        label.Tag         = new Location(lat, lon);
                        label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                        var translateTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[0];
                        translateTransform.X = StrokeThickness / 2d + 2d;
                        translateTransform.Y = -label.DesiredSize.Height / 2d;
                    }
                }

                while (Children.Count > childIndex)
                {
                    Children.RemoveAt(Children.Count - 1);
                }
            }

            // don't use MapPanel.Location because labels may be at more than 180° distance from map center

            for (int i = 1; i < Children.Count; i++)
            {
                var label             = (TextBlock)Children[i];
                var location          = (Location)label.Tag;
                var viewportTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[2];
                var viewportPosition  = ParentMap.LocationToViewportPoint(location);
                viewportTransform.X = viewportPosition.X;
                viewportTransform.Y = viewportPosition.Y;
            }

            base.OnViewportChanged(e);
        }
        protected override void OnViewportChanged()
        {
            var bounds     = ParentMap.ViewportTransform.Inverse.TransformBounds(new Rect(new Point(), ParentMap.RenderSize));
            var start      = ParentMap.MapTransform.Transform(new Point(bounds.X, bounds.Y));
            var end        = ParentMap.MapTransform.Transform(new Point(bounds.X + bounds.Width, bounds.Y + bounds.Height));
            var minSpacing = MinLineSpacing * 360d / (Math.Pow(2d, ParentMap.ZoomLevel) * 256d);
            var spacing    = LineSpacings[LineSpacings.Length - 1];

            if (spacing >= minSpacing)
            {
                spacing = LineSpacings.FirstOrDefault(s => s >= minSpacing);
            }

            var labelStart = new Location(
                Math.Ceiling(start.Latitude / spacing) * spacing,
                Math.Ceiling(start.Longitude / spacing) * spacing);

            var labelEnd = new Location(
                Math.Floor(end.Latitude / spacing) * spacing,
                Math.Floor(end.Longitude / spacing) * spacing);

            var lineStart = new Location(
                Math.Min(Math.Max(labelStart.Latitude - spacing, -ParentMap.MapTransform.MaxLatitude), ParentMap.MapTransform.MaxLatitude),
                labelStart.Longitude - spacing);

            var lineEnd = new Location(
                Math.Min(Math.Max(labelEnd.Latitude + spacing, -ParentMap.MapTransform.MaxLatitude), ParentMap.MapTransform.MaxLatitude),
                labelEnd.Longitude + spacing);

            if (!lineStart.Equals(graticuleStart) || !lineEnd.Equals(graticuleEnd))
            {
                graticuleStart = lineStart;
                graticuleEnd   = lineEnd;

                var geometry = (PathGeometry)path.Data;
                geometry.Figures.Clear();
                geometry.Transform = ParentMap.ViewportTransform;

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += spacing)
                {
                    var figure = new PathFigure
                    {
                        StartPoint = ParentMap.MapTransform.Transform(new Location(lat, lineStart.Longitude)),
                        IsClosed   = false,
                        IsFilled   = false
                    };

                    figure.Segments.Add(new LineSegment
                    {
                        Point = ParentMap.MapTransform.Transform(new Location(lat, lineEnd.Longitude)),
                    });

                    geometry.Figures.Add(figure);
                }

                for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += spacing)
                {
                    var figure = new PathFigure
                    {
                        StartPoint = ParentMap.MapTransform.Transform(new Location(lineStart.Latitude, lon)),
                        IsClosed   = false,
                        IsFilled   = false
                    };

                    figure.Segments.Add(new LineSegment
                    {
                        Point = ParentMap.MapTransform.Transform(new Location(lineEnd.Latitude, lon)),
                    });

                    geometry.Figures.Add(figure);
                }

                var childIndex = 1; // 0 for Path
                var format     = spacing < 1d ? "{0} {1}°{2:00}'" : "{0} {1}°";

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += spacing)
                {
                    for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += spacing)
                    {
                        TextBlock label;

                        if (childIndex < Children.Count)
                        {
                            label = (TextBlock)Children[childIndex];
                        }
                        else
                        {
                            var renderTransform = new TransformGroup();
                            renderTransform.Children.Add(new TranslateTransform());
                            renderTransform.Children.Add(ParentMap.RotateTransform);
                            renderTransform.Children.Add(new TranslateTransform());

                            label = new TextBlock
                            {
                                RenderTransform = renderTransform
                            };

                            label.SetBinding(TextBlock.ForegroundProperty, new Binding
                            {
                                Source = this,
                                Path   = new PropertyPath("Foreground")
                            });

                            Children.Add(label);
                        }

                        childIndex++;

                        if (FontFamily != null)
                        {
                            label.FontFamily = FontFamily;
                        }

                        label.FontSize    = FontSize;
                        label.FontStyle   = FontStyle;
                        label.FontStretch = FontStretch;
                        label.FontWeight  = FontWeight;
                        label.Text        = string.Format("{0}\n{1}", CoordinateString(lat, format, "NS"), CoordinateString(Location.NormalizeLongitude(lon), format, "EW"));
                        label.Tag         = new Location(lat, lon);
                        label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

                        var translateTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[0];
                        translateTransform.X = StrokeThickness / 2d + 2d;
                        translateTransform.Y = -label.DesiredSize.Height / 2d;
                    }
                }

                while (Children.Count > childIndex)
                {
                    Children.RemoveAt(Children.Count - 1);
                }
            }

            // don't use MapPanel.Location because labels may be at more than 180° distance from map center

            for (int i = 1; i < Children.Count; i++)
            {
                var label             = (TextBlock)Children[i];
                var location          = (Location)label.Tag;
                var viewportTransform = (TranslateTransform)((TransformGroup)label.RenderTransform).Children[2];
                var viewportPosition  = ParentMap.LocationToViewportPoint(location);
                viewportTransform.X = viewportPosition.X;
                viewportTransform.Y = viewportPosition.Y;
            }

            base.OnViewportChanged();
        }
Example #27
0
        /// <summary>
        ///     对module配置与参数进行基础验证,子类重写后需要显式调用并判定返回值,如返回值不为Success,则不再执行子类后续逻辑
        /// </summary>
        /// <param name="parameter">参数</param>
        public override ExecuteResult <ITaskResult[]> Execute(TaskParameter parameter)
        {
            var baseResult = base.Execute(parameter);

            if (baseResult.Status != ResultStatus.Success)
            {
                return(ExecuteResult <ITaskResult[]> .Cancel("未找到触发会员的Parent Map."));
            }

            var mapList = new List <ParentMap>();
            var userMap = Resolve <IUserMapService>().GetParentMapFromCache(ShareOrderUser.Id);
            var map     = userMap.ParentMap.DeserializeJson <List <ParentMap> >();

            if (map == null)
            {
                return(ExecuteResult <ITaskResult[]> .Cancel("未找到触发会员的Parent Map."));
            }

            IList <ITaskResult> resultList = new List <ITaskResult>();
            long lvKey     = 0; //用于判断级差
            long userIdKey = 0; //第一个营业部userID要记录
            var  iKey      = false;
            var  firLv     = false;

            foreach (var teamRangCultivateItem in Configuration.TeamRangCultivateItems)
            {
                // 将自己加上去
                var parentMap = new ParentMap
                {
                    UserId      = ShareOrderUser.Id,
                    ParentLevel = 0
                };

                map = map.AddBefore(parentMap).ToList();

                for (var i = 0; i < TeamLevel; i++)
                {
                    var level  = 0;
                    var tempLv = 0;
                    if (map.Count < i + 1)
                    {
                        break;
                    }

                    var item  = map[i];
                    var grade = Resolve <IGradeService>().GetGrade(teamRangCultivateItem.GradeId);
                    if (grade == null)
                    {
                        break;
                    }

                    var gradeList = Resolve <IAutoConfigService>().GetList <UserGradeConfig>();

                    base.GetShareUser(item.UserId, out var shareUser);
                    var shareGradeContribute = gradeList.FirstOrDefault(u => u.Id == shareUser.GradeId).Contribute;

                    //如果是营业部 则不再判断其他等级
                    if (shareGradeContribute >= 500000)
                    {
                        level = 4;
                        iKey  = true;

                        if (i == 0)
                        {
                            userIdKey = shareUser.Id;
                        }
                    }

                    if (shareGradeContribute >= 500000)
                    {
                        level = 4;
                    }

                    if (shareGradeContribute >= 100000 && shareGradeContribute < 500000)
                    {
                        level = 3;
                    }

                    if (shareGradeContribute >= 10000 && shareGradeContribute < 100000)
                    {
                        level = 2;
                    }

                    if (shareGradeContribute >= 0 && shareGradeContribute < 10000)
                    {
                        level = 1;
                    }

                    if (i == 0)
                    {
                        lvKey = level; //获得下单人等级
                    }

                    if (level < lvKey)
                    {
                        continue;
                    }

                    if (i >= 4)
                    {
                        break;
                    }

                    #region 区分判断

                    var tempContribute =
                        gradeList.FirstOrDefault(u => u.Id == teamRangCultivateItem.GradeId).Contribute;
                    if (tempContribute >= 500000)
                    {
                        tempLv = 4;
                    }

                    if (tempContribute >= 100000 && tempContribute < 500000)
                    {
                        tempLv = 3;
                    }

                    if (tempContribute >= 10000 && tempContribute < 100000)
                    {
                        tempLv = 2;
                    }

                    if (tempContribute >= 0 && tempContribute < 10000)
                    {
                        tempLv = 1;
                    }

                    #endregion 区分判断

                    if (level == tempLv)
                    {
                        if (userIdKey == shareUser.Id && i != 0)
                        {
                            continue;
                        }

                        if (level == 0)
                        {
                            continue;
                        }

                        var mapSingle = mapList.FirstOrDefault(u => u.UserId == level);
                        if (mapSingle == null)
                        {
                            var temp = new ParentMap
                            {
                                UserId      = level,
                                ParentLevel = 1 //计算该等级出现次数
                            };
                            //如果第一个加入的值为营业厅 则不判断其他
                            if (mapList.Count() == 0 && level == 4)
                            {
                                iKey = true;
                            }

                            //如果等级小于报单人 则跳过
                            if (lvKey <= level)
                            {
                                mapList.Add(temp);
                            }

                            continue;
                        }
                        else
                        {
                            var num = mapList.FirstOrDefault(u => u.UserId == level).ParentLevel;
                            mapList.Remove(mapSingle);
                            var temp = new ParentMap
                            {
                                UserId      = level,
                                ParentLevel = num + 1 //用于计算该等级出现次数
                            };
                            mapList.Add(temp);

                            mapSingle.ParentLevel = num + 1;
                        }

                        var gradeName = Resolve <IGradeService>().GetGrade(shareUser.GradeId);
                        if (mapSingle.ParentLevel == 2)
                        {
                            if (lvKey > mapSingle.UserId)
                            {
                                continue;
                            }

                            lvKey = mapSingle.UserId;

                            var intro       = $"{gradeName.Name}育成一代";
                            var shareAmount = BaseFenRunAmount * teamRangCultivateItem.FristAmount;
                            if (shareAmount > 0)
                            {
                                CreateResultList(shareAmount, ShareOrderUser, shareUser, parameter, Configuration,
                                                 resultList, intro);
                            }
                        }

                        if (mapSingle.ParentLevel == 3 && mapSingle.UserId == 4)
                        {
                            var intro       = $"{gradeName.Name}育成二代";
                            var shareAmount = BaseFenRunAmount * teamRangCultivateItem.SecondAmount;
                            if (shareAmount > 0)
                            {
                                CreateResultList(shareAmount, ShareOrderUser, shareUser, parameter, Configuration,
                                                 resultList, intro);
                            }

                            break;
                        }

                        if (mapSingle.ParentLevel >= 3)
                        {
                            break;
                        }
                    }
                }
            }

            return(ExecuteResult <ITaskResult[]> .Success(resultList.ToArray()));
        }
        /// <summary>
        ///     对module配置与参数进行基础验证,子类重写后需要显式调用并判定返回值,如返回值不为Success,则不再执行子类后续逻辑
        /// </summary>
        /// <param name="parameter">参数</param>
        public override ExecuteResult <ITaskResult[]> Execute(TaskParameter parameter)
        {
            var baseResult = base.Execute(parameter);

            if (baseResult.Status != ResultStatus.Success)
            {
                return(ExecuteResult <ITaskResult[]> .Cancel("未找到触发会员的Parent Map."));
            }

            var userMap = Resolve <IUserMapService>().GetParentMapFromCache(ShareOrderUser.Id);
            var map     = userMap.ParentMap.DeserializeJson <List <ParentMap> >();

            if (map == null)
            {
                return(ExecuteResult <ITaskResult[]> .Cancel("未找到触发会员的Parent Map."));
            }

            IList <ITaskResult> resultList = new List <ITaskResult>();
            // 获取最大极差比例
            var maxRatio = Configuration.TeamRangeRateItems.Max(r => r.MaxRate);
            // 将自己加上去
            var parentMap = new ParentMap
            {
                UserId      = ShareOrderUser.Id,
                ParentLevel = 0
            };

            map = map.AddBefore(parentMap).ToList();
            //已用过的极差比例
            var useRatio = 0.0m;

            for (var i = 0; i < TeamLevel; i++)
            {
                if (useRatio >= maxRatio)
                {
                    break; // 已使用的比例超过最大比例
                }

                if (map.Count < i + 1)
                {
                    break;
                }

                var item = map[i];
                base.GetShareUser(item.UserId, out var shareUser); //从基类获取分润用户
                var shareGrade = Resolve <IGradeService>().GetGrade(shareUser.GradeId);
                if (shareGrade == null)
                {
                    continue;
                }

                var userRule = Configuration.TeamRangeRateItems.FirstOrDefault(r => r.GradeId == shareGrade.Id);
                if (userRule == null)
                {
                    continue;
                }

                //当前分润用户最大极差
                var shareUserRate = userRule.MaxRate;

                //剩余极差比例=当前极差比例-已使用比例
                var ratio = shareUserRate - useRatio;
                if (ratio <= 0)
                {
                    continue;
                }

                useRatio += ratio;
                var shareAmount = ratio * BaseFenRunAmount; // 极差分润
                CreateResultList(shareAmount, ShareOrderUser, shareUser, parameter, Configuration, resultList);
            }
            //分期

            return(ExecuteResult <ITaskResult[]> .Success(resultList.ToArray()));
        }
Example #29
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (ParentMap != null)
            {
                var bounds     = ParentMap.ViewportTransform.Inverse.TransformBounds(new Rect(ParentMap.RenderSize));
                var start      = ParentMap.MapTransform.Transform(new Point(bounds.X, bounds.Y));
                var end        = ParentMap.MapTransform.Transform(new Point(bounds.X + bounds.Width, bounds.Y + bounds.Height));
                var minSpacing = MinLineSpacing * 360d / (Math.Pow(2d, ParentMap.ZoomLevel) * TileSource.TileSize);
                var spacing    = LineSpacings[LineSpacings.Length - 1];

                if (spacing >= minSpacing)
                {
                    spacing = LineSpacings.FirstOrDefault(s => s >= minSpacing);
                }

                var labelFormat = spacing < 1d ? "{0} {1}°{2:00}'" : "{0} {1}°";
                var labelStart  = new Location(
                    Math.Ceiling(start.Latitude / spacing) * spacing,
                    Math.Ceiling(start.Longitude / spacing) * spacing);

                var latLabels = new List <Label>((int)((end.Latitude - labelStart.Latitude) / spacing) + 1);
                var lonLabels = new List <Label>((int)((end.Longitude - labelStart.Longitude) / spacing) + 1);

                for (var lat = labelStart.Latitude; lat <= end.Latitude; lat += spacing)
                {
                    latLabels.Add(new Label(lat, CoordinateString(lat, labelFormat, "NS")));

                    drawingContext.DrawLine(Pen,
                                            ParentMap.LocationToViewportPoint(new Location(lat, start.Longitude)),
                                            ParentMap.LocationToViewportPoint(new Location(lat, end.Longitude)));
                }

                for (var lon = labelStart.Longitude; lon <= end.Longitude; lon += spacing)
                {
                    lonLabels.Add(new Label(lon, CoordinateString(Location.NormalizeLongitude(lon), labelFormat, "EW")));

                    drawingContext.DrawLine(Pen,
                                            ParentMap.LocationToViewportPoint(new Location(start.Latitude, lon)),
                                            ParentMap.LocationToViewportPoint(new Location(end.Latitude, lon)));
                }

                if (Foreground != null && Foreground != Brushes.Transparent && latLabels.Count > 0 && lonLabels.Count > 0)
                {
                    var latLabelOrigin = new Point(StrokeThickness / 2d + 2d, -StrokeThickness / 2d - FontSize / 4d);
                    var lonLabelOrigin = new Point(StrokeThickness / 2d + 2d, StrokeThickness / 2d + FontSize);
                    var transform      = Matrix.Identity;
                    transform.Rotate(ParentMap.Heading);

                    foreach (var latLabel in latLabels)
                    {
                        foreach (var lonLabel in lonLabels)
                        {
                            GlyphRun latGlyphRun;
                            GlyphRun lonGlyphRun;

                            if (!glyphRuns.TryGetValue(latLabel.Text, out latGlyphRun))
                            {
                                latGlyphRun = GlyphRunText.Create(latLabel.Text, Typeface, FontSize, latLabelOrigin);
                                glyphRuns.Add(latLabel.Text, latGlyphRun);
                            }

                            if (!glyphRuns.TryGetValue(lonLabel.Text, out lonGlyphRun))
                            {
                                lonGlyphRun = GlyphRunText.Create(lonLabel.Text, Typeface, FontSize, lonLabelOrigin);
                                glyphRuns.Add(lonLabel.Text, lonGlyphRun);
                            }

                            var position = ParentMap.LocationToViewportPoint(new Location(latLabel.Position, lonLabel.Position));

                            drawingContext.PushTransform(new MatrixTransform(
                                                             transform.M11, transform.M12, transform.M21, transform.M22, position.X, position.Y));

                            drawingContext.DrawGlyphRun(Foreground, latGlyphRun);
                            drawingContext.DrawGlyphRun(Foreground, lonGlyphRun);
                            drawingContext.Pop();
                        }
                    }

                    var removeKeys = glyphRuns.Keys.Where(k => !latLabels.Any(l => l.Text == k) && !lonLabels.Any(l => l.Text == k));

                    foreach (var key in removeKeys.ToList())
                    {
                        glyphRuns.Remove(key);
                    }
                }
                else
                {
                    glyphRuns.Clear();
                }
            }
        }
Example #30
0
 private bool IsBlocked()
 => !ParentMap.CellIsInBounds(GetCell()) ||
 (GetCell() != StartCell && ParentMap.GetBlockingVector(Position).Skip(2).Take(3).Any(b => b != 0));