Ejemplo n.º 1
0
        private void GenerateTerrain(int gx, int gy)
        {
            FP x  = gx * this.CellSize;
            FP fP = gy * this.CellSize;
            List <Vertices> list = MarchingSquares.DetectSquares(new AABB(new TSVector2(x, fP), new TSVector2(x + this.CellSize, fP + this.CellSize)), this.SubCellSize, this.SubCellSize, this._terrainMap, this.Iterations, true);
            bool            flag = list.Count == 0;

            if (!flag)
            {
                this._bodyMap[gx, gy] = new List <Body>();
                TSVector2 tSVector = new TSVector2(1f / (float)this.PointsPerUnit, 1f / (float)(-(float)this.PointsPerUnit));
                foreach (Vertices current in list)
                {
                    current.Scale(ref tSVector);
                    current.Translate(ref this._topLeft);
                    Vertices        vertices = SimplifyTools.CollinearSimplify(current, FP.Zero);
                    List <Vertices> list2    = Triangulate.ConvexPartition(vertices, this.Decomposer, true, FP.EN3);
                    foreach (Vertices current2 in list2)
                    {
                        bool flag2 = current2.Count > 2;
                        if (flag2)
                        {
                            this._bodyMap[gx, gy].Add(BodyFactory.CreatePolygon(this.World, current2, 1, null));
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public static Vertices DouglasPeuckerSimplify(Vertices vertices, FP distanceTolerance)
        {
            bool     flag = vertices.Count <= 3;
            Vertices result;

            if (flag)
            {
                result = vertices;
            }
            else
            {
                bool[] array = new bool[vertices.Count];
                for (int i = 0; i < vertices.Count; i++)
                {
                    array[i] = true;
                }
                SimplifyTools.SimplifySection(vertices, 0, vertices.Count - 1, array, distanceTolerance);
                Vertices vertices2 = new Vertices(vertices.Count);
                for (int j = 0; j < vertices.Count; j++)
                {
                    bool flag2 = array[j];
                    if (flag2)
                    {
                        vertices2.Add(vertices[j]);
                    }
                }
                result = vertices2;
            }
            return(result);
        }
Ejemplo n.º 3
0
        private static List <Vertices> Execute(Vertices subject, Vertices clip, PolyClipType clipType, out PolyClipError error)
        {
            Debug.Assert(subject.IsSimple() && clip.IsSimple(), "Non simple input!", "Input polygons must be simple (cannot intersect themselves).");
            Vertices vertices;
            Vertices vertices2;

            YuPengClipper.CalculateIntersections(subject, clip, out vertices, out vertices2);
            TSVector2 lowerBound  = subject.GetAABB().LowerBound;
            TSVector2 lowerBound2 = clip.GetAABB().LowerBound;
            TSVector2 tSVector;

            TSVector2.Min(ref lowerBound, ref lowerBound2, out tSVector);
            tSVector = TSVector2.one - tSVector;
            bool flag = tSVector != TSVector2.zero;

            if (flag)
            {
                vertices.Translate(ref tSVector);
                vertices2.Translate(ref tSVector);
            }
            vertices.ForceCounterClockWise();
            vertices2.ForceCounterClockWise();
            List <FP> poly1Coeff;
            List <YuPengClipper.Edge> poly1Simplicies;

            YuPengClipper.CalculateSimplicalChain(vertices, out poly1Coeff, out poly1Simplicies);
            List <FP> poly2Coeff;
            List <YuPengClipper.Edge> poly2Simplicies;

            YuPengClipper.CalculateSimplicalChain(vertices2, out poly2Coeff, out poly2Simplicies);
            List <YuPengClipper.Edge> simplicies;

            YuPengClipper.CalculateResultChain(poly1Coeff, poly1Simplicies, poly2Coeff, poly2Simplicies, clipType, out simplicies);
            List <Vertices> list;

            error     = YuPengClipper.BuildPolygonsFromChain(simplicies, out list);
            tSVector *= -1f;
            for (int i = 0; i < list.Count; i++)
            {
                list[i].Translate(ref tSVector);
                SimplifyTools.CollinearSimplify(list[i], FP.Zero);
            }
            return(list);
        }
Ejemplo n.º 4
0
        private void GenerateTerrain(int gx, int gy)
        {
            FP ax = gx * CellSize;
            FP ay = gy * CellSize;

            List <Vertices> polys = MarchingSquares.DetectSquares(new AABB(new TSVector2(ax, ay), new TSVector2(ax + CellSize, ay + CellSize)), SubCellSize, SubCellSize, _terrainMap, Iterations, true);

            if (polys.Count == 0)
            {
                return;
            }

            _bodyMap[gx, gy] = new List <Body>();

            // create the scale vector
            TSVector2 scale = new TSVector2(1f / PointsPerUnit, 1f / -PointsPerUnit);

            // create physics object for this grid cell
            foreach (Vertices item in polys)
            {
                // does this need to be negative?
                item.Scale(ref scale);
                item.Translate(ref _topLeft);
                Vertices simplified = SimplifyTools.CollinearSimplify(item, FP.Zero);

                List <Vertices> decompPolys = Triangulate.ConvexPartition(simplified, Decomposer, true, FP.EN3);

                foreach (Vertices poly in decompPolys)
                {
                    if (poly.Count > 2)
                    {
                        _bodyMap[gx, gy].Add(BodyFactory.CreatePolygon(World, poly, 1, null));
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private static void SimplifySection(Vertices vertices, int i, int j, bool[] usePoint, FP distanceTolerance)
        {
            bool flag = i + 1 == j;

            if (!flag)
            {
                TSVector2 tSVector  = vertices[i];
                TSVector2 tSVector2 = vertices[j];
                FP        fP        = -1.0;
                int       num       = i;
                for (int k = i + 1; k < j; k++)
                {
                    TSVector2 tSVector3 = vertices[k];
                    FP        fP2       = LineTools.DistanceBetweenPointAndLineSegment(ref tSVector3, ref tSVector, ref tSVector2);
                    bool      flag2     = fP2 > fP;
                    if (flag2)
                    {
                        fP  = fP2;
                        num = k;
                    }
                }
                bool flag3 = fP <= distanceTolerance;
                if (flag3)
                {
                    for (int l = i + 1; l < j; l++)
                    {
                        usePoint[l] = false;
                    }
                }
                else
                {
                    SimplifyTools.SimplifySection(vertices, i, num, usePoint, distanceTolerance);
                    SimplifyTools.SimplifySection(vertices, num, j, usePoint, distanceTolerance);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Combine a list of triangles into a list of convex polygons.
        ///
        /// Note: This only works on triangles.
        /// </summary>
        ///<param name="triangles">The triangles.</param>
        ///<param name="maxPolys">The maximun number of polygons to return.</param>
        ///<param name="tolerance">The tolerance</param>
        public static List <Vertices> PolygonizeTriangles(List <Vertices> triangles, int maxPolys = int.MaxValue, float tolerance = 0.001f)
        {
            if (triangles.Count <= 0)
            {
                return(triangles);
            }

            List <Vertices> polys = new List <Vertices>();

            bool[] covered = new bool[triangles.Count];
            for (int i = 0; i < triangles.Count; ++i)
            {
                covered[i] = false;

                //Check here for degenerate triangles
                Vertices  triangle = triangles[i];
                TSVector2 a        = triangle[0];
                TSVector2 b        = triangle[1];
                TSVector2 c        = triangle[2];

                if ((a.x == b.x && a.y == b.y) || (b.x == c.x && b.y == c.y) || (a.x == c.x && a.y == c.y))
                {
                    covered[i] = true;
                }
            }

            int polyIndex = 0;

            bool notDone = true;

            while (notDone)
            {
                int currTri = -1;
                for (int i = 0; i < triangles.Count; ++i)
                {
                    if (covered[i])
                    {
                        continue;
                    }

                    currTri = i;
                    break;
                }

                if (currTri == -1)
                {
                    notDone = false;
                }
                else
                {
                    Vertices poly = new Vertices(3);

                    for (int i = 0; i < 3; i++)
                    {
                        poly.Add(triangles[currTri][i]);
                    }

                    covered[currTri] = true;
                    int index = 0;
                    for (int i = 0; i < 2 * triangles.Count; ++i, ++index)
                    {
                        while (index >= triangles.Count)
                        {
                            index -= triangles.Count;
                        }
                        if (covered[index])
                        {
                            continue;
                        }
                        Vertices newP = AddTriangle(triangles[index], poly);
                        if (newP == null)
                        {
                            continue; // is this right
                        }
                        if (newP.Count > Settings.MaxPolygonVertices)
                        {
                            continue;
                        }

                        if (newP.IsConvex())
                        {
                            //Or should it be IsUsable?  Maybe re-write IsConvex to apply the angle threshold from Box2d
                            poly           = new Vertices(newP);
                            covered[index] = true;
                        }
                    }

                    //We have a maximum of polygons that we need to keep under.
                    if (polyIndex < maxPolys)
                    {
                        SimplifyTools.MergeParallelEdges(poly, tolerance);

                        //If identical points are present, a triangle gets
                        //borked by the MergeParallelEdges function, hence
                        //the vertex number check
                        if (poly.Count >= 3)
                        {
                            polys.Add(new Vertices(poly));
                        }
                        else
                        {
                            Debug.WriteLine("Skipping corrupt poly.");
                        }
                    }

                    if (poly.Count >= 3)
                    {
                        polyIndex++; //Must be outside (polyIndex < polysLength) test
                    }
                }
            }

            //TODO: Add sanity check
            //Remove empty vertice collections
            for (int i = polys.Count - 1; i >= 0; i--)
            {
                if (polys[i].Count == 0)
                {
                    polys.RemoveAt(i);
                }
            }

            return(polys);
        }
Ejemplo n.º 7
0
        public static List <Vertices> PolygonizeTriangles(List <Vertices> triangles, int maxPolys = 2147483647, float tolerance = 0.001f)
        {
            bool            flag = triangles.Count <= 0;
            List <Vertices> result;

            if (flag)
            {
                result = triangles;
            }
            else
            {
                List <Vertices> list  = new List <Vertices>();
                bool[]          array = new bool[triangles.Count];
                for (int i = 0; i < triangles.Count; i++)
                {
                    array[i] = false;
                    Vertices  vertices  = triangles[i];
                    TSVector2 tSVector  = vertices[0];
                    TSVector2 tSVector2 = vertices[1];
                    TSVector2 tSVector3 = vertices[2];
                    bool      flag2     = (tSVector.x == tSVector2.x && tSVector.y == tSVector2.y) || (tSVector2.x == tSVector3.x && tSVector2.y == tSVector3.y) || (tSVector.x == tSVector3.x && tSVector.y == tSVector3.y);
                    if (flag2)
                    {
                        array[i] = true;
                    }
                }
                int  num   = 0;
                bool flag3 = true;
                while (flag3)
                {
                    int num2 = -1;
                    for (int j = 0; j < triangles.Count; j++)
                    {
                        bool flag4 = array[j];
                        if (!flag4)
                        {
                            num2 = j;
                            break;
                        }
                    }
                    bool flag5 = num2 == -1;
                    if (flag5)
                    {
                        flag3 = false;
                    }
                    else
                    {
                        Vertices vertices2 = new Vertices(3);
                        for (int k = 0; k < 3; k++)
                        {
                            vertices2.Add(triangles[num2][k]);
                        }
                        array[num2] = true;
                        int l = 0;
                        int m = 0;
                        while (m < 2 * triangles.Count)
                        {
                            while (l >= triangles.Count)
                            {
                                l -= triangles.Count;
                            }
                            bool flag6 = array[l];
                            if (!flag6)
                            {
                                Vertices vertices3 = SimpleCombiner.AddTriangle(triangles[l], vertices2);
                                bool     flag7     = vertices3 == null;
                                if (!flag7)
                                {
                                    bool flag8 = vertices3.Count > Settings.MaxPolygonVertices;
                                    if (!flag8)
                                    {
                                        bool flag9 = vertices3.IsConvex();
                                        if (flag9)
                                        {
                                            vertices2 = new Vertices(vertices3);
                                            array[l]  = true;
                                        }
                                    }
                                }
                            }
                            m++;
                            l++;
                        }
                        bool flag10 = num < maxPolys;
                        if (flag10)
                        {
                            SimplifyTools.MergeParallelEdges(vertices2, tolerance);
                            bool flag11 = vertices2.Count >= 3;
                            if (flag11)
                            {
                                list.Add(new Vertices(vertices2));
                            }
                            else
                            {
                                Debug.WriteLine("Skipping corrupt poly.");
                            }
                        }
                        bool flag12 = vertices2.Count >= 3;
                        if (flag12)
                        {
                            num++;
                        }
                    }
                }
                for (int n = list.Count - 1; n >= 0; n--)
                {
                    bool flag13 = list[n].Count == 0;
                    if (flag13)
                    {
                        list.RemoveAt(n);
                    }
                }
                result = list;
            }
            return(result);
        }
        /// <summary>
        /// Implements "A new algorithm for Boolean operations on general polygons"
        /// available here: http://liama.ia.ac.cn/wiki/_media/user:dong:dong_cg_05.pdf
        /// Merges two polygons, a subject and a clip with the specified operation. Polygons may not be
        /// self-intersecting.
        ///
        /// Warning: May yield incorrect results or even crash if polygons contain collinear points.
        /// </summary>
        /// <param name="subject">The subject polygon.</param>
        /// <param name="clip">The clip polygon, which is added,
        /// substracted or intersected with the subject</param>
        /// <param name="clipType">The operation to be performed. Either
        /// Union, Difference or Intersection.</param>
        /// <param name="error">The error generated (if any)</param>
        /// <returns>A list of closed polygons, which make up the result of the clipping operation.
        /// Outer contours are ordered counter clockwise, holes are ordered clockwise.</returns>
        private static List <Vertices> Execute(Vertices subject, Vertices clip, PolyClipType clipType, out PolyClipError error)
        {
            Debug.Assert(subject.IsSimple() && clip.IsSimple(), "Non simple input!", "Input polygons must be simple (cannot intersect themselves).");

            // Copy polygons
            Vertices slicedSubject;
            Vertices slicedClip;

            // Calculate the intersection and touch points between
            // subject and clip and add them to both
            CalculateIntersections(subject, clip, out slicedSubject, out slicedClip);

            // Translate polygons into upper right quadrant
            // as the algorithm depends on it
            TSVector2 lbSubject = subject.GetAABB().LowerBound;
            TSVector2 lbClip    = clip.GetAABB().LowerBound;
            TSVector2 translate;

            TSVector2.Min(ref lbSubject, ref lbClip, out translate);
            translate = TSVector2.one - translate;
            if (translate != TSVector2.zero)
            {
                slicedSubject.Translate(ref translate);
                slicedClip.Translate(ref translate);
            }

            // Enforce counterclockwise contours
            slicedSubject.ForceCounterClockWise();
            slicedClip.ForceCounterClockWise();

            List <Edge> subjectSimplices;
            List <FP>   subjectCoeff;
            List <Edge> clipSimplices;
            List <FP>   clipCoeff;

            // Build simplical chains from the polygons and calculate the
            // the corresponding coefficients
            CalculateSimplicalChain(slicedSubject, out subjectCoeff, out subjectSimplices);
            CalculateSimplicalChain(slicedClip, out clipCoeff, out clipSimplices);

            List <Edge> resultSimplices;

            // Determine the characteristics function for all non-original edges
            // in subject and clip simplical chain and combine the edges contributing
            // to the result, depending on the clipType
            CalculateResultChain(subjectCoeff, subjectSimplices, clipCoeff, clipSimplices, clipType,
                                 out resultSimplices);

            List <Vertices> result;

            // Convert result chain back to polygon(s)
            error = BuildPolygonsFromChain(resultSimplices, out result);

            // Reverse the polygon translation from the beginning
            // and remove collinear points from output
            translate *= -1f;
            for (int i = 0; i < result.Count; ++i)
            {
                result[i].Translate(ref translate);
                SimplifyTools.CollinearSimplify(result[i], FP.Zero);
            }
            return(result);
        }