I'm working on implementing various subdivision algorithms (such as catmull-clark); to do this efficiently requires a good way to store information about a grid of tesselated polygons. I implemented the half-edge data structure as outlined by flipcode, but now I'm not sure how to populate the data structure from vertices!
My initial attempt was to
create vertices
group vertices into faces
sort vertices within faces (using their angle relative to the centroid)
for each face, grab the first vertex and then walk through the sorted vertex list to create a half-edge list.
However, this creates a list of faces (with half-edges) that don't have any information about adjacent faces! This also feels a bit wrong, because it seems as if the faces are really the first-class object and the edges provide auxiliary information; I really feel like I should be creating edges from the vertices and then sorting out the faces from there. But again, I'm not really sure how to go about it that way -- I can't think of a way to create a list of half-edges without creating the faces first.
Any suggestions for what the best way to go turning data about vertices (and faces) into half-edges?
First, I'd like to point you to an excellent C++ implementation of the half-edge data structure: OpenMesh. If you want to use it, make sure you work you way through the tutorial. If (and only if) you do that, working with OpenMesh is quite straightforward. It also contains some nice methods on top of which you can implement subdivision or reduction algorithms.
Now to your question:
However, this creates a list of faces (with half-edges) that don't have any information about adjacent faces! This also feels a bit wrong, because it seems as if the faces are really the first-class object and the edges provide auxiliary information
I think this somewhat misses the point of the half-edge data structure. In a half-edge structure, it is the half-edges that carry the most information!
Quoting shamelessly from the OpenMesh documentation (see also the figure there):
Each vertex references one outgoing halfedge, i.e. a halfedge that starts at this vertex.
Each face references one of the halfedges bounding it.
Each halfedge provides a handle to
the vertex it points to ,
the face it belongs to
the next halfedge inside the face (ordered counter-clockwise) ,
the opposite halfedge ,
(optionally: the previous halfedge in the face ).
As you see, most information is stored in the half-edges - these are the primary objects. Iterating over meshes in this data-structure is all about cleverly following pointers.
However, this creates a list of faces (with half-edges) that don't have any information about adjacent faces!
This is perfectly ok! As you see above, a face references only one bounding half edge. Assuming a triangle mesh, the chain of pointers you follow to get the 3 adjacent triangles to a given face F is the following:
F -> halfEdge -> oppositeHalfEdge -> face
F -> halfEdge -> nextHalfEdge -> oppositeHalfEdge -> face
F -> halfEdge -> previousHalfEdge -> oppositeHalfEdge -> face
Optionally, you can use nextHalfEdge -> nextHalfEdge if you don't use the 'previous' pointers. This, of course, generalizes easily to quads or higher order polygons.
If you set the pointers listed above correctly when building your mesh, then you can iterate over all kinds of adjacencies in your mesh like this. If you use OpenMesh, you can use a bunch of special iterators that to the pointer chasing for you.
Setting the "opposite half edge" pointers is of course the tricky part when building a half-edge structure from a "triangle soup". I suggest to use a map data-structure of some kind to keep track of half-edges already created.
To be more specific, here is some very conceptual pseudo-code for creating a half-edge mesh from faces. I omitted the vertex part, which is simpler, and can be implemented in the same spirit. I assume that iteration over a face edges is ordered (e.g. clock-wise).
I assume half edges are implemented as structs of type HalfEdge, which contain the pointers listed above as members.
struct HalfEdge
{
HalfEdge * oppositeHalfEdge;
HalfEdge * nextHalfEdge;
Vertex * vertex;
Face * face;
}
Let Edges be a map from pairs of vertex identifiers to pointers to the actual half-edge instances, e.g.
map< pair<unsigned int, unsigned int>, HalfEdge* > Edges;
in C++. Here is the construction pseudo-code (without the vertex and face part):
map< pair<unsigned int, unsigned int>, HalfEdge* > Edges;
for each face F
{
for each edge (u,v) of F
{
Edges[ pair(u,v) ] = new HalfEdge();
Edges[ pair(u,v) ]->face = F;
}
for each edge (u,v) of F
{
set Edges[ pair(u,v) ]->nextHalfEdge to next half-edge in F
if ( Edges.find( pair(v,u) ) != Edges.end() )
{
Edges[ pair(u,v) ]->oppositeHalfEdge = Edges[ pair(v,u) ];
Edges[ pair(v,u) ]->oppositeHalfEdge = Edges[ pair(u,v) ];
}
}
}
EDIT: Made the code a bit less pseudo, to be more clear about the Edges map and the pointers.
Consider we have a list of triangles, each of which is specified by 3 vertex IDs in counterclockwise order, and the task is to construct the half-edge data structure representing this triangulation. If the vertices are given as 3d-vectors (as in STL file format) then the works starts from giving unique identifiers to each distinct vertex, which is accomplish via a hash map from 3d-vector to vertex ID.
After that we progressively consider every triangle from the list. And the first thing is to find or create its three edges (each of which consists of a pair of half-edges). If some edge is shared by two triangles and the other triangle was already added in the data structure then we find that edge, otherwise new edge must be created.
To find whether an edge between vertices v1 and v2 already exists, we use a flat map from a vertex to one of half-edges with the origin in it. All other half-edges with the same origin can be enumerated using already constructed half-edge data structure. So the algorithm for this step is to look at every half-edge originating in v1 and test whether its destination is v2. If no such edge is found, then two half-edges must be created. In the terms of flipcode: pair of one created half-edge points on the other, vert on v1 and v2 respectively, and next on existing half-edges in v1 and v2, or if it was the first half-edge in a vertex then on itself.
When all 3 edges of the current triangle are found or created, face field of half-edges having that triangle at the left points to new HE_face record representing the triangle.
After all triangles are passed, the data structure is ready. There are certain optimizations and improvements that can be implemented, but the basic idea is as presented above.
All mesh libraries based on half-edge data structure construct it during mesh opening from a standard file format, such as STL/PLY/OBJ/OFF/… So it is a good idea at least to look at their code, and probably even integrate them in your software instead of creating your own implementation:
OpenMesh is a good C++ library already presented in the other answer.
MeshLib is a younger library also written in C++, which opens standard file formats considerably faster (based on my observations especially STLs); this suggests better optimizations in the conversion (see MRMeshBuilder.cpp) in half-edge data structure (MRMeshTopology.h).
Related
I'm working through the polygon triangulation algorithm in Computational Geometry:
Algorithms and Applications, 3rd edition, by Mark de Berg and others. The data structure used to represent the polygon is called a "doubly-connected edge list". As the book describes, "[it] contains a record for each face, edge, and vertex". Each edge is actually stored as two "half edges", representing each side of the edge. This makes it easier to walk the half edges around a face. The half edge records look like:
// Pseudocode. No particular language. The properties need to be pointers/references of some kind.
struct HalfEdge {
Vertex origin;
HalfEdge twin;
Face incidentFace;
HalfEdge next;
HalfEdge previous;
}
Now imagine I'm processing this polygon, with one face (so far) called Face1. I need to add a diagonal at the dotted line. This will create a new face (Face2). It seems like I need to walk all those HalfEdges that now surround Face2 and set their incidentFace property to point to Face2.
But the book says:
The diagonals computed for the split and merge vertices are added to the doubly-connected edge list. To access the doubly-connected edge list we use cross-pointers between the edges in the status structure and the corresponding edges in the doubly-connected edge list. Adding a diagonal can then be done in constant time with some simple pointer manipulations.
I don't see any further explanation. I'm not sure what a "cross pointer" means here. The "status structure" refers to a binary search tree of edges that is used to easily find the edge to the left of a given vertex, as the polygon is processed from top to bottom.
Can anyone explain this further? How are they able to update all the edges in constant time?
The same book (page 33) says:
Even more important is to realize that in
many applications the faces of the subdivision carry no interesting meaning
(think of the network of rivers or roads that we looked at before). If that is the case, we can completely forget about the face records, and the IncidentFace() field of half-edges. As we will see, the algorithm of the next section doesn’t need these fields (and is actually simpler to implement if we don’t need to update them).
So, you don't need to modify the incidentFace field in any half-edges after each diagonal insertion - you will be able to find vertices of all the monotone polygons using the next field of the HalfEdge record after all the necessary diagonals are inserted into the DCEL.
The most intricate job here is to set next and prev fields of newly inserted half-edges, and to modify these fields in existing half-edges. Exactly four existing half-edges need to be updated after each insertion - but it's not easy to find them.
As you already know, each DCEL vertex record contains a field, pointing to any half-edge, originating in this vertex. If you keep this field pointing to an internal half-edge or most recently inserted half-edge, then it'll be a little bit easier to find half-edges, which need updates in their next and prev fields after each insertion.
I'm trying to implement a vector graphics "drafting" system, where, in essence, users can draw lines on the screen and interact with the regions created by intersecting lines. I'm struggling with determining/evaluating what these regions are.
I've tried a few different solutions to this problem, chiefly keeping a list of edges and running a BFS to find shortest cycles, but this brought up a myriad of issues where the BFS would shortcut in illegal ways, and holes and degenerate edges caused more problems than I could count, so I moved on to a DCEL, half-edge system.
I've read seemingly everything I can on this topic, including two articles referenced frequently on here: http://kaba.hilvi.org/homepage/blog/halfedge/halfedge.htm and http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml. However, neither of these seem to answer this problem that I have when it comes to dynamically adding edges to the graph.
Let's say I start out with this single edge. Image
The half-edges connect with each other in a cycle, and the global, unbounded "outside face" is connected to one of the half edges. Easy, got that.
Then we add another edge, attached to the center vertex: Image
The new half-edges work fine, and we update the edges that flow into v1's next pointers to be the only other edges available that aren't their twins. Again, makes sense to me.
What confuses me to no end is what happens here, when we add a third edge to the center vertex: Image
I know that's what it's supposed to look like and link up to be, but I am so bewildered on how to achieve that programmatically, because I'm not sure how I can determine whether the edge (4,1) should point to edge (1,2), or edge (1,3) (similarly for what edge should point to (1,4)).
The answer seems obvious when looking at the image, but when you try to rationalize it in a robust, airtight algorithmic way, my brain melts and I can't figure it out. The textbook I'm reading (Computational Geometry, Mark de Berg et al., pg 35), just says
"[to test where the edge] should be in the cyclic order of the edges
around vertex v".
The algorithm given in the hilvi.org article for finding the outgoing and incoming edges to link up with doesn't even seem to work, as it will take vertex 1, and follow its outgoing edge's twin until it finds a "free" edge, which in this case, is (2,1) which is wrong. (Unless I'm understanding it incorrectly, I could be understanding this whole problem wrong.)
So I'm absolutely stumped. My only idea now is to create some sort of heading attribute for each half edge, where I measure the angle created by the edge, and choose the edges that way, and maybe that's right, but that seems so against what the half-edge structure seems to support, at least in the articles I'm reading about it, nothing seems to mention anything like that. Any help would be extremely appreciated. I've been on this problem for over a week now and just can't seem to get unstuck.
Right, so I've spent a lot of time thinking about this problem, and to be honest I'm kinda surprised that I can't find a direct answer to this issue. So, in case anyone in the future runs into a similar problem of wanting to populate a half-edge graph from the ground up, here's a solution that works. I don't have a blog, so I'm writing it here.
I have no idea if it's the best answer, but it works in linear time and seems simple to me.
I'll be dealing with the following objects/classes, that vary slightly from the conventional DCEL:
class Vertex {
x;
y;
edges = []; //A list of all Half Edges with their origin at this vertex.
//Technically speaking this could be calculated as needed,
and you could just keep a single outgoing edge, but I'm not
in crucial need of space in my application so I'm just
using an array of all of them.
}
class HalfEdge {
origin; //The Vertex which this half-edge emanates from
twin; // The half-edge pair to this half-edge
face; // The region/face this half-edge is incident to
next; // The half-edge that this half-edge points to
prev; // The half-edge that points to this half-edge
angle; //The number of degrees this hedge is CW from the segment (0, 0) -> (inf, 0)
}
class Face {
outer_edge; //An arbitrary half-edge on the outer boundary defining this face.
inner_edges = []; //A collection of arbitrary half-edges, each defining
//A hole in the face.
global; //A boolean describing if the face is the global face or not.
//This could also be done by having a single "global face" Face instance.
//This is simply how I did it.
}
For initializing a vertex at(x,y):
Verify that a vertex with the given (x,y) coordinates does not already exist. If it does, you don't have to do anything (except maybe return this existing vertex if you're using it immediately).
If it doesn't, allocate space for and create a new vertex with the corresponding x,y values, and with its incident edge null.
For initializing an edge from vertex A to vertex B:
Similarly to many of the articles about this topic, we create two new instances of HalfEdge, one from vertex A to B, one from B to A. They link to each other in that we set their twin, prev, and next pointers all to the other half-edge (hedge).
We also set the angle of the hedge. The angle is calculated clockwise from the positive x-axis. The function I implemented is below. This is super important to making this data structure work properly, and that fact that I haven't read anything in the literature about this being important makes me think there has to be a better way, but I digress.
setAngle(){
const dx = this.destination().x - this.origin.x;
const dy = this.destination().y - this.origin.y;
const l = Math.sqrt(dx * dx + dy * dy);
if (dy > 0) {
this.angle = toDeg(Math.acos(dx / l));
} else {
this.angle = toDeg(Math.PI * 2 - Math.acos(dx / l));
}
function toDeg(rads) {
return 180 * rads / Math.PI;
}
}
Next, we pair the vertices with their new edges by adding them to their Vertex's edge list, and then we sort the edge list by the hedge's angles from smallest (0) to largest (359).
Then and this is the crucial step, in order to link everything up properly, we grab the closest hedge to the new hedge we're trying to link up in CCW order. Basically, wherever our new hedge ends up in the edge list, it's that index - 1 (if index = 0, we return edges[edges.length - 1]). Take that edge's twin, and that becomes our AIn described in the hivli article above. BOut = AIn.next.
We set AIn.next = hedgeAB and similarly, hedgeAB.prev = AIn, then hedgeBA.next = AOut, AOut.prev = hedgeBA. Perform steps 3-5 for the hedgeBA as well, except running the CCW search on vertex B.
Then, if both vertex A and B were "old" vertices, meaning their edge lists now have at least 2 elements each, a new face has potentially been added, and we need to find it (the edge case is having two isolated edges and connecting them to create an unbounded bucket or cap shape)
For initializing a Face:
We need to find all the cycles in a graph. For my first implementation of this, I recalculated all of the cycles every single time, resetting all the faces. This isn't necessary, but it also isn't too expensive, since we're not running a search, everything is in linear time with respect to the number of cycles and number of vertices in each cycle.
To do this, we get a list of all the hedges in the graph. It doesn't really matter how you do this, I decided to keep an array of every hedge that I passed into my cycle-finder function each time.
Then we look through that list, while the list isn't empty, we take the first item and run its cycle, removing every hedge we find along the way from the list, and adding it into a new cycle, which we add to another list
With this new list of cycles, we need to determine whether the cycle is an inside/outside cycle. There are a lot of ways to do this, and the Computational Geometry book mentioned above has a great section about it. The one that I used is to calculate the area defined by each cycle. If the area is >= 0, the cycle is defined by "inside" hedges. Otherwise, it's defined by "outside" hedges.
The last step is to set all the face records, again, the aforementioned textbook has a lot of great details about this, but the basic idea is to basically create a virtual "graph" of these cycles, and connect outside cycles (which are holes in faces), to their corresponding inside cycles, which are the outer boundaries of faces. To do this, you look at the leftmost vertex of the cycle and extend a ray out infinitely to the left, and "connect" the cycle with the first downward-facing hedge of a cycle the ray hits (I'll leave the implementation up to you, I have no idea if my way is the best, in short, I checked every cycle with a leftmost vertex left of the current cycle and calculated the rightmost intersection with the y value of the leftmost vertex of the current cycle, and then checked if that was facing downward).
With this graph of cycles, run a BFS/DFS starting from each "inside-hedge" cycle (not the holes), and create a face with an arbitrary hedge from the inside-hedge cycle as the outer edge, (or null if it's the global face), and an arbitrary hedge from each found hole-cycle to the face's inner components.
Hey presto, that's it. If you check everything every time, that handles everything. It handles face splitting like a charm and is very robust and quick. I don't know if it's right, but it works.
I'm working on an implementation of the Slab Decomposition algorithm, for point location and I'm stuck in one of its final steps.
I have a list of vertexes and also a list of the vertexes' neighbors (for example, neighbor[0] has all vertexes that are connected to the vertex 0).
I can create the slabs described in the algorithm just fine, but after I detect between which line segments a point is, I don't know how to get the whole partition/cycle/face the point is in.
Basically, I have this
And this is what I want
I could just try to detect all cycles, in a brute force manner, but efficiency is important here. Any idea on how I should approach this problem?
All vertexes and line segments come from an input file, so I could order them in a certain way if it helps with the detection.
Thanks in advance
You could store the planar straight-line graph as a doubly connected edge list. The pertinent feature of the DCEL representation is that the base object be a half-edge (each segment gives rise to two oppositely oriented half-edges, with a tail and a head) with two operations:
DNext(HalfEdge e) - returns the next half-edge with the same head as e
in counterclockwise order around the head
Sym(HalfEdge e) - returns the oppositely oriented half-edge
corresponding to the same edge.
Then you can iterate through the half-edges comprising the face with e = Sym(DNext(e)) until e returns to its starting value.
To compute the DCEL representation in the first place is a matter of sorting the half-edges by angle and then linking them together. There's a way to compare the angles of two half-edges using a 2x2 determinant calculation (avoiding an arctangent, if that's relevant to you).
Note: The description became a little longer than expected. Do you know a readable implementation of this algorithm using this mesh? Please let me know!
I'm trying to implement Catmull-Clark subdivision using Matlab, because later on the results have to be compared with some other stuff already implemented in Matlab. First try was with a Vertex-Face mesh, the algorithm works but it is not very efficient, since you need neighbouring information for edges and faces. Therefore, I'm now using a half-edge mesh. See also
Designing a Data Structure for Polyhedral Surfaces, by Lutz Kettner (PDF link on that page).
My problem lies in finding the Twin HalfEdges, I'm just not sure how to do this. Below I'm describing my thoughts on the implementation, trying to keep it concise.
Half-Edge mesh (using indices to Vertices/HalfEdges/Faces):
Vertex (x,y,z,Outgoing_HalfEdge)
HalfEdge (HeadVertex (or TailVertex, which one should I use), Next, Face, Twin).
Face (HalfEdge)
To keep it simple for now, assume that every face is a quadrilateral. The actual mesh is a list of Vertices, HalfEdges and Faces. The new mesh will consist of NewVertices, NewHalfEdges and NewFaces, like this (note: Number_... is the number of ...):
NumberNewVertices: Number_Faces + Number_HalfEdges/2 + Number_Vertices
NumberNewHalfEdges: 4 * 4 * NumberFaces
NumberNewfaces: 4 * NumberFaces
Catmull-Clark:
Find the FacePoint (centroid) of each Face:
--> Just average the x,y,z values of the vertices, save as a NewVertex.
Find the EdgePoint of each HalfEdge:
--> To prevent duplicates (each HalfEdge has a Twin which would result in the same HalfEdge)
--> Only calculate EdgePoints of the HalfEdge which has the lowest index of the Pair.
Update old Vertices
Ok, now all the new Vertices are calculated (however, their Outgoing_HalfEdge is still unknown). Next step to save the new HalfEdges and Faces. This is the part causing me problems!
Loop through each old Face, there are 4 new Faces to be created
(because of the quadrilateral assumption)
First create the 4 new HalfEdges per New Face, starting at the FacePoint to the Edgepoint
Next a new HalfEdge from the EdgePoint to an Updated Vertex
Another new one from the Updated Vertex to the next EdgePoint
Finally the fourth new HalfEdge from the EdgePoint back to the FacePoint.
The HeadVertex of each new HalfEdge is known, the Next HalfEdge too. The Face is also known (since it is the new face you're creating!). Only the Twin HalfEdge is unknown, how should I know this?
By the way, while looping through the Vertices of the new Face, assign the Outgoing_HalfEdge to the Vertices. This is probably the place to find out which HalfEdge is the Twin.
Finally, after the 4 new HalfEdges are created, save the Face with the HalfVertex index the last newly created HalfVertex.
I hope this is clear, if needed I can post my (obviously not-yet-finished) Matlab code.
Edit: Thanks for moving my thread. I posted a link to the source code in a comment, please notice that this implementation considers general polygonal meshes, so not only quadrilateral meshes.
Furthermore, the twins of new HalfEdges 1 and 4 (red numbers in each new Face) are rather easy to find if you consider an old quadrilateral face divided into 4 new Faces (green numbers):
So, how to find the Twins of the 2- and 3 HalfEdges?
It seems the conceptual problem you've had is that you're trying to add half-edges one at a time and then wondering how they add up. Edges, though, are the real unit of modification, so you should always add them in pairs.
To implement (a single pass of) the algorithm, I'll annotate each of the model elements with a "newly created" flag, which indicates whether the element was created as a result of the algorithm. The top-level loop is to iterate on non-modified faces.
First ensure that each of the original edges of the face has been split. While doing this, create a list of each "new" vertex indicent to the face; these are the midpoints.
-- a. To split an edge, we first locate the corresponding half-edge. Create a new vertex. We insert a new pair of half-edges into each linked list, adjusting the endpoints to the new vertex. Mark all four of the half-edges as new as well as the new vertex.
The first stop of subdividing the face is different than the others. Create a new vertex V to be in the middle of the old face and select a new vertex W incident to the face. We'll connect them as follows. Suppose the linked list of edges near W looks like ..aWb... Create a new pair of half edges c and d. Replace W in the linked list with WcVdW to make the list '..aWcVdWb..'. This creates a "floating edge" in the middle of the face. The data structure, however, ensures that we have a linked list of half-edges that represent the inner perimeter of the polygon. Mark vertex W and the half edges c and d as new.
Now for each remaining new vertex, we'll create a new pair of half-edges, but this time each pair will also create a new face. Select the previous ..cVdWb.. linked list sequence. Because all the original edge have been subdivided, that list extends to ..cVdWbXeYf... X is an old vertex and Y is a new one. Create a new pair of half edges g and g that will connect vertices V and Y. Extract the sequence VdWbXeY from the linked list and add g to it to create a new face [VdWbXeYg]. Add the half edge h to connect V and Y in the old face to make ..cVhYf... Mark the new face as new. If there are not more new vertices, we're done. If not, map the names ..cVhYf.. to ..cVdWb.. for iteration.
The notation is kind of nasty, but conceptually its pretty easy. Each of the three steps adds half-edges in pairs; in step 1 by dividing an edge, in steps 2 and 3 by adding them. Each of these additions keeps the incidence invariants of the polyhedron representation intact, which means you get improved locality of modification in the code.
I want to generate random points in a 2D space, this points will be nodes of a planar graph (built using Gabriel graph algorithm or RNG ).
I wrote java code to do this, but I have two hard problem to solve.
1) I need that all edges of the graph are not longer than a given threshold
2) After I want know faces of graph, a face is a collection of nodes connected by edge. A face does not contain within it other nodes. In image below faces are signed by label (F1, F2...)
How to do these two thing ? some algorithms ? There is some way already known?
Below there is an example of the graph that I must to create
http://imageshack.us/photo/my-images/688/immagineps.png/
If you can tolerate some variance in the number of points, then you could modify your Gabriel graph algorithm to be incremental (most of the effort would be making your Delaunay algorithm incremental) and then whenever an edge is too long, insert a random point in the circle having that edge as a diameter.
The most convenient data structures for plane graphs are edge-centric: for example, the doubly-connected edge list and the quad-edge representations. If you're not already using a data structure of this type for the Delaunay step (and I can't imagine why you wouldn't be), you can sort each vertex's outgoing connections by angle. From there, it's easy to implement a function that takes a half-edge and returns the next half-edge on the same face in counterclockwise order. Now iterate through all of the half-edges, and for each half-edge not already visited, iterate around the face until you return to where you started. Label all of the half-edges in the inner iteration as one face.