Example #1
0
 public TweenAlpha(PolygonData target, double startingValue, double finalValue, double changeSpeed)
 {
     this.target       = target;
     this.currentValue = startingValue;
     this.finalValue   = finalValue;
     this.changeSpeed  = changeSpeed;
 }
Example #2
0
        public bool InPolygon(PolygonData data)
        {
            double x = data.Point.X;
            double y = data.Point.Y;

            // массив абсцисс вершин многоугольника
            double[] xArray = new double[data.Polygon.Length];
            // массив ординат вершин многоугольника
            double[] yArray = new double[data.Polygon.Length];

            for (int i = 0; i < data.Polygon.Length; i++)
            {
                xArray[i] = data.Polygon[i].X;
                yArray[i] = data.Polygon[i].Y;
            }

            int  j      = xArray.Length - 1;
            bool inPoly = false;

            for (int i = 0; i < xArray.Length; i++)
            {
                if (((yArray[i] <= y && y < yArray[j]) || (yArray[j] <= y && y < yArray[i])) &&
                    (yArray[j] - yArray[i]) != 0 &&
                    (x > (xArray[j] - xArray[i]) * (y - yArray[i]) / (yArray[j] - yArray[i]) + xArray[i]))
                {
                    inPoly = !inPoly;
                }
                j = i;
            }
            return(inPoly);
        }
Example #3
0
        /// <summary>
        /// Adds new positions and new polygons to the underlying PolyMesh of this object,
        /// keying their indices using the provided key.
        ///
        /// The Polygons in newPolygons should index the newPositions directly; they are
        /// both added using the PolyMesh Append() operation, which will modify the polygons
        /// in the newPolygons list (specifically, their underlying vertex indices lists will
        /// be modified to match the indices of the positions that are added to the PolyMesh).
        ///
        /// If you'd like to retrieve this data to modify it later, provide the same key to
        /// the ModifyDataFor() method, which will return a PolyMesh object and indices into
        /// its data that you can modify freely.
        ///
        /// Positions are never re-used by LivePolyMeshObjects, so they are less optimal than
        /// manipulating a PolyMesh directly (however, this has no impact on the resulting
        /// Unity mesh representation).
        /// </summary>
        public void AddDataFor(object key, List <Vector3> newPositions,
                               List <Polygon> newPolygons,
                               List <Edge> newSmoothEdges,
                               List <Color> newColors = null)
        {
            PolygonData polygonData;

            if (objectPolygonData.TryGetValue(key, out polygonData))
            {
                throw new System.InvalidOperationException(
                          "Data for the provided key already exists: " + key.ToString());
            }

            var newPositionIndices = Pool <List <int> > .Spawn();

            newPositionIndices.Clear();
            var newPolygonIndices = Pool <List <int> > .Spawn();

            newPolygonIndices.Clear();
            polyMesh.Append(newPositions,
                            newPolygons,
                            newPositionIndices,
                            newPolygonIndices,
                            newSmoothEdges: newSmoothEdges,
                            newColors: newColors);

            objectPolygonData[key] = new PolygonData()
            {
                a = newPositionIndices,
                b = newPolygonIndices
            };

            RefreshUnityMesh();
        }
Example #4
0
 // find an ear (always a triangle) of the polygon and return the index of the middle (second) vertex in the ear
 public static int FindEar(PolygonData poly)
 {
     for (int i = 0; i < poly.PtList.Count - 2; i++)
     {
         if (poly.VertexType(i + 1) == PolygonType.Convex)
         {
             // get the three points of the triangle we are about to test
             PointF a = poly.PtList[i];
             PointF b = poly.PtList[i + 1];
             PointF c = poly.PtList[i + 2];
             bool   foundAPointInTheTriangle = false;        // see if any of the other points in the polygon are in this triangle
             for (int j = 0; j < poly.PtListOpen.Count; j++) // don't check the last point, which is a duplicate of the first
             {
                 if (j != i && j != i + 1 && j != i + 2 && PointInTriangle(poly.PtList[j], a, b, c))
                 {
                     foundAPointInTheTriangle = true;
                 }
             }
             if (!foundAPointInTheTriangle) // the middle point of this triangle is convex and none of the other points in the polygon are in this triangle, so it is an ear
             {
                 return(i + 1);             // EXITING HERE!
             }
         }
     }
     throw new ApplicationException("Improperly formed polygon");
 }
Example #5
0
 public OscillatingAlpha(PolygonData target, double period, double amplitude, Func <double, double> valueTransform, Color color)
 {
     this.target         = target;
     this.period         = period;
     this.amplitude      = amplitude;
     this.valueTransform = valueTransform;
     this.color          = color;
 }
        private PolygonView CreatePolygonView(PolygonData data)
        {
            PolygonView polygonView = m_PolygonsPool.Count > 0
                ? m_PolygonsPool.Pop()
                : Instantiate(m_PolygonPrefab, transform, false);

            polygonView.SetShapeData(data);
            return(polygonView);
        }
Example #7
0
        private SceneObject unitSprite(IGrouping<Vector2D, CombatantInfo> hex, IEnumerable<PlayerInfo> players)
		{
			var polygons = new List<PolygonData>();
			IAnimator animator = null;

			var hexTransform = Matrix4.CreateTranslation(hexX(hex.Key), hexY(hex.Key), 0);
			
			var unitSelected = (this.currentUnit != null && this.currentUnit.Position == hex.Key);
			var unit = unitSelected ? this.currentUnit : biggestStack(hex);
			var unitSprite = GalaxyTextures.Get.Sprite(unit.Design.ImagePath);
			var alpha = players.All(x => unit.CloakedFor(x) || x == unit.Owner) ? 0.65 : 1;
			
			var unitDrawable = new PolygonData(
				CombatantZ,
				new SpriteData(hexTransform, unitSprite.Id, Color.FromArgb((int)(alpha * 255), unit.Owner.Color), null, true),
				SpriteHelpers.UnitRect(unitSprite).ToList()
			);
			if (unitSelected)
			{
				animator = new OscillatingAlpha(
					unitDrawable, 
					AnimationPeriod, 
					0.6, 
					x => (x + 0.4) * alpha, 
					unit.Owner.Color);
			}

			polygons.Add(unitDrawable);			
			
			var otherUnits = hex.Where(x => x != unit).Select(x => x.Owner).Distinct().ToList();
			for(int i = 0; i < otherUnits.Count; i++)
				polygons.Add(new PolygonData(
					CombatantZ,
					new SpriteData(
						Matrix4.CreateScale(0.2f, 0.2f, 1) * Matrix4.CreateTranslation(0.5f, 0.2f * i + 0.5f, 0) * hexTransform,  
						GalaxyTextures.Get.FleetIndicator.Id,
						otherUnits[i].Color, 
						null, true
					),
					SpriteHelpers.UnitRect(GalaxyTextures.Get.FleetIndicator).ToList()
				));

			polygons.Add(new PolygonData(
				CombatantZ,
				new SpriteData(
					Matrix4.CreateScale(0.2f, 0.2f, 1) * Matrix4.CreateTranslation(0.5f, -0.5f, 0) * hexTransform,
					TextRenderUtil.Get.TextureId,
					Color.Gray, 
					null, true
				),
				TextRenderUtil.Get.BufferRaster(new ThousandsFormatter().Format(unit.Count), -1, Matrix4.Identity).ToList()
			));

			return new SceneObject(polygons, animator: animator);
		}
Example #8
0
        public IActionResult ReceiveAndCheckData([FromBody] PolygonData polygonData)
        {
            bool   inPoly = _polyService.InPolygon(polygonData);
            Result result = new Result
            {
                InPolygon = inPoly,
                Name      = polygonData.Name
            };

            return(Ok(result));
        }
Example #9
0
        public void Point_On_Polygon_Vertex(double x, double y)
        {
            PolygonData data = new PolygonData
            {
                Polygon = _polygonPoints,
                Point   = new Point {
                    X = x, Y = y
                }
            };
            bool result = _polyService.InPolygon(data);

            Assert.False(result);
        }
Example #10
0
File: Form1.cs Project: ghfog/test
        private void AddPolygon(int x, int y, int pitch)
        {
            int v0, v1, v2, v3;

            if (((x & 1) ^ (y & 1)) == 0)
            {
                v0 = ((y + 0) * pitch) + (x + 0);
                v1 = ((y + 0) * pitch) + (x + 1);
                v2 = ((y + 1) * pitch) + (x + 0);
                v3 = ((y + 1) * pitch) + (x + 1);
            }
            else
            {
                v0 = ((y + 0) * pitch) + (x + 1); // c1
                v1 = ((y + 0) * pitch) + (x + 0); // c0
                v2 = ((y + 1) * pitch) + (x + 1); // c3
                v3 = ((y + 1) * pitch) + (x + 0); // c2
            }

            Color c0, c1, c2, c3;

            c0 = this.m_VertexList[v0].m_Color;
            c1 = this.m_VertexList[v1].m_Color;
            c2 = this.m_VertexList[v2].m_Color;
            c3 = this.m_VertexList[v3].m_Color;

            // 同じ色かつ抜き職
            if ((c0.ToArgb() == Color.White.ToArgb()) && (c0.ToArgb() == c1.ToArgb()) && (c1.ToArgb() == c2.ToArgb()) && (c2.ToArgb() == c3.ToArgb()))
            {
                return;
            }

            if (!((c0.ToArgb() == Color.White.ToArgb()) && (c0.ToArgb() == c1.ToArgb()) && (c1.ToArgb() == c2.ToArgb())))
            {
                PolygonData polygon = new PolygonData();
                polygon.m_Index0 = v0;
                polygon.m_Index1 = v1;
                polygon.m_Index2 = v2;
                this.m_PolygonList.Add(polygon);
            }

            if (!((c3.ToArgb() == Color.White.ToArgb()) && (c3.ToArgb() == c2.ToArgb()) && (c2.ToArgb() == c1.ToArgb())))
            {
                PolygonData polygon = new PolygonData();
                polygon.m_Index0 = v3;
                polygon.m_Index1 = v2;
                polygon.m_Index2 = v1;
                this.m_PolygonList.Add(polygon);
            }
        }
Example #11
0
 public static PolygonData[] GetDataFromFile(string path)
 {
     PolygonData[] ret;
     TextAsset mesh = (TextAsset)Resources.Load(path);
     string[] s = mesh.text.Split('\n');
     ret = new PolygonData[s.Length];
     int idx = 0;
     foreach (string str in s)
     {
         if (str.Length < 10) continue;
         ret[idx] = new PolygonData(str);
         Debug.Log(idx);
         idx++;
     }
     return ret;
 }
Example #12
0
        private void AddPolygon(LocationCollection list, bool useMultiColors)
        {
            PolygonData data = new PolygonData();

            if (useMultiColors)
            {
                data.ShapeFill = new MapShapeFill()
                {
                    Fill            = new SolidColorBrush(Color.FromArgb(80, (byte)rndNumberGenerator.Next(0, 255), (byte)rndNumberGenerator.Next(0, 255), (byte)rndNumberGenerator.Next(0, 255))),
                    Stroke          = brushes[rndNumberGenerator.Next(0, brushes.Length)],
                    StrokeThickness = 2,
                };
            }
            data.Points = list;
            this.vizLayer.Items.Add(data);
        }
        private IEnumerable <PolygonData> unitSpriteData(IGrouping <Vector2D, CombatantInfo> hex, IEnumerable <PlayerInfo> players)
        {
            var hexTransform = Matrix4.CreateTranslation(hexX(hex.Key), hexY(hex.Key), 0);

            var unitSelected = (this.currentUnit != null && this.currentUnit.Position == hex.Key);
            var unit         = unitSelected ? this.currentUnit : biggestStack(hex);
            var unitSprite   = GalaxyTextures.Get.Sprite(unit.Design.ImagePath);
            var alpha        = players.All(x => unit.CloakedFor(x) || x == unit.Owner) ? 0.65 : 1;

            var unitDrawable = new PolygonData(
                CombatantZ,
                new SpriteData(hexTransform, unitSprite.Id, Color.FromArgb((int)(alpha * 255), unit.Owner.Color)),
                SpriteHelpers.UnitRectVertexData(unitSprite)
                );

            if (unitSelected)
            {
                this.currentUnitDrawable = unitDrawable;
            }

            yield return(unitDrawable);

            var otherUnits = hex.Where(x => x != unit).Select(x => x.Owner).Distinct().ToList();

            for (int i = 0; i < otherUnits.Count; i++)
            {
                yield return(new PolygonData(
                                 CombatantZ,
                                 new SpriteData(
                                     Matrix4.CreateScale(0.2f, 0.2f, 1) * Matrix4.CreateTranslation(0.5f, 0.2f * i + 0.5f, 0) * hexTransform,
                                     GalaxyTextures.Get.FleetIndicator.Id,
                                     otherUnits[i].Color
                                     ),
                                 SpriteHelpers.UnitRectVertexData(GalaxyTextures.Get.FleetIndicator)
                                 ));
            }

            yield return(new PolygonData(
                             CombatantZ,
                             new SpriteData(
                                 Matrix4.CreateScale(0.2f, 0.2f, 1) * Matrix4.CreateTranslation(0.5f, -0.5f, 0) * hexTransform,
                                 TextRenderUtil.Get.TextureId,
                                 Color.Gray
                                 ),
                             TextRenderUtil.Get.BufferText(new ThousandsFormatter().Format(unit.Count), -1, Matrix4.Identity).ToList()
                             ));
        }
Example #14
0
        /// <summary>
        /// This method returns a 3D representation of this area
        /// </summary>
        /// <param name="nodesDict">List of all the nodes on the map</param>
        /// <param name="map">bounds of the map</param>
        /// <param name="brush">Color of this area</param>
        /// <returns>ModelUIElement3D of this area</returns>
        public virtual ModelUIElement3D get3DSurface(Dictionary <long, OsmSharp.Osm.Node> nodesDict, Map map, System.Windows.Media.SolidColorBrush brush)
        {
            List <PointF> ptlist = getScaledPointsSurface(nodesDict, map);

            // Divide the polygons in triangles, this is code (and these two classes) are from: https://polygontriangulation.codeplex.com/
            PolygonData     poly      = new PolygonData(ptlist);
            List <PointF[]> triangles = Triangulation2D.Triangulate(poly);

            // Surrounding tags of the mesh
            ModelUIElement3D model         = new ModelUIElement3D();
            GeometryModel3D  geometryModel = new GeometryModel3D();

            // Mesh and his his properties
            MeshGeometry3D    mesh      = new MeshGeometry3D();
            DiffuseMaterial   material  = new DiffuseMaterial((System.Windows.Media.Brush)brush);
            Point3DCollection positions = new Point3DCollection();
            Int32Collection   indices   = new Int32Collection();

            // Add points and indices to their collection
            foreach (PointF[] points in triangles)
            {
                foreach (PointF point in points)
                {
                    positions.Add(new Point3D(point.X, point.Y, height));
                }

                int count = positions.Count;
                indices.Add(count - 3);
                indices.Add(count - 2);
                indices.Add(count - 1);
            }

            // Add these collections to the mesh
            mesh.Positions       = positions;
            mesh.TriangleIndices = indices;

            // Set the color of front and back of the triangle
            geometryModel.Material     = material;
            geometryModel.BackMaterial = material;

            // Add the mesh to the model
            geometryModel.Geometry = mesh;
            model.Model            = geometryModel;

            return(model);
        }
Example #15
0
        // From Wikipedia:
        // One way to triangulate a simple polygon is by using the assertion that any simple polygon
        // without holes has at least two so called 'ears'. An ear is a triangle with two sides on the edge
        // of the polygon and the other one completely inside it. The algorithm then consists of finding
        // such an ear, removing it from the polygon (which results in a new polygon that still meets
        // the conditions) and repeating until there is only one triangle left.

        // the algorithm here aims for simplicity over performance. there are other, more performant
        // algorithms that are much more complex.

        // convert a triangle to a list of triangles. each triangle is represented by a PointF array of length 3.
        public static List <PointF[]> Triangulate(PolygonData poly)
        {
            List <PointF[]> triangles = new List <PointF[]>();  // accumulate the triangles here

            // keep clipping ears off of poly until only one triangle remains
            while (poly.PtListOpen.Count > 3)  // if only 3 points are left, we have the final triangle
            {
                int midvertex = FindEar(poly); // find the middle vertex of the next "ear"
                triangles.Add(new PointF[] { poly.PtList[midvertex - 1], poly.PtList[midvertex], poly.PtList[midvertex + 1] });
                // create a new polygon that clips off the ear; i.e., all vertices but midvertex
                List <PointF> newPts = new List <PointF>(poly.PtList);
                newPts.RemoveAt(midvertex);     // clip off the ear
                poly = new PolygonData(newPts); // poly now has one less point
            }
            // only a single triangle remains, so add it to the triangle list
            triangles.Add(poly.PtListOpen.ToArray());
            return(triangles);
        }
Example #16
0
 public PolygonLinesDontIntersectValidator(PolygonData polygonData)
 {
     m_PolygonData = polygonData;
     m_PolygonData.GeometryUpdated.Subscribe(base.Update);
 }
Example #17
0
 public PolygonPointsAreInOnePlaneValidator(PolygonData polygonData)
 {
     m_PolygonData = polygonData;
     m_PolygonData.GeometryUpdated.Subscribe(base.Update);
 }
Example #18
0
        /// <summary>
        /// Perform the Triangulation of the Input.
        /// </summary>
        /// <param name="polygon">The Input Polygon</param>
        /// <param name="holes">The Input Polygon</param>
        /// <returns>List of Indices representing the Triangulation of the Polygon</returns>
        public static Int32Collection Triangulate(IList <Point> polygon, List <List <Point> > holes = null)
        {
            // Allocate and initialize List of Indices in Polygon
            var result = new Int32Collection();

            // Point-List from Input
            // (we don't want the first and last Point to be present two times)
            var points = polygon.ToList();

            if (points[0] == points[points.Count - 1])
            {
                points.RemoveAt(points.Count - 1);
            }
            var count = points.Count;

            // Sort the Input and create the Datastructures
            // Make the Polygon CounterClockWise
            var didReverse = false;

            if (!IsCCW(polygon))
            {
                points.Reverse();
                didReverse = true;
            }

            // Skip Polygons that don't need Triangulation
            if (count < 3)
            {
                return(null);
            }
            else if (count == 3)
            {
                if (!didReverse)
                {
                    return(new Int32Collection {
                        0, 1, 2
                    });
                }
                else
                {
                    return(new Int32Collection {
                        0, 2, 1
                    });
                }
            }

            var poly = new PolygonData(points);

            if (holes != null)
            {
                foreach (var hole in holes)
                {
                    poly.AddHole(hole);
                }
            }
            // Sort Points from highest y to lowest y
            // and if two or more Points have the same y Value from lowest x to highest x Value
            var events = new List <PolygonPoint>(poly.Points);

            events.Sort();

            // Calculate the Diagonals in the Down Sweep
            var diagonals = CalculateDiagonals(events);

            // Reverse the Order of the Events
            events.Reverse();
            // Add the Diagonals in the Up Sweep (and remove duplicates)
            diagonals.AddRange(CalculateDiagonals(events, false));
            diagonals = diagonals.Distinct().ToList();

            // Use Diagonals to split into nonotone Polygons
            var monotonePolygons = SplitIntoPolygons(poly, diagonals);

            // y-Monotone Polygons
            // Triangulate
            foreach (var monoton in monotonePolygons.Where(m => m != null))
            {
                var indices = TriangulateMonotone(monoton);
                foreach (var index in indices)
                {
                    result.Add(index);
                }
            }

            // If we reversed the Polygon,
            // we need to reverse the result also to get a correct Triangulation
            if (didReverse)
            {
                // Transform back every calculated Index
                for (int i = 0; i < result.Count; i++)
                {
                    result[i] = count - result[i] - 1;
                }
            }

            // Return all calculated Triangleindices
            return(result);
        }
Example #19
0
        /// <summary>
        /// Split Polygon into subpolagons using the calculated Diagonals
        /// </summary>
        /// <param name="poly">The Base-Polygon</param>
        /// <param name="diagonals">The Split-Diagonals</param>
        /// <returns>List of Subpolygons</returns>
        private static List <PolygonData> SplitIntoPolygons(PolygonData poly, List <Tuple <int, int> > diagonals)
        {
            if (diagonals.Count == 0)
            {
                return new List <PolygonData>()
                       {
                           poly
                       }
            }
            ;

            diagonals = diagonals.OrderBy(d => d.Item1).ThenBy(d => d.Item2).ToList();
            var edges = new SortedDictionary <int, List <PolygonEdge> >();

            foreach (var edge in poly.Points.Select(p => p.EdgeTwo)
                     .Union(diagonals.Select(d => new PolygonEdge(poly.Points[d.Item1], poly.Points[d.Item2])))
                     .Union(diagonals.Select(d => new PolygonEdge(poly.Points[d.Item2], poly.Points[d.Item1]))))
            {
                if (!edges.ContainsKey(edge.PointOne.Index))
                {
                    edges.Add(edge.PointOne.Index, new List <PolygonEdge>()
                    {
                        edge
                    });
                }
                else
                {
                    edges[edge.PointOne.Index].Add(edge);
                }
            }

            var subPolygons = new List <PolygonData>();

            var cnt = 0;

            foreach (var edge in edges)
            {
                cnt += edge.Value.Count;
            }

            // For each Diagonal
            while (edges.Count > 0)
            {
                // Start at first Diagonal Point
                var currentPoint     = edges.First().Value.First().PointOne;
                var nextEdge         = new PolygonEdge(null, null);
                var subPolygonPoints = new List <PolygonPoint>();
                // March along the edges to form a monotone Polygon
                // Until the current Point equals the StartPoint
                do
                {
                    // Add the current Point
                    subPolygonPoints.Add(currentPoint);
                    // Select the next Edge
                    var possibleEdges = edges[currentPoint.Index].ToList();
                    nextEdge = BestEdge(currentPoint, nextEdge, possibleEdges);
                    // Remove Edge from possible Edges
                    edges[currentPoint.Index].Remove(nextEdge);
                    if (edges[currentPoint.Index].Count == 0)
                    {
                        edges.Remove(currentPoint.Index);
                    }

                    // Move to the next Point
                    currentPoint = nextEdge.PointTwo;
                }while (subPolygonPoints[0].Index != currentPoint.Index);
                // Add the new SubPolygon
                subPolygons.Add(new PolygonData(subPolygonPoints));
            }

            return(subPolygons);
        }
Example #20
0
        /// <summary>
        /// Triangulate the y-Monotone Polygons.
        /// </summary>
        /// <param name="monoton">The y-Monotone Polygon to triangle</param>
        /// <returns>Index-List of Polygon Points (Indices from the original Polygon)</returns>
        private static Int32Collection TriangulateMonotone(PolygonData monoton)
        {
            // Collection to return
            Int32Collection result = new Int32Collection();

            // Sort the Events
            var events = new List <PolygonPoint>(monoton.Points);

            events.Sort();

            // Stack of Events to push to and pop from
            var pointStack = new Stack <PolygonPoint>();

            // Push the first two Events
            pointStack.Push(events[0]);
            pointStack.Push(events[1]);

            // Left- and right Chain for Triangulation
            var left  = (events[0].Next == events[1]) ? events[1] : events[0];
            var right = (events[0].Last == events[1]) ? events[1] : events[0];

            // Count of Points
            var pointCnt = monoton.Points.Count;

            // Handle the 3rd...n-th Point to triangle
            for (int i = 2; i < pointCnt; i++)
            {
                // The current Point
                var newPoint = events[i];
                var top      = pointStack.Peek();
                // If the new Point is not on the same side as the last Point on the Stack
                //if (!(leftChain.Contains(top) && leftChain.Contains(newPoint) || rightChain.Contains(top) && rightChain.Contains(newPoint)))
                if (!(top.Last == newPoint || top.Next == newPoint))
                {
                    // Determine this Point's Chain (left or right)
                    if (left.Next == newPoint)
                    {
                        left = newPoint;
                    }
                    else if (right.Last == newPoint)
                    {
                        right = newPoint;
                    }

                    // Third triangle Point
                    var p2 = top;
                    // While there is a Point on the Stack
                    while (pointStack.Count != 0)
                    {
                        // Pop and set the third Point
                        top = pointStack.Pop();
                        p2  = top;
                        if (pointStack.Count != 0)
                        {
                            // Pop again
                            top = pointStack.Pop();

                            // Add to the result. The Order is depending on the Side
                            if (left == newPoint)
                            {
                                result.Add(newPoint.Index);
                                result.Add(p2.Index);
                                result.Add(top.Index);
                            }
                            else
                            {
                                result.Add(newPoint.Index);
                                result.Add(top.Index);
                                result.Add(p2.Index);
                            }
                        }
                        // If more Points are on the Stack,
                        // Push the Point back again, to be able to form the Triangles
                        if (pointStack.Count != 0)
                        {
                            pointStack.Push(top);
                        }
                    }
                    // Push the last to Points on the Stack
                    pointStack.Push(events[i - 1]);
                    pointStack.Push(newPoint);
                }
                // If the newPoint is on the same Side (i.e. Chain)
                else
                {
                    // Get to Point on the Stack
                    top = pointStack.Pop();
                    var p2 = top;

                    // Determine this Point's Chain (left or right)
                    if (left.Next == newPoint && right.Last == newPoint)
                    {
                        if (top.Last == newPoint)
                        {
                            right = newPoint;
                        }
                        else if (top.Next == newPoint)
                        {
                            left = newPoint;
                        }
                        else
                        {
                            throw new Exception("Triangulation error");
                        }
                    }
                    else if (left.Next == newPoint)
                    {
                        left = newPoint;
                    }
                    else if (right.Last == newPoint)
                    {
                        right = newPoint;
                    }

                    while (pointStack.Count != 0)
                    {
                        // If the Triangle is possible, add it to the result (Point Order depends on the Side)
                        if (right == newPoint && IsCCW(new List <Point> {
                            newPoint.Point, p2.Point, pointStack.Peek().Point
                        }))
                        {
                            top = pointStack.Pop();
                            result.Add(newPoint.Index);
                            result.Add(p2.Index);
                            result.Add(top.Index);
                            p2 = top;
                        }
                        else if (left == newPoint && !IsCCW(new List <Point> {
                            newPoint.Point, p2.Point, pointStack.Peek().Point
                        }))
                        {
                            top = pointStack.Pop();
                            result.Add(newPoint.Index);
                            result.Add(top.Index);
                            result.Add(p2.Index);
                            p2 = top;
                        }
                        // No Triangle possible, just leave the Loop
                        else
                        {
                            break;
                        }
                    }
                    // Push the last two Points on the Stack
                    pointStack.Push(p2);
                    pointStack.Push(newPoint);
                }
            }
            // Return the Triangulation
            return(result);
        }
Example #21
0
 public PolygonBusiness()
 {
     polygonData = new PolygonData();
 }
Example #22
0
        private bool parseOverlapDataFile()
        {
            if (string.IsNullOrEmpty(sourceFile))
            {
                MessageBox.Show("Specify an overlap data file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            var xd = new XmlDocument();
            xd.Load(sourceFile);

            //Get the reference point
            XmlNode refNode = xd.SelectSingleNode("//scu/reference");

            //Validate
            if (refNode == null)
            {
                MessageBox.Show("Invalid overlap data file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            XmlNodeList polygonNodes = xd.SelectNodes("//scu/polygon");

            //Validate
            if (polygonNodes == null || polygonNodes.Count == 0)
            {
                MessageBox.Show("File contains no polygon data!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            polygons = new PolygonData[polygonNodes.Count];
            for (int i = 0; i < polygonNodes.Count; i++)
            {
                string slc = polygonNodes[i].SelectSingleNode("coordsLeft").InnerText;
                string src = polygonNodes[i].SelectSingleNode("coordsRight").InnerText;

                string[] lcrds = slc.Split(' ');
                string[] rcrds = src.Split(' ');

                int N = lcrds.Length - 1;

                string[] crds = new string[2*N];

                Array.Reverse(rcrds, 0, N);

                Array.Copy(lcrds, crds, N);
                Array.Copy(rcrds, 0, crds, N, N);

                polygons[i] = new PolygonData();
                polygons[i].Coordinates = new PointF[2*N + 1];

                int j;
                for (j = 0; j < crds.Length; j++)
                {
                    polygons[i].Coordinates[j] = convertToPointF(crds[j]);
                }
                polygons[i].Coordinates[j] = polygons[i].Coordinates[0]; //Close polygon
            }

            return true;
        }
Example #23
0
        private XmlNode createLinearRingElement(XmlDocument document, ref PolygonData polygon)
        {
            XmlElement main = document.CreateElement("LinearRing");

            XmlElement child = document.CreateElement("coordinates");

            child.InnerText = "";
            for (int i = 0; i < polygon.Coordinates.Length; i++)
            {
                string sy = polygon.Coordinates[i].Y.ToString("R", CultureInfo.InvariantCulture);
                string sx = polygon.Coordinates[i].X.ToString("R", CultureInfo.InvariantCulture);

                child.InnerText += string.Format("{0},{1},0 ", sy, sx);
            }

            main.AppendChild(child);

            return main;
        }
Example #24
0
        private XmlNode createPlacemarkElement(XmlDocument document, int id, ref PolygonData polygon)
        {
            XmlElement main = document.CreateElement("Placemark");

            XmlElement child = document.CreateElement("name");
            child.InnerText = string.Format("Polygon {0}", id);
            main.AppendChild(child);

            child = document.CreateElement("styleUrl");
            child.InnerText = "#sh_overlap";
            main.AppendChild(child);

            XmlElement pg = document.CreateElement("Polygon");

            child = document.CreateElement("tessellate");
            child.InnerText = "1";
            pg.AppendChild(child);

            XmlElement bnd = document.CreateElement("outerBoundaryIs");
            bnd.AppendChild(createLinearRingElement(document, ref polygon));
            pg.AppendChild(bnd);

            main.AppendChild(pg);

            return main;
        }
Example #25
0
 private void OnEnable()
 {
     polygonData = target as PolygonData;
 }
Example #26
0
 public PolygonBlueprint(ShapeDataFactory dataFactory) : base(dataFactory)
 {
     PolygonData = dataFactory.CreatePolygonData();
     OnDeserialized();
 }
 public PolygonUniquenessValidator(PolygonData polygonData)
 {
     m_PolygonData = polygonData;
     m_PolygonData.NameUpdated.Subscribe(OnUniqueDeterminingPropertyUpdated);
 }