Example #1
0
        public void EqualTest0()
        {
            Vertex v0 = new Vertex();
            Vertex v1 = new Vertex();

            Assert.IsTrue(v0.Equals(v1));
            Assert.IsTrue(v1.Equals(v0));

            Assert.IsTrue(v0.Equals((object)v1));
            Assert.IsTrue(v1.Equals((object)v0));

            Assert.IsTrue(v0 == v1);
            Assert.IsFalse(v0 != v1);
        }
Example #2
0
        public void EqualTest1()
        {
            Vertex v0 = new Vertex(new Vector3(2f, 234.4f, 30f), new Vector2(-341f, 234000f), new Vector3(9f, 24.4f, 330f), new Vector3(255f, 2.4f, 10.315f));
            Vertex v1 = new Vertex(new Vector3(2f, 234.4f, 30f), new Vector2(-341f, 234000f), new Vector3(9f, 24.4f, 330f), new Vector3(255f, 2.4f, 10.315f));

            Assert.IsTrue(v0.Equals(v1));
            Assert.IsTrue(v1.Equals(v0));

            Assert.IsTrue(v0.Equals((object)v1));
            Assert.IsTrue(v1.Equals((object)v0));

            Assert.IsTrue(v0 == v1);
            Assert.IsFalse(v0 != v1);
        }
Example #3
0
        public void TestEquals()
        {
            var vertex = new Vertex(12.34f, -98.7f, 54);

            Assert.False(vertex.Equals((object)null));
            Assert.False(vertex.Equals(12345));

            var vertex2 = new Vertex();
            Assert.False(vertex.Equals((object)vertex2));

            vertex2 = new Vertex(12.34f, -98.7f, 54);
            Assert.True(vertex.Equals((object)vertex2));

            Assert.True(vertex.Equals((object)vertex));
        }
Example #4
0
		public void Equals()
		{
			Vertex vertex1 = new Vertex(2.0,3.0,4.0);
			Vertex vertex2 = new Vertex(2.0,3.0,4.0);
			Assert.IsTrue(vertex1.Equals(vertex2));
			vertex1.x = 1.0;
			Assert.IsFalse(vertex1.Equals(vertex2));
			vertex1.x = 2.0;
			vertex1.y = 2.0;
			Assert.IsFalse(vertex1.Equals(vertex2));
			vertex1.y = 3.0;
			vertex1.z = 5.0;
			Assert.IsFalse(vertex1.Equals(vertex2));
			Assert.IsFalse(vertex1.Equals(null));
			Assert.IsFalse(vertex1.Equals("string"));
		}
Example #5
0
        public bool ContainsPoint(Vertex point)
        {
            //return true if the point to test is one of the vertices
            if (point.Equals(A) || point.Equals(B) || point.Equals(C))
                return true;

            bool oddNodes = false;

            if (checkPointToSegment(C, A, point))
                oddNodes = !oddNodes;
            if (checkPointToSegment(A, B, point))
                oddNodes = !oddNodes;
            if (checkPointToSegment(B, C, point))
                oddNodes = !oddNodes;

            return oddNodes;
        }
        public void Vertex_Equals_IsTrue_Test()
        {
            // Assign
            var vertexA = new Vertex("a");
            var vertexB = new Vertex("a");

            // Act
            bool actual = vertexA.Equals(vertexB);

            // Assert
            bool expected = true;
            Assert.AreEqual(expected, actual);
        }
Example #7
0
 public bool contains(Vertex a)
 {
     return(v1.Equals(a) || v2.Equals(a));
 }
Example #8
0
    // Method that uses a pseudo-BFS algorithm to create solvable lock and key puzzles (in terms of dungeon navigation)
    void SpawnKeysAndDoors()
    {
        Vertex start = mapData.start;

        SpawnKey(mapData.FindRoom(start), 0f);
        SpawnDoors(start, verticesArr[1]);
        HashSet <Vertex> lockedRooms = new HashSet <Vertex>();
        HashSet <Vertex> keyRooms    = new HashSet <Vertex>();

        keyRooms.Add(verticesArr[0]);
        bool endIsLocked = false;

        for (int i = 1; i < distancesArr.Length - 1; i++)
        {
            if (i + 1 < distancesArr.Length)
            {
                if (distancesArr[i] == distancesArr[i + 1])
                {
                    HashSet <Vertex> neighbors0 = new HashSet <Vertex>();
                    HashSet <Vertex> neighbors1 = new HashSet <Vertex>();
                    foreach (Edge edge in mapData.mstEdges)
                    {
                        Vertex v0 = mapData.mesh.vertices[edge.P0];
                        Vertex v1 = mapData.mesh.vertices[edge.P1];

                        if (v0.Equals(verticesArr[i]) || v1.Equals(verticesArr[i]))
                        {
                            neighbors0.Add(v0);
                            neighbors0.Add(v1);
                        }
                        if (v0.Equals(verticesArr[i + 1]) || v1.Equals(verticesArr[i + 1]))
                        {
                            neighbors1.Add(v0);
                            neighbors1.Add(v1);
                        }
                    }
                    Vertex doorHereRoom = null;
                    foreach (Vertex neighbor in neighbors0)
                    {
                        if (neighbors1.Contains(neighbor))
                        {
                            doorHereRoom = neighbor;
                            break;
                        }
                    }
                    if (doorHereRoom != null)
                    {
                        bool bossPath = CheckIfPathContainsBoss(doorHereRoom, verticesArr[i]);
                        if (bossPath)
                        {
                            if (!endIsLocked)
                            {
                                Vertex placeKeyHere = FurthestRoomBFS(doorHereRoom, verticesArr[i + 1]);
                                SpawnKey(mapData.FindRoom(placeKeyHere), 0f);
                                SpawnDoors(doorHereRoom, verticesArr[i]);
                                keyRooms.Add(verticesArr[i + 1]);

                                if (verticesArr[i].Equals(mapData.end))
                                {
                                    endIsLocked = true;
                                }
                                else
                                {
                                    lockedRooms.Add(verticesArr[i]);
                                }
                            }
                        }
                        else
                        {
                            if (!endIsLocked)
                            {
                                Vertex placeKeyHere = FurthestRoomBFS(doorHereRoom, verticesArr[i]);
                                SpawnKey(mapData.FindRoom(placeKeyHere), 0f);
                                SpawnDoors(doorHereRoom, verticesArr[i + 1]);
                                keyRooms.Add(verticesArr[i]);
                                if (verticesArr[i + 1].Equals(mapData.end))
                                {
                                    endIsLocked = true;
                                }
                                else
                                {
                                    lockedRooms.Add(verticesArr[i + 1]);
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!endIsLocked)
        {
            foreach (Edge edge in mapData.mstEdges)
            {
                Vertex v0 = mapData.mesh.vertices[edge.P0];
                Vertex v1 = mapData.mesh.vertices[edge.P1];
                if (mapData.FindRoom(v0).Equals(mapData.FindRoom(mapData.end)) || mapData.FindRoom(v1).Equals(mapData.FindRoom(mapData.end)))
                {
                    if (mapData.FindRoom(v0).Equals(mapData.FindRoom(mapData.end)))
                    {
                        SpawnDoors(v1, v0);
                    }
                    else
                    {
                        SpawnDoors(v0, v1);
                    }
                }
            }
            bool extraKeyPlaced = false;
            while (!extraKeyPlaced)
            {
                foreach (Vertex vertex in lockedRooms)
                {
                    if (Random.Range(0, 100) < 25)
                    {
                        SpawnKey(mapData.FindRoom(vertex), -1.5f);
                        extraKeyPlaced = true;
                        break;
                    }
                }
            }
        }
    }
Example #9
0
        private void ThenEqualsAndEqualsOperatorReturnTrueForSimilarVertex()
        {
            Vertex similar = CreateVertexWithStartPositionByVector();

            Assert.True(_vertex.Equals(similar) == (_vertex == similar));
        }
Example #10
0
 /// <summary>
 /// vがこの辺の始点であるかを返します。
 /// </summary>
 /// <param name="v">頂点</param>
 /// <returns>vがこの辺の始点であればtrue。それ以外ならばfalse</returns>
 public bool IsConnectedFrom(Vertex v)
 {
     return(v.Equals(s));
 }
Example #11
0
 /// <summary>
 /// 指定された頂点が、この辺の始点か終点のいずれかであるかを返します。
 /// </summary>
 /// <param name="v">頂点</param>
 /// <returns>vが始点か終点ならばtrue。それ以外ならばfalse</returns>
 public bool IsConnectedWith(Vertex v)
 {
     return(v.Equals(s) || v.Equals(t));
 }
        /// <summary>
        /// Locates an edge of a triangle which contains a location
        /// specified by a Vertex v.
        /// The edge returned has the
        /// property that either v is on e, or e is an edge of a triangle containing v.
        /// The search starts from startEdge amd proceeds on the general direction of v.
        /// </summary>
        /// <remarks>
        /// This locate algorithm relies on the subdivision being Delaunay. For
        /// non-Delaunay subdivisions, this may loop for ever.
        /// </remarks>
        /// <param name="v">the location to search for</param>
        /// <param name="startEdge">an edge of the subdivision to start searching at</param>
        /// <returns>a QuadEdge which contains v, or is on the edge of a triangle containing v</returns>
        /// <exception cref="LocateFailureException">
        /// if the location algorithm fails to converge in a reasonable
        /// number of iterations
        /// </exception>
        public QuadEdge LocateFromEdge(Vertex v, QuadEdge startEdge)
        {
            int iter = 0;
            int maxIter = _quadEdges.Count;

            QuadEdge e = startEdge;

            while (true)
            {
                iter++;

                /*
                 * So far it has always been the case that failure to locate indicates an
                 * invalid subdivision. So just fail completely. (An alternative would be
                 * to perform an exhaustive search for the containing triangle, but this
                 * would mask errors in the subdivision topology)
                 *
                 * This can also happen if two vertices are located very close together,
                 * since the orientation predicates may experience precision failures.
                 */
                if (iter > maxIter)
                {
                    throw new LocateFailureException(e.ToLineSegment());
                    // String msg = "Locate failed to converge (at edge: " + e + ").
                    // Possible causes include invalid Subdivision topology or very close
                    // sites";
                    // System.err.println(msg);
                    // dumpTriangles();
                }

                if ((v.Equals(e.Orig)) || (v.Equals(e.Dest)))
                {
                    break;
                }
                if (v.RightOf(e))
                {
                    e = e.Sym;
                }
                else if (!v.RightOf(e.ONext))
                {
                    e = e.ONext;
                }
                else if (!v.RightOf(e.DPrev))
                {
                    e = e.DPrev;
                }
                else
                {
                    // on edge or in triangle containing edge
                    break;
                }
            }
            // System.out.println("Locate count: " + iter);
            return e;
        }
 /// <summary>
 /// Tests whether a vertex is a vertex of the outer triangle.
 /// </summary>
 /// <param name="v">the vertex to test</param>
 /// <returns>true if the vertex is an outer triangle vertex</returns>
 public bool IsFrameVertex(Vertex v)
 {
     if (v.Equals(_frameVertex[0]))
         return true;
     if (v.Equals(_frameVertex[1]))
         return true;
     if (v.Equals(_frameVertex[2]))
         return true;
     return false;
 }
        /// <summary>
        /// Ermittelt die kürzeseten Wege zwischen alle Knoten im Graphen, soweit kein Zielknoten angegeben ist.
        /// Ist hingegen einer angegeben, werden die Distanzen nur so lange berechnet, bis die Distanz des Zielknotens berechnet wurde.
        /// </summary>
        /// <typeparam name="T">Der Datentyp des Graphen.</typeparam>
        /// <param name="graph">Der Graph.</param>
        /// <param name="start">Der Startknoten</param>
        /// <param name="target">Wenn angegeben, wird der Algorithmus so lange ausgeführt, bis die Distanz dieses Knotens berechnet wurde.</param>
        public static Graph <T> Dijkstra <T>(this Graph <T> graph, Vertex <T> start, Vertex <T> target = null)
        {
            if (!graph.IsWeighted)
            {
                throw new ArgumentException("Der Dijkstra Algorithmus kann nur auf Graphen mit gewichteten Kanten durchgeführt werden.");
            }

            // Die Workinglist initialisieren.
            List <Vertex <T> > workingList = new List <Vertex <T> >();

            // Die Distanzen initialisieren.
            foreach (Vertex <T> vertex in graph.Vertices)
            {
                if (vertex.Equals(start))
                {
                    vertex.DijkstraDistance = 0;
                }
                else
                {
                    vertex.DijkstraDistance = int.MaxValue;
                }

                // Den Knoten der working List hinzufügen.
                workingList.Add(vertex);
            }

            start.DijkstraAncestor = start;

            while (workingList.Count > 0)
            {
                // Ermittel den Knoten mit der aktuell geringsten Dijkstra Distanz
                Vertex <T> actual = workingList
                                    .Aggregate((curMin, v) =>
                                               (curMin == null || (v.DijkstraDistance ?? int.MaxValue) < curMin.DijkstraDistance ? v : curMin));

                workingList.Remove(actual);
                //actual.Visit();

                // Dijkstradistanz und -vorgänger anpassen (falls nötig) für alle Nachbarknoten der ausgehenden Kanten des aktuellen Knotens
                foreach (Edge <T> edge in graph.Edges.Where(e => e.From.Equals(actual)))
                {
                    if (workingList.Contains(edge.To) && graph.GetVertex(edge.From).DijkstraDistance + edge.Weight < graph.GetVertex(edge.To).DijkstraDistance)
                    {
                        edge.To.DijkstraDistance = edge.From.DijkstraDistance + edge.Weight;
                        edge.To.DijkstraAncestor = actual;
                    }
                }

                // im ungerichteten Graphen müssen auch die Nachbarn der rückläufigen Kanten angepasst werden.
                if (!graph.IsDirected)
                {
                    foreach (Edge <T> edge in graph.Edges.Where(e => e.To.Equals(actual)))
                    {
                        if (workingList.Contains(edge.From) && graph.GetVertex(edge.To).DijkstraDistance + edge.Weight < graph.GetVertex(edge.From).DijkstraDistance)
                        {
                            edge.From.DijkstraDistance = edge.To.DijkstraDistance + edge.Weight;
                            edge.From.DijkstraAncestor = actual;
                        }
                    }
                }

                // Wenn die Distanz zum gesuchten Knoten gefunden ist, kann hier abgebrochen werden.
                if (target != null && actual.Equals(target))
                {
                    return(graph);
                }
            }

            return(graph);
        }
 public bool Equals(Edge other)
 {
     return(A.Equals(other.A) && B.Equals(other.B));
 }
Example #16
0
 public bool Contains(Vertex vertex)
 {
     return(vertex.Equals(vertexA) || vertex.Equals(vertexB));
 }
Example #17
0
    // Breadth-first search method that traverses the graph to see if a boss room exists at the end of that branch.
    bool CheckIfPathContainsBoss(Vertex splitRoom, Vertex roomToBoss)
    {
        Queue <Vertex> q       = new Queue <Vertex>();
        List <Vertex>  visited = new List <Vertex>();

        visited.Add(splitRoom);
        Dictionary <Vertex, int> distances = new Dictionary <Vertex, int>();
        Vertex source = roomToBoss;

        foreach (Vertex vertex in vertices)
        {
            distances.Add(vertex, 0);
            if (source == null)
            {
                source = vertex;
            }
        }
        visited.Add(source);
        q.Enqueue(source);

        while (q.Count != 0)
        {
            Vertex v = q.Peek();
            //Debug.Log("Start/End peek v " + v.x + " " + v.y);
            foreach (Edge neighborEdge in mapData.mstEdges)
            {
                Vertex v0 = mapData.mesh.vertices[neighborEdge.P0];
                Vertex v1 = mapData.mesh.vertices[neighborEdge.P1];
                if (v0.Equals(v) || v1.Equals(v))
                {
                    Vertex neighbor = null;
                    if (!v0.Equals(v))
                    {
                        Debug.Log("Start/End v0");
                        neighbor = v0;
                    }
                    else if (!v1.Equals(v))
                    {
                        Debug.Log("Start/End v1");
                        neighbor = v1;
                    }
                    else
                    {
                    }
                    if (!visited.Contains(neighbor))
                    {
                        q.Enqueue(neighbor);

                        visited.Add(neighbor);
                        distances[neighbor] = distances[v] + 1;
                    }
                }
            }
            q.Dequeue();
        }
        foreach (Vertex vertex in visited)
        {
            if (mapData.FindRoom(vertex).Equals(mapData.FindRoom(mapData.end)))
            {
                return(true);
            }
        }
        return(false);
    }
Example #18
0
    // Breadth-first search method that traverses the graph to locate the furthest room away.
    // Method will place a key in that furthest room.
    Vertex FurthestRoomBFS(Vertex splitRoom, Vertex keyPlacementContender)
    {
        Queue <Vertex> q       = new Queue <Vertex>();
        List <Vertex>  visited = new List <Vertex>();

        visited.Add(splitRoom);
        Dictionary <Vertex, int> distances = new Dictionary <Vertex, int>();
        Vertex source = keyPlacementContender;

        foreach (Vertex vertex in vertices)
        {
            distances.Add(vertex, 0);
            if (source == null)
            {
                source = vertex;
            }
        }
        visited.Add(source);
        q.Enqueue(source);

        while (q.Count != 0)
        {
            Vertex v = q.Peek();
            foreach (Edge neighborEdge in mapData.mstEdges)
            {
                Vertex v0 = mapData.mesh.vertices[neighborEdge.P0];
                Vertex v1 = mapData.mesh.vertices[neighborEdge.P1];
                if (v0.Equals(v) || v1.Equals(v))
                {
                    Vertex neighbor = null;
                    if (!v0.Equals(v))
                    {
                        Debug.Log("Start/End v0");
                        neighbor = v0;
                    }
                    else if (!v1.Equals(v))
                    {
                        Debug.Log("Start/End v1");
                        neighbor = v1;
                    }
                    else
                    {
                    }
                    if (!visited.Contains(neighbor))
                    {
                        q.Enqueue(neighbor);

                        visited.Add(neighbor);
                        distances[neighbor] = distances[v] + 1;
                    }
                }
            }
            q.Dequeue();
        }
        foreach (Vertex vertex in vertices)
        {
            if (distances[vertex] > distances[source])
            {
                Debug.Log("Start/End distance: " + distances[vertex]);
                source = vertex;
            }
        }
        return(source);
    }
Example #19
0
        public static List <Vertex> GetConvexHull(List <Vertex> points)
        {
            //If we have just 3 points, then they are the convex hull, so return those
            if (points.Count == 3)
            {
                //These might not be ccw, and they may also be colinear
                return(points);
            }

            //If fewer points, then we cant create a convex hull
            if (points.Count < 3)
            {
                return(null);
            }



            //The list with points on the convex hull
            List <Vertex> convexHull = new List <Vertex>();

            //Step 1. Find the vertex with the smallest x coordinate
            //If several have the same x coordinate, find the one with the smallest z
            Vertex startVertex = points[0];

            Vector3 startPos = startVertex.position;

            for (int i = 1; i < points.Count; i++)
            {
                Vector3 testPos = points[i].position;

                //Because of precision issues, we use Mathf.Approximately to test if the x positions are the same
                if (testPos.x < startPos.x || (Mathf.Approximately(testPos.x, startPos.x) && testPos.z < startPos.z))
                {
                    startVertex = points[i];

                    startPos = startVertex.position;
                }
            }

            //This vertex is always on the convex hull
            convexHull.Add(startVertex);

            points.Remove(startVertex);



            //Step 2. Loop to generate the convex hull
            Vertex currentPoint = convexHull[0];

            //Store colinear points here - better to create this list once than each loop
            List <Vertex> colinearPoints = new List <Vertex>();

            int counter = 0;

            while (true)
            {
                //After 2 iterations we have to add the start position again so we can terminate the algorithm
                //Cant use convexhull.count because of colinear points, so we need a counter
                if (counter == 2)
                {
                    points.Add(convexHull[0]);
                }

                //Pick next point randomly
                Vertex nextPoint = points[Random.Range(0, points.Count)];

                //To 2d space so we can see if a point is to the left is the vector ab
                Vector2 a = currentPoint.GetPos2D_XZ();

                Vector2 b = nextPoint.GetPos2D_XZ();

                //Test if there's a point to the right of ab, if so then it's the new b
                for (int i = 0; i < points.Count; i++)
                {
                    //Dont test the point we picked randomly
                    if (points[i].Equals(nextPoint))
                    {
                        continue;
                    }

                    Vector2 c = points[i].GetPos2D_XZ();

                    //Where is c in relation to a-b
                    // < 0 -> to the right
                    // = 0 -> on the line
                    // > 0 -> to the left
                    float relation = GeometryTools.IsAPointLeftOfVectorOrOnTheLine(a, b, c);

                    //Colinear points
                    //Cant use exactly 0 because of floating point precision issues
                    //This accuracy is smallest possible, if smaller points will be missed if we are testing with a plane
                    float accuracy = 0.00001f;

                    if (relation < accuracy && relation > -accuracy)
                    {
                        colinearPoints.Add(points[i]);
                    }
                    //To the right = better point, so pick it as next point on the convex hull
                    else if (relation < 0f)
                    {
                        nextPoint = points[i];

                        b = nextPoint.GetPos2D_XZ();

                        //Clear colinear points
                        colinearPoints.Clear();
                    }
                    //To the left = worse point so do nothing
                }



                //If we have colinear points
                if (colinearPoints.Count > 0)
                {
                    colinearPoints.Add(nextPoint);

                    //Sort this list, so we can add the colinear points in correct order
                    colinearPoints = colinearPoints.OrderBy(n => Vector3.SqrMagnitude(n.position - currentPoint.position)).ToList();

                    convexHull.AddRange(colinearPoints);

                    currentPoint = colinearPoints[colinearPoints.Count - 1];

                    //Remove the points that are now on the convex hull
                    for (int i = 0; i < colinearPoints.Count; i++)
                    {
                        points.Remove(colinearPoints[i]);
                    }

                    colinearPoints.Clear();
                }
                else
                {
                    convexHull.Add(nextPoint);

                    points.Remove(nextPoint);

                    currentPoint = nextPoint;
                }

                //Have we found the first point on the hull? If so we have completed the hull
                if (currentPoint.Equals(convexHull[0]))
                {
                    //Then remove it because it is the same as the first point, and we want a convex hull with no duplicates
                    convexHull.RemoveAt(convexHull.Count - 1);

                    break;
                }

                counter += 1;
            }

            return(convexHull);
        }
Example #20
0
 private IEnumerable <Edge> Find()
 {
     return(Edges.Where(i => SelectedC1.Equals(i.Source) && SelectedC2.Equals(i.Target) || SelectedC1.Equals(i.Target) && SelectedC2.Equals(i.Source)));
 }
        /// <summary>
        /// Inserts a new site into the Subdivision, connecting it to the vertices of
        /// the containing triangle (or quadrilateral, if the split point falls on an
        /// existing edge).
        /// </summary>
        /// <remarks>
        /// <para>
        /// This method does NOT maintain the Delaunay condition. If desired, this must
        /// be checked and enforced by the caller.
        /// </para>
        /// <para>
        /// This method does NOT check if the inserted vertex falls on an edge. This
        /// must be checked by the caller, since this situation may cause erroneous
        /// triangulation
        /// </para>
        /// </remarks>
        /// <param name="v">the vertex to insert</param>
        /// <returns>a new quad edge terminating in v</returns>
        public QuadEdge InsertSite(Vertex v)
        {
            QuadEdge e = Locate(v);

            if ((v.Equals(e.Orig, _tolerance)) || (v.Equals(e.Dest, _tolerance)))
            {
                return e; // point already in subdivision.
            }

            // Connect the new point to the vertices of the containing
            // triangle (or quadrilateral, if the new point fell on an
            // existing edge.)
            QuadEdge baseQE = MakeEdge(e.Orig, v);
            QuadEdge.Splice(baseQE, e);
            QuadEdge startEdge = baseQE;
            do
            {
                baseQE = Connect(e, baseQE.Sym);
                e = baseQE.OPrev;
            } while (e.LNext != startEdge);

            return startEdge;
        }
Example #22
0
 public bool Equals(Edge x, Edge y)
 {
     return(Vertex.Equals(x, y.Id));
 }
 /// <summary>
 /// Tests whether a <see cref="Vertex"/> is the start or end vertex of a
 /// <see cref="QuadEdge"/>, up to the subdivision tolerance distance.
 /// </summary>
 /// <param name="e" />
 /// <param name="v" />
 /// <returns>true if the vertex is a endpoint of the edge</returns>
 public bool IsVertexOfEdge(QuadEdge e, Vertex v)
 {
     if ((v.Equals(e.Orig, _tolerance)) || (v.Equals(e.Dest, _tolerance)))
     {
         return true;
     }
     return false;
 }
Example #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="centre"></param>
        /// <param name="baseGraph"></param>
        /// <param name="origin"></param>
        /// <param name="destination"></param>
        /// <param name="singleVertices"></param>
        /// <param name="scan"></param>
        /// <returns name="visibleVertices">List of vertices visible from the analysed vertex</returns>
        public static List <Vertex> VisibleVertices(
            Vertex centre,
            Graph baseGraph,
            Vertex origin                = null,
            Vertex destination           = null,
            List <Vertex> singleVertices = null,
            bool halfScan                = true,
            bool reducedGraph            = true,
            bool maxVisibility           = false)
        {
            #region Initialize variables and sort vertices
            List <Edge>   edges    = baseGraph.edges;
            List <Vertex> vertices = baseGraph.vertices;


            if (origin != null)
            {
                vertices.Add(origin);
            }
            if (destination != null)
            {
                vertices.Add(destination);
            }
            if (singleVertices != null)
            {
                vertices.AddRange(singleVertices);
            }


            Vertex maxVertex   = vertices.OrderByDescending(v => v.DistanceTo(centre)).First();
            double maxDistance = centre.DistanceTo(maxVertex) * 1.5;
            //vertices = vertices.OrderBy(v => Point.RadAngle(centre.point, v.point)).ThenBy(v => centre.DistanceTo(v)).ToList();
            vertices = Vertex.OrderByRadianAndDistance(vertices, centre);

            #endregion

            #region Initialize openEdges
            //Initialize openEdges with any intersection edges on the half line
            //from centre to maxDistance on the XAxis
            List <EdgeKey> openEdges = new List <EdgeKey>();
            double         xMax      = Math.Abs(centre.X) + 1.5 * maxDistance;
            Edge           halfEdge  = Edge.ByStartVertexEndVertex(centre, Vertex.ByCoordinates(xMax, centre.Y, centre.Z));
            foreach (Edge e in edges)
            {
                if (centre.OnEdge(e))
                {
                    continue;
                }
                if (halfEdge.Intersects(e))
                {
                    if (e.StartVertex.OnEdge(halfEdge))
                    {
                        continue;
                    }
                    if (e.EndVertex.OnEdge(halfEdge))
                    {
                        continue;
                    }
                    EdgeKey k = new EdgeKey(halfEdge, e);
                    openEdges.AddItemSorted(k);
                }
            }

            #endregion

            List <Vertex> visibleVertices = new List <Vertex>();
            Vertex        prev            = null;
            bool          prevVisible     = false;
            for (var i = 0; i < vertices.Count; i++)
            {
                Vertex vertex = vertices[i];
                if (vertex.Equals(centre) || vertex.Equals(prev))
                {
                    continue;
                }                                                              // v == to centre or to previous when updating graph
                //Check only half of vertices as eventually they will become 'v'
                if (halfScan && Vertex.RadAngle(centre, vertex) > Math.PI)
                {
                    break;
                }
                //Removing clock wise edges incident on v
                if (openEdges.Count > 0 && baseGraph.graph.ContainsKey(vertex))
                {
                    foreach (Edge edge in baseGraph.graph[vertex])
                    {
                        int orientation = Vertex.Orientation(centre, vertex, edge.GetVertexPair(vertex));

                        if (orientation == -1)
                        {
                            EdgeKey k     = new EdgeKey(centre, vertex, edge);
                            int     index = openEdges.BisectIndex(k) - 1;
                            index = (index < 0) ? openEdges.Count - 1 : index;
                            if (openEdges.Count > 0 && openEdges.ElementAt(index).Equals(k))
                            {
                                openEdges.RemoveAt(index);
                            }
                        }
                    }
                }

                //Checking if p is visible from p.
                bool    isVisible     = false;
                Polygon vertexPolygon = null;
                if (vertex.polygonId >= 0)
                {
                    baseGraph.polygons.TryGetValue(vertex.polygonId, out vertexPolygon);
                }
                // If centre is on an edge of a inner polygon vertex belongs, check if the centre-vertex edge lies inside
                // or if on one of vertex's edges.
                if (vertexPolygon != null && !vertexPolygon.isBoundary && vertexPolygon.ContainsVertex(centre))
                {
                    Vertex mid = Vertex.MidVertex(centre, vertex);
                    // If mid is on any edge of vertex, is visible, otherwise not.
                    foreach (Edge edge in baseGraph.graph[vertex])
                    {
                        if (mid.OnEdge(edge))
                        {
                            isVisible = true;
                            break;
                        }
                    }
                }
                //No collinear vertices
                else if (prev == null || Vertex.Orientation(centre, prev, vertex) != 0 || !prev.OnEdge(centre, vertex))
                {
                    if (openEdges.Count == 0)
                    {
                        if (vertexPolygon != null && vertexPolygon.isBoundary && vertexPolygon.ContainsVertex(centre))
                        {
                            isVisible = vertexPolygon.ContainsVertex(Vertex.MidVertex(centre, vertex));
                        }
                        else
                        {
                            isVisible = true;
                        }
                    }
                    else if (vertex.OnEdge(openEdges.First().Edge) || !openEdges.First().Edge.Intersects(new Edge(centre, vertex))) //TODO: Change this intersection to Edge.Intersects
                    {
                        isVisible = true;
                    }
                }
                //For collinear vertices, if previous was not visible, vertex is not either
                else if (!prevVisible)
                {
                    isVisible = false;
                }
                //For collinear vertices, if prev was visible need to check that
                //the edge from prev to vertex does not intersect with any open edge
                else
                {
                    isVisible = true;
                    foreach (EdgeKey k in openEdges)
                    {
                        //if (!k.edge.Contains(prev) && EdgeIntersect(prev, vertex, k.edge))
                        if (EdgeIntersect(prev, vertex, k.Edge) && !k.Edge.Contains(prev))
                        {
                            isVisible = false;
                            break;
                        }
                    }
                    // If visible (doesn't intersect any open edge) and edge 'prev-vertex'
                    // is in any polygon, vertex is visible if it belongs to a external boundary
                    if (isVisible && EdgeInPolygon(prev, vertex, baseGraph, maxDistance))
                    {
                        isVisible = IsBoundaryVertex(vertex, baseGraph);
                    }

                    // If still visible (not inside polygon or is boundary vertex),
                    // if not on 'centre-prev' edge means there is a gap between prev and vertex
                    if (isVisible && !vertex.OnEdge(centre, prev))
                    {
                        isVisible = !IsBoundaryVertex(vertex, baseGraph);
                    }
                }

                //If vertex is visible and centre belongs to any polygon, checks
                //if the visible edge is interior to its polygon
                if (isVisible && centre.polygonId >= 0 && !baseGraph.GetAdjecentVertices(centre).Contains(vertex))
                {
                    if (IsBoundaryVertex(centre, baseGraph) && IsBoundaryVertex(vertex, baseGraph))
                    {
                        isVisible = EdgeInPolygon(centre, vertex, baseGraph, maxDistance);
                    }
                    else
                    {
                        isVisible = !EdgeInPolygon(centre, vertex, baseGraph, maxDistance);
                    }
                }


                prev        = vertex;
                prevVisible = isVisible;


                if (isVisible)
                {
                    // Check reducedGraph if vertices belongs to different polygons
                    if (reducedGraph && centre.polygonId != vertex.polygonId)
                    {
                        bool isOriginExtreme = true;
                        bool isTargetExtreme = true;
                        // For reduced graphs, it is checked if the edge is extrem or not.
                        // For an edge to be extreme, the edges coincident at the start and end vertex
                        // will have the same orientation (both clock or counter-clock wise)

                        // Vertex belongs to a polygon
                        if (centre.polygonId >= 0 && !IsBoundaryVertex(centre, baseGraph))
                        {
                            var orientationsOrigin = baseGraph.GetAdjecentVertices(centre).Select(otherVertex => Vertex.Orientation(vertex, centre, otherVertex)).ToList();
                            isOriginExtreme = orientationsOrigin.All(o => o == orientationsOrigin.First());
                        }

                        if (vertex.polygonId >= 0 && !IsBoundaryVertex(vertex, baseGraph))
                        {
                            var orientationsTarget = baseGraph.GetAdjecentVertices(vertex).Select(otherVertex => Vertex.Orientation(centre, vertex, otherVertex)).ToList();
                            isTargetExtreme = orientationsTarget.All(o => o == orientationsTarget.First());
                        }

                        if (isTargetExtreme || isOriginExtreme)
                        {
                            visibleVertices.Add(vertex);
                        }
                    }
                    else
                    {
                        visibleVertices.Add(vertex);
                    }
                }

                if (baseGraph.Contains(vertex))
                {
                    foreach (Edge e in baseGraph.graph[vertex])
                    {
                        if (!centre.OnEdge(e) && Vertex.Orientation(centre, vertex, e.GetVertexPair(vertex)) == 1)
                        {
                            EdgeKey k = new EdgeKey(centre, vertex, e);
                            openEdges.AddItemSorted(k);
                        }
                    }
                }

                if (isVisible && maxVisibility && vertex.polygonId >= 0)
                {
                    List <Vertex> vertexPairs       = baseGraph.GetAdjecentVertices(vertex);
                    int           firstOrientation  = Vertex.Orientation(centre, vertex, vertexPairs[0]);
                    int           secondOrientation = Vertex.Orientation(centre, vertex, vertexPairs[1]);
                    bool          isColinear        = false;

                    //if both edges lie on the same side of the centre-vertex edge or one of them is colinear or centre is contained on any of the edges
                    if (firstOrientation == secondOrientation || firstOrientation == 0 || secondOrientation == 0)
                    {
                        Vertex rayVertex        = vertex.Translate(Vector.ByTwoVertices(centre, vertex), maxDistance);
                        Edge   rayEdge          = Edge.ByStartVertexEndVertex(centre, rayVertex);
                        Vertex projectionVertex = null;

                        // if both orientation are not on the same side, means that one of them is colinear
                        isColinear = firstOrientation != secondOrientation ? true : false;

                        foreach (EdgeKey ek in openEdges)
                        {
                            Vertex intersection = rayEdge.Intersection(ek.Edge) as Vertex;
                            if (intersection != null && !intersection.Equals(vertex))
                            {
                                projectionVertex = intersection;
                                Polygon polygon = null;
                                baseGraph.polygons.TryGetValue(vertex.polygonId, out polygon);
                                if (polygon != null)
                                {
                                    // If polygon is internal, don't compute intersection if mid point lies inside the polygon but not on its edges
                                    Vertex mid          = Vertex.MidVertex(vertex, intersection);
                                    bool   containsEdge = Vertex.Orientation(centre, vertex, mid) != 0 && polygon.ContainsVertex(mid);
                                    if (!polygon.isBoundary && containsEdge)
                                    {
                                        projectionVertex = null;
                                    }
                                }
                                break;
                            }
                        }
                        if (projectionVertex != null)
                        {
                            // if edges are before rayEdge, projection Vertex goes after vertex
                            if (firstOrientation == -1 || secondOrientation == -1)
                            {
                                visibleVertices.Add(projectionVertex);
                            }
                            else
                            {
                                visibleVertices.Insert(visibleVertices.Count - 1, projectionVertex);
                            }
                        }
                    }
                    if (vertexPairs.Contains(centre) && !visibleVertices.Contains(centre))
                    {
                        visibleVertices.Add(centre);
                    }
                }
            }

            return(visibleVertices);
        }
Example #25
0
    public Graph Kruskal()
    {
        // 1. A <- Empty set
        ArrayList A = new ArrayList();

        // 2. for each vertex v E V[G]
        // 3.    do Make-Set(v)

        for (Iterator <Vertex> vxiter = GetVertices(); vxiter.hasNext();)
        {
            Vertex v = vxiter.next();
            v.representative = v;               // I am in my set
            v.members        = new ArrayList(); // I have no members in my set
        }

        // 4. sort the edges of E by nondecreasing weight w
        // Creates the edges objects
        //int j;
        ArrayList Vneighbors = new ArrayList();

        //Vertex u;

        // Sort the Edges in non decreasing order
        sortEdges(new EdgeComparer());

        // 5. for each edge in the nondecresing order
        Vertex vaux, urep, vrep;

        for (Iterator <EdgeIfc> edgeiter = GetEdges(); edgeiter.hasNext();)
        {
            // 6. if Find-Set(u)!=Find-Set(v)
            EdgeIfc e1 = edgeiter.next();
            Vertex  u  = e1.GetStart();
            Vertex  v  = e1.GetEnd();

            if (!(v.representative.GetName()).Equals(u.representative.GetName()))
            {
                // 7. A <- A U {(u,v)}
                A.Add(e1);

                // 8. Union(u,v)
                urep = u.representative;
                vrep = v.representative;

                if ((urep.members).Count > (vrep.members).Count)
                {     // we Add elements of v to u
                    for (int j = 0; j < (vrep.members).Count; j++)
                    {
                        vaux = ( Vertex )(vrep.members[j]);
                        vaux.representative = urep;
                        (urep.members).Add(vaux);
                    }
                    v.representative    = urep;
                    vrep.representative = urep;
                    (urep.members).Add(v);
                    if (!v.Equals(vrep))
                    {
                        (urep.members).Add(vrep);
                    }
                    (vrep.members).Clear();
                }
                else
                {      // we Add elements of u to v
                    for (int j = 0; j < (urep.members).Count; j++)
                    {
                        vaux = ( Vertex )(urep.members[j]);
                        vaux.representative = vrep;
                        (vrep.members).Add(vaux);
                    }
                    u.representative    = vrep;
                    urep.representative = vrep;
                    (vrep.members).Add(u);
                    if (!u.Equals(urep))
                    {
                        (vrep.members).Add(urep);
                    }
                    (urep.members).Clear();
                } // else
            }     // of if
        }         // of for numedges

        // 9. return A
        // Creates the new Graph that contains the SSSP
        string theName;
        Graph  newGraph = new  Graph();

        // Creates and Adds the vertices with the same name
        for (Iterator <Vertex> vxiter = GetVertices(); vxiter.hasNext();)
        {
            theName = vxiter.next().GetName();
            newGraph.AddVertex(new  Vertex().assignName(theName));
        }

        // Creates the edges from the NewGraph
        Vertex  theStart, theEnd;
        Vertex  theNewStart, theNewEnd;
        EdgeIfc theEdge;

        // For each edge in A we find its two vertices
        // make an edge for the new graph from with the correspoding
        // new two vertices
        for (int i = 0; i < A.Count; i++)
        {
            // theEdge with its two vertices
            theEdge  = ( Edge )A[i];
            theStart = theEdge.GetStart();
            theEnd   = theEdge.GetEnd();

            // Find the references in the new Graph
            theNewStart = newGraph.findsVertex(theStart.GetName());
            theNewEnd   = newGraph.findsVertex(theEnd.GetName());

            // Creates the new edge with new start and end vertices
            // in the newGraph
            // and ajusts the adorns based on the old edge
            // Adds the new edge to the newGraph
            // dja - the fix below fixes a bug where the proper adjust adorns Gets called
//            EdgeIfc theNewEdge = newGraph.AddEdge( theNewStart, theNewEnd );
//            theNewEdge.adjustAdorns( theEdge );
            Edge theNewEdge = ( Edge )newGraph.AddEdge(theNewStart, theNewEnd);
            theNewEdge.adjustAdorns(( Edge )theEdge);
        }
        return(newGraph);
    } // kruskal
        public void Equals_WhenCalledOnEqualVertices_ShouldReturnTrue()
        {
            Vertex v = new Vertex(3, 4);

            Assert.IsTrue(_sampleVertex.Equals(v));
        }
Example #27
0
 /// <summary>
 /// vがこの辺の終点であるかを返します。
 /// </summary>
 /// <param name="v">頂点</param>
 /// <returns>vがこの辺の終点であればtrue。それ以外ならばfalse</returns>
 public bool IsConnectedTo(Vertex v)
 {
     return(v.Equals(t));
 }
Example #28
0
        /// <summary>
        /// Adds a triangle to the mesh using absolute vertices
        /// </summary>
        /// <param name="v1"></param>
        /// <param name="v2"></param>
        /// <param name="v3"></param>
        public void Add(Vertex v1, Vertex v2, Vertex v3)
        {
            //do not include any triangles that have been smashed into lines
            if (v1.Equals(v2) || v2.Equals(v3) || v1.Equals(v3))
                return;

            // If a vertex of the triangle is not yet in the vertices list,
            // add it and set its index to the current index count
            if (!m_vertices.ContainsKey(v1))
                m_vertices[v1] = m_vertices.Count;
            if (!m_vertices.ContainsKey(v2))
                m_vertices[v2] = m_vertices.Count;
            if (!m_vertices.ContainsKey(v3))
                m_vertices[v3] = m_vertices.Count;

            //do not include any triangles we already have
            if (!_triIndex.Add(new IndexedTriangle(m_vertices[v1], m_vertices[v2], m_vertices[v3])))
                return;

            _meshData.AddTriangle(v1, v2, v3);
        }
Example #29
0
        /***
         * method: findShortestPath
         * find shortest path from the starting vertex to the ending vertex
         * using Dijkstra’s algorithm
         * @param fromVertex: starting vertex
         * @param toVertex: ending vertex
         * @param comparator: compare mode
         * @return a string array of 3 shortest paths
         */
        public String[] FindShortestPath(String fromVertex, String toVertex, String comparator)
        {
            String[]      shortestPaths = new String[3];               // results
            List <Vertex> queue         = new List <Vertex>(Vertices); // hold all current vertices

            Vertex.Comparator = comparator;                            // compare mode
            int shortestPathValue  = int.MaxValue,                     // shortest path value
                shortestPathValue2 = int.MaxValue,                     // second shortest path value
                shortestPathValue3 = int.MaxValue;                     // third shortest path value

            Vertex[] shortestVertices = new Vertex[3];                 // path sources

            // initial graph to search
            SetupDijstraksSearch(fromVertex);
            ClearPreviousVertices();

            while (queue.Count != 0)
            {
                queue.Sort();
                Vertex currentVertex = queue[0];
                queue.RemoveAt(0);

                /*
                 * if the vertex on the top of the queue is the destination and the queue is not empty,
                 * (there is a shortcut to go to destination without going through every vertex),
                 * remove another vertex and add the current vertex back into the queue. This is not
                 * necessary to find the shortest path, but since we are interested in finding 3
                 * shortest paths, this step is crucial.
                 */
                if (currentVertex.Equals(new Vertex(toVertex)) && queue.Count != 0)
                {
                    queue.Sort();
                    Vertex newVertex = queue[0];
                    queue.RemoveAt(0);
                    queue.Add(currentVertex);
                    currentVertex = newVertex;
                }

                foreach (Vertex adjacentVertex in currentVertex.AdjacentVertices)
                {
                    if (queue.Contains(adjacentVertex))
                    {
                        // get values
                        int currentVertexValue = currentVertex.GetComparator(comparator);
                        int edgeValue          = Edges[Edges.IndexOf(new Edge(
                                                                         currentVertex, adjacentVertex))].GetComparator(comparator);
                        int adjacentVertexComparatorValue = adjacentVertex.GetComparator(comparator);
                        int currentPathValue = currentVertexValue + edgeValue;

                        // if find new shortest path from starting vertex to the current.adj one
                        if (currentPathValue < adjacentVertexComparatorValue)
                        {
                            // update adjacent vertex
                            UpdateVertex(adjacentVertex, currentVertex);

                            // update new shortest value
                            if (adjacentVertex.Equals(new Vertex(toVertex)))
                            {
                                shortestVertices[0] = new Vertex(adjacentVertex);
                                shortestPathValue   = currentVertexValue + edgeValue;
                            }
                        }
                        // second shortest path
                        else if (currentPathValue > shortestPathValue &&
                                 currentPathValue < shortestPathValue2)
                        {
                            /*
                             * if already found the second shortest path (the current
                             * is the new second shortest <=> old second become third),
                             * copy old second to third and create new second shortest
                             */
                            if (ContainsVertex(shortestVertices[1], adjacentVertex))
                            {
                                shortestVertices[2] = new Vertex(shortestVertices[1]);
                                shortestPathValue3  = shortestVertices[2].CompareValue;
                            }

                            shortestVertices[1] = new Vertex(shortestVertices[0]);
                            UpdateVertex(shortestVertices[1], currentVertex);
                            shortestPathValue2 = currentPathValue;
                        }
                        // third shortest path
                        else if (currentPathValue > shortestPathValue2 &&
                                 currentPathValue < shortestPathValue3)
                        {
                            // apply the same logic as second shortest path
                            if (ContainsVertex(shortestVertices[1], adjacentVertex))
                            {
                                shortestVertices[2] = new Vertex(shortestVertices[1]);
                            }

                            shortestVertices[2] = new Vertex(shortestVertices[1]);
                            UpdateVertex(shortestVertices[2], currentVertex);
                            shortestPathValue3 = currentPathValue;
                        }
                    }
                }

                // update priority queue
                if (queue.Count != 0)
                {
                    Vertex vertex = queue[0];
                    queue.RemoveAt(0);
                    queue.Add(vertex);
                }
            }

            // print paths
            for (int i = 0; i < 3; i++)
            {
                shortestPaths[i] = PrintShortestPath(shortestVertices[i]);
            }

            return(shortestPaths);
        }
Example #30
0
 public bool Equals(Midpoint other)
 {
     return(Position.Equals(other.Position));
 }
 public bool Equals(Bone other)
 {
     return(position.Equals(other.position) && orientation.Equals(other.orientation) && scaling.Equals(other.scaling) && name.Equals(other.name) &&
            opposingBoneIndex.Equals(other.opposingBoneIndex) && parentBoneIndex.Equals(other.parentBoneIndex) && hash.Equals(other.hash) && unknown2.Equals(other.unknown2));
 }
    public void DigRiver(List<Vertex> path, int width, float depthFactor)
    {
        float[,] depthField = new float[terrainSize, terrainSize]; //depth to dig
        float[,] distField = new float[terrainSize, terrainSize]; //distance from line
        float[,] pathMark = new float[terrainSize, terrainSize]; //path number which will effect the vertex

        for (int x = 0; x < terrainSize; x++)
        {
            for (int z = 0; z < terrainSize; z++)
            {
                depthField[x, z] = 666;//mark
                distField[x, z] = 666;//mark
            }
        }

        //should be min 2
        int areaFactor = 2;

        List<float> widthInPoints = AssignWidthToPoints(path, width);

        for (int i = 0; i < path.Count - 1; i++)
        {
            Vertex v1 = path[i];
            Vertex v2 = path[i + 1];
            float width1 = widthInPoints[i];
            float width2 = widthInPoints[i+1];

            Vertex topLeftCorner = new Vertex(0, 0);
            Vertex botRightCorner = new Vertex(0, 0);
            //evaluate position of affected area
            if (v1.x < v2.x)
            {
                topLeftCorner.x = (int)(v1.x - width1 * areaFactor);
                botRightCorner.x = (int)(v2.x + width2 * areaFactor);
            }
            else
            {
                topLeftCorner.x = (int)(v2.x - width2 * areaFactor);
                botRightCorner.x = (int)(v1.x + width1 * areaFactor);
            }
            if (v1.z < v2.z)
            {
                topLeftCorner.z = (int)(v2.z + width2 * areaFactor);
                botRightCorner.z = (int)(v1.z - width1 * areaFactor);
            }
            else
            {
                topLeftCorner.z = (int)(v1.z + width1 * areaFactor);
                botRightCorner.z = (int)(v2.z - width2 * areaFactor);
            }

            if (topLeftCorner.Equals(botRightCorner))
            {
                Debug.Log("same vertices");
                break;
            }

            for (int x = topLeftCorner.x; x < botRightCorner.x; x++)
            {
                for (int z = topLeftCorner.z; z > botRightCorner.z; z--)
                {

                    if (ftm.CheckBounds(x, z) && fmc.BelongsToPath(x, z, v1, v2, 2*width * areaFactor))
                    {
                        bool valid = true;
                        Vertex vert = new Vertex(x, z);
                        float distance = fmc.GetDistanceFromLine(vert, v1, v2);

                        float depth = 0;

                        if (distance == 0) //sinc is not defined at 0
                            distance += 0.01f;

                        //determine width (interpolation between points)
                        float localWidth = GetLocalWidth(vert, v1, v2, width1, width2);
                        //float localWidth = 1;
                        if(localWidth < width)
                        {
                            Debug.Log("!");
                        }

                        if(distance > areaFactor * localWidth)
                        {
                            valid = false;
                        }

                        depth = MySinc(distance, localWidth, depthFactor);

                        if (valid && depthField[vert.x, vert.z] == 666) //hasnt been modified yet
                        {
                            depthField[vert.x, vert.z] = depth;
                            distField[vert.x, vert.z] = distance;
                            pathMark[vert.x, vert.z] = 1;//path
                            //widthFactor += 0.0003f;
                        }
                        else if (valid && depthField[vert.x, vert.z] != 666) //has been modified but I can dig it better (valid shouldnt be neccessary)
                        {
                            if (distance < distField[vert.x, vert.z])
                            {
                                //depthField[vert.x, vert.z] = Math.Min(depthField[vert.x, vert.z], depth);
                                depthField[vert.x, vert.z] = depth;
                                distField[vert.x, vert.z] = distance;
                                //widthFactor += 0.0003f;
                            }
                            //depthField[vert.x, vert.z] = (depthField[vert.x, vert.z] + depth)/2;
                        }

                    }
                }
            }

        }

        //fix corners

        for (int i = 0; i < path.Count; i++)
        {
            Vertex corner = path[i];
            //Debug.Log(corner);
            for (int x = corner.x - 2 * areaFactor * width; x < corner.x + 2 * areaFactor * width; x++)
            {
                for (int z = corner.z - 2 * areaFactor * width; z < corner.z + 2 * areaFactor * width; z++)
                {
                    if (ftm.CheckBounds(x, z))
                    {
                        float distance = fmc.GetDistance(corner, new Vertex(x, z));
                        //if (i == 10)
                        //Debug.Log(i+":"+distance);

                        if (distance < areaFactor * widthInPoints[i])
                        {
                            float depth = 0;

                            if (distance == 0) //sinc is not defined at 0
                                distance += 0.01f;

                            depth = MySinc(distance, widthInPoints[i], depthFactor);

                            if (depthField[x, z] == 666) //hasnt been modified yet
                            {
                                depthField[x, z] = depth;
                                //rg.ColorPixel(x, z, 1, greenColor);
                                pathMark[x, z] = 2;//corner
                                distField[x, z] = distance;
                                //Debug.Log(depth);
                            }
                            else if (depthField[x, z] != 666) //has been modified but maybe badly
                            {
                                if (distance < distField[x, z])
                                {
                                    depthField[x, z] = depth;
                                    distField[x, z] = distance;
                                    pathMark[x, z] = 2;
                                }
                                //depthField[x, z] = Math.Min(depthField[x, z], depth);
                                //depthField[x, z] = (depthField[x, z] + depth)/2; //blbost
                                //ColorPixel(x, z, 1,redColor);
                                //Debug.Log(x + "," + z);

                            }

                        }
                        else
                        {
                            //ColorPixel(x, z, 0, greenColor);
                        }
                    }
                }

            }
        }

        //filter result
        float[,] filtField = new float[terrainSize, terrainSize];
        for (int x = 0; x < terrainSize; x++)
        {
            for (int z = 0; z < terrainSize; z++)
            {
                if (depthField[x, z] != 666)
                {
                    filtField[x, z] += ftm.GetMedian(x,z,2, depthField);
                }
            }
        }

        //apply digging
        for (int x = 0; x < terrainSize; x++)
        {
            for (int z = 0; z < terrainSize; z++)
            {
                if (depthField[x, z] != 666)
                {
                    //vertices[x, z].y += depthField[x, z] * depthFactor;
                    vertices[x, z].y += filtField[x, z] * depthFactor;
                }
            }
        }

        rg.terrain.build();

        //ColorPixel(20, 20, 0, greenColor);
        //color digging

        //pathmark:
        //  1 = river
        //  2 = corner
        for (int x = 0; x < terrainSize; x++)
        {
            for (int z = 0; z < terrainSize; z++)
            {
                if (pathMark[x, z] == 1)
                {
                    //fd.ColorPixel(x, z, 0, fd.redColor);
                }
                else if (pathMark[x, z] == 2)
                {
                    //fd.ColorPixel(x, z, 0, fd.greenColor);
                }
            }
        }
    }
 public bool Equals(VertexInPlane <TVertex> other)
 {
     return(Vertex.Equals(other.Vertex) && Position.Equals(other.Position));
 }
Example #34
0
        public void EqualTest3()
        {
            //Texture coord is different
            Vertex v0 = new Vertex(new Vector3(2f, 234.4f, 30f), new Vector2(-341f, 99000f), new Vector3(9f, 24.4f, 330f), new Vector3(255f, 2.4f, 10.315f));
            Vertex v1 = new Vertex(new Vector3(2f, 234.4f, 30f), new Vector2(-341f, 234000f), new Vector3(9f, 24.4f, 330f), new Vector3(255f, 2.4f, 10.315f));

            Assert.IsFalse(v0.Equals(v1));
            Assert.IsFalse(v1.Equals(v0));

            Assert.IsFalse(v0.Equals((object)v1));
            Assert.IsFalse(v1.Equals((object)v0));

            Assert.IsFalse(v0 == v1);
            Assert.IsTrue(v0 != v1);
        }
Example #35
0
        public static Graph Dijkstra(Graph graph, Vertex origin, Vertex destination, Graph tempGraph = null)
        {
            MinPriorityQ <Vertex, double> Q = new MinPriorityQ <Vertex, double>();
            bool originInGraph = false;

            foreach (Vertex v in graph.vertices)
            {
                if (v.Equals(origin))
                {
                    originInGraph = true;
                    Q.Add(origin, 0);
                }
                else
                {
                    Q.Add(v, Double.PositiveInfinity);
                }
            }

            //If tempGraph is not null, means graph doesn't contain origin and/or destination vertices.
            if (!originInGraph)
            {
                Q.Add(origin, 0);
            }

            if (!graph.Contains(destination))
            {
                Q.Add(destination, Double.PositiveInfinity);
            }

            Dictionary <Vertex, Vertex> ParentVertices = new Dictionary <Vertex, Vertex>();
            List <Vertex> S = new List <Vertex>();

            while (Q.Size > 0)
            {
                double minDistance = Q.PeekValue();
                Vertex vertex      = Q.Take();
                S.Add(vertex);

                if (vertex.Equals(destination))
                {
                    break;
                }

                List <Edge> edges = new List <Edge>();
                edges.AddRange(graph.GetVertexEdges(vertex));
                if (tempGraph != null && tempGraph.edges.Any())
                {
                    edges.AddRange(tempGraph.GetVertexEdges(vertex));
                }

                foreach (Edge e in edges)
                {
                    Vertex w         = e.GetVertexPair(vertex);
                    double newLength = minDistance + e.Length;

                    if (!S.Contains(w) && newLength < Q.GetValue(w))
                    {
                        Q.UpdateItem(w, newLength);
                        //dist[w] = newLength;
                        ParentVertices[w] = vertex;
                    }
                }
            }

            Graph  path = new Graph();
            Vertex dest = destination;

            while (dest != origin)
            {
                Vertex parent = ParentVertices[dest];
                path.AddEdge(new Edge(parent, dest));
                dest = parent;
            }
            // Reversing edges list so they will be sorted from origin to target
            path.edges.Reverse();
            return(path);
        }
Example #36
0
        private void Walkup(Vertex <T> vertex, IEdge <Vertex <T> > edge)
        {
            var source = edge.Source;
            var target = edge.Target;

            if (source.Equals(target))
            {
                selfLoopsNew.Add(edge);
                return;
            }

            var w = vertex.Equals(source) ? target : vertex;

            if (w.DFSNumber < vertex.DFSNumber || edge.Equals(w.DFSEdge))
            {
                return;
            }

            w.BackEdges.Add(edge);
            var timestamp = vertex.DFSNumber;

            w.BackedgeFlag = timestamp;

            var leadVertex = w;

            while (true)
            {
                var foundRoot = true;

                // Move to the root of the current bicomp or the first visited
                // vertex on the bicomp by going up each side in parallel
                foreach (var faceVertex in IterateBothSides(leadVertex))
                {
                    if (faceVertex.Visited == timestamp)
                    {
                        foundRoot = false;
                        break;
                    }

                    leadVertex         = faceVertex;
                    leadVertex.Visited = timestamp;
                }

                // If we've found the root of a bicomp through a path we haven't
                // seen before, update pertinent_roots with a handle to the
                // current bicomp. Otherwise, we've just seen a path we've been
                // up before, so break out of the main while loop.
                if (foundRoot)
                {
                    var dfsChild = leadVertex.CanonicalDFSChild;
                    var parent   = dfsChild.Parent;

                    dfsChild.DFSChildHandle.FirstVertex.Visited  = timestamp;
                    dfsChild.DFSChildHandle.SecondVertex.Visited = timestamp;

                    if (dfsChild.LowPoint < vertex.DFSNumber ||
                        dfsChild.LeastAncestor < vertex.DFSNumber
                        )
                    {
                        parent.PertinentRoots.AddLast(dfsChild.DFSChildHandle);
                    }
                    else
                    {
                        parent.PertinentRoots.AddFirst(dfsChild.DFSChildHandle);
                    }

                    if (parent != vertex && parent.Visited != timestamp)
                    {
                        leadVertex = parent;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
        }
Example #37
0
		public Edge findEdge(Vertex vet1, Vertex vet2) {
			if (!vet1.Equals(vet2)) {
				if (directed) {
					foreach (Edge e in edges)
						if (((e.getStart().getName().Equals(vet1.getName())) &&
							(e.getEnd().getName().Equals(vet2.getName()))))
							return e;
				} else {
					foreach (Edge e in edges)
						if (((e.getStart().getName().Equals(vet1.getName())) &&
							(e.getEnd().getName().Equals(vet2.getName()))) ||
							((e.getStart().getName().Equals(vet2.getName())) &&
								(e.getEnd().getName().Equals(vet1.getName()))))
							return e;
				}
			}
			return null;

		}
Example #38
0
    public Grid Prims(Vertex start)
    {
        Grid U = new Grid(width, height);

        foreach (Vertex v in vertexSet)
        {
            if (!start.Equals(v))
            {
                U.addVertex(v);
            }
        }
        HashSet <Vertex> difference = new HashSet <Vertex> ();

        foreach (Vertex v in vertexSet)
        {
            difference.Add(v);
        }
        difference.ExceptWith(U.vertexSet);
        List <Edge> connectingEdges = new List <Edge> ();

        //check for edge from G.V - U to U
        foreach (Edge e in this.edges)
        {
            foreach (Vertex a in difference)
            {
                foreach (Vertex b in U.vertexSet)
                {
                    if (e.contains(a) && e.contains(b))
                    {
                        connectingEdges.Add(e);
                    }
                }
            }
        }
        while (U.vertexSet.Count > 0 && connectingEdges.Count > 0)
        {
            //Find the minimum weight edge
            int minWeight      = connectingEdges [0].weight;
            int minWeightIndex = 0;
            for (int i = 1; i < connectingEdges.Count; i++)
            {
                if (connectingEdges [i].weight < minWeight)
                {
                    minWeight      = connectingEdges [i].weight;
                    minWeightIndex = i;
                }
            }
            //set the parent and remove it from U
            if (U.vertexSet.Contains(connectingEdges [minWeightIndex].v1))
            {
                connectingEdges [minWeightIndex].v1.setParent(connectingEdges [minWeightIndex].v2);
                U.removeVertex(connectingEdges [minWeightIndex].v1);
            }
            else
            {
                connectingEdges [minWeightIndex].v2.setParent(connectingEdges [minWeightIndex].v1);
                U.removeVertex(connectingEdges [minWeightIndex].v2);
            }
            U.addEdge(connectingEdges[minWeightIndex]);

            //update the difference again
            foreach (Vertex v in vertexSet)
            {
                difference.Add(v);
            }
            difference.ExceptWith(U.vertexSet);

            //check for edge from G.V - U to U again because of updated U
            connectingEdges.Clear();
            foreach (Edge e in this.edges)
            {
                foreach (Vertex a in difference)
                {
                    foreach (Vertex b in U.vertexSet)
                    {
                        if (e.contains(a) && e.contains(b))
                        {
                            connectingEdges.Add(e);
                        }
                    }
                }
            }
        }
        return(U);
    }