public void UpdateEdge(HalfEdge3 halfEdge, Matrix4x4 Q1, Matrix4x4 Q2) { this.halfEdge = halfEdge; //Compute the optimal contraction target v for the pair (v1, v2) and the qem at this position CalculateMergePositionANDqem(this.halfEdge, Q1, Q2); }
//Help method to build a triangle and add it to a mesh //v1-v2-v3 should be sorted clock-wise //v1-v2 should be the cut edge (if we have a cut edge), and we know this triangle has a cut edge if newEdges != null private static void AddTriangleToMesh(MyMeshVertex v1, MyMeshVertex v2, MyMeshVertex v3, HalfEdgeData3 mesh, HashSet <HalfEdge3> newEdges) { //Create three new vertices HalfEdgeVertex3 half_v1 = new HalfEdgeVertex3(v1.position, v1.normal); HalfEdgeVertex3 half_v2 = new HalfEdgeVertex3(v2.position, v2.normal); HalfEdgeVertex3 half_v3 = new HalfEdgeVertex3(v3.position, v3.normal); //Create three new half-edges that points TO these vertices HalfEdge3 e_to_v1 = new HalfEdge3(half_v1); HalfEdge3 e_to_v2 = new HalfEdge3(half_v2); HalfEdge3 e_to_v3 = new HalfEdge3(half_v3); //Create the face (which is a triangle) which needs a reference to one of the edges HalfEdgeFace3 f = new HalfEdgeFace3(e_to_v1); //Connect the data: //Connect the edges clock-wise e_to_v1.nextEdge = e_to_v2; e_to_v2.nextEdge = e_to_v3; e_to_v3.nextEdge = e_to_v1; e_to_v1.prevEdge = e_to_v3; e_to_v2.prevEdge = e_to_v1; e_to_v3.prevEdge = e_to_v2; //Each vertex needs a reference to an edge going FROM that vertex half_v1.edge = e_to_v2; half_v2.edge = e_to_v3; half_v3.edge = e_to_v1; //Each edge needs a reference to the face e_to_v1.face = f; e_to_v2.face = f; e_to_v3.face = f; //Each edge needs an opposite edge //This is slow process but we need it to be able to split meshes which are not connected //You could do this afterwards when all triangles have been generate, but Im not sure which is the fastest... //Save the data mesh.verts.Add(half_v1); mesh.verts.Add(half_v2); mesh.verts.Add(half_v3); mesh.edges.Add(e_to_v1); mesh.edges.Add(e_to_v2); mesh.edges.Add(e_to_v3); mesh.faces.Add(f); //Save the new edge if (newEdges != null) { //We know the knew edge goes from v1 to v2, so we should save the half-edge that points to v2 newEdges.Add(e_to_v2); } }
//Connect an edge with an unknown opposite edge which has not been connected //If no opposite edge exists, it means it has no neighbor which is possible if there's a hole public void TryFindOppositeEdge(HalfEdge3 e) { //We need to find an edge which is: // - going to a position where this edge is coming from // - coming from a position this edge points to //An edge is pointing to a position MyVector3 pTo = e.prevEdge.v.position; MyVector3 pFrom = e.v.position; foreach (HalfEdge3 eOther in edges) { //Don't need to check edges that have already been connected if (eOther.oppositeEdge != null) { continue; } //Is this edge pointing from a specific vertex to a specific vertex //If so it means we have found an edge going in the other direction if (eOther.v.position.Equals(pTo) && eOther.prevEdge.v.position.Equals(pFrom)) { //Connect them with each other e.oppositeEdge = eOther; eOther.oppositeEdge = e; break; } } }
//Get a list with unique edges //Currently we have two half-edges for each edge, making it time consuming to go through them public List <HalfEdge3> GetUniqueEdges() { List <HalfEdge3> uniqueEdges = new List <HalfEdge3>(); foreach (HalfEdge3 e in edges) { MyVector3 p1 = e.v.position; MyVector3 p2 = e.prevEdge.v.position; bool isInList = false; for (int j = 0; j < uniqueEdges.Count; j++) { HalfEdge3 testEdge = uniqueEdges[j]; MyVector3 p1_test = testEdge.v.position; MyVector3 p2_test = testEdge.prevEdge.v.position; if ((p1.Equals(p1_test) && p2.Equals(p2_test)) || (p2.Equals(p1_test) && p1.Equals(p2_test))) { isInList = true; break; } } if (!isInList) { uniqueEdges.Add(e); } } return(uniqueEdges); }
//Get all edges that make up this face //If you need all vertices you can use this method because each edge points to a vertex public List <HalfEdge3> GetEdges() { List <HalfEdge3> allEdges = new List <HalfEdge3>(); HalfEdge3 currentEdge = this.edge; int safety = 0; do { allEdges.Add(currentEdge); currentEdge = currentEdge.nextEdge; safety += 1; if (safety > 100000) { Debug.LogWarning("Stuck in infinite loop when getting all edges from a face"); return(null); } }while (currentEdge != this.edge); return(allEdges); }
private static void AddHolesToMeshes(HashSet <HalfEdgeData3> newMeshesO, HashSet <HalfEdgeData3> newMeshesI, HashSet <Hole> allHoles) { //This may happen if the original mesh has holes in it and the plane intersects one of those holes. //Then we can't identify the hole as closed and we can't repair the hole anyway if (allHoles == null) { return; } foreach (Hole hole in allHoles) { HalfEdge3 holeEdgeI = hole.holeEdgeI; HalfEdge3 holeEdgeO = hole.holeEdgeO; //Outside foreach (HalfEdgeData3 mesh in newMeshesO) { //This edge was generated when we created the infrastructure //So we just have to check if it's a part of the mesh if (mesh.edges.Contains(holeEdgeO)) { mesh.MergeMesh(hole.holeMeshO); } } //Inside foreach (HalfEdgeData3 mesh in newMeshesI) { if (mesh.edges.Contains(holeEdgeI)) { mesh.MergeMesh(hole.holeMeshI); } } } }
//Help method to above private void RemoveTriangleAndConnectOppositeSides(HalfEdge3 e) { //AB is the edge we want to contract HalfEdge3 e_AB = e; HalfEdge3 e_BC = e.nextEdge; HalfEdge3 e_CA = e.nextEdge.nextEdge; //The triangle belonging to this edge HalfEdgeFace3 f_ABC = e.face; //Delete the triangle (which will also delete the vertices and edges belonging to that face) //We have to do it before we re-connect the edges because it sets all opposite edges to null, making a hole DeleteFace(f_ABC); //Connect the opposite edges of the edges which are not a part of the edge we want to delete //This will connect the opposite sides of the hole //We move vertices in another method if (e_BC.oppositeEdge != null) { //The edge on the opposite side of BC should have its opposite edge connected with the opposite edge of CA e_BC.oppositeEdge.oppositeEdge = e_CA.oppositeEdge; } if (e_CA.oppositeEdge != null) { e_CA.oppositeEdge.oppositeEdge = e_BC.oppositeEdge; } }
//If we know that the vertex positions were created in the same way (no floating point precision issues) //we can generate a lookup table of all edges which should make it faster to find an opposite edge for each edge //This method takes rough 0.1 seconds for the bunny, while the slow method takes 1.6 seconds public void ConnectAllEdgesFast() { //Create the lookup table //Important in this case that Edge3 is a struct Dictionary <Edge3, HalfEdge3> edgeLookup = new Dictionary <Edge3, HalfEdge3>(); //We can also maybe create a list of all edges which are not connected, so we don't have to search through all edges again? //List<HalfEdge3> unconnectedEdges = new List<HalfEdge3>(); foreach (HalfEdge3 e in edges) { //Dont add it if its opposite is not null //Sometimes we run this method if just a few edges are not connected //This means this edge is already connected, so it cant possibly be connected with the edges we want to connect if (e.oppositeEdge != null) { continue; } //Each edge points TO a vertex Vector3 p2 = e.v.position; Vector3 p1 = e.prevEdge.v.position; edgeLookup.Add(new Edge3(p1, p2), e); } //Connect edges foreach (HalfEdge3 e in edges) { //This edge is already connected //Is faster to first do a null check if (e.oppositeEdge != null) //if (!(e.oppositeEdge is null)) //Is slightly slower { continue; } //Each edge points TO a vertex, so the opposite edge goes in the opposite direction Vector3 p1 = e.v.position; Vector3 p2 = e.prevEdge.v.position; Edge3 edgeToLookup = new Edge3(p1, p2); //This is slightly faster than first edgeLookup.ContainsKey(edgeToLookup) HalfEdge3 eOther = null; edgeLookup.TryGetValue(edgeToLookup, out eOther); if (eOther != null) { //Connect them with each other e.oppositeEdge = eOther; eOther.oppositeEdge = e; } //This edge doesnt exist so opposite edge must be null } }
public Hole(HalfEdgeData3 holeMeshI, HalfEdgeData3 holeMeshO, HalfEdge3 holeEdgeI, HalfEdge3 holeEdgeO) { this.holeMeshI = holeMeshI; this.holeMeshO = holeMeshO; this.holeEdgeI = holeEdgeI; this.holeEdgeO = holeEdgeO; }
//Compute the optimal contraction target v for the pair (v1, v2) private void CalculateMergePositionANDqem(HalfEdge3 e, Matrix4x4 Q1, Matrix4x4 Q2) { //The basic idea is that we want to find a position on the edge that minimizes the error //Assume for simplicity that the contraction target are v = (v1 + v2) * 0.5f, or v = v1, or v = v2 //Add the other versions in the future! //Adding just 3 alternatives instead of using just the average position, adds 0.2 seconds for the bunny (2400 iterations) //But the result is slightly better Vector3 p1 = e.prevEdge.v.position; Vector3 p2 = e.v.position; Vector3 v1 = p1; Vector3 v2 = p2; Vector3 v3 = (p1 + p2) * 0.5f; //Compute the Quadric Error Metric at each point v float qem1 = CalculateQEM(v1, Q1, Q2); float qem2 = CalculateQEM(v2, Q1, Q2); float qem3 = CalculateQEM(v3, Q1, Q2); //Find which vertex minimized the qem if (qem1 < qem2 && qem1 < qem3) { this.mergePosition = v1; this.qem = qem1; } else if (qem2 < qem1 && qem2 < qem3) { this.mergePosition = v2; this.qem = qem2; } else { this.mergePosition = v3; this.qem = qem3; } }
//We might end up with multiple holes, so we need to identify all of them //Input is just a list of all edges that form the hole(s) //The output list is sorted so we can walk around the hole private static HashSet <List <HalfEdge3> > IdentifySeparateHoles(HashSet <HalfEdge3> cutEdges) { HashSet <List <HalfEdge3> > allHoles = new HashSet <List <HalfEdge3> >(); //Alternative create a linked list, which should identify all holes automatically? //Faster to just pick a start edge HalfEdge3 startEdge = cutEdges.FakePop(); //Add it back so we can stop the algorithm cutEdges.Add(startEdge); List <HalfEdge3> sortedHoleEdges = new List <HalfEdge3>() { startEdge }; //The first edge is needed to stop the algorithm, so don't remove it! //cutEdges.Remove(startEdge); //Then we can use the cutEdges to find our way around the hole's edge //We cant use the half-edge data structure because multiple edges may start at a vertex int safety = 0; while (true) { //Find an edge that starts at the last sorted cut edge HalfEdge3 nextEdge = null; MyVector3 lastPos = sortedHoleEdges[sortedHoleEdges.Count - 1].v.position; foreach (HalfEdge3 e in cutEdges) { //A half-edge points to a vertex, so we want and edge going from the last vertex if (e.prevEdge.v.position.Equals(lastPos)) { nextEdge = e; cutEdges.Remove(nextEdge); break; } } if (nextEdge == null) { Debug.Log("Could not find a next edge when filling the hole"); break; } //The hole is back where it started else if (nextEdge == startEdge) { //Debug.Log($"Number of edges to fill this hole: {sortedHoleEdges.Count}"); allHoles.Add(sortedHoleEdges); //We have another hole if (cutEdges.Count > 0) { startEdge = cutEdges.FakePop(); //Add it back so we can stop the algorithm cutEdges.Add(startEdge); //Start over with a new list sortedHoleEdges = new List <HalfEdge3>() { startEdge }; } //No more holes else { Debug.Log($"The mesh has {allHoles.Count} holes"); break; } } else { sortedHoleEdges.Add(nextEdge); } safety += 1; if (safety > 20000) { Debug.Log("Stuck in infinite loop when finding connected cut edges"); //Debug.Log(sortedHoleEdges.Count); break; } } return(allHoles); }
//v1-v2-v3 should be clock-wise which is Unity standard public HalfEdgeFace3 AddTriangle(MyMeshVertex v1, MyMeshVertex v2, MyMeshVertex v3, bool findOppositeEdge = false) { //Create three new vertices HalfEdgeVertex3 half_v1 = new HalfEdgeVertex3(v1.position, v1.normal); HalfEdgeVertex3 half_v2 = new HalfEdgeVertex3(v2.position, v2.normal); HalfEdgeVertex3 half_v3 = new HalfEdgeVertex3(v3.position, v3.normal); //Create three new half-edges that points TO these vertices HalfEdge3 e_to_v1 = new HalfEdge3(half_v1); HalfEdge3 e_to_v2 = new HalfEdge3(half_v2); HalfEdge3 e_to_v3 = new HalfEdge3(half_v3); //Create the face (which is a triangle) which needs a reference to one of the edges HalfEdgeFace3 f = new HalfEdgeFace3(e_to_v1); //Connect the data: //Connect the edges clock-wise e_to_v1.nextEdge = e_to_v2; e_to_v2.nextEdge = e_to_v3; e_to_v3.nextEdge = e_to_v1; e_to_v1.prevEdge = e_to_v3; e_to_v2.prevEdge = e_to_v1; e_to_v3.prevEdge = e_to_v2; //Each vertex needs a reference to an edge going FROM that vertex half_v1.edge = e_to_v2; half_v2.edge = e_to_v3; half_v3.edge = e_to_v1; //Each edge needs a reference to the face e_to_v1.face = f; e_to_v2.face = f; e_to_v3.face = f; //Each edge needs an opposite edge //This is slow process //You could do this afterwards when all triangles have been generate //Doing it in this method takes 2.7 seconds for the bunny //Doing it afterwards takes 0.1 seconds by using the fast method and 1.6 seconds for the slow method //The reason is that we keep searching the list for an opposite which doesnt exist yet, so we get more searches even though //the list is shorter as we build up the mesh //But you could maybe do it here if you just add a new triangle? if (findOppositeEdge) { TryFindOppositeEdge(e_to_v1); TryFindOppositeEdge(e_to_v2); TryFindOppositeEdge(e_to_v3); } //Save the data this.verts.Add(half_v1); this.verts.Add(half_v2); this.verts.Add(half_v3); this.edges.Add(e_to_v1); this.edges.Add(e_to_v2); this.edges.Add(e_to_v3); this.faces.Add(f); return(f); }
//Return all edges going to this vertex = all edges that references this vertex position //meshData is needed if we cant spring around this vertex because there might be a hole in the mesh //If so we have to search through all edges in the entire mesh public HashSet <HalfEdge3> GetEdgesPointingToVertex(HalfEdgeData3 meshData) { HashSet <HalfEdge3> allEdgesGoingToVertex = new HashSet <HalfEdge3>(); //This is the edge that goes to this vertex HalfEdge3 currentEdge = this.edge.prevEdge; //if (currentEdge == null) Debug.Log("Edge is null"); int safety = 0; do { allEdgesGoingToVertex.Add(currentEdge); //This edge is going to the vertex but in another triangle HalfEdge3 oppositeEdge = currentEdge.oppositeEdge; if (oppositeEdge == null) { Debug.LogWarning("We cant rotate around this vertex because there are holes in the mesh"); //Better to clear than to null or we have to create a new hashset when filling it the brute force way allEdgesGoingToVertex.Clear(); break; } //if (oppositeEdge == null) Debug.Log("Opposite edge is null"); currentEdge = oppositeEdge.prevEdge; safety += 1; if (safety > 1000) { Debug.LogWarning("Stuck in infinite loop when getting all edges around a vertex"); allEdgesGoingToVertex.Clear(); break; } }while (currentEdge != this.edge.prevEdge); //If there are holes in the triangulation around the vertex, //we have to use the brute force approach and look at edges if (allEdgesGoingToVertex.Count == 0 && meshData != null) { HashSet <HalfEdge3> edges = meshData.edges; foreach (HalfEdge3 e in edges) { //An edge points TO a vertex if (e.v.position.Equals(position)) { allEdgesGoingToVertex.Add(e); } } } return(allEdgesGoingToVertex); }
//Fill the hole (or holes) in the mesh private static HashSet <Hole> FillHoles(HashSet <HalfEdge3> holeEdgesI, HashSet <HalfEdge3> holeEdgesO, OrientedPlane3 orientedCutPlane, Transform meshTrans, MyVector3 planeNormal) { if (holeEdgesI == null || holeEdgesI.Count == 0) { Debug.Log("This mesh has no hole"); return(null); } //Find all separate holes HashSet <List <HalfEdge3> > allHoles = IdentifySeparateHoles(holeEdgesI); if (allHoles.Count == 0) { Debug.LogWarning("Couldn't identify any holes even though we have hole edges"); return(null); } //Debug //foreach (List<HalfEdge3> hole in allHoles) //{ // foreach (HalfEdge3 e in hole) // { // Debug.DrawLine(meshTrans.TransformPoint(e.v.position.ToVector3()), Vector3.zero, Color.white, 5f); // } //} //Fill the hole with a mesh HashSet <Hole> holeMeshes = new HashSet <Hole>(); foreach (List <HalfEdge3> hole in allHoles) { HalfEdgeData3 holeMeshI = new HalfEdgeData3(); HalfEdgeData3 holeMeshO = new HalfEdgeData3(); //Transform vertices to local position of the cut plane to make it easier to triangulate with Ear Clipping //Ear CLipping wants vertices in 2d List <MyVector2> sortedEdges_2D = new List <MyVector2>(); Transform planeTrans = orientedCutPlane.planeTrans; foreach (HalfEdge3 e in hole) { MyVector3 pMeshSpace = e.v.position; //Mesh space to Global space Vector3 pGlobalSpace = meshTrans.TransformPoint(pMeshSpace.ToVector3()); //Global space to Plane space Vector3 pPlaneSpace = planeTrans.InverseTransformPoint(pGlobalSpace); //Y is normal direction so should be 0 MyVector2 p2D = new MyVector2(pPlaneSpace.x, pPlaneSpace.z); sortedEdges_2D.Add(p2D); } //Triangulate with Ear Clipping HashSet <Triangle2> triangles = _EarClipping.Triangulate(sortedEdges_2D, null, optimizeTriangles: false); //Debug.Log($"Number of triangles from Ear Clipping: {triangles.Count}"); //Transform vertices to mesh space and half-edge data structure foreach (Triangle2 t in triangles) { //3d space Vector3 p1 = new Vector3(t.p1.x, 0f, t.p1.y); Vector3 p2 = new Vector3(t.p2.x, 0f, t.p2.y); Vector3 p3 = new Vector3(t.p3.x, 0f, t.p3.y); //Plane space to Global space Vector3 p1Global = planeTrans.TransformPoint(p1); Vector3 p2Global = planeTrans.TransformPoint(p2); Vector3 p3Global = planeTrans.TransformPoint(p3); //Global space to Mesh space Vector3 p1Mesh = meshTrans.InverseTransformPoint(p1Global); Vector3 p2Mesh = meshTrans.InverseTransformPoint(p2Global); Vector3 p3Mesh = meshTrans.InverseTransformPoint(p3Global); //For inside mesh MyMeshVertex v1_I = new MyMeshVertex(p1Mesh.ToMyVector3(), planeNormal); MyMeshVertex v2_I = new MyMeshVertex(p2Mesh.ToMyVector3(), planeNormal); MyMeshVertex v3_I = new MyMeshVertex(p3Mesh.ToMyVector3(), planeNormal); //For inside mesh MyMeshVertex v1_O = new MyMeshVertex(p1Mesh.ToMyVector3(), -planeNormal); MyMeshVertex v2_O = new MyMeshVertex(p2Mesh.ToMyVector3(), -planeNormal); MyMeshVertex v3_O = new MyMeshVertex(p3Mesh.ToMyVector3(), -planeNormal); //Now we can finally add this triangle to the half-edge data structure AddTriangleToMesh(v1_I, v2_I, v3_I, holeMeshI, null); AddTriangleToMesh(v1_O, v3_O, v2_O, holeMeshO, null); } //We also need an edge belonging to the mesh (not hole mesh) to easier merge mesh with hole //The hole edges were generated for the Inside mesh HalfEdge3 holeEdgeI = hole[0]; //But we also need an edge for the Outside mesh bool foundCorrespondingEdge = false; MyVector3 eGoingTo = holeEdgeI.v.position; MyVector3 eGoingFrom = holeEdgeI.prevEdge.v.position; foreach (HalfEdge3 holeEdgeO in holeEdgesO) { MyVector3 eOppsiteGoingTo = holeEdgeO.v.position; MyVector3 eOppsiteGoingFrom = holeEdgeO.prevEdge.v.position; if (eOppsiteGoingTo.Equals(eGoingFrom) && eOppsiteGoingFrom.Equals(eGoingTo)) { Hole newHoleMesh = new Hole(holeMeshI, holeMeshO, holeEdgeI, holeEdgeO); holeMeshes.Add(newHoleMesh); foundCorrespondingEdge = true; break; } } if (!foundCorrespondingEdge) { Debug.Log("Couldnt find opposite edge in hole, so no hole was added"); } } return(holeMeshes); }
//Find all visible triangles from a point //Also find edges on the border between invisible and visible triangles public static void FindVisibleTrianglesAndBorderEdgesFromPoint(Vector3 p, HalfEdgeData3 convexHull, out HashSet <HalfEdgeFace3> visibleTriangles, out HashSet <HalfEdge3> borderEdges) { //Flood-fill from the visible triangle to find all other visible triangles //When you cross an edge from a visible triangle to an invisible triangle, //save the edge because thhose edge should be used to build triangles with the point //These edges should belong to the triangle which is not visible borderEdges = new HashSet <HalfEdge3>(); //Store all visible triangles here so we can't visit triangles multiple times visibleTriangles = new HashSet <HalfEdgeFace3>(); //Start the flood-fill by finding a triangle which is visible from the point //A triangle is visible if the point is outside the plane formed at the triangles //Another sources is using the signed volume of a tetrahedron formed by the triangle and the point HalfEdgeFace3 visibleTriangle = FindVisibleTriangleFromPoint(p, convexHull.faces); //If we didn't find a visible triangle, we have some kind of edge case and should move on for now if (visibleTriangle == null) { Debug.LogWarning("Couldn't find a visible triangle so will ignore the point"); return; } //The queue which we will use when flood-filling Queue <HalfEdgeFace3> trianglesToFloodFrom = new Queue <HalfEdgeFace3>(); //Add the first triangle to init the flood-fill trianglesToFloodFrom.Enqueue(visibleTriangle); List <HalfEdge3> edgesToCross = new List <HalfEdge3>(); int safety = 0; while (true) { //We have visited all visible triangles if (trianglesToFloodFrom.Count == 0) { break; } HalfEdgeFace3 triangleToFloodFrom = trianglesToFloodFrom.Dequeue(); //This triangle is always visible and should be deleted visibleTriangles.Add(triangleToFloodFrom); //Investigate bordering triangles edgesToCross.Clear(); edgesToCross.Add(triangleToFloodFrom.edge); edgesToCross.Add(triangleToFloodFrom.edge.nextEdge); edgesToCross.Add(triangleToFloodFrom.edge.nextEdge.nextEdge); //Jump from this triangle to a bordering triangle foreach (HalfEdge3 edgeToCross in edgesToCross) { HalfEdge3 oppositeEdge = edgeToCross.oppositeEdge; if (oppositeEdge == null) { Debug.LogWarning("Found an opposite edge which is null"); break; } HalfEdgeFace3 oppositeTriangle = oppositeEdge.face; //Have we visited this triangle before (only test visible triangles)? if (trianglesToFloodFrom.Contains(oppositeTriangle) || visibleTriangles.Contains(oppositeTriangle)) { continue; } //Check if this triangle is visible //A triangle is visible from a point the point is outside of a plane formed with the triangles position and normal Plane3 plane = new Plane3(oppositeTriangle.edge.v.position, oppositeTriangle.edge.v.normal); bool isPointOutsidePlane = _Geometry.IsPointOutsidePlane(p, plane); //This triangle is visible so save it so we can flood from it if (isPointOutsidePlane) { trianglesToFloodFrom.Enqueue(oppositeTriangle); } //This triangle is invisible. Since we only flood from visible triangles, //it means we crossed from a visible triangle to an invisible triangle, so save the crossing edge else { borderEdges.Add(oppositeEdge); } } safety += 1; if (safety > 50000) { Debug.Log("Stuck in infinite loop when flood-filling visible triangles"); break; } } }
/// <summary> /// /// </summary> /// <param name="points">The points from which we want to build the convex hull</param> /// <param name="removeUnwantedTriangles">At the end of the algorithm, try to remove triangles from the hull that we dont want, //such as needles where one edge is much shorter than the other edges in the triangle</param> /// <param name="normalizer">Is only needed for debugging</param> /// <returns></returns> public static HalfEdgeData3 GenerateConvexHull(HashSet <Vector3> points, bool removeUnwantedTriangles, Normalizer3 normalizer = null) { HalfEdgeData3 convexHull = new HalfEdgeData3(); //Step 1. Init by making a tetrahedron (triangular pyramid) and remove all points within the tetrahedron System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); //timer.Start(); BuildFirstTetrahedron(points, convexHull); //timer.Stop(); //Debug.Log($"Testrahedron {timer.ElapsedMilliseconds/1000f}"); //Debug.Log(convexHull.faces.Count); //return convexHull; //Step 2. For each other point: // -If the point is within the hull constrcuted so far, remove it // - Otherwise, see which triangles are visible to the point and remove them // Then build new triangles from the edges that have no neighbor to the point List <Vector3> pointsToAdd = new List <Vector3>(points); int removedPointsCounter = 0; //int debugCounter = 0; foreach (Vector3 p in pointsToAdd) { //Is this point within the tetrahedron bool isWithinHull = _Intersections.PointWithinConvexHull(p, convexHull); if (isWithinHull) { points.Remove(p); removedPointsCounter += 1; continue; } //Find visible triangles and edges on the border between the visible and invisible triangles HashSet <HalfEdgeFace3> visibleTriangles = null; HashSet <HalfEdge3> borderEdges = null; FindVisibleTrianglesAndBorderEdgesFromPoint(p, convexHull, out visibleTriangles, out borderEdges); //Remove all visible triangles foreach (HalfEdgeFace3 triangle in visibleTriangles) { convexHull.DeleteFace(triangle); } //Make new triangle by connecting all edges on the border with the point //Debug.Log($"Number of border edges: {borderEdges.Count}"); //int debugStop = 11; //Save all ned edges so we can connect them with an opposite edge //To make it faster you can use the ideas in the Valve paper to get a sorted list of newEdges HashSet <HalfEdge3> newEdges = new HashSet <HalfEdge3>(); foreach (HalfEdge3 borderEdge in borderEdges) { //Each edge is point TO a vertex Vector3 p1 = borderEdge.prevEdge.v.position; Vector3 p2 = borderEdge.v.position; /* * if (debugCounter > debugStop) * { * Debug.DrawLine(normalizer.UnNormalize(p1).ToVector3(), normalizer.UnNormalize(p2).ToVector3(), Color.white, 2f); * * Debug.DrawLine(normalizer.UnNormalize(p1).ToVector3(), normalizer.UnNormalize(p).ToVector3(), Color.gray, 2f); * Debug.DrawLine(normalizer.UnNormalize(p2).ToVector3(), normalizer.UnNormalize(p).ToVector3(), Color.gray, 2f); * * convexHull.AddTriangle(p2, p1, p); * } * else * { * //Debug.Log(borderEdge.face); * * convexHull.AddTriangle(p2, p1, p); * } */ //The border edge belongs to a triangle which is invisible //Because triangles are oriented clockwise, we have to add the vertices in the other direction //to build a new triangle with the point HalfEdgeFace3 newTriangle = convexHull.AddTriangle(p2, p1, p); //Connect the new triangle with the opposite edge on the border //When we create the face we give it a reference edge which goes to p2 //So the edge we want to connect is the next edge HalfEdge3 edgeToConnect = newTriangle.edge.nextEdge; edgeToConnect.oppositeEdge = borderEdge; borderEdge.oppositeEdge = edgeToConnect; //Two edges are still not connected, so save those HalfEdge3 e1 = newTriangle.edge; //HalfEdge3 e2 = newTriangle.edge.nextEdge; HalfEdge3 e3 = newTriangle.edge.nextEdge.nextEdge; newEdges.Add(e1); //newEdges.Add(e2); newEdges.Add(e3); } //timer.Start(); //Two edges in each triangle are still not connected with an opposite edge foreach (HalfEdge3 e in newEdges) { if (e.oppositeEdge != null) { continue; } convexHull.TryFindOppositeEdge(e, newEdges); } //timer.Stop(); //Connect all new triangles and the triangles on the border, //so each edge has an opposite edge or flood filling will be impossible //timer.Start(); //convexHull.ConnectAllEdges(); //timer.Stop(); //if (debugCounter > debugStop) //{ // break; //} //debugCounter += 1; } //Debug.Log($"Connect half-edges took {timer.ElapsedMilliseconds/1000f} seconds"); Debug.Log($"Removed {removedPointsCounter} points during the construction of the hull because they were inside the hull"); // // Clean up // //Merge concave edges according to the paper //Remove unwanted triangles, such as slivers and needles //Which is maybe not needed because when you add a Unity convex mesh collider to the result of this algorithm, there are still slivers //Unity's mesh collider is also using quads and not just triangles //But if you add enough points, so you end up with many points on the hull you can see that Unitys convex mesh collider is not capturing all points, so they must be using some simplification algorithm //Run the hull through the mesh simplification algorithm if (removeUnwantedTriangles) { convexHull = MeshSimplification_QEM.Simplify(convexHull, maxEdgesToContract: int.MaxValue, maxError: 0.0001f, normalizeTriangles: true); } return(convexHull); }
//Needles. Triangle where the longest edge is much longer than the shortest one. private static bool RemoveNeedle(HalfEdgeData3 meshData, Normalizer3 normalizer = null) { HashSet <HalfEdgeFace3> triangles = meshData.faces; bool foundNeedle = false; foreach (HalfEdgeFace3 triangle in triangles) { /* * List<HalfEdge3> edges = triangle.GetEdges(); * * //Sort the edges from shortest to longest * List<HalfEdge3> edgesSorted = edges.OrderBy(e => e.Length()).ToList(); * * //The ratio between the shortest and longest side * float edgeLengthRatio = edgesSorted[0].Length() / edgesSorted[2].Length(); */ //Instead of using a million lists, we know we have just three edges we have to sort, so we can do better HalfEdge3 e1 = triangle.edge; HalfEdge3 e2 = triangle.edge.nextEdge; HalfEdge3 e3 = triangle.edge.nextEdge.nextEdge; //We want e1 to be the shortest and e3 to be the longest if (e1.SqrLength() > e3.SqrLength()) { (e1, e3) = (e3, e1); } if (e1.SqrLength() > e2.SqrLength()) { (e1, e2) = (e2, e1); } //e1 is now the shortest edge, so we just need to check the second and third if (e2.SqrLength() > e3.SqrLength()) { (e2, e3) = (e3, e2); } //The ratio between the shortest and longest edge float edgeLengthRatio = e1.Length() / e3.Length(); //This is a needle if (edgeLengthRatio < NEEDLE_RATIO) { //Debug.Log("We found a needle triangle"); TestAlgorithmsHelpMethods.DebugDrawTriangle(triangle, Color.blue, Color.red, normalizer); //Remove the needle by merging the shortest edge MyVector3 mergePosition = (e1.v.position + e1.prevEdge.v.position) * 0.5f; meshData.ContractTriangleHalfEdge(e1, mergePosition); foundNeedle = true; //Now we have to restart because the triangulation has changed break; } } return(foundNeedle); }
//Generate a Voronoi diagram in 3d space given a Delaunay triangulation in 3d space public static HashSet <VoronoiCell3> GenerateVoronoiDiagram(HalfEdgeData3 delaunayTriangulation) { //If we dont need the voronoi sitePos, which is the center of the voronoi cell, we can use the half-edge data structure //If not we have the create a child class for voronoi HashSet <VoronoiCell3> voronoiDiagram = new HashSet <VoronoiCell3>(); //Step 1. Generate a center of circle for each triangle because this process is slow in 3d space Dictionary <HalfEdgeFace3, Vector3> circleCenterLookup = new Dictionary <HalfEdgeFace3, Vector3>(); HashSet <HalfEdgeFace3> delaunayTriangles = delaunayTriangulation.faces; foreach (HalfEdgeFace3 triangle in delaunayTriangles) { Vector3 p1 = triangle.edge.v.position; Vector3 p2 = triangle.edge.nextEdge.v.position; Vector3 p3 = triangle.edge.nextEdge.nextEdge.v.position; Vector3 circleCenter = _Geometry.CalculateCircleCenter(p1, p2, p3); //https://www.redblobgames.com/x/1842-delaunay-voronoi-sphere/ suggested circleCenter should be moved to get a better surface //But it generates a bad result //float d = Mathf.Sqrt(circleCenter.x * circleCenter.x + circleCenter.y * circleCenter.y + circleCenter.z * circleCenter.z); //MyVector3 circleCenterMove = new MyVector3(circleCenter.x / d, circleCenter.y / d, circleCenter.z / d); //circleCenter = circleCenterMove; circleCenterLookup.Add(triangle, circleCenter); } //Step 2. Generate the voronoi cells HashSet <HalfEdgeVertex3> delaunayVertices = delaunayTriangulation.verts; //In the half-edge data structure we have multiple vertices at the same position, //so we have to track which vertex positions have been added HashSet <Vector3> addedSites = new HashSet <Vector3>(); foreach (HalfEdgeVertex3 v in delaunayVertices) { //Has this site already been added? if (addedSites.Contains(v.position)) { continue; } addedSites.Add(v.position); //This vertex is a cite pos in the voronoi diagram VoronoiCell3 cell = new VoronoiCell3(v.position); voronoiDiagram.Add(cell); //All triangles are fully connected so no null opposite edges should exist //So to generate the voronoi cell, we just rotate clock-wise around each vertex in the delaunay triangulation HalfEdge3 currentEdge = v.edge; int safety = 0; while (true) { //Build an edge going from the opposite face to this face //Each vertex has an edge going FROM it HalfEdgeFace3 oppositeTriangle = currentEdge.oppositeEdge.face; HalfEdgeFace3 thisTriangle = currentEdge.face; Vector3 oppositeCircleCenter = circleCenterLookup[oppositeTriangle]; Vector3 thisCircleCenter = circleCenterLookup[thisTriangle]; VoronoiEdge3 edge = new VoronoiEdge3(oppositeCircleCenter, thisCircleCenter, v.position); cell.edges.Add(edge); //Jump to the next triangle //Each vertex has an edge going FROM it //And we want to rotate around a vertex clockwise //So the edge we should jump over is: HalfEdge3 jumpEdge = currentEdge.nextEdge.nextEdge; HalfEdge3 oppositeEdge = jumpEdge.oppositeEdge; //Are we back where we started? if (oppositeEdge == v.edge) { break; } currentEdge = oppositeEdge; safety += 1; if (safety > 10000) { Debug.Log("Stuck in infinite loop when generating voronoi cells"); break; } } } return(voronoiDiagram); }
public HalfEdgeFace3(HalfEdge3 edge) { this.edge = edge; }
//TODO: //- Calculate the optimal contraction target v and not just the average between two vertices or one of the two endpoints //- Sometimes at the end of a simplification process, the QEM is NaN because the normal of the triangle has length 0 because two vertices are at the same position. This has maybe to do with "mesh inversion." The reports says that you should compare the normal of each neighboring face before and after the contraction. If the normal flips, undo the contraction or penalize it. The temp solution to solve this problem is to set the matrix to zero matrix if the normal is NaN //- The algorithm can also join vertices that are within ||v1 - v2|| < distance, so test to add that. It should merge the hole in the bunny //- Maybe there's a faster (and simpler) way by using unique edges instead of double the calculations for an edge going in the opposite direction? //- A major bottleneck is finding edges going to a specific vertex. The problem is that if there are holes in the mesh, we can't just rotate around the vertex to find the edges - we have to search through ALL edges. In the regular mesh structure, we have a list of all vertices, so moving a vertex would be fast if we moved it in that list, so all edges should reference a vertex in a list? //- Is edgesToContract the correct way to stop the algorithm? Maybe it should be number of vertices in the final mesh? //- Visualize the error by using some color scale. //- Some times when we contract an edge we end up with invalid triangles, such as triangles with area 0. Are all these automatically removed if we weigh each error with triangle area? Or do we need to check that the triangulation is valid after contracting an edge? /// <summary> /// Merge edges to simplify a mesh /// Based on reports by Garland and Heckbert, "Surface simplification using quadric error metrics" /// Is called: "Iterative pair contraction with the Quadric Error Metric (QEM)" /// </summary> /// <param name="halfEdgeMeshData">Original mesh</param> /// <param name="maxEdgesToContract">How many edges do we want to merge (the algorithm stops if it can't merge more edges)</param> /// <param name="maxError">Stop merging edges if the error is bigger than the maxError, which will prevent the algorithm from changing the shape of the mesh</param> /// <param name="normalizeTriangles">Sometimes the quality improves if we take triangle area into account when calculating ther error</param> /// <param name="normalizer">Is only needed for debugging</param> /// <returns>The simplified mesh</returns> /// If you set edgesToContract to max value, then it will continue until it cant merge any more edges or the maxError is reached /// If you set maxError to max value, then it will continue to merge edges until it cant merge or max edgesToContract is reached public static HalfEdgeData3 Simplify(HalfEdgeData3 halfEdgeMeshData, int maxEdgesToContract, float maxError, bool normalizeTriangles = false, Normalizer3 normalizer = null) { System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); // // Compute the Q matrices for all the initial vertices // //Put the result in a lookup dictionary //This assumes we have no floating point precision issues, so vertices at the same position have to be at the same position Dictionary <Vector3, Matrix4x4> qMatrices = new Dictionary <Vector3, Matrix4x4>(); HashSet <HalfEdgeVertex3> vertices = halfEdgeMeshData.verts; //timer.Start(); //0.142 seconds for the bunny (0.012 for dictionary lookup, 0.024 to calculate the Q matrices, 0.087 to find edges going to vertex) foreach (HalfEdgeVertex3 v in vertices) { //Have we already calculated a Q matrix for this vertex? //Remember that we have multiple vertices at the same position in the half-edge data structure //timer.Start(); if (qMatrices.ContainsKey(v.position)) { continue; } //timer.Stop(); //Calculate the Q matrix for this vertex //timer.Start(); //Find all edges meeting at this vertex HashSet <HalfEdge3> edgesPointingToThisVertex = v.GetEdgesPointingToVertex(halfEdgeMeshData); //timer.Stop(); //timer.Start(); Matrix4x4 Q = CalculateQMatrix(edgesPointingToThisVertex, normalizeTriangles); //timer.Stop(); qMatrices.Add(v.position, Q); } //timer.Stop(); // // Select all valid pairs that can be contracted // List <HalfEdge3> validPairs = new List <HalfEdge3>(halfEdgeMeshData.edges); // // Compute the cost of contraction for each pair // HashSet <QEM_Edge> QEM_edges = new HashSet <QEM_Edge>(); //We need a lookup table to faster remove and update QEM_edges Dictionary <HalfEdge3, QEM_Edge> halfEdge_QEM_Lookup = new Dictionary <HalfEdge3, QEM_Edge>(); foreach (HalfEdge3 halfEdge in validPairs) { Vector3 p1 = halfEdge.prevEdge.v.position; Vector3 p2 = halfEdge.v.position; Matrix4x4 Q1 = qMatrices[p1]; Matrix4x4 Q2 = qMatrices[p2]; QEM_Edge QEM_edge = new QEM_Edge(halfEdge, Q1, Q2); QEM_edges.Add(QEM_edge); halfEdge_QEM_Lookup.Add(halfEdge, QEM_edge); } // // Sort all pairs, with the minimum cost pair at the top // //The fastest way to keep the data sorted is to use a heap Heap <QEM_Edge> sorted_QEM_edges = new Heap <QEM_Edge>(QEM_edges.Count); foreach (QEM_Edge e in QEM_edges) { sorted_QEM_edges.Add(e); } // // Start contracting edges // //For each edge we want to remove for (int i = 0; i < maxEdgesToContract; i++) { //Check that we can simplify the mesh //The smallest mesh we can have is a tetrahedron with 4 faces, itherwise we get a flat triangle if (halfEdgeMeshData.faces.Count <= 4) { Debug.Log($"Cant contract more than {i} edges"); break; } // // Remove the pair (v1,v2) of the least cost and contract the pair // //timer.Start(); QEM_Edge smallestErrorEdge = sorted_QEM_edges.RemoveFirst(); //This means an edge in this face has already been contracted //We are never removing edges from the heap after contracting and edges, //so we do it this way for now, which is maybe better? if (smallestErrorEdge.halfEdge.face == null) { //This edge wasn't contracted so don't add it to iteration i -= 1; continue; } if (smallestErrorEdge.qem > maxError) { Debug.Log($"Cant contract more than {i} edges because reached max error"); break; } //timer.Stop(); //timer.Start(); //Get the half-edge we want to contract HalfEdge3 edgeToContract = smallestErrorEdge.halfEdge; //Need to save the endpoints so we can remove the old Q matrices from the pos-matrix lookup table Edge3 contractedEdgeEndpoints = new Edge3(edgeToContract.prevEdge.v.position, edgeToContract.v.position); //Contract edge HashSet <HalfEdge3> edgesPointingToNewVertex = halfEdgeMeshData.ContractTriangleHalfEdge(edgeToContract, smallestErrorEdge.mergePosition, timer); //timer.Stop(); // // Remove all QEM_edges that belonged to the faces we contracted // //This is not needed if we check if an edge in the triangle has already been contracted /* * //timer.Start(); * * //This edge doesnt exist anymore, so remove it from the lookup * halfEdge_QEM_Lookup.Remove(edgeToContract); * * //Remove the two edges that were a part of the triangle of the edge we contracted * RemoveHalfEdgeFromQEMEdges(edgeToContract.nextEdge, QEM_edges, halfEdge_QEM_Lookup); * RemoveHalfEdgeFromQEMEdges(edgeToContract.nextEdge.nextEdge, QEM_edges, halfEdge_QEM_Lookup); * * //Remove the three edges belonging to the triangle on the opposite side of the edge we contracted * //If there was an opposite side... * if (edgeToContract.oppositeEdge != null) * { * HalfEdge3 oppositeEdge = edgeToContract.oppositeEdge; * * RemoveHalfEdgeFromQEMEdges(oppositeEdge, QEM_edges, halfEdge_QEM_Lookup); * RemoveHalfEdgeFromQEMEdges(oppositeEdge.nextEdge, QEM_edges, halfEdge_QEM_Lookup); * RemoveHalfEdgeFromQEMEdges(oppositeEdge.nextEdge.nextEdge, QEM_edges, halfEdge_QEM_Lookup); * } * //timer.Stop(); */ //Remove the edges start and end vertices from the pos-matrix lookup table qMatrices.Remove(contractedEdgeEndpoints.p1); qMatrices.Remove(contractedEdgeEndpoints.p2); //timer.Stop(); // // Update all QEM_edges that is now connected with the new contracted vertex because their errors have changed // //The contracted position has a new Q matrix Matrix4x4 QNew = CalculateQMatrix(edgesPointingToNewVertex, normalizeTriangles); //Add the Q matrix to the pos-matrix lookup table qMatrices.Add(smallestErrorEdge.mergePosition, QNew); //Update the error of the QEM_edges of the edges that pointed to and from one of the two old Q matrices //Those edges are the same edges that points to the new vertex and goes from the new vertex //timer.Start(); foreach (HalfEdge3 edgeToV in edgesPointingToNewVertex) { //The edge going from the new vertex is the next edge of the edge going to the vertex HalfEdge3 edgeFromV = edgeToV.nextEdge; //To QEM_Edge QEM_edgeToV = halfEdge_QEM_Lookup[edgeToV]; Edge3 edgeToV_endPoints = QEM_edgeToV.GetEdgeEndPoints(); Matrix4x4 Q1_edgeToV = qMatrices[edgeToV_endPoints.p1]; Matrix4x4 Q2_edgeToV = QNew; QEM_edgeToV.UpdateEdge(edgeToV, Q1_edgeToV, Q2_edgeToV); sorted_QEM_edges.UpdateItem(QEM_edgeToV); //From QEM_Edge QEM_edgeFromV = halfEdge_QEM_Lookup[edgeFromV]; Edge3 edgeFromV_endPoints = QEM_edgeFromV.GetEdgeEndPoints(); Matrix4x4 Q1_edgeFromV = QNew; Matrix4x4 Q2_edgeFromV = qMatrices[edgeFromV_endPoints.p2]; QEM_edgeFromV.UpdateEdge(edgeFromV, Q1_edgeFromV, Q2_edgeFromV); sorted_QEM_edges.UpdateItem(QEM_edgeFromV); } //timer.Stop(); } //Timers: 0.78 to generate the simplified bunny (2400 edge contractions) (normalizing triangles is 0.05 seconds slower) //Init: // - 0.1 to convert to half-edge data structure // - 0.14 to calculate a Q matrix for each unique vertex //Loop (total time): // - 0.04 to find smallest QEM error // - 0.25 to merge the edges (the bottleneck is where we have to find all edges pointing to a vertex) // - 0.02 to remove the data that was destroyed when we contracted an edge // - 0.13 to update QEM edges //Debug.Log($"It took {timer.ElapsedMilliseconds / 1000f} seconds to measure whatever we measured"); return(halfEdgeMeshData); }
// // Contract an edge if we know we are dealing only with triangles // //Returns all edge pointing to the new vertex public HashSet <HalfEdge3> ContractTriangleHalfEdge(HalfEdge3 e, Vector3 mergePos, System.Diagnostics.Stopwatch timer = null) { //Step 1. Get all edges pointing to the vertices we will merge //And edge is going TO a vertex, so this edge goes from v1 to v2 HalfEdgeVertex3 v1 = e.prevEdge.v; HalfEdgeVertex3 v2 = e.v; //timer.Start(); //It's better to get these before we remove triangles because then we will get a messed up half-edge system? HashSet <HalfEdge3> edgesGoingToVertex_v1 = v1.GetEdgesPointingToVertex(this); HashSet <HalfEdge3> edgesGoingToVertex_v2 = v2.GetEdgesPointingToVertex(this); //timer.Stop(); //Step 2. Remove the triangles, which will create a hole, //and the edges on the opposite sides of the hole are connected RemoveTriangleAndConnectOppositeSides(e); //We might also have an opposite triangle, so we may have to delete a total of two triangles if (e.oppositeEdge != null) { RemoveTriangleAndConnectOppositeSides(e.oppositeEdge); } //Step 3. Move the vertices to the merge position //Some of these edges belong to the triangles we removed, but it doesnt matter because this operation is fast //We can at the same time find the edges pointing to the new vertex HashSet <HalfEdge3> edgesPointingToVertex = new HashSet <HalfEdge3>(); if (edgesGoingToVertex_v1 != null) { foreach (HalfEdge3 edgeToV in edgesGoingToVertex_v1) { //This edge belonged to one of the faces we removed if (edgeToV.face == null) { continue; } edgeToV.v.position = mergePos; edgesPointingToVertex.Add(edgeToV); } } if (edgesGoingToVertex_v2 != null) { foreach (HalfEdge3 edgeToV in edgesGoingToVertex_v2) { //This edge belonged to one of the faces we removed if (edgeToV.face == null) { continue; } edgeToV.v.position = mergePos; edgesPointingToVertex.Add(edgeToV); } } return(edgesPointingToVertex); }
//Connect an edge with an unknown opposite edge which has not been connected //If no opposite edge exists, it means it has no neighbor which is possible if there's a hole public void TryFindOppositeEdge(HalfEdge3 e) { TryFindOppositeEdge(e, edges); }
public QEM_Edge(HalfEdge3 halfEdge, Matrix4x4 Q1, Matrix4x4 Q2) { UpdateEdge(halfEdge, Q1, Q2); }