public void PolygonToByteArray()
        {
            Coordinate[] coords = new Coordinate[20];
            Random rnd = new Random();
            Coordinate center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
            for (int i = 0; i < 19; i++)
            {
                coords[i] = new Coordinate(center.X + Math.Cos((i * 10) * Math.PI / 10), center.Y + (i * 10) * Math.PI / 10);
            }
            coords[19] = new Coordinate(coords[0].X, coords[0].Y);
            Polygon pg = new Polygon(coords);
            byte[] vals = pg.ToBinary();
            WkbReader wkr = new WkbReader();
            IGeometry g = wkr.Read(vals);
            Polygon pgcheck = g as Polygon;
            if (pgcheck != null)
            {
                for (int i = 0; i < pg.NumGeometries; i++)
                {
                    Assert.AreEqual(pg.Coordinates[i].X, pgcheck.Coordinates[i].X);
                    Assert.AreEqual(pg.Coordinates[i].Y, pgcheck.Coordinates[i].Y);
                }
                Assert.AreEqual(pg.Area, pgcheck.Area);
                Assert.AreEqual(pg.Centroid.X, pgcheck.Centroid.X);
                Assert.AreEqual(pg.Centroid.Y, pgcheck.Centroid.Y);
                Assert.AreEqual(pg.Length, pgcheck.Length);
                Assert.AreEqual(pg.Envelope.Width, pgcheck.Envelope.Width);
                Assert.AreEqual(pg.Envelope.Height, pgcheck.Envelope.Height);
            }
            else
            {
                Assert.Fail("The test failed bc the check pgcheck was null.");
            }

        }
Ejemplo n.º 2
0
 private Polygon BuildGpcPolygonFromPointArray(Point[] pointArray)
 {
     Polygon polygon = new Polygon();
     VertexList contour = new VertexList(pointArray);
     polygon.AddContour(contour, false);
     return polygon;
 }
Ejemplo n.º 3
0
 public Division(Polygon Shape, int subs=0)
 {
     _shape = Shape;
       _subdivisions = new Division[subs];
       _field = new Field("solid", new string[]{"argent"});
       _chargeGroups = new List<ChargeGroup> {};
 }
Ejemplo n.º 4
0
        public ReactiveHud()
        {
            mObjectOverMarker = Polygon.CreateRectangle(1, 1);
            mObjectOverMarker.Color = System.Drawing.Color.Red;

            #region Create mModelOver

            mModelOverHighlight.Visible = false;
            ModelManager.AddModel(mModelOverHighlight);
            ModelManager.AddToLayer(mModelOverHighlight, SpriteManager.Camera.Layer);
            mModelOverHighlight.ColorOperation = Microsoft.DirectX.Direct3D.TextureOperation.Add;
            mModelOverHighlight.Red = 90f;
            mModelOverHighlight.Green = 90f;
            mModelOverHighlight.Blue = 90f;

            mSelectedModelHighlight.Visible = false;
            ModelManager.AddModel(mSelectedModelHighlight);
            ModelManager.AddToLayer(mSelectedModelHighlight, SpriteManager.Camera.Layer);
            mSelectedModelHighlight.ColorOperation = Microsoft.DirectX.Direct3D.TextureOperation.Add;
            mSelectedModelHighlight.Red = 160;
            mSelectedModelHighlight.Green = 160;
            mSelectedModelHighlight.Blue = 160;
            
            #endregion

			mSpriteFrameIndividualSpriteOutline = new SpriteFrameIndividualSpriteOutline();
            mTextWidthHandles = new TextWidthHandles();

            ShapeManager.AddPolygon(mObjectOverMarker);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="zonePerimeter">Perimeter of hte zone</param>
 /// <param name="stayOutside">Polygons to stay outside of</param>
 /// <param name="speedCommand">Recommended Speed command</param>
 public ZoneBehavior(ArbiterZoneId zoneId, Polygon zonePerimeter, Polygon[] stayOutside, ScalarSpeedCommand recommendedSpeedCommand)
 {
     this.zoneId = zoneId;
     this.zonePerimeter = zonePerimeter;
     this.stayOutside = stayOutside;
     this.speedCommand = recommendedSpeedCommand;
 }
Ejemplo n.º 6
0
		public static List<SlicePerimeterSegment> CreateSegmentListFromString(string segmentListData)
		{
			List<SlicePerimeterSegment> output = new List<SlicePerimeterSegment>();
			string[] segmentData = segmentListData.Split('|');
			foreach (string segment in segmentData)
			{
				if (segment != "")
				{
					List<IntPoint> outPoints = new Polygon();
					string[] points = segment.Split('&');
					foreach (string point in points)
					{
						string[] coordinates = point.Split(',');
						string elementX = coordinates[0];
						string elementY = coordinates[1];
                        int xIndex = elementX.IndexOf("x:");
                        int yIndex = elementY.IndexOf("y:");
						outPoints.Add(new IntPoint(int.Parse(elementX.Substring(xIndex+2)), int.Parse(elementY.Substring(yIndex+2))));
					}
					output.Add(new SlicePerimeterSegment(outPoints[0], outPoints[1]));
				}
			}

			return output;
		}
Ejemplo n.º 7
0
 public HotSpot(Vector2[] vertices, Texture2D texture)
 {
     shape = new Polygon(vertices);
     this.texture = texture;
     this.MouseEnabled = true;
     this.Name = "HotSpot" + counter++;
 }
        private async void StartButton_Click(object sender, RoutedEventArgs e)
        {

            outputGraphicsLayer.Graphics.Clear();

            InstructionsTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;

            InstructionsTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;
            StartButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            ResetButton.Visibility = Windows.UI.Xaml.Visibility.Visible;

            //Get the user's input geometry and add it to the map
            inputDifferencePolygonGeometry = (await mapView1.Editor.RequestShapeAsync(DrawShape.Polygon)) as Polygon;
            drawGraphicsLayer.Graphics.Clear();
            drawGraphicsLayer.Graphics.Add(new Graphic { Geometry = inputDifferencePolygonGeometry });

            //Simplify the input geometry
            var simplifyGeometry = GeometryEngine.Simplify(inputDifferencePolygonGeometry);

            //Generate the difference geometries
            var inputGeometries1 = inputGraphicsLayer.Graphics.Select(x => x.Geometry).ToList();
            var inputGeometries2 = new List<Geometry> { simplifyGeometry };
            var differenceOutputGeometries = GeometryEngine.Difference(inputGeometries1, inputGeometries2);

            //Add the difference geometries to the amp
            foreach (var geom in differenceOutputGeometries)
            {
                outputGraphicsLayer.Graphics.Add(new Graphic { Geometry = geom });
            }

            ResetButton.IsEnabled = true;
        }
Ejemplo n.º 9
0
 public SideWalkExtruder(Polygon polygon, Mesh mesh, float quantity, float outlineOffset)
 {
     _polygon = polygon;
     _mesh = mesh;
     _quantity = quantity;
     _outlineOffset = outlineOffset;
 }
Ejemplo n.º 10
0
        public void ExtensionsPolygonAddWaysAcceptsCollectionOfOSMWays()
        {
            OSMDB db = new OSMDB();

            OSMNode p1 = new OSMNode(1, 10, 15);
            OSMNode p2 = new OSMNode(2, 0, 15);
            OSMNode p3 = new OSMNode(3, 0, 0);

            OSMWay way1 = new OSMWay(10);
            OSMWay way2 = new OSMWay(11);

            db.Nodes.Add(p1);
            db.Nodes.Add(p2);
            db.Nodes.Add(p3);

            way1.Nodes.Add(p1.ID);
            way1.Nodes.Add(p2.ID);
            way1.Nodes.Add(p3.ID);

            way2.Nodes.Add(p3.ID);
            way2.Nodes.Add(p1.ID);

            Polygon<OSMNode> target = new Polygon<OSMNode>();
            target.AddWays(new OSMWay[] {way1, way2}, db);

            Assert.Equal(3, target.VerticesCount);
            CompareVerticesLists(new IPointGeo[] { p3, p2, p1 }, target.Vertices);
        }
Ejemplo n.º 11
0
        private static Polygon MultiPolygonWktToPolygon(string wkt)
        {
            var polygon = new Polygon();

            var pointCollection = new PointCollection();
            var removed = wkt.Replace("MULTIPOLYGON (", "");
            var preSplit = removed.Replace(")), ((", "|");
            var rings = preSplit.Split('|');

            foreach (var r in rings)
            {
                PointCollection pc = new PointCollection();

                var r1 = r.Replace("(", "");
                var r2 = r1.Replace(")", "");
                var r3 = r2.Trim();

                var coords = r3.Split(',');
                foreach(var coord in coords)
                {
                    coord.Trim();
                    var xy = coord.Trim().Split(' ');
                    if (xy.Length != 2)
                    continue;

                    pc.Add(new MapPoint(double.Parse(xy[0], CultureInfo.InvariantCulture), double.Parse(xy[1], CultureInfo.InvariantCulture)));
                }

                polygon.Rings.Add(pc);
            }

            return polygon;
        }
Ejemplo n.º 12
0
        public void Multipg()
        {
            var rnd = new Random();
            var pg = new Polygon[50];
            var pgcheck = new GeoAPI.Geometries.IPolygon[50];
            var gf = new NetTopologySuite.Geometries.GeometryFactory();
            for (var i = 0; i < 50; i++)
            {
                var center = new Coordinate((rnd.NextDouble() * 360) - 180, (rnd.NextDouble() * 180) - 90);
                var coord = new Coordinate[36];
                var coordscheck = new GeoAPI.Geometries.Coordinate[36];
                for (var ii = 0; ii < 36; ii++)
                {
                    coord[ii] = new Coordinate(center.X + Math.Cos((ii * 10) * Math.PI / 10), center.Y + (ii * 10) * Math.PI / 10);
                    var x = coord[ii].X;
                    var y = coord[ii].Y;
                    var c = new GeoAPI.Geometries.Coordinate(x, y);
                    coordscheck[ii] = c;
                }
                coord[35] = new Coordinate(coord[0].X, coord[0].Y);
                coordscheck[35] = new GeoAPI.Geometries.Coordinate(coordscheck[0].X, coordscheck[0].Y);
                var ring = gf.CreateLinearRing(coordscheck);
                pgcheck[i] = gf.CreatePolygon(ring, null);
                pg[i] = new Polygon(coord);

            }
            var mpg = new MultiPolygon(pg);
            var mpgcheck = gf.CreateMultiPolygon(pgcheck);
            for (var ii = 0; ii < mpg.Coordinates.Count; ii++)
            {
                Assert.AreEqual(mpg.Coordinates[ii].X, mpgcheck.Coordinates[ii].X);
                Assert.AreEqual(mpg.Coordinates[ii].Y, mpgcheck.Coordinates[ii].Y);
            }
        }
 public void AddBooleanPolygon(Polygon polygon)
 {
     if(!booleanPolygons.Contains(polygon)) {
         booleanPolygons.Add(polygon);
         UpdateMesh();
     }
 }
Ejemplo n.º 14
0
 public Polygon ToPolygon(int offset = 0)
 {
     offset += HitBox;
     var result = new Polygon();
     var innerRadius = -0.1562f * Distance + 687.31f;
     var outerRadius = 0.35256f * Distance + 133f;
     outerRadius = outerRadius / (float) Math.Cos(2 * Math.PI / CircleLineSegmentN);
     var innerCenters = LeagueSharp.Common.Geometry.CircleCircleIntersection(
         Start, End, innerRadius, innerRadius);
     var outerCenters = LeagueSharp.Common.Geometry.CircleCircleIntersection(
         Start, End, outerRadius, outerRadius);
     var innerCenter = innerCenters[0];
     var outerCenter = outerCenters[0];
     var direction = (End - outerCenter).Normalized();
     var end = (Start - outerCenter).Normalized();
     var maxAngle = (float) (direction.AngleBetween(end) * Math.PI / 180);
     var step = -maxAngle / CircleLineSegmentN;
     for (var i = 0; i < CircleLineSegmentN; i++)
     {
         var angle = step * i;
         var point = outerCenter + (outerRadius + 15 + offset) * direction.Rotated(angle);
         result.Add(point);
     }
     direction = (Start - innerCenter).Normalized();
     end = (End - innerCenter).Normalized();
     maxAngle = (float) (direction.AngleBetween(end) * Math.PI / 180);
     step = maxAngle / CircleLineSegmentN;
     for (var i = 0; i < CircleLineSegmentN; i++)
     {
         var angle = step * i;
         var point = innerCenter + Math.Max(0, innerRadius - offset - 100) * direction.Rotated(angle);
         result.Add(point);
     }
     return result;
 }
Ejemplo n.º 15
0
        public Tile( Polygon boundary, Polygon drawn, Geometry geometry )
            : this()
        {
            Boundary = boundary;
            Drawn = drawn;
            Geometry = geometry;

            // Make the vertex circle.
            VertexCircle = boundary.CircumCircle;

            // ZZZ - we shouldn't do this here (I did it for the slicing study page).
            //VertexCircle.Radius = 1.0;

            //
            // Below are experimentations with different vertex circle sizes.
            //

            //VertexCircle.Radius *= (1+1.0/9);

            // cuts adjacent cells at midpoint
            // Math.Sqrt(63)/6 for {3,6}
            // (1 + 1.0/5) for {3,7}
            // (1 + 1.0/9) for {3,8}
            // (1 + 1.0/20) for {3,9}

            // cuts at 1/3rd
            // 2/Math.Sqrt(3) for {3,6}
        }
Ejemplo n.º 16
0
    // fusion de la forme de base (liner, margelle) et rectangle exterieur
    // pour la triangulation
    // voir http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
    protected void MergedInnerAndOuter()
    {
        Bounds polyBounds = _polygon.bounds;
        Vector3 extents = polyBounds.extents;
        Vector3 center = polyBounds.center;

        // Pythagore
        float translation = _outlineOffset * 1.41421356f; // sqrt (2)

        Vector2 upRightDir = new Vector2 (1, 1).normalized * translation;
        Vector2 upRight = new Vector2 (center.x + extents.x, center.z + extents.z) + upRightDir;

        Vector2 downRightDir = new Vector2 (1, -1).normalized * translation;
        Vector2 downRight = new Vector2 (center.x + extents.x, center.z - extents.z) + downRightDir;

        Vector2 downLeftDir = new Vector2 (-1, -1).normalized * translation;
        Vector2 downLeft = new Vector2 (center.x - extents.x, center.z - extents.z) + downLeftDir;

        Vector2 upLeftDir = new Vector2 (-1, 1).normalized * translation;
        Vector2 upLeft = new Vector2 (center.x - extents.x, center.z + extents.z) + upLeftDir;

        PolygonRawData outerRawPoly = new PolygonRawData ();
        outerRawPoly.Add (upRight);
        outerRawPoly.Add (downRight);
        outerRawPoly.Add (downLeft);
        outerRawPoly.Add (upLeft);

        Polygon outerPolygon = new Polygon (outerRawPoly);
        _mergedPolygon = PolygonOperation.MergeInnerAndOuter (_polygon, outerPolygon);
    }
		/// <summary>
		/// XAML creation of polygon and polyline geometries are currently not supported, so
		/// here they are created in code. Points are generated in the XAML for this sample.
		/// </summary>
		private void CreateGeometries()
		{
			var layer = mapView1.Map.Layers.OfType<GraphicsLayer>().First();
			int i = 0;
			foreach (var g in layer.Graphics)
				g.Attributes["Label"] = "Label #" + (++i).ToString();

			Polyline line = new Polyline(FromArray(-100,-30, -80,0, -60,-30, -40,0), SpatialReferences.Wgs84);
			var graphic = new Graphic(line, (Esri.ArcGISRuntime.Symbology.Symbol)Resources["OutlinedAndDashedSymbol"]);
			graphic.Attributes["Label"] = "OutlinedAndDashedSymbol";
			layer.Graphics.Add(graphic);

			Polygon polygon = new Polygon(FromArray(-30,-30, 0,-30, 0,0, -15,-10, -30,0, -30,-30), SpatialReferences.Wgs84);
			graphic = new Graphic(polygon, (Esri.ArcGISRuntime.Symbology.Symbol)Resources["VertexFillSymbol"]);
			graphic.Attributes["Label"] = "VertexFillSymbol";
			layer.Graphics.Add(graphic);

			//CIM symbols can only be created from JSON. The JSON is currently only constructed by publishing services to ArcGIS Server with advanced symbology
			string CIMSymbolJson = "{\"type\":\"CIMSymbolReference\",\"symbol\":{\"type\":\"CIMLineSymbol\",\"symbolLayers\":[{\"type\":\"CIMFilledStroke\",\"enable\":true,\"effects\":[{\"type\":\"CIMGeometricEffectArrow\",\"geometricEffectArrowType\":\"Block\",\"primitiveName\":null,\"width\":35}],\"capStyle\":\"Round\",\"pattern\":{\"type\":\"CIMSolidPattern\",\"color\":[0,0,0,255]},\"width\":2,\"lineStyle3D\":\"Strip\",\"alignment\":\"Center\",\"joinStyle\":\"Miter\",\"miterLimit\":10,\"patternFollowsStroke\":true}]},\"symbolName\":null}";
			var cimsymbol = Esri.ArcGISRuntime.Symbology.Symbol.FromJson(CIMSymbolJson);
			Polyline line2 = new Polyline(FromArray(20, -30, 30, 0, 50, -30, 70, 0), SpatialReferences.Wgs84);
			graphic = new Graphic(line2, cimsymbol);
			graphic.Attributes["Label"] = "CIM Symbol";
			layer.Graphics.Add(graphic);

			i = 0;
			foreach (var g in layer.Graphics)
			{
				g.Attributes["SymbolType"] = g.Symbol.GetType().Name;
				g.Attributes["ID"] = ++i;
			}
		}
Ejemplo n.º 18
0
        public SpriteGridBorder(Cursor cursor, Camera camera)
        {
            this.cursor = cursor;
            this.camera = camera;

            mMainRectangle = Polygon.CreateRectangle(1,1);
            ShapeManager.AddPolygon(mMainRectangle);



            mCornerHandles = new Polygon[4];
            mSideHandles = new Polygon[4];
            for (int i = 0; i < 4; i++)
            {
                mCornerHandles[i] = Polygon.CreateRectangle(.5f, .5f);
                mCornerHandles[i].Color = System.Drawing.Color.Yellow;
                ShapeManager.AddPolygon(mCornerHandles[i]);

                mSideHandles[i] = Polygon.CreateRectangle(.5f, .5f);
                mSideHandles[i].Color = System.Drawing.Color.Yellow;
                ShapeManager.AddPolygon(mSideHandles[i]);
            }
             
            Visible = false;
        }
Ejemplo n.º 19
0
    protected bool _upCap = false; // bouche t'on le haut de l'extrusion

    #endregion Fields

    #region Constructors

    public PolygonExtruder(Polygon polygon, 
		                    Mesh mesh,
		                    float quantity,
		                    bool upCap,
		                    bool bottomCap,
		                    bool inverseNormal)
    {
        _polygon = polygon;
        _mesh = mesh;
        _quantity = quantity;
        _upCap = upCap;
        _bottomCap = bottomCap;
        _inverseNormal = inverseNormal;

        if (_quantity > 0)
        {
            _inverseUpAndDown = true;
        }

        //		foreach (Vector3  v in _mesh.vertices)
        //		{
        //			Debug.Log (v);
        //		}
        //
        //		foreach (int i in _mesh.triangles)
        //		{
        //			Debug.Log (i);
        //		}
    }
Ejemplo n.º 20
0
		public static Polygons GetCorrectedWinding(this Polygons polygonsToFix)
		{
			polygonsToFix = Clipper.CleanPolygons(polygonsToFix);
			Polygon boundsPolygon = new Polygon();
			IntRect bounds = Clipper.GetBounds(polygonsToFix);
			bounds.left -= 10;
			bounds.bottom += 10;
			bounds.right += 10;
			bounds.top -= 10;

			boundsPolygon.Add(new IntPoint(bounds.left, bounds.top));
			boundsPolygon.Add(new IntPoint(bounds.right, bounds.top));
			boundsPolygon.Add(new IntPoint(bounds.right, bounds.bottom));
			boundsPolygon.Add(new IntPoint(bounds.left, bounds.bottom));

			Clipper clipper = new Clipper();

			clipper.AddPaths(polygonsToFix, PolyType.ptSubject, true);
			clipper.AddPath(boundsPolygon, PolyType.ptClip, true);

			PolyTree intersectionResult = new PolyTree();
			clipper.Execute(ClipType.ctIntersection, intersectionResult);

			Polygons outputPolygons = Clipper.ClosedPathsFromPolyTree(intersectionResult);

			return outputPolygons;
		}
Ejemplo n.º 21
0
 /// <summary>
 /// Decompose polygon into triangles
 /// </summary>
 /// <param name="polygon"></param>
 /// <returns></returns>
 public List<Polygon> DecomposePolygon(Polygon polygon)
 {
     List<Polygon> triangles = new List<Polygon>();
     bool foundAll = false;
     while (!foundAll)
     {
         for (int i = 1; i < polygon.Count - 1; i++)
         {
             if (polygon.Count == 3)
             {
                 triangles.Add(polygon);
                 foundAll = true;
             }
             // make a triangle
             Polygon thisTriangle = new Polygon();
             for (int j = -1; j <= 1; j++)
                 thisTriangle.Add(polygon[i - j]);
             // check if the triangle is an ear. If so, add to the list of triangles
             if (IsEar(thisTriangle, polygon))
             {
                 triangles.Add(thisTriangle);
                 polygon.RemoveAt(i);
                 continue;
             }
         }
     }
     return triangles;
 }
		private async void StartButton_Click(object sender, RoutedEventArgs e)
		{
			SetupUI();

			// InstructionsTextBlock.Visibility = Windows.UI.Xaml.Visibility.Visible;
			StartButton.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

			//Get the user's input
			densifyPolygonGeometry = (await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon)) as Polygon;

			//Create a graphic and add it to the PolygonGraphicsLayer
			var thePolygonGraphic = new Graphic
			{
				Geometry = densifyPolygonGeometry,
				Symbol = polygonSymbol
			};
			graphicsLayerPolygon.Graphics.Add(thePolygonGraphic);

			//show the vertices for the polygon
			foreach (var vert in densifyPolygonGeometry.Parts.FirstOrDefault().GetPoints())
			{
				var graphic = new Graphic { Geometry = new MapPoint(vert.X, vert.Y), Symbol = defaultVertexMarkerSymbol };
				graphicsLayerVertices.Graphics.Add(graphic);
			}

			DensifyPolygonsButton.IsEnabled = true;
		}
        // Draw the unsimplified polygon
        private void DrawPolygon()
        {
            MapPoint center = MyMapView.Extent.GetCenter();
            double lat = center.Y;
            double lon = center.X + 300;
            double latOffset = 300;
            double lonOffset = 300;

            var points = new PointCollection()
            {
                new MapPoint(lon - lonOffset, lat),
                new MapPoint(lon, lat + latOffset),
                new MapPoint(lon + lonOffset, lat),
                new MapPoint(lon, lat - latOffset),
                new MapPoint(lon - lonOffset, lat),
                new MapPoint(lon - 2 * lonOffset, lat + latOffset),
                new MapPoint(lon - 3 * lonOffset, lat),
                new MapPoint(lon - 2 * lonOffset, lat - latOffset),
                new MapPoint(lon - 1.5 * lonOffset, lat + latOffset),
                new MapPoint(lon - lonOffset, lat)
            };
            _unsimplifiedPolygon = new Polygon(points, MyMapView.SpatialReference);

			_polygonOverlay.Graphics.Clear();
			_polygonOverlay.Graphics.Add(new Graphic(_unsimplifiedPolygon));
        }
Ejemplo n.º 24
0
        public void MillionSquare()
        {
            Polygon P = new Polygon(MillionSquarePoints);
            Detector D = new Detector(P);

            Assert.AreEqual(D.Result, 3999996000001);
        }
Ejemplo n.º 25
0
 public static Polygon ToPolygon(this Path v) {
     var polygon = new Polygon();
     foreach (var point in v) {
         polygon.Add(new Vector2(point.X, point.Y));
     }
     return polygon;
 }
        // Gets the users digitized area of interest polygon
        private async void AreaOfInterestButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _graphicsOverlay.Graphics.Clear();

                Polygon aoi = null;
                if (chkFreehand.IsChecked == true)
                {
                    var boundary = await MyMapView.Editor.RequestShapeAsync(DrawShape.Freehand) as Polyline;
                    if (boundary.Parts.First().Count <= 1)
                        return;

                    aoi = new Polygon(boundary.Parts, MyMapView.SpatialReference);
                    aoi = GeometryEngine.Simplify(aoi) as Polygon;
                }
                else
                {
                    aoi = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon) as Polygon;
                }

                _graphicsOverlay.Graphics.Add(new Graphic(aoi));
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
Ejemplo n.º 27
0
    public int[] getTrianglesByPolygon(Polygon polygon)
    {
        int triangleCount = polygon.points.Count-1;
        int verticCount = 2*triangleCount;
        int[] triangles = new int[12 * triangleCount];
        for (int i = 0; i < triangleCount; i++)
        {
            triangles[i * 12 + 0] = (2 * i + 0) % verticCount;
            triangles[i * 12 + 1] = (2 * i + 2) % verticCount;
            triangles[i * 12 + 2] = verticCount;

            triangles[i * 12 + 3] = (2 * i + 3) % verticCount;
            triangles[i * 12 + 4] = (2 * i + 1) % verticCount;
            triangles[i * 12 + 5] = verticCount + 1;

            triangles[i * 12 + 6] = (2 * i + 0) % verticCount;
            triangles[i * 12 + 7] = (2 * i + 1) % verticCount;
            triangles[i * 12 + 8] = (2 * i + 3) % verticCount;

            triangles[i * 12 + 9] = (2 * i + 3) % verticCount;
            triangles[i * 12 + 10] = (2 * i + 2) % verticCount;
            triangles[i * 12 + 11] = (2 * i + 0) % verticCount;
        }
        return triangles;
    }
Ejemplo n.º 28
0
 private Plane(IPlaneEntity entity, double size, bool display = false)
     : base(entity, false)
 {
     InitializeGuaranteedProperties();
     if (display && size>1)
         mDisplayPolygon = CreatePlaneVisuals(size,true);
 }
		// Draw the unsimplified polygon
		private void DrawPolygon()
		{
			// Get current viewpoints extent from the MapView
			var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
			var viewpointExtent = currentViewpoint.TargetGeometry.Extent; 

			MapPoint center = viewpointExtent.GetCenter();
			double lat = center.Y;
			double lon = center.X + 300;
			double latOffset = 300;
			double lonOffset = 300;

			var points = new PointCollection()
			{
				new MapPoint(lon - lonOffset, lat),
				new MapPoint(lon, lat + latOffset),
				new MapPoint(lon + lonOffset, lat),
				new MapPoint(lon, lat - latOffset),
				new MapPoint(lon - lonOffset, lat),
				new MapPoint(lon - 2 * lonOffset, lat + latOffset),
				new MapPoint(lon - 3 * lonOffset, lat),
				new MapPoint(lon - 2 * lonOffset, lat - latOffset),
				new MapPoint(lon - 1.5 * lonOffset, lat + latOffset),
				new MapPoint(lon - lonOffset, lat)
			};
			_unsimplifiedPolygon = new Polygon(points, MyMapView.SpatialReference);

			_polygonOverlay.Graphics.Clear();
			_polygonOverlay.Graphics.Add(new Graphic(_unsimplifiedPolygon));
		}
Ejemplo n.º 30
0
        private static Polygon mergePartialBuffers(List<Polygon> buffers)
        {
            Polygon temp = new Polygon();
            ICollection<IGeometry> gc;
            while (buffers.Count > 1)
            {
                List<Polygon> tempBuffers = new List<Polygon>();
                for (int i = 0; i < buffers.Count; i += 2)
                {
                    if (i + 1 == buffers.Count)
                        tempBuffers.Add(buffers[i]);
                    else
                    {
                        gc = buffers[i].Union(buffers[i + 1]);
                        if (gc.Count > 0)
                            temp = (Polygon)((GeometryCollection)gc)[0];
                        tempBuffers.Add(temp);
                    }
                }
                buffers = tempBuffers;
            }

            if (buffers.Count == 0)
                return null;

            return buffers[0];

        }
Ejemplo n.º 31
0
        public void optimize()
        {
            List <bool> picked = new List <bool>();

            for (int polygonIndex = 0; polygonIndex < polygons.Count; polygonIndex++)
            {
                int     bestPointIndex = -1;
                double  closestDist    = double.MaxValue;
                Polygon currentPolygon = polygons[polygonIndex];
                for (int pointIndex = 0; pointIndex < currentPolygon.Count; pointIndex++)
                {
                    double dist = (currentPolygon[pointIndex] - startPosition).LengthSquared();
                    if (dist < closestDist)
                    {
                        bestPointIndex = pointIndex;
                        closestDist    = dist;
                    }
                }
                polyStart.Add(bestPointIndex);
                picked.Add(false);
            }

            //IntPoint incommingPerpundicularNormal = new IntPoint(0, 0);
            IntPoint currentPosition = startPosition;

            for (int positionIndex = 0; positionIndex < polygons.Count; positionIndex++)
            {
                int    bestIndex = -1;
                double bestDist  = double.MaxValue;
                for (int polygonIndex = 0; polygonIndex < polygons.Count; polygonIndex++)
                {
                    if (picked[polygonIndex] || polygons[polygonIndex].Count < 1)
                    {
                        continue;
                    }

                    if (polygons[polygonIndex].Count == 2)
                    {
                        double dist = (polygons[polygonIndex][0] - currentPosition).LengthSquared();
                        //dist += Math.Abs(incommingPerpundicularNormal.Dot(polygons[polygonIndex][1] - polygons[polygonIndex][0].normal(1000))) * 0.0001f;
                        if (dist < bestDist)
                        {
                            bestIndex = polygonIndex;
                            bestDist  = dist;
                            polyStart[polygonIndex] = 0;
                        }

                        dist = (polygons[polygonIndex][1] - currentPosition).LengthSquared();
                        //dist += Math.Abs(incommingPerpundicularNormal.Dot(polygons[polygonIndex][0] - polygons[polygonIndex][1].normal(1000))) * 0.0001f;
                        if (dist < bestDist)
                        {
                            bestIndex = polygonIndex;
                            bestDist  = dist;
                            polyStart[polygonIndex] = 1;
                        }
                    }
                    else
                    {
                        double dist = (polygons[polygonIndex][polyStart[polygonIndex]] - currentPosition).LengthSquared();
                        if (dist < bestDist)
                        {
                            bestIndex = polygonIndex;
                            bestDist  = dist;
                        }
                    }
                }

                if (bestIndex > -1)
                {
                    if (polygons[bestIndex].Count == 2)
                    {
                        int endIndex = (polyStart[bestIndex] + 1) % 2;
                        currentPosition = polygons[bestIndex][endIndex];
                        //incommingPerpundicularNormal = (polygons[bestIndex][endIndex] - polygons[bestIndex][polyStart[bestIndex]]).normal(1000).CrossZ();
                    }
                    else
                    {
                        currentPosition = polygons[bestIndex][polyStart[bestIndex]];
                        //incommingPerpundicularNormal = new IntPoint(0, 0);
                    }
                    picked[bestIndex] = true;
                    polyOrder.Add(bestIndex);
                }
            }

            currentPosition = startPosition;
            for (int n = 0; n < polyOrder.Count; n++)
            {
                int    nr       = polyOrder[n];
                int    best     = -1;
                double bestDist = double.MaxValue;
                for (int i = 0; i < polygons[nr].Count; i++)
                {
                    double dist = (polygons[nr][i] - currentPosition).LengthSquared();
                    if (dist < bestDist)
                    {
                        best     = i;
                        bestDist = dist;
                    }
                }
                polyStart[nr] = best;
                if (polygons[nr].Count <= 2)
                {
                    currentPosition = polygons[nr][(best + 1) % 2];
                }
                else
                {
                    currentPosition = polygons[nr][best];
                }
            }
        }
Ejemplo n.º 32
0
 public void addPolygon(Polygon polygon)
 {
     this.polygons.Add(polygon);
 }
Ejemplo n.º 33
0
        private void MovePointsInsideIfPossible(IntPoint startPointIn, IntPoint endPointIn, Polygon pathThatIsInside)
        {
            if (OutlineData.DistanceFromOutside != null)
            {
                // move every segment that can be inside the boundary to be within the boundary
                if (pathThatIsInside.Count > 1 && InsetAmount > 0)
                {
                    IntPoint startPoint = startPointIn;
                    for (int i = 0; i < pathThatIsInside.Count - 1; i++)
                    {
                        IntPoint testPoint = pathThatIsInside[i];
                        IntPoint endPoint  = i < pathThatIsInside.Count - 2 ? pathThatIsInside[i + 1] : endPointIn;

                        IntPoint inPolyPosition;
                        if (OutlineData.MovePointAwayFromEdge(testPoint, InsetAmount, out inPolyPosition))
                        {
                            // It moved so test if it is a good point
                            //if (OutlineData.Polygons.FindIntersection(startPoint, inPolyPosition, OutlineData.EdgeQuadTrees) != Intersection.Intersect
                            //&& OutlineData.Polygons.FindIntersection(inPolyPosition, endPoint, OutlineData.EdgeQuadTrees) != Intersection.Intersect)
                            {
                                testPoint           = inPolyPosition;
                                pathThatIsInside[i] = testPoint;
                            }
                        }

                        startPoint = testPoint;
                    }
                }
            }
        }
Ejemplo n.º 34
0
        public static bool Cross(Circle circle, Polygon polygon)
        {
            // Pour croiser un polygone il suffit de croiser un de ses cotés

            return(polygon.Sides.Exists(s => circle.Cross(s)));
        }
Ejemplo n.º 35
0
    public bool RunFunnel(List <Vector3> left, List <Vector3> right, List <Vector3> funnelPath)
    {
        if (left.Count <= 3)
        {
            return(false);
        }

        System.Console.WriteLine("Start");

        //Remove identical vertices
        while (left[1] == left[2] && right[1] == right[2])
        {
            System.Console.WriteLine("Removing identical left and right");
            left.RemoveAt(1);
            right.RemoveAt(1);
        }

        /*while (right[1] == right[2]) {
         *      System.Console.WriteLine ("Removing identical right");
         *      right.RemoveAt (1);
         *      left.RemoveAt (1);
         * }*/

        Vector3 swPoint = left[2];

        if (swPoint == left[1])
        {
            swPoint = right[2];
        }

        /*if (Polygon.IsColinear (left[0],left[1],right[1])) {
         *      System.Console.WriteLine ("	Colinear");
         *      left[0] += (left[2]-left[0]).normalized*0.001F;
         *      if (Polygon.IsColinear (left[0],left[1],right[1])) {
         *              Debug.LogError ("WUT!!!");//NOTE - CAN ACTUALLY HAPPEN!
         *      }
         * }*/


        //Solves cases where the start point lies on the wrong side of the first funnel portal
        if (Polygon.IsColinear(left[0], left[1], right[1]) || Polygon.Left(left[1], right[1], swPoint) == Polygon.Left(left[1], right[1], left[0]))
        {
            Debug.DrawLine(left[1], right[1], new Color(0, 0, 0, 0.5F));
            Debug.DrawLine(left[0], swPoint, new Color(0, 0, 0, 0.5F));
            System.Console.WriteLine("Wrong Side");
            left[0]  = Mathfx.NearestPointStrict(left[1], right[1], left[0]);
            left[0] += (left[0] - swPoint).normalized * 0.001F;        //Tiny move to the right side to prevent floating point errors, too bad with that .normalized call though, could perhaps be optimized
            right[0] = left[0];
        }

        //Switch left and right to really be on the "left" and "right" sides
        if (!Polygon.IsClockwise(left[0], left[1], right[1]) && !Polygon.IsColinear(left[0], left[1], right[1]))
        {
            System.Console.WriteLine("Wrong Side 2");
            List <Vector3> tmp = left;
            left  = right;
            right = tmp;
        }

        /*for (int i=1;i<leftFunnel.Length-1;i++) {
         *
         *      float unitWidth = 5;
         *      Int3 normal = (rightFunnel[i]-leftFunnel[i]);
         *      float magn = normal.worldMagnitude;
         *      normal /= magn;
         *      normal *= Mathf.Clamp (unitWidth,0,(magn/2F));
         *      leftFunnel[i] += normal;
         *      rightFunnel[i] -= normal;
         * }*/


        funnelPath.Add(left[0]);

        Vector3 portalApex  = left[0];
        Vector3 portalLeft  = left[1];
        Vector3 portalRight = right[1];

        int apexIndex  = 0;
        int rightIndex = 1;
        int leftIndex  = 1;

        //yield return 0;

        for (int i = 2; i < left.Count; i++)
        {
            if (funnelPath.Count > 200)
            {
                Debug.LogWarning("Avoiding infinite loop");
                break;
            }

            Vector3 pLeft  = left[i];
            Vector3 pRight = right[i];

            /*Debug.DrawLine (portalApex,portalLeft,Color.red);
             * Debug.DrawLine (portalApex,portalRight,Color.yellow);
             * Debug.DrawLine (portalApex,left,Color.cyan);
             * Debug.DrawLine (portalApex,right,Color.cyan);*/

            if (Polygon.TriangleArea2(portalApex, portalRight, pRight) >= 0)
            {
                if (portalApex == portalRight || Polygon.TriangleArea2(portalApex, portalLeft, pRight) <= 0)
                {
                    portalRight = pRight;
                    rightIndex  = i;
                }
                else
                {
                    funnelPath.Add(portalLeft);
                    portalApex = portalLeft;
                    apexIndex  = leftIndex;

                    portalLeft  = portalApex;
                    portalRight = portalApex;

                    leftIndex  = apexIndex;
                    rightIndex = apexIndex;

                    i = apexIndex;

                    //yield return 0;
                    continue;
                }
            }

            if (Polygon.TriangleArea2(portalApex, portalLeft, pLeft) <= 0)
            {
                if (portalApex == portalLeft || Polygon.TriangleArea2(portalApex, portalRight, pLeft) >= 0)
                {
                    portalLeft = pLeft;
                    leftIndex  = i;
                }
                else
                {
                    funnelPath.Add(portalRight);
                    portalApex = portalRight;
                    apexIndex  = rightIndex;

                    portalLeft  = portalApex;
                    portalRight = portalApex;

                    leftIndex  = apexIndex;
                    rightIndex = apexIndex;

                    i = apexIndex;

                    //yield return 0;
                    continue;
                }
            }

            //yield return 0;
        }

        //yield return 0;

        funnelPath.Add(left[left.Count - 1]);
        return(true);
    }
Ejemplo n.º 36
0
        // ------------------------- CreateFirstVisual ------------------------
        /// <summary>
        ///   Creates content for the first visual sample.</summary>
        /// <param name="shouldMeasure">
        ///   true to remeasure the layout.</param>
        /// <returns>
        ///   The canvas containing the visual.</returns>
        public Canvas CreateFirstVisual(bool shouldMeasure)
        {
            Canvas canvas1 = new Canvas();

            canvas1.Width  = 96 * 8.5;
            canvas1.Height = 96 * 11;

            // Top-Left
            TextBlock label = new TextBlock();

            label.Foreground = Brushes.DarkBlue;
            label.FontFamily = new System.Windows.Media.FontFamily("Arial");
            label.FontSize   = 36.0;
            label.Text       = "TopLeft";
            Canvas.SetTop(label, 0);
            Canvas.SetLeft(label, 0);
            canvas1.Children.Add(label);

            // Bottom-Right
            label            = new TextBlock();
            label.Foreground = Brushes.Bisque;
            label.Text       = "BottomRight";
            label.FontFamily = new System.Windows.Media.FontFamily("Arial");
            label.FontSize   = 56.0;
            Canvas.SetTop(label, 750);
            Canvas.SetLeft(label, 520);
            canvas1.Children.Add(label);

            // Top-Right
            label            = new TextBlock();
            label.Foreground = Brushes.BurlyWood;
            label.Text       = "TopRight";
            label.FontFamily = new System.Windows.Media.FontFamily("CASTELLAR");
            label.FontSize   = 32.0;
            Canvas.SetTop(label, 0);
            Canvas.SetLeft(label, 520);
            canvas1.Children.Add(label);

            // Bottom-Left
            label            = new TextBlock();
            label.Foreground = Brushes.Cyan;
            label.Text       = "BottomLeft";
            label.FontFamily = new System.Windows.Media.FontFamily("Arial");
            label.FontSize   = 18.0;
            Canvas.SetTop(label, 750);
            Canvas.SetLeft(label, 0);
            canvas1.Children.Add(label);

            // Add a rectangle to the page
            Rectangle firstRectangle = new Rectangle();

            firstRectangle.Fill = new SolidColorBrush(Colors.Red);
            Thickness thick = new Thickness();

            thick.Left            = 150;
            thick.Top             = 150;
            firstRectangle.Margin = thick;
            firstRectangle.Width  = 300;
            firstRectangle.Height = 300;
            canvas1.Children.Add(firstRectangle);
            //_visual = firstRectangle;

            //Add a button to the page
            Button firstButton = new Button();

            firstButton.Background      = Brushes.LightYellow;
            firstButton.BorderBrush     = new SolidColorBrush(Colors.Black);
            firstButton.BorderThickness = new Thickness(4);
            firstButton.Content         = "I am button 1...";
            firstButton.FontSize        = 16.0;
            thick.Left         = 80;
            thick.Top          = 250;
            firstButton.Margin = thick;
            canvas1.Children.Add(firstButton);

            // Add an Ellipse
            Ellipse         firstEllipse         = new Ellipse();
            SolidColorBrush firstSolidColorBrush = new SolidColorBrush(Colors.DarkCyan);

            firstSolidColorBrush.Opacity = 0.7;
            firstEllipse.Fill            = firstSolidColorBrush;
            SetEllipse(firstEllipse, 500, 350, 120, 250);
            canvas1.Children.Add(firstEllipse);

            // Adding a Polygon
            Polygon polygon = new Polygon();

            polygon.Fill    = Brushes.Bisque;
            polygon.Opacity = 0.2;
            PointCollection points = new PointCollection();

            points.Add(new Point(50, 0));
            points.Add(new Point(10, 30));
            points.Add(new Point(30, 170));
            points.Add(new Point(90, 40));
            points.Add(new Point(230, 180));
            points.Add(new Point(200, 60));
            points.Add(new Point(240, 10));
            points.Add(new Point(70, 130));
            polygon.Points = points;
            polygon.Stroke = Brushes.Navy;
            Canvas.SetTop(polygon, 300);
            Canvas.SetLeft(polygon, 160);
            canvas1.Children.Add(polygon);

            if (shouldMeasure)
            {
                Size sz = new Size(8.5 * 96, 11 * 96);
                canvas1.Measure(sz);
                canvas1.Arrange(new Rect(new Point(), sz));
                canvas1.UpdateLayout();
            }

            return(canvas1);
        }// end:CreateFirstVisual()
Ejemplo n.º 37
0
 private void ClickOnPolygone(object sender, MouseEventArgs args) => ChangePolygone = polygone;
Ejemplo n.º 38
0
 protected abstract void OnRenderInternal(Map mpa, Polygon polygon, Graphics g);
Ejemplo n.º 39
0
        }// end:CreateFirstVisual()

        // ------------------------- CreateSecondVisual -----------------------
        /// <summary>
        ///   Creates content for the second visual sample.</summary>
        /// <param name="shouldMeasure">
        ///   true to remeasure the layout.</param>
        /// <returns>
        ///   The canvas containing the visual.</returns>
        public Canvas CreateSecondVisual(bool shouldMeasure)
        {
            Canvas canvas = new Canvas();

            Ellipse ellipse = new Ellipse();

            ellipse.Fill = Brushes.LightSeaGreen;
            SetEllipse(ellipse, 130, 200, 100, 70);
            ellipse.Stroke = Brushes.Black;
            canvas.Children.Add(ellipse);

            Rectangle rectangle = new Rectangle();

            rectangle.Fill    = Brushes.PowderBlue;
            rectangle.Opacity = 0.8;
            rectangle.RadiusX = 5;
            rectangle.RadiusY = 5;
            rectangle.Stroke  = Brushes.Orange;
            rectangle.Height  = 200;
            rectangle.Width   = 350;
            Canvas.SetTop(rectangle, 50);
            Canvas.SetLeft(rectangle, 100);
            canvas.Children.Add(rectangle);

            Polygon polygon = new Polygon();

            polygon.Fill    = Brushes.MediumVioletRed;
            polygon.Opacity = 0.7;
            PointCollection points = new PointCollection();

            points.Add(new Point(50, 0));
            points.Add(new Point(10, 30));
            points.Add(new Point(30, 170));
            points.Add(new Point(90, 40));
            points.Add(new Point(230, 180));
            points.Add(new Point(200, 60));
            points.Add(new Point(240, 10));
            points.Add(new Point(70, 130));
            polygon.Points = points;
            polygon.Stroke = Brushes.Navy;
            Canvas.SetTop(polygon, 150);
            Canvas.SetLeft(polygon, 250);
            canvas.Children.Add(polygon);

            TextBlock scribble = new TextBlock();

            scribble.Foreground = Brushes.Green;
            scribble.FontFamily =
                new System.Windows.Media.FontFamily("Courier New");
            scribble.FontSize = 18;
            scribble.Opacity  = 0.5;
            Canvas.SetLeft(scribble, 96 * 3.7);
            Canvas.SetTop(scribble, 96 * 10.3);
            canvas.Children.Add(scribble);

            TextBlock para = new TextBlock();

            para.Text       = "This is a piece of text content.";
            para.FontSize   = 16;
            para.FontFamily =
                new System.Windows.Media.FontFamily("Comic Sans MS");
            para.Foreground = Brushes.Orange;
            Canvas.SetTop(para, 96 * 6);
            Canvas.SetLeft(para, 15);
            canvas.Children.Add(para);

            para            = new TextBlock();
            para.Text       = "This is the second piece of text content.";
            para.FontSize   = 16;
            para.FontFamily =
                new System.Windows.Media.FontFamily("Comic Sans MS");
            para.Foreground = Brushes.Blue;
            Canvas.SetTop(para, 96 * 7.2);
            Canvas.SetLeft(para, 15);
            canvas.Children.Add(para);

            para            = new TextBlock();
            para.Text       = "This is the last text section.";
            para.FontSize   = 16;
            para.FontFamily =
                new System.Windows.Media.FontFamily("Comic Sans MS");
            para.Foreground = Brushes.Red;
            Canvas.SetTop(para, 96 * 8.4);
            Canvas.SetLeft(para, 15);
            canvas.Children.Add(para);

            if (shouldMeasure)
            {
                Size sz = new Size(8.5 * 96, 11 * 96);
                canvas.Measure(sz);
                canvas.Arrange(new Rect(new Point(), sz));
                canvas.UpdateLayout();
            }

            return(canvas);
        }// end:CreateSecondVisual()
Ejemplo n.º 40
0
        /// <summary>
        /// Creates the mesh instance based on the values calculated beforehand.
        /// </summary>
        /// <param name="upperIndices">The indices of the upper face.</param>
        /// <param name="sideIndices">The indices of the side faces.</param>
        /// <param name="lowerIndices">The indices of the lower face.</param>
        /// <param name="upperVertices">The vertices of the upper face.</param>
        /// <param name="lowerVertices">The vertices of the lower face.</param>
        /// <param name="polygon">The polygon for checking points etc.</param>
        /// <returns>The created mesh.</returns>
        private static Mesh CreateMesh(List <short> upperIndices, List <short> sideIndices, List <short> lowerIndices, List <Vector2> upperVertices, List <Vector3> lowerVertices, Polygon polygon)
        {
            Mesh mesh = new Mesh();

            List <short> indices = new List <short>();

            indices.AddRange(upperIndices);
            indices.AddRange(sideIndices);
            lowerIndices.Reverse();
            indices.AddRange(lowerIndices);

            mesh.indexArray = indices.ToArray();

            List <Vector3> vertices = new List <Vector3>();

            foreach (Vector2 vector in upperVertices)
            {
                vertices.Add(new Vector3(vector.X, 0, vector.Y));
            }

            vertices.AddRange(lowerVertices);

            mesh.vertexArray = CreateUVMap(vertices);
            mesh.polygon     = polygon;

            return(mesh);
        }
Ejemplo n.º 41
0
        public override void Run(List <Point> points, List <Line> lines, List <Polygon> polygons, ref List <Point> outPoints, ref List <Line> outLines, ref List <Polygon> outPolygons)
        {
            /*
             * this function will take set of points
             * return only the points on the boundary of the polygon
             * it don't deal with colinear points
             * we could make the algo faster by excluding the non extreme points from building the triangle also
             * proof that this will not affect the non extreme detection !!! ******
             */

            /*
             * this will affect outpoints and I will deal with it to make things alright
             */

            // preprocessing
            List <Point> tmp = new List <Point>();

            for (int i = 0; i < points.Count; i++)
            {
                bool dup = false;
                for (int j = 0; j < i; j++)
                {
                    if (Math.Abs(points[i].X - points[j].X) <= Constants.Epsilon && Math.Abs(points[i].Y - points[j].Y) <= Constants.Epsilon)
                    {
                        dup = true;
                        break;
                    }
                }
                if (dup)
                {
                    continue;
                }
                tmp.Add(points[i]);
            }
            points.Clear();
            points = tmp;

            Point_in_convex_polygon check_p_in_t = new Point_in_convex_polygon();

            bool[] is_extreme = new bool[points.Count];
            for (int i = 0; i < points.Count; i++)
            {
                is_extreme[i] = true;
            }

            for (int i = 0; i < points.Count; i++)
            {
                // don't use non extreme points in checking
                // as if we have the same point more than 1 time they will exclude each other
                if (is_extreme[i] == false)
                {
                    continue;
                }

                for (int j = 0; j < points.Count; j++)
                {
                    if (is_extreme[j] == false)
                    {
                        continue;
                    }
                    if (i == j)
                    {
                        continue;
                    }

                    for (int k = 0; k < points.Count; k++)
                    {
                        if (is_extreme[k] == false)
                        {
                            continue;
                        }
                        if (k == i || k == j)
                        {
                            continue;
                        }
                        Point a = points[i], b = points[j], c = points[k];

                        // check if points are colinear
                        Enums.TurnType t = HelperMethods.CheckTurn(new Line(a, b), c);
                        if (t == Enums.TurnType.Colinear)
                        {
                            continue;
                        }

                        // loop throw the points
                        for (int index = 0; index < points.Count; index++)
                        {
                            if (is_extreme[index] == false || index == i || index == j || index == k)
                            {
                                continue;
                            }
                            // check if the point is inside the polygon triangle
                            List <Line>    tmp_ll   = new List <Line>();
                            List <Polygon> tmp_pl   = new List <Polygon>();
                            Polygon        tmp_poly = new Polygon();
                            Point          p        = points[index];

                            // does the order matters !???
                            tmp_ll.Add(new Line(a, b));
                            tmp_ll.Add(new Line(b, c));
                            tmp_ll.Add(new Line(c, a));

                            tmp_poly.lines = tmp_ll;
                            tmp_pl.Add(tmp_poly);

                            // tmp out lists
                            // does C# have garbage collector !??
                            List <Point>   tmp_outpoints   = new List <Point>();
                            List <Line>    tmp_outlines    = new List <Line>();
                            List <Polygon> tmp_outpolygons = new List <Polygon>();
                            List <Point>   in_points       = new List <Point>();
                            in_points.Add(p);
                            check_p_in_t.Run(in_points, new List <Line>(), tmp_pl, ref tmp_outpoints, ref tmp_outlines, ref tmp_outpolygons);
                            if (tmp_outpoints.Count != 0)
                            {
                                is_extreme[index] = false;
                            }
                        }
                    }
                }
            }

            // return extreme points
            for (int i = 0; i < points.Count; i++)
            {
                if (is_extreme[i] == true)
                {
                    outPoints.Add(points[i]);
                }
            }
            return;
        }
Ejemplo n.º 42
0
        private async void CreateNewFeatureCollection()
        {
            // Create the schema for a points table (one text field to contain a name attribute)
            List <Field> pointFields = new List <Field>();
            Field        placeField  = new Field(FieldType.Text, "Place", "Place Name", 50);

            pointFields.Add(placeField);

            // Create the schema for a lines table (one text field to contain a name attribute)
            List <Field> lineFields    = new List <Field>();
            Field        boundaryField = new Field(FieldType.Text, "Boundary", "Boundary Name", 50);

            lineFields.Add(boundaryField);

            // Create the schema for a polygon table (one text field to contain a name attribute)
            List <Field> polyFields = new List <Field>();
            Field        areaField  = new Field(FieldType.Text, "AreaName", "Area Name", 50);

            polyFields.Add(areaField);

            // Instantiate FeatureCollectionTables with schema and geometry type
            FeatureCollectionTable pointsTable = new FeatureCollectionTable(pointFields, GeometryType.Point, SpatialReferences.Wgs84);
            FeatureCollectionTable linesTable  = new FeatureCollectionTable(lineFields, GeometryType.Polyline, SpatialReferences.Wgs84);
            FeatureCollectionTable polysTable  = new FeatureCollectionTable(polyFields, GeometryType.Polygon, SpatialReferences.Wgs84);

            // Set rendering for each table
            pointsTable.Renderer = CreateRenderer(GeometryType.Point);
            linesTable.Renderer  = CreateRenderer(GeometryType.Polyline);
            polysTable.Renderer  = CreateRenderer(GeometryType.Polygon);

            // Create a new point feature, provide geometry and attribute values
            Feature pointFeature = pointsTable.CreateFeature();

            pointFeature.SetAttributeValue(placeField, "Current location");
            MapPoint point1 = new MapPoint(-79.497238, 8.849289, SpatialReferences.Wgs84);

            pointFeature.Geometry = point1;

            // Create a new line feature, provide geometry and attribute values
            Feature lineFeature = linesTable.CreateFeature();

            lineFeature.SetAttributeValue(boundaryField, "AManAPlanACanalPanama");
            MapPoint point2 = new MapPoint(-80.035568, 9.432302, SpatialReferences.Wgs84);
            Polyline line   = new Polyline(new MapPoint[] { point1, point2 });

            lineFeature.Geometry = line;

            // Create a new polygon feature, provide geometry and attribute values
            Feature polyFeature = polysTable.CreateFeature();

            polyFeature.SetAttributeValue(areaField, "Restricted area");
            MapPoint point3 = new MapPoint(-79.337936, 8.638903, SpatialReferences.Wgs84);
            MapPoint point4 = new MapPoint(-79.11409, 8.895422, SpatialReferences.Wgs84);
            Polygon  poly   = new Polygon(new MapPoint[] { point1, point3, point4 });

            polyFeature.Geometry = poly;

            try
            {
                // Add the new features to the appropriate feature collection table
                await pointsTable.AddFeatureAsync(pointFeature);

                await linesTable.AddFeatureAsync(lineFeature);

                await polysTable.AddFeatureAsync(polyFeature);

                // Create a feature collection and add the feature collection tables
                FeatureCollection featuresCollection = new FeatureCollection();
                featuresCollection.Tables.Add(pointsTable);
                featuresCollection.Tables.Add(linesTable);
                featuresCollection.Tables.Add(polysTable);

                // Create a FeatureCollectionLayer
                FeatureCollectionLayer collectionLayer = new FeatureCollectionLayer(featuresCollection);

                // When the layer loads, zoom the map view to the extent of the feature collection
                await collectionLayer.LoadAsync();

                MyMapView.SetViewpoint(new Viewpoint(collectionLayer.FullExtent));

                // Add the layer to the Map's Operational Layers collection
                MyMapView.Map.OperationalLayers.Add(collectionLayer);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
Ejemplo n.º 43
0
 private void UpdateGlobals()
 {
     GlobalMustHave = _Apply(LocalMustHave, Rotation, Offset);
     GlobalNiceHave = _Apply(LocalNiceHave, Rotation, Offset);
 }
Ejemplo n.º 44
0
        public Scene LoadData(string path)
        {
            char[] split = new char[] { ' ' };

            //  Create a scene and polygon.
            Scene   scene   = new Scene();
            Polygon polygon = new Polygon();

            string mtlName = null;

            //  Create a stream reader.
            using (StreamReader reader = new StreamReader(path))
            {
                //  Read line by line.
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    //  Skip any comments (lines that start with '#').
                    if (line.StartsWith("#"))
                    {
                        continue;
                    }

                    //  Do we have a texture coordinate?
                    if (line.StartsWith("vt"))
                    {
                        //  Get the texture coord strings.
                        string[] values = line.Substring(3).Split(split, StringSplitOptions.RemoveEmptyEntries);
                        float    x      = float.Parse(values[0], CultureInfo.InvariantCulture);
                        float    y      = float.Parse(values[1], CultureInfo.InvariantCulture);

                        //  Parse texture coordinates.
                        float u = x;
                        float v = 1.0f - y;

                        //  Add the texture coordinate.
                        polygon.UVs.Add(new UV(u, v));
                        continue;
                    }

                    //  Do we have a normal coordinate?
                    if (line.StartsWith("vn"))
                    {
                        //  Get the normal coord strings.
                        string[] values = line.Substring(3).Split(split, StringSplitOptions.RemoveEmptyEntries);

                        //  Parse normal coordinates.
                        float x = float.Parse(values[0], CultureInfo.InvariantCulture);
                        float y = float.Parse(values[1], CultureInfo.InvariantCulture);
                        float z = float.Parse(values[2], CultureInfo.InvariantCulture);

                        //  Add the normal.
                        polygon.Normals.Add(new Vertex(x, y, z));
                        continue;
                    }

                    //  Do we have a vertex?
                    if (line.StartsWith("v"))
                    {
                        //  Get the vertex coord strings.
                        string[] values = line.Substring(2).Split(split, StringSplitOptions.RemoveEmptyEntries);

                        //  Parse vertex coordinates.
                        float x = float.Parse(values[0], CultureInfo.InvariantCulture);
                        float y = float.Parse(values[1], CultureInfo.InvariantCulture);
                        float z = float.Parse(values[2], CultureInfo.InvariantCulture);

                        //   Add the vertices.
                        polygon.Vertices.Add(new Vertex(x, y, z));

                        continue;
                    }

                    //  Do we have a face?
                    if (line.StartsWith("f"))
                    {
                        Face face = new Face();

                        if (!string.IsNullOrWhiteSpace(mtlName))
                        {
                            face.Material = scene.Assets.FirstOrDefault(t => t.Name == mtlName) as Material;
                        }

                        //  Get the face indices
                        string[] indices = line.Substring(2).Split(split, StringSplitOptions.RemoveEmptyEntries);

                        //  Add each index.
                        foreach (var index in indices)
                        {
                            //  Split the parts.
                            string[] parts = index.Split(new char[] { '/' }, StringSplitOptions.None);

                            //  Add each part.
                            face.Indices.Add(new Index(
                                                 (parts.Length > 0 && parts[0].Length > 0) ? int.Parse(parts[0], CultureInfo.InvariantCulture) - 1 : -1,
                                                 (parts.Length > 1 && parts[1].Length > 0) ? int.Parse(parts[1], CultureInfo.InvariantCulture) - 1 : -1,
                                                 (parts.Length > 2 && parts[2].Length > 0) ? int.Parse(parts[2], CultureInfo.InvariantCulture) - 1 : -1));
                        }

                        //  Add the face.
                        polygon.Faces.Add(face);
                        continue;
                    }

                    if (line.StartsWith("mtllib"))
                    {
                        // Load materials file.
                        string mtlPath = ReadMaterialValue(line);
                        if (!Path.IsPathRooted(mtlPath))
                        {
                            // It's better to build an absolute path here, rather than
                            // messing with Environment.CurrentDirectory
                            mtlPath = Path.Combine(Path.GetDirectoryName(path), mtlPath);
                        }

                        LoadMaterials(mtlPath, scene);
                    }

                    if (line.StartsWith("usemtl"))
                    {
                        mtlName = ReadMaterialValue(line);
                    }
                }
            }

            scene.SceneContainer.AddChild(polygon);

            return(scene);
        }
Ejemplo n.º 45
0
 public FillPolygon()
 {
     this.shape = new SixLabors.Shapes.Polygon(new LinearLineSegment(new Vector2(10, 10),
                                                                     new Vector2(550, 50),
                                                                     new Vector2(200, 400)));
 }
 public VisibilityPolygon(Polygon p) : base(p)
 {
 }
Ejemplo n.º 47
0
    public static Vector3 GetNextTarget(Path path, Vector3 currPosition, float offset, float pickNextWaypointMargin)
    {
        if (path.error)
        {
            return(currPosition);
        }

        Int3 currentPosition = (Int3)currPosition;

        int startIndex = 0;
        int endIndex   = path.path.Length;

        //Int3 pos = (Int3)currentPosition;

        //int minDist = -1;
        //int minNode = -1;

        INavmesh navmeshGraph = AstarData.GetGraph(path.path[0]) as INavmesh;

        if (navmeshGraph == null)
        {
            Debug.LogError("Couldn't cast graph to the appropriate type (graph isn't a Navmesh type graph, it doesn't implement the INavmesh interface)");
            return(currPosition);           ///Apply (path,start,end, startIndex, endIndex, graph);
        }

        Int3[] vertices = navmeshGraph.vertices;

        //float minDist2 = -1;
        //int minNode2 = -1;

        //Debug.Log (meshPath.Length + " "+path.Length +" "+startIndex+" "+endIndex);

        /*for (int i=startIndex;i< endIndex;i++) {
         *      MeshNode node = path.path[i] as MeshNode;
         *
         *      if (node == null) {
         *              Debug.LogWarning ("Path could not be casted to Mesh Nodes");
         *              return currentPosition;//return base.Apply (path,start,end, startIndex, endIndex, graph);
         *      }
         *
         *      //if (Polygon.TriangleArea2 (vertices[node.v1],vertices[node.v2],currentPosition) >= 0 || Polygon.TriangleArea2 (vertices[node.v2],vertices[node.v3],currentPosition) >= 0 || Polygon.TriangleArea2 (vertices[node.v3],vertices[node.v1],currentPosition) >= 0) {
         *
         *      if (!Polygon.IsClockwise (vertices[node.v1],vertices[node.v2],pos) || !Polygon.IsClockwise (vertices[node.v2],vertices[node.v3],pos) || !Polygon.IsClockwise (vertices[node.v3],vertices[node.v1],pos)) {
         *
         *              if (minDist == -1) {
         *                      float dist2 = (node.position-pos).sqrMagnitude;
         *                      if (minDist2 == -1 || dist2 < minDist2) {
         *                              minDist2 = dist2;
         *                              minNode2 = i;
         *                      }
         *              }
         *              continue;
         *      }
         *
         *      Debug.DrawLine (vertices[node.v1],vertices[node.v2],Color.blue);
         *      Debug.DrawLine (vertices[node.v2],vertices[node.v3],Color.blue);
         *      Debug.DrawLine (vertices[node.v3],vertices[node.v1],Color.blue);
         *
         *
         *      int dist = node.position.y-pos.y;
         *
         *      if (minDist == -1 || dist < minDist) {
         *              minDist = dist;
         *              minNode = i;
         *      }
         *
         * }*/

        MeshNode lastNode = path.path[endIndex - 1] as MeshNode;

        if (lastNode == null)
        {
            Debug.LogWarning("Path could not be casted to Mesh Nodes");
            return(currentPosition);           //return base.Apply (path,start,end, startIndex, endIndex, graph);
        }

        PathNNConstraint constraint = PathNNConstraint.Default;

        constraint.SetStart(lastNode);
        NNInfo nninfo = NavMeshGraph.GetNearestForce(path.path, vertices, currPosition, constraint);

        currentPosition = nninfo.clampedPosition;

        /*for (int i=startIndex;i< endIndex;i++) {
         *      if (nninfo.node == path.path[i]) {
         *              minNode = i;
         *      }
         * }*/

        //Node minNode = nninfo.node;

        /*startIndex = minNode;
         * if (startIndex == -1) {
         *      startIndex = minNode2;
         *      currentPosition = path.path[minNode2].position;
         * }
         * if (startIndex == -1) {
         *      Debug.Log ("Couldn't find current node");
         *      return currentPosition;
         * }*/

        MeshNode[] meshPath = new MeshNode[endIndex - startIndex];

        for (int i = startIndex; i < endIndex; i++)
        {
            meshPath[i - startIndex] = path.path[i] as MeshNode;
        }
        //return Vector3.zero;

        //Vector3[] vertices = null;

        if (leftFunnel == null || leftFunnel.Length < meshPath.Length + 1)
        {
            leftFunnel = new Int3[meshPath.Length + 1];
        }
        if (rightFunnel == null || rightFunnel.Length < meshPath.Length + 1)
        {
            rightFunnel = new Int3[meshPath.Length + 1];
        }
        int leftFunnelLength = meshPath.Length + 1;

        //int rightFunnelLength = meshPath.Length+1;

        leftFunnel[0]  = currentPosition;
        rightFunnel[0] = currentPosition;

        leftFunnel[meshPath.Length]  = path.endPoint;
        rightFunnel[meshPath.Length] = path.endPoint;

        int lastLeftIndex  = -1;
        int lastRightIndex = -1;

        for (int i = 0; i < meshPath.Length - 1; i++)
        {
            //Find the connection between the nodes

            MeshNode n1 = meshPath[i];
            MeshNode n2 = meshPath[i + 1];

            bool foundFirst = false;

            int first  = -1;
            int second = -1;

            for (int x = 0; x < 3; x++)
            {
                //Vector3 vertice1 = vertices[n1.vertices[x]];
                //n1[x] gets the vertice index for vertex number 'x' in the node. Equal to n1.GetVertexIndex (x)
                int vertice1 = n1[x];
                for (int y = 0; y < 3; y++)
                {
                    //Vector3 vertice2 = vertices[n2.vertices[y]];
                    int vertice2 = n2[y];

                    if (vertice1 == vertice2)
                    {
                        if (foundFirst)
                        {
                            second = vertice2;
                            break;
                        }
                        else
                        {
                            first      = vertice2;
                            foundFirst = true;
                        }
                    }
                }
            }

            //Debug.DrawLine ((Vector3)vertices[first]+Vector3.up*0.1F,(Vector3)vertices[second]+Vector3.up*0.1F,Color.cyan);
            //Debug.Log (first+" "+second);
            if (first == lastLeftIndex)
            {
                leftFunnel[i + 1]  = vertices[first];
                rightFunnel[i + 1] = vertices[second];
                lastLeftIndex      = first;
                lastRightIndex     = second;
            }
            else if (first == lastRightIndex)
            {
                leftFunnel[i + 1]  = vertices[second];
                rightFunnel[i + 1] = vertices[first];
                lastLeftIndex      = second;
                lastRightIndex     = first;
            }
            else if (second == lastLeftIndex)
            {
                leftFunnel[i + 1]  = vertices[second];
                rightFunnel[i + 1] = vertices[first];
                lastLeftIndex      = second;
                lastRightIndex     = first;
            }
            else
            {
                leftFunnel[i + 1]  = vertices[first];
                rightFunnel[i + 1] = vertices[second];
                lastLeftIndex      = first;
                lastRightIndex     = second;
            }
        }

        //Switch the arrays so the right funnel really is on the right side (and vice versa)
        if (!Polygon.IsClockwise(currentPosition, leftFunnel[1], rightFunnel[1]))
        {
            Int3[] tmp = leftFunnel;
            leftFunnel  = rightFunnel;
            rightFunnel = tmp;
        }

        for (int i = 1; i < leftFunnelLength - 1; i++)
        {
            //float unitWidth = 2;
            Int3 normal = (rightFunnel[i] - leftFunnel[i]);

            float magn = normal.worldMagnitude;
            normal         /= magn;
            normal         *= Mathf.Clamp(offset, 0, (magn / 2F));
            leftFunnel[i]  += normal;
            rightFunnel[i] -= normal;
            //Debug.DrawLine (rightFunnel[i],leftFunnel[i],Color.blue);
        }

        /*for (int i=0;i<path.Length-1;i++) {
         *      Debug.DrawLine (path[i].position,path[i+1].position,Color.blue);
         * }*/

        /*for (int i=0;i<leftFunnel.Length-1;i++) {
         *      Debug.DrawLine (leftFunnel[i],leftFunnel[i+1],Color.red);
         *      Debug.DrawLine (rightFunnel[i],rightFunnel[i+1],Color.magenta);
         * }*/

        if (tmpList == null)
        {
            tmpList = new List <Vector3>(3);
        }

        List <Vector3> funnelPath = tmpList;

        funnelPath.Clear();

        funnelPath.Add(currentPosition);

        Int3 portalApex  = currentPosition;
        Int3 portalLeft  = leftFunnel[0];
        Int3 portalRight = rightFunnel[0];

        int apexIndex  = 0;
        int rightIndex = 0;
        int leftIndex  = 0;

        //yield return 0;

        for (int i = 1; i < leftFunnelLength; i++)
        {
            Int3 left  = leftFunnel[i];
            Int3 right = rightFunnel[i];

            /*Debug.DrawLine (portalApex,portalLeft,Color.red);
             * Debug.DrawLine (portalApex,portalRight,Color.yellow);
             * Debug.DrawLine (portalApex,left,Color.cyan);
             * Debug.DrawLine (portalApex,right,Color.cyan);*/

            if (Polygon.TriangleArea2(portalApex, portalRight, right) >= 0)
            {
                if (portalApex == portalRight || Polygon.TriangleArea2(portalApex, portalLeft, right) <= 0)
                {
                    portalRight = right;
                    rightIndex  = i;
                }
                else
                {
                    funnelPath.Add((Vector3)portalLeft);

                    //if (funnelPath.Count > 3)
                    //break;

                    portalApex = portalLeft;
                    apexIndex  = leftIndex;

                    portalLeft  = portalApex;
                    portalRight = portalApex;

                    leftIndex  = apexIndex;
                    rightIndex = apexIndex;

                    i = apexIndex;

                    //yield return 0;
                    continue;
                }
            }

            if (Polygon.TriangleArea2(portalApex, portalLeft, left) <= 0)
            {
                if (portalApex == portalLeft || Polygon.TriangleArea2(portalApex, portalRight, left) >= 0)
                {
                    portalLeft = left;
                    leftIndex  = i;
                }
                else
                {
                    funnelPath.Add((Vector3)portalRight);

                    //if (funnelPath.Count > 3)
                    //break;

                    portalApex = portalRight;
                    apexIndex  = rightIndex;

                    portalLeft  = portalApex;
                    portalRight = portalApex;

                    leftIndex  = apexIndex;
                    rightIndex = apexIndex;

                    i = apexIndex;

                    //yield return 0;
                    continue;
                }
            }

            //yield return 0;
        }

        //yield return 0;

        funnelPath.Add(path.endPoint);

        Vector3[] p = funnelPath.ToArray();


        if (p.Length <= 1)
        {
            return(currentPosition);
        }

        for (int i = 1; i < p.Length - 1; i++)
        {
            Vector3 closest = Mathfx.NearestPointStrict(p[i], p[i + 1], currentPosition);
            if ((closest - (Vector3)currentPosition).sqrMagnitude < pickNextWaypointMargin * pickNextWaypointMargin)
            {
                continue;
            }
            else
            {
                return(p[i]);
            }
        }
        return(p[p.Length - 1]);
    }
Ejemplo n.º 48
0
        public void Centroid()
        {
            // Square in Quadrant I
            var polygon = new Polygon
                          (
                new[]
            {
                Vector3.Origin,
                new Vector3(6.0, 0.0),
                new Vector3(6.0, 6.0),
                new Vector3(0.0, 6.0),
            }
                          );
            var centroid = polygon.Centroid();

            Assert.Equal(3.0, centroid.X);
            Assert.Equal(3.0, centroid.Y);

            // Square in Quadrant II
            polygon = new Polygon
                      (
                new[]
            {
                Vector3.Origin,
                new Vector3(-6.0, 0.0),
                new Vector3(-6.0, 6.0),
                new Vector3(0.0, 6.0),
            }
                      );
            centroid = polygon.Centroid();
            Assert.Equal(-3.0, centroid.X);
            Assert.Equal(3.0, centroid.Y);

            // Square in Quadrant III
            polygon = new Polygon
                      (
                new[]
            {
                Vector3.Origin,
                new Vector3(-6.0, 0.0),
                new Vector3(-6.0, -6.0),
                new Vector3(0.0, -6.0),
            }
                      );
            centroid = polygon.Centroid();
            Assert.Equal(-3.0, centroid.X);
            Assert.Equal(-3.0, centroid.Y);

            // Square in Quadrant IV
            polygon = new Polygon
                      (
                new[]
            {
                Vector3.Origin,
                new Vector3(6.0, 0.0),
                new Vector3(6.0, -6.0),
                new Vector3(0.0, -6.0),
            }
                      );
            centroid = polygon.Centroid();
            Assert.Equal(3.0, centroid.X);
            Assert.Equal(-3.0, centroid.Y);

            // Bow Tie in Quadrant I
            polygon = new Polygon
                      (
                new[]
            {
                new Vector3(1.0, 1.0),
                new Vector3(4.0, 4.0),
                new Vector3(7.0, 1.0),
                new Vector3(7.0, 9.0),
                new Vector3(4.0, 6.0),
                new Vector3(1.0, 9.0)
            }
                      );
            centroid = polygon.Centroid();
            Assert.Equal(4.0, centroid.X);
            Assert.Equal(5.0, centroid.Y);

            // Bow Tie in Quadrant III
            polygon = new Polygon
                      (
                new[]
            {
                new Vector3(-1.0, -1.0),
                new Vector3(-4.0, -4.0),
                new Vector3(-7.0, -1.0),
                new Vector3(-7.0, -9.0),
                new Vector3(-4.0, -6.0),
                new Vector3(-1.0, -9.0)
            }
                      );
            centroid = polygon.Centroid();
            Assert.Equal(-4.0, centroid.X);
            Assert.Equal(-5.0, centroid.Y);
        }
Ejemplo n.º 49
0
        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)      //地图移动
        {
            if (axMapControl1.LayerCount == 0)
            {
                return;
            }
            sMapUnits = "千米";//GetMapUnit(axMapControl1.Map.MapUnits);  //求量测所需的单位
            #region 状态栏
            //就绪


            //比例尺
            labelItem2.Text = " 比例尺 1:" + ((long)this.axMapControl1.MapScale).ToString();
            //坐标
            lbl_Coordinate.Text = "当前坐标:X:" + e.mapX.ToString() + " Y: " + e.mapY.ToString();
            #endregion

            pMovePt = (axMapControl1.Map as IActiveView).ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
            #region 长度量算
            if (pMouseOperate == "MeasureLength")
            {
                if (pNewLineFeedback != null)
                {
                    pNewLineFeedback.MoveTo(pMovePt);
                }
                double deltaX = 0; //两点之间X差值
                double deltaY = 0; //两点之间Y差值

                if ((pPointPt != null) && (pNewLineFeedback != null))
                {
                    deltaX         = pMovePt.X - pPointPt.X;
                    deltaY         = pMovePt.Y - pPointPt.Y;
                    dSegmentLength = Math.Round(111.199 * (Math.Sqrt((deltaY * deltaY) + (deltaX * deltaX) * (Math.Cos((pPointPt.Y + pMovePt.Y) / 2) * Math.Cos((pPointPt.Y + pMovePt.Y) / 2)))), 3);
                    dToltalLength  = dToltalLength + dSegmentLength;
                    if (frmMeasureResult != null)
                    {
                        frmMeasureResult.lblMeasureResult.Text = String.Format(
                            "当前量测的距离为:{0:.###}{1};\r\n总长度为: {2:.###}{1}",
                            dSegmentLength, sMapUnits, dToltalLength);
                        dToltalLength = dToltalLength - dSegmentLength; //鼠标移动到新点重新开始计算
                    }
                    frmMeasureResult.frmClosed += new FrmMeasureResult.FrmClosedEventHandler(frmMeasureResult_frmColsed);
                }
            }
            #endregion
            #region 面积量算
            if (pMouseOperate == "MeasureArea")
            {
                if (pNewPolygonFeedback != null)
                {
                    pNewPolygonFeedback.MoveTo(pMovePt);
                }

                IPointCollection pPointCol = new Polygon();
                IPolygon         pPolygon  = new PolygonClass();
                IGeometry        pGeo      = null;

                ITopologicalOperator pTopo = null;
                for (int i = 0; i <= pAreaPointCol.PointCount - 1; i++)
                {
                    pPointCol.AddPoint(pAreaPointCol.get_Point(i), ref missing, ref missing);
                }
                pPointCol.AddPoint(pMovePt, ref missing, ref missing);

                if (pPointCol.PointCount < 3)
                {
                    return;
                }
                pPolygon = pPointCol as IPolygon;

                if ((pPolygon != null))
                {
                    pPolygon.Close();
                    pGeo  = pPolygon as IGeometry;
                    pTopo = pGeo as ITopologicalOperator;
                    //使几何图形的拓扑正确
                    pTopo.Simplify();
                    pGeo.Project(axMapControl1.Map.SpatialReference);
                    IArea pArea = pGeo as IArea;

                    frmMeasureResult.lblMeasureResult.Text = String.Format(
                        "总面积为:{0:.####}平方{1};\r\n总长度为:{2:.####}{1}",
                        pArea.Area, sMapUnits, pPolygon.Length);
                    pPolygon = null;
                }
            }
            #endregion
            #region 移动显示名称
            IFeatureLayer pFeatureLayer8 = axMapControl1.Map.get_Layer(0) as IFeatureLayer; //定位的图层包括了很多要素
            pFeatureLayer8.DisplayField = "name";
            pFeatureLayer8.ShowTips     = true;
            string pTip8;
            pTip8 = pFeatureLayer8.get_TipText(e.mapX, e.mapY, axMapControl1.ActiveView.FullExtent.Width / 1000);
            if (pTip8 != null && pTip8 != " ")
            {
                toolTip1.SetToolTip(axMapControl1, "这里是:" + pTip8);
            }
            else
            {
                toolTip1.SetToolTip(axMapControl1, "");
            }
            #endregion
        }
Ejemplo n.º 50
0
        public void Union()
        {
            var p1 = new Polygon
                     (
                new[]
            {
                new Vector3(),
                new Vector3(4.0, 0.0),
                new Vector3(4.0, 4.0),
                new Vector3(0.0, 4.0)
            }
                     );
            var p2 = new Polygon
                     (
                new[]
            {
                new Vector3(3.0, 1.0),
                new Vector3(7.0, 1.0),
                new Vector3(7.0, 5.0),
                new Vector3(3.0, 5.0)
            }
                     );
            var p3 = new Polygon
                     (
                new[]
            {
                new Vector3(3.0, 2.0),
                new Vector3(8.0, 2.0),
                new Vector3(8.0, 3.0),
                new Vector3(3.0, 3.0)
            }
                     );
            var ps = new List <Polygon> {
                p2, p3
            };

            var vertices = p1.Union(p2).Vertices;

            Assert.Contains(vertices, p => p.X == 0.0 && p.Y == 0.0);
            Assert.Contains(vertices, p => p.X == 4.0 && p.Y == 0.0);
            Assert.Contains(vertices, p => p.X == 4.0 && p.Y == 1.0);
            Assert.Contains(vertices, p => p.X == 7.0 && p.Y == 1.0);
            Assert.Contains(vertices, p => p.X == 7.0 && p.Y == 5.0);
            Assert.Contains(vertices, p => p.X == 3.0 && p.Y == 5.0);
            Assert.Contains(vertices, p => p.X == 3.0 && p.Y == 4.0);
            Assert.Contains(vertices, p => p.X == 0.0 && p.Y == 4.0);

            vertices = p1.Union(ps).Vertices;

            Assert.Contains(vertices, p => p.X == 0.0 && p.Y == 0.0);
            Assert.Contains(vertices, p => p.X == 4.0 && p.Y == 0.0);
            Assert.Contains(vertices, p => p.X == 4.0 && p.Y == 1.0);
            Assert.Contains(vertices, p => p.X == 7.0 && p.Y == 1.0);
            Assert.Contains(vertices, p => p.X == 7.0 && p.Y == 2.0);
            Assert.Contains(vertices, p => p.X == 8.0 && p.Y == 2.0);
            Assert.Contains(vertices, p => p.X == 8.0 && p.Y == 3.0);
            Assert.Contains(vertices, p => p.X == 7.0 && p.Y == 3.0);
            Assert.Contains(vertices, p => p.X == 7.0 && p.Y == 5.0);
            Assert.Contains(vertices, p => p.X == 3.0 && p.Y == 5.0);
            Assert.Contains(vertices, p => p.X == 3.0 && p.Y == 4.0);
            Assert.Contains(vertices, p => p.X == 0.0 && p.Y == 4.0);
        }
Ejemplo n.º 51
0
        public void TestFeatureSerialization()
        {
            // a feature with a point.
            var geometry = (Geometry) new Point(new GeoCoordinate(0, 1));
            var feature  = new Feature(geometry);

            var serialized = feature.ToGeoJson();

            serialized = serialized.RemoveWhitespace();

            Assert.AreEqual("{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Point\",\"coordinates\":[1.0,0.0]}}",
                            serialized);

            feature = new Feature(geometry, new SimpleGeometryAttributeCollection(new GeometryAttribute[]
            {
                new GeometryAttribute()
                {
                    Key   = "key1",
                    Value = "value1"
                }
            }));

            serialized = feature.ToGeoJson();
            serialized = serialized.RemoveWhitespace();

            Assert.AreEqual("{\"type\":\"Feature\",\"properties\":{\"key1\":\"value1\"},\"geometry\":{\"type\":\"Point\",\"coordinates\":[1.0,0.0]}}",
                            serialized);

            // a feature with a linestring.
            geometry = new LineString(
                new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 1),
                new GeoCoordinate(1, 1),
                new GeoCoordinate(1, 0)
            });
            feature = new Feature(geometry);

            serialized = feature.ToGeoJson();
            serialized = serialized.RemoveWhitespace();

            Assert.AreEqual("{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"LineString\",\"coordinates\":[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]]}}",
                            serialized);

            // a featurer with a linearring.
            geometry = new LineairRing(
                new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 1),
                new GeoCoordinate(1, 1),
                new GeoCoordinate(1, 0),
                new GeoCoordinate(0, 0)
            });
            feature = new Feature(geometry);

            serialized = feature.ToGeoJson();
            serialized = serialized.RemoveWhitespace();

            Assert.AreEqual("{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0],[0.0,0.0]]]}}",
                            serialized);

            // a featurer with a polygon.
            geometry = new Polygon(new LineairRing(
                                       new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 1),
                new GeoCoordinate(1, 1),
                new GeoCoordinate(1, 0),
                new GeoCoordinate(0, 0)
            }));
            feature = new Feature(geometry);

            serialized = feature.ToGeoJson();
            serialized = serialized.RemoveWhitespace();

            Assert.AreEqual("{\"type\":\"Feature\",\"properties\":{},\"geometry\":{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0],[0.0,0.0]]]}}",
                            serialized);
        }
        public ElementSet AddElementsFromShapefile(ElementSet omiElementSet, string shapefilePath)
        {
            //this uses the free SharpMap API for reading a shapefile
            VectorLayer myLayer = new VectorLayer("elements_layer");

            myLayer.DataSource = new ShapeFile(shapefilePath);
            myLayer.DataSource.Open();

            //set spatial reference from shapefile
            SpatialReference sprf = new SpatialReference();

            sprf.ID = myLayer.DataSource.SRID.ToString();
            omiElementSet.SpatialReference = sprf;

            //add elements to elementset from shapefile
            for (uint i = 0; i < myLayer.DataSource.GetFeatureCount(); ++i)
            {
                FeatureDataRow feat         = myLayer.DataSource.GetFeature(i);
                string         GeometryType = Convert.ToString(
                    feat.Geometry.AsText().Substring(
                        0, feat.Geometry.AsText().IndexOf(' ')));

                Element e = new Element();

                if (feat.Table.Columns.IndexOf("HydroCode") != -1)
                {
                    e.ID = feat.ItemArray[feat.Table.Columns.IndexOf("HydroCode")].ToString();
                }

                if (GeometryType == "POINT")
                {
                    omiElementSet.ElementType = ElementType.XYPoint;
                    Point  p = (Point)feat.Geometry;
                    Vertex v = new Vertex();
                    v.x = p.X;
                    v.y = p.Y;
                    e.AddVertex(v);
                }
                if (GeometryType == "POLYGON")
                {
                    omiElementSet.ElementType = ElementType.XYPolygon;
                    Polygon    p  = (Polygon)feat.Geometry;
                    LinearRing lr = p.ExteriorRing;

                    //Only loop until lr.Vertices.Count-2 b/c the first element is the same
                    // as the last element within the exterior ring.  This will thrown an error
                    // within the OATC element mapper, when trying to map elements.  Also this
                    // loop arranges the vertices of the exterior ring in counter clockwise order
                    // as needed for the element mapping.
                    for (int j = lr.Vertices.Count - 2; j >= 0; j--)
                    {
                        Vertex v = new Vertex();
                        v.x = lr.Vertices[j].X;
                        v.y = lr.Vertices[j].Y;
                        e.AddVertex(v);
                    }
                }
                if (GeometryType == "LINESTRING")
                {
                    omiElementSet.ElementType = ElementType.XYPolyLine;
                    LineString ls = (LineString)feat.Geometry;
                    //Point endpt = ls.EndPoint;
                    //Point startpt = ls.StartPoint;
                    for (int j = 0; j < ls.Vertices.Count; j++)
                    {
                        Vertex v = new Vertex();
                        v.x = ls.Vertices[j].X;
                        v.y = ls.Vertices[j].Y;
                        e.AddVertex(v);
                    }
                }
                omiElementSet.AddElement(e);
            }
            return(omiElementSet);
        }
Ejemplo n.º 53
0
        public static bool Contains(Circle circleContaining, Polygon polygonContained)
        {
            // Pour contenir un polygone il suffit de contenir tous ses cotés

            return(polygonContained.Sides.TrueForAll(s => circleContaining.Contains(s)));
        }
Ejemplo n.º 54
0
        public void TestGeometryCollectionSerialization()
        {
            var geometry1 = new LineString(
                new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 1),
                new GeoCoordinate(1, 1),
                new GeoCoordinate(1, 0)
            });
            var geometry2 = new LineString(
                new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 2),
                new GeoCoordinate(2, 2),
                new GeoCoordinate(2, 0)
            });
            var geometry3 = new LineString(
                new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 3),
                new GeoCoordinate(3, 3),
                new GeoCoordinate(3, 0)
            });
            var geometry4 = new LineairRing(
                new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 1),
                new GeoCoordinate(1, 1),
                new GeoCoordinate(1, 0),
                new GeoCoordinate(0, 0)
            });
            var geometry5 = new Polygon(new LineairRing(
                                            new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 1),
                new GeoCoordinate(1, 1),
                new GeoCoordinate(1, 0),
                new GeoCoordinate(0, 0)
            }));
            var geometry6 = new MultiPolygon(geometry5, new Polygon(new LineairRing(
                                                                        new GeoCoordinate[]
            {
                new GeoCoordinate(0, 0),
                new GeoCoordinate(0, 2),
                new GeoCoordinate(2, 2),
                new GeoCoordinate(2, 0),
                new GeoCoordinate(0, 0)
            })));
            var geometry7          = new Point(new GeoCoordinate(0, 1));
            var geometry8          = new MultiPoint(geometry7, new Point(new GeoCoordinate(0, 2)));
            var geometryCollection = new GeometryCollection(
                geometry1, geometry2, geometry3,
                geometry4, geometry5, geometry6,
                geometry7, geometry8);

            var serialized = geometryCollection.ToGeoJson();

            serialized = serialized.RemoveWhitespace();

            Assert.AreEqual("{\"type\":\"GeometryCollection\",\"geometries\":[{\"type\":\"LineString\",\"coordinates\":[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0]]},{\"type\":\"LineString\",\"coordinates\":[[0.0,0.0],[2.0,0.0],[2.0,2.0],[0.0,2.0]]},{\"type\":\"LineString\",\"coordinates\":[[0.0,0.0],[3.0,0.0],[3.0,3.0],[0.0,3.0]]},{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0],[0.0,0.0]]]},{\"type\":\"Polygon\",\"coordinates\":[[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0],[0.0,0.0]]]},{\"type\":\"MultiPolygon\",\"coordinates\":[[[[0.0,0.0],[1.0,0.0],[1.0,1.0],[0.0,1.0],[0.0,0.0]]],[[[0.0,0.0],[2.0,0.0],[2.0,2.0],[0.0,2.0],[0.0,0.0]]]]},{\"type\":\"Point\",\"coordinates\":[1.0,0.0]},{\"type\":\"MultiPoint\",\"coordinates\":[[1.0,0.0],[2.0,0.0]]}]}",
                            serialized);
        }
Ejemplo n.º 55
0
        public bool CreatePathInsideBoundary(IntPoint startPointIn, IntPoint endPointIn, Polygon pathThatIsInside, bool optimizePath = true, int layerIndex = -1)
        {
            if (IsSimpleConvex)
            {
                return(true);
            }

            var goodPath = CalculatePath(startPointIn, endPointIn, pathThatIsInside, layerIndex);

            if (goodPath)
            {
                if (optimizePath)
                {
                    OptimizePathPoints(pathThatIsInside);
                }

                if (pathThatIsInside.Count == 0)
                {
                    if ((startPointIn - endPointIn).Length() > InsetAmount * 3)
                    {
                        pathThatIsInside.Add(startPointIn);
                        pathThatIsInside.Add(endPointIn);
                    }
                    else
                    {
                        return(true);
                    }
                }

                CutIntoSmallSegments(pathThatIsInside);

                MovePointsInsideIfPossible(startPointIn, endPointIn, pathThatIsInside);

                var cleanPath = pathThatIsInside.CleanClosedPolygon(InsetAmount / 2);
                pathThatIsInside.Clear();
                pathThatIsInside.AddRange(cleanPath);

                // remove any segment that goes to one point and then back to same point (a -> b -> a)
                RemoveUTurnSegments(startPointIn, endPointIn, pathThatIsInside);
            }

            //Remove0LengthSegments(startPointIn, endPointIn, pathThatIsInside);

            if (saveBadPathToDisk)
            {
                AllPathSegmentsAreInsideOutlines(pathThatIsInside, startPointIn, endPointIn, true, layerIndex);
            }

            CalculatedPath?.Invoke(this, pathThatIsInside, startPointIn, endPointIn);

            return(goodPath);
        }
Ejemplo n.º 56
0
        public static List <RealPoint> GetCrossingPoints(Circle circle, Polygon polygon)
        {
            // Croisement du cercle avec tous les segments du polygone

            return(polygon.Sides.SelectMany(s => s.GetCrossingPoints(circle)).Distinct().ToList());
        }
Ejemplo n.º 57
0
        private static void RemoveUTurnSegments(IntPoint startPointIn, IntPoint endPointIn, Polygon pathThatIsInside)
        {
            if (pathThatIsInside.Count > 1)
            {
                IntPoint startPoint = startPointIn;
                for (int i = 0; i < pathThatIsInside.Count - 1; i++)
                {
                    IntPoint testPoint = pathThatIsInside[i];
                    IntPoint endPoint  = i < pathThatIsInside.Count - 2 ? pathThatIsInside[i + 1] : endPointIn;

                    if (endPoint == startPoint)
                    {
                        // remove the test point
                        pathThatIsInside.RemoveAt(i);
                        // and remove the end point (it is the same as the start point
                        pathThatIsInside.RemoveAt(i);
                        // don't advance past the start point
                        i--;
                    }
                    else
                    {
                        startPoint = testPoint;
                    }
                }
            }
        }
Ejemplo n.º 58
0
        private bool CalculatePath(IntPoint startPointIn, IntPoint endPointIn, Polygon pathThatIsInside, int layerIndex)
        {
            double z = startPointIn.Z;

            startPointIn.Z = 0;
            endPointIn.Z   = 0;
            if (OutlineData?.Polygons == null ||
                OutlineData?.Polygons.Count == 0)
            {
                return(false);
            }

            // neither needed to be moved
            if (OutlineData.Polygons.FindIntersection(startPointIn, endPointIn, OutlineData.EdgeQuadTrees) == Intersection.None &&
                OutlineData.PointIsInside((startPointIn + endPointIn) / 2) == QTPolygonsExtensions.InsideState.Inside)
            {
                return(true);
            }

            OutlineData.RemovePointList.Dispose();

            pathThatIsInside.Clear();

            //Check if we are inside the boundaries
            IntPointNode startPlanNode = null;
            var          lastAddedNode = GetWayPointInside(startPointIn, out startPlanNode);

            IntPointNode endPlanNode   = null;
            var          lastToAddNode = GetWayPointInside(endPointIn, out endPlanNode);

            long startToEndDistanceSqrd  = (endPointIn - startPointIn).LengthSquared();
            long moveStartInDistanceSqrd = (startPlanNode.Position - lastAddedNode.Position).LengthSquared();
            long moveEndInDistanceSqrd   = (endPlanNode.Position - lastToAddNode.Position).LengthSquared();

            // if we move both points less than the distance of this segment
            if (startToEndDistanceSqrd < moveStartInDistanceSqrd &&
                startToEndDistanceSqrd < moveEndInDistanceSqrd)
            {
                // then go ahead and say it is a good path
                return(true);
            }

            var crossings = new List <(int polyIndex, int pointIndex, IntPoint position)>(OutlineData.Polygons.FindCrossingPoints(lastAddedNode.Position, lastToAddNode.Position, OutlineData.EdgeQuadTrees));

            if (crossings.Count == 0)
            {
                return(true);
            }
            crossings.Sort(new PolygonAndPointDirectionSorter(lastAddedNode.Position, lastToAddNode.Position));
            foreach (var crossing in crossings.SkipSame())
            {
                IntPointNode crossingNode = OutlineData.Waypoints.FindNode(crossing.Item3, findNodeDist);
                // for every crossing try to connect it up in the waypoint data
                if (crossingNode == null)
                {
                    crossingNode = AddTempWayPoint(OutlineData.RemovePointList, crossing.Item3);
                    // also connect it to the next and prev points on the polygon it came from
                    HookUpToEdge(crossingNode, crossing.Item1, crossing.Item2);
                }

                if (lastAddedNode != crossingNode &&
                    (SegmentIsAllInside(lastAddedNode, crossingNode) || lastAddedNode.Links.Count == 0))
                {
                    OutlineData.Waypoints.AddPathLink(lastAddedNode, crossingNode);
                }
                else if (crossingNode.Links.Count == 0)
                {
                    // link it to the edge it is on
                    HookUpToEdge(crossingNode, crossing.Item1, crossing.Item2);
                }
                lastAddedNode = crossingNode;
            }

            if (lastAddedNode != lastToAddNode &&
                (OutlineData.PointIsInside((lastAddedNode.Position + lastToAddNode.Position) / 2) == QTPolygonsExtensions.InsideState.Inside ||
                 lastToAddNode.Links.Count == 0))
            {
                // connect the last crossing to the end node
                OutlineData.Waypoints.AddPathLink(lastAddedNode, lastToAddNode);
            }

            Path <IntPointNode> path = OutlineData.Waypoints.FindPath(startPlanNode, endPlanNode, true);

            foreach (var node in path.Nodes.SkipSamePosition())
            {
                pathThatIsInside.Add(new IntPoint(node.Position, z));
            }

            if (path.Nodes.Length == 0 && saveBadPathToDisk)
            {
                WriteErrorForTesting(layerIndex, startPointIn, endPointIn, 0);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 59
0
        private Geometry ReadSvgNode(XElement node)
        {
            Geometry result = null;

            switch (node.Name.LocalName.ToLower())
            {
            case "svg":
            {
                double?newwidth;
                double?newheight;
                Rect?  newviewbox;

                newwidth   = GetDoubleAttribute(node.Attribute("width"));
                newheight  = GetDoubleAttribute(node.Attribute("height"));
                newviewbox = GetRectAttribute(node.Attribute("viewBox"));

                Clip                  = newviewbox.HasValue ? new RectangleGeometry(newviewbox.Value) : null;
                Width                 = newviewbox.HasValue ? newviewbox.Value.Right : newwidth.HasValue ? newwidth.Value : double.NaN;
                Height                = newviewbox.HasValue ? newviewbox.Value.Bottom : newheight.HasValue ? newheight.Value : double.NaN;
                ViewBox               = newviewbox.HasValue ? newviewbox.Value : Rect.Empty;
                ViewBoxWidth          = newviewbox.HasValue ? newviewbox.Value.Width : double.NaN;
                ViewBoxHeight         = newviewbox.HasValue ? newviewbox.Value.Height : double.NaN;
                translateTransform.X  = newviewbox.HasValue ? -newviewbox.Value.X : 0;
                translateTransform.Y  = newviewbox.HasValue ? -newviewbox.Value.Y : 0;
                scaleTransform.ScaleX = newviewbox.HasValue ? newviewbox.Value.Right / (double)newviewbox.Value.Width : 1;
                scaleTransform.ScaleY = newviewbox.HasValue ? newviewbox.Value.Bottom / (double)newviewbox.Value.Height : 1;

                GeometryGroup geometrygroup = new GeometryGroup()
                {
                    FillRule = FillRule.Nonzero
                };
                if (node.HasElements)
                {
                    foreach (XElement child in node.Elements())
                    {
                        var geometry = ReadSvgNode(child);
                        if (geometry != null)
                        {
                            geometrygroup.Children.Add(geometry);
                        }
                    }
                }
                result = geometrygroup;
                break;
            }

            case "g":
            {
                GeometryGroup geometrygroup = new GeometryGroup()
                {
                    FillRule = FillRule.Nonzero
                };
                if (node.HasElements)
                {
                    foreach (XElement child in node.Elements())
                    {
                        var geometry = ReadSvgNode(child);
                        if (geometry != null)
                        {
                            geometrygroup.Children.Add(geometry);
                        }
                    }
                }
                result = geometrygroup;
                break;
            }

            case "path":
            {
                foreach (var attr in node.Attributes())
                {
                    if (attr.Name.LocalName == "d" && !string.IsNullOrEmpty(attr.Value))
                    {
                        try
                        {
                            return(Geometry.Parse(attr.Value));
                        }
                        catch { }
                    }
                }
                break;
            }

            case "line":
            {
                double x1, y1, x2, y2;
                if (GetDoubleAttribute(node.Attribute("x1"), out x1) && GetDoubleAttribute(node.Attribute("y1"), out y1) && GetDoubleAttribute(node.Attribute("x2"), out x2) && GetDoubleAttribute(node.Attribute("y2"), out y2))
                {
                    result = new LineGeometry(new Point(x1, y2), new Point(x2, y2));
                }
                break;
            }

            case "rect":
            {
                double x, y, w, h;
                if (GetDoubleAttribute(node.Attribute("x"), out x) && GetDoubleAttribute(node.Attribute("y"), out y) && GetDoubleAttribute(node.Attribute("width"), out w) && GetDoubleAttribute(node.Attribute("height"), out h))
                {
                    result = new RectangleGeometry(new Rect(x, y, w, h));
                }
                break;
            }

            case "ellipse":
            {
                double cx, cy, rx, ry;
                if (GetDoubleAttribute(node.Attribute("cx"), out cx) && GetDoubleAttribute(node.Attribute("cy"), out cy) && GetDoubleAttribute(node.Attribute("rx"), out rx) && GetDoubleAttribute(node.Attribute("ry"), out ry))
                {
                    result = new EllipseGeometry(new Point(cx, cy), rx, ry);
                }
                break;
            }

            case "circle":
            {
                double cx, cy, r;
                if (GetDoubleAttribute(node.Attribute("cx"), out cx) && GetDoubleAttribute(node.Attribute("cy"), out cy) && GetDoubleAttribute(node.Attribute("r"), out r))
                {
                    result = new EllipseGeometry(new Point(cx, cy), r, r);
                }
                break;
            }

            case "polyline":
            {
                try
                {
                    Polyline   polyline = new Polyline();
                    XAttribute attr     = node.Attribute("points");
                    if (attr != null && !string.IsNullOrEmpty(attr.Value))
                    {
                        polyline.Points = PointCollection.Parse(attr.Value);
                        polyline.Measure(ViewBox.Size);
                        polyline.Arrange(ViewBox);
                        result = polyline.RenderedGeometry;
                    }
                }
                catch { }
                break;
            }

            case "polygon":
            {
                try
                {
                    Polygon    polygon = new Polygon();
                    XAttribute attr    = node.Attribute("points");
                    if (attr != null && !string.IsNullOrEmpty(attr.Value))
                    {
                        polygon.Points = PointCollection.Parse(attr.Value);
                        polygon.Measure(ViewBox.Size);
                        polygon.Arrange(ViewBox);
                        result = polygon.RenderedGeometry;
                    }
                }
                catch { }
                break;
            }
            }

            if (result != null)
            {
                result.Transform = GetTransformAttribute(node.Attribute("transform"));
            }

            return(result);
        }
Ejemplo n.º 60
0
        private void ConfigureThenRoute()
        {
            // Guard against error conditions.
            if (_routeParameters == null)
            {
                ShowMessage("Not ready yet", "Sample isn't ready yet; define route parameters first.");
                return;
            }

            if (_stopsOverlay.Graphics.Count < 2)
            {
                ShowMessage("Not enough stops", "Add at least two stops before solving a route.");
                return;
            }

            // Clear any existing route from the map.
            _routeOverlay.Graphics.Clear();

            // Configure the route result to include directions and stops.
            _routeParameters.ReturnStops      = true;
            _routeParameters.ReturnDirections = true;

            // Create a list to hold stops that should be on the route.
            List <Stop> routeStops = new List <Stop>();

            // Create stops from the graphics.
            foreach (Graphic stopGraphic in _stopsOverlay.Graphics)
            {
                // Note: this assumes that only points were added to the stops overlay.
                MapPoint stopPoint = (MapPoint)stopGraphic.Geometry;

                // Create the stop from the graphic's geometry.
                Stop routeStop = new Stop(stopPoint);

                // Set the name of the stop to its position in the list.
                routeStop.Name = $"{_stopsOverlay.Graphics.IndexOf(stopGraphic) + 1}";

                // Add the stop to the list of stops.
                routeStops.Add(routeStop);
            }

            // Configure the route parameters with the stops.
            _routeParameters.ClearStops();
            _routeParameters.SetStops(routeStops);

            // Create a list to hold barriers that should be routed around.
            List <PolygonBarrier> routeBarriers = new List <PolygonBarrier>();

            // Create barriers from the graphics.
            foreach (Graphic barrierGraphic in _barriersOverlay.Graphics)
            {
                // Get the polygon from the graphic.
                Polygon barrierPolygon = (Polygon)barrierGraphic.Geometry;

                // Create a barrier from the polygon.
                PolygonBarrier routeBarrier = new PolygonBarrier(barrierPolygon);

                // Add the barrier to the list of barriers.
                routeBarriers.Add(routeBarrier);
            }

            // Configure the route parameters with the barriers.
            _routeParameters.ClearPolygonBarriers();
            _routeParameters.SetPolygonBarriers(routeBarriers);

            // If the user allows stops to be re-ordered, the service will find the optimal order.
            _routeParameters.FindBestSequence = AllowReorderStopsCheckbox.IsChecked == true;

            // If the user has allowed re-ordering, but has a definite start point, tell the service to preserve the first stop.
            _routeParameters.PreserveFirstStop = PreserveFirstStopCheckbox.IsChecked == true;

            // If the user has allowed re-ordering, but has a definite end point, tell the service to preserve the last stop.
            _routeParameters.PreserveLastStop = PreserveLastStopCheckbox.IsChecked == true;

            // Calculate and show the route.
            CalculateAndShowRoute();
        }