Sub topic 13
Adjacency queries and the half-edge structure
This chapter assumes you know the indexed face set from earlier in the tutorial (a vertex list plus face index lists), the idea of winding order, and the boundary and manifold checks based on counting faces per edge. You should also be able to read short Python classes.
Why adjacency matters
An indexed face set answers one question cheaply: which vertices make up this face? Many modeling operations ask the opposite kind of question:
- Which faces touch this vertex?
- Which vertices are connected to this vertex by an edge?
- Which face lies across this edge?
- What is the boundary loop that this edge belongs to?
Smoothing, subdivision, edge loops, bevels, and hole filling all depend on these queries. They are called adjacency queries: they ask about elements that share an element.
With only vertices and faces, every such query scans all faces. That costs O(F) per query, and a smoothing pass that asks the question for every vertex costs O(V·F). On a mesh with a million faces, that is far too slow.
Option 1: precomputed lookup tables
The simplest fix is to build dictionaries once and then query them in constant time.
from collections import defaultdict
def build_tables(faces):
edge_faces = defaultdict(list) # undirected edge -> faces using it
vertex_faces = defaultdict(list) # vertex -> faces using it
for f, face in enumerate(faces):
n = len(face)
for i in range(n):
a, b = face[i], face[(i + 1) % n]
edge_faces[(min(a, b), max(a, b))].append(f)
vertex_faces[a].append(f)
return edge_faces, vertex_facesBuilding both tables is linear in the number of face corners. After that, "which faces share this edge?" is one dictionary lookup, and len(edge_faces[e]) gives the same counts used for the boundary and manifold checks.
The tables have two weaknesses.
- They are unordered.
vertex_faces[v]tells you which faces touchv, but not their order aroundv. Many algorithms need to walk around a vertex in sequence. - They are rebuilt after edits. Splitting an edge or deleting a face changes several lists. Keeping the tables correct by hand is error-prone, so most code rebuilds them from scratch.
Option 2: the half-edge structure
The half-edge structure stores each undirected edge as two directed halves, one for each face that borders it. Each half-edge belongs to exactly one face and records its neighbors through pointers. In practice these pointers are indices into arrays.
Every half-edge h stores:
origin: the vertex it starts from.face: the face on its left, which is the face whose winding produced this direction.next: the following half-edge in the same face loop.prev: the preceding half-edge in the same face loop.twin: the half-edge running the opposite way along the same edge, which belongs to the neighboring face. It is-1on a boundary.
The destination of h is not stored. It is origin[next[h]].
The key property is that walking next repeatedly circles a face. Walking twin crosses to the neighbor face. Combining the two moves, twin[prev[h]], rotates around the origin vertex of h. That single combination answers most vertex queries.
Building half-edges from a face list
The builder below creates one half-edge per face corner. A dictionary from directed edge (a, b) to half-edge index lets it connect twins in a second pass.
class HalfEdgeMesh:
def __init__(self, faces):
self.origin, self.face, self.next, self.prev = [], [], [], []
self.face_start = [] # first half-edge of each face
lookup = {} # directed edge (a, b) -> half-edge index
for f, loop in enumerate(faces):
n = len(loop)
start = len(self.origin)
self.face_start.append(start)
for i in range(n):
a, b = loop[i], loop[(i + 1) % n]
if (a, b) in lookup:
raise ValueError(f"directed edge {(a, b)} used twice")
lookup[(a, b)] = start + i
self.origin.append(a)
self.face.append(f)
self.next.append(start + (i + 1) % n)
self.prev.append(start + (i - 1) % n)
self.twin = [-1] * len(self.origin)
for (a, b), h in lookup.items():
self.twin[h] = lookup.get((b, a), -1)
self.vertex_he = {} # one outgoing half-edge per vertex
for h, v in enumerate(self.origin):
self.vertex_he.setdefault(v, h)
def dest(self, h):
return self.origin[self.next[h]]
def face_loop(self, f):
"""Half-edges around face f, in winding order."""
start = h = self.face_start[f]
while True:
yield h
h = self.next[h]
if h == start:
return
def outgoing(self, v):
"""All half-edges leaving vertex v, rotating around v."""
start = h = self.vertex_he[v]
while True:
yield h
t = self.twin[self.prev[h]]
if t == -1:
break # hit a boundary going one way
h = t
if h == start:
return # full circle: interior vertex
h = start # boundary vertex: go the other way
while True:
t = self.twin[h]
if t == -1:
return
h = self.next[t]
yield h
def vertex_neighbors(self, v):
out = set()
for h in self.outgoing(v):
out.add(self.dest(h))
out.add(self.origin[self.prev[h]])
return sorted(out)
def face_neighbors(self, f):
return sorted(self.face[self.twin[h]]
for h in self.face_loop(f) if self.twin[h] != -1)The second add in vertex_neighbors matters only at a boundary. The last half-edge arriving at the vertex has no twin, so its origin is a neighbor that no outgoing half-edge points to.
Now run it on the cube from earlier in the tutorial and on an open mesh made of two triangles.
cube_faces = [
(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
(3, 7, 6, 2), (0, 4, 7, 3), (1, 2, 6, 5),
]
cube = HalfEdgeMesh(cube_faces)
print(cube.vertex_neighbors(0)) # [1, 3, 4]
print(cube.face_neighbors(0)) # [2, 3, 4, 5]
open_mesh = HalfEdgeMesh([(0, 1, 2), (0, 2, 3)])
print(open_mesh.vertex_neighbors(0)) # [1, 2, 3]
print(open_mesh.twin) # [-1, -1, 3, 2, -1, -1]The cube's bottom face has four neighbors and does not touch the top face, so [2, 3, 4, 5] is correct. In the open mesh, only the shared diagonal has twins. Every other half-edge shows -1, which marks the boundary.
What each query costs
| Query | Face list scan | Lookup tables | Half-edge |
|---|---|---|---|
| Vertices of a face | O(1) | O(1) | O(k), k = face size |
| Faces around a vertex | O(F) | O(1), unordered | O(d), ordered, d = vertex degree |
| Face across an edge | O(F) | O(1) | O(1) via `twin` |
| Boundary edges | O(F) | O(E) | O(E), or follow `twin == -1` loops |
| Memory per corner | 1 index | several list entries | about five integers |
The half-edge structure pays for its ordered traversal with memory and with a stricter input requirement.
Boundaries and the `-1` twin
A boundary half-edge has no twin because only one face uses that edge. You can follow a boundary loop by starting at a half-edge h with twin[h] == -1, moving to next[h], and then rotating around its origin until you find another half-edge with no twin. Many implementations avoid this search by adding an extra "outside" face with its own half-edges, so every real half-edge has a twin. That removes special cases from the traversal code at the cost of one fake face per hole.
Failure modes
The half-edge structure assumes a clean, manifold, consistently wound mesh. When the input breaks that assumption, the failure usually appears in one of these forms.
- Inconsistent winding. Two neighboring faces traverse their shared edge in the same direction. The builder sees the same directed edge
(a, b)twice and raises an error. This is the same condition thatcheck_edgesreported asinconsistent. - Edge shared by three or more faces. Three faces cannot all pair up. Whatever their winding, at least two use the same direction, so the builder rejects it. The half-edge structure cannot represent this edge, because each half-edge has only one
twinslot. - Bowtie vertices. Two fans of faces meet at a single vertex with no shared edge. Every edge is still manifold, so the builder accepts the mesh. But
vertex_he[v]points into only one fan, andoutgoing(v)never reaches the other. Neighbor lists for this vertex are silently incomplete. Detect it by comparing the number of half-edges thatoutgoing(v)visits with the total number of half-edges whose origin isv. - Duplicate vertices at the same position. Two vertices with identical coordinates but different indices make a visible seam into an open boundary. Topologically the surface is torn, even though it looks continuous. Welding vertices by position fixes this.
- Stale structure after edits. If you change
facesafter building the half-edge arrays, the pointers no longer match. Either rebuild or use operations that update all affected pointers together.
Choosing a representation
- Use the plain indexed face set for storage, file formats, and GPU upload. It is compact and what renderers consume.
- Use lookup tables when you need a few unordered queries on a mesh that does not change, such as finding boundary edges once.
- Use half-edges when an algorithm walks around vertices or faces repeatedly, or edits topology. Smoothing, subdivision, and edge-loop selection fit here.
- Convert between them freely. Building half-edges from a face list is linear, and the face list can be regenerated from
face_loop.
Other connectivity structures exist, such as winged-edge and corner tables for triangle meshes. They store similar information with different trade-offs. Half-edge is the most common general-purpose choice for polygon meshes with mixed face sizes.
Exercise
In the half-edge structure, h runs from vertex a to vertex b in face f. Which expression gives the half-edge that leaves a in the neighboring face on the other side of the edge arriving at a? Explain why it works.
Show answer
twin[prev[h]]. The half-edge prev[h] runs from some vertex z to a in the same face f. Its twin runs the opposite way along the same edge, from a to z, and belongs to the neighboring face. That half-edge also leaves a, so repeating this step rotates around a through all the faces that touch it.
Exercise
A mesh has two triangles, (0, 1, 2) and (2, 1, 3), sharing the edge between vertices 1 and 2. Does HalfEdgeMesh accept it? If not, what is the problem and what change fixes it?
Show answer
It does not accept it. The first face uses the directed edge (1, 2), and the second face (2, 1, 3) uses (1, 3), (3, 2) and (2, 1). Looking at the shared edge again: the first face has 1 to 2, and the second has 2 to 1, so the directions are opposite and the builder accepts it. The mesh is therefore valid, and twin pairs the two half-edges. A mesh that fails would be (0, 1, 2) with (1, 2, 3), where both faces use the directed edge (1, 2). Flipping the second face to (3, 2, 1) restores consistent winding.