Data structureintro
Indexed face set
Also called face-vertex mesh, shared vertex representation.
A mesh stored as an array of vertex positions and a list of faces, each given by the indices of its vertices, the form of most mesh files.
- Time
- O(c) boundary-edgesO(n + c) expected buildO(1 + k) expected edge-faces
- Space
- Θ(n + c) extra
- Where
- c = the number of corners, the sum of the face sizes; k = the size of the answer; m = the number of faces; n = the number of vertices
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
An indexed face set stores a polygon mesh as two lists: an array of vertex positions, and a list of faces, where each face is the list of the indices of its vertices in order. Each vertex is stored once and the faces share it by index. This is the form of most mesh files, such as OFF, OBJ and PLY, and the name comes from the IndexedFaceSet node of VRML. The two lists alone answer "which vertices does this face have" in constant time, but not "which faces are next to this face". This page adds an edge table, a hash table from each undirected edge to the faces that use it, which answers the adjacency queries in expected time proportional to the answer and finds the boundary and non-manifold edges.
In plain words
Think of a model made of flat tiles. You write a numbered list of the corner points of all tiles, with each point written one time. Then, for each tile, you write the numbers of its corners in the order you meet them when you go around the tile. Two tiles that touch use the same numbers for their shared corners.
This is all a mesh file needs. To move a point, you change one line, and every tile that uses it moves with it. To find the tiles next to a given tile, you make a second list: for each side of a tile, which tiles use that side. A side that only one tile uses is on the edge of a hole. A side that three or more tiles use is a place where the surface branches.
The abstract type
The structure holds a mesh with vertices and faces. A face is a sequence of distinct vertex indices. The order gives the orientation: by the convention of most formats, the vertices go counterclockwise when the face is seen from outside, so the outward normal follows the right-hand rule. The operations are:
- : make the structure from the positions and the faces .
- : the faces that have as an edge.
- : the faces other than that share an edge with .
- : the faces that have as a vertex.
- : the edges that one face uses. : the edges that three or more faces use.
- : the Euler characteristic of the mesh.
Representation
| field | meaning |
|---|---|
| the position of each vertex | |
| each face as a tuple of vertex indices, in order | |
| a hash map from the key of each edge to the list of its uses : edge of face | |
| for each vertex, the faces that use it |
The first two rows are the file. The last two rows are derived from them, and a program builds them after it reads the file. The key of an edge has no direction, so both faces of an edge use the same entry. The index in a use tells the direction: face goes along the edge from to .
Operations
BUILD(V, F)- 1
E ← empty hash map; VF[v] ← empty list for each vertex v - 2
for each face f, each corner i = 0 .. |F[f]| − 1 do - 3
u ← F[f][i]; v ← F[f][(i + 1) mod |F[f]|] - 4
append (f, i) to E[{u, v}] - 5
append f to VF[u] EDGE-FACES(u, v)- 6
return the faces of the uses in E[{u, v}], or nothing if there is no entry FACE-NEIGHBORS(f)- 7
for each edge e of f, each use (g, j) in E[e] with g ≠ f and g not yet output do output g BOUNDARY-EDGES- 8
return the keys e of E with |E[e]| = 1 EULER- 9
return n − |E| + m
Line L4 puts both directions of an edge in one entry, because the key is the sorted pair. A closed manifold mesh has exactly two uses in each entry. Line L8 lists the edges of the holes, and the same scan with lists the non-manifold edges. Line L9 counts each distinct edge once, because each one is one key of .
The edge table can also test the orientation. Two faces that share an edge are oriented the same way exactly when they go along it in opposite directions. Two uses of an edge in the same direction show a flipped face, which consistent mesh orientation repairs.
Example
A unit square made of two triangles, in the OFF format:
OFF
4 2 0
0 0 0
1 0 0
1 1 0
0 1 0
3 0 1 2
3 0 2 3
The header gives 4 vertices and 2 faces. Each face line starts with the number of its vertices. BUILD makes this edge table:
| edge | uses | count |
|---|---|---|
| 1 | ||
| 1 | ||
| , | 2 | |
| 1 | ||
| 1 |
The diagonal has two uses. Face 0 goes along it from 2 to 0 (edge 2 of ), and face 1 goes from 0 to 2 (edge 0 of ). The directions are opposite, so the two faces have the same orientation. FACE-NEIGHBORS(0) is . The four other edges are boundary edges, and , the value for a disk.
The same square as a triangle soup, the form of an STL file, has 6 vertices, with and written twice, and the faces and . Now no edge has two uses, the faces have no neighbours, and : two separate triangles. Vertex welding merges the duplicate points and gives back the first form.
Correctness
The loop of line L2 keeps this invariant: for each edge , the entry lists, in order, the uses of by the corners scanned so far, and has no empty entry. Line L4 adds each corner to the entry of exactly its own edge. So at the end, each entry lists all uses of its edge, and the keys are exactly the distinct edges. EDGE-FACES, FACE-NEIGHBORS and BOUNDARY-EDGES read these lists, and EULER counts the keys. The full proof is below.
Proof: The edge table and the vertex table of an indexed face set answer the adjacency queries exactlyfull
Setup. The input is a vertex array of length and a face list , where each face has distinct indices in . Edge of is the undirected pair . Write for the list of all pairs such that edge of face is , in the order of the scan.
Claim. After BUILD (lines L1 to L5):
- For each undirected pair , the table entry is , and has no other keys.
- For each vertex , lists the faces that contain , each one time, in increasing order.
So EDGE-FACES (line L6) returns the faces on the edge, FACE-NEIGHBORS (line L7) returns exactly the faces other than that share an edge with , BOUNDARY-EDGES (line L8) returns exactly the edges with one incidence, and line L9 returns of the cell complex.
Proof of 1. The invariant of the loop of line L2 is: after the faces and the first corners of are processed, is the list of the pairs of that come from those corners, in order, and has a key only if this list is not empty. It holds at the start, when is empty. Line L3 computes edge of , and line L4 appends to the entry of exactly that edge, creating the key if it is new. No other entry changes. So the invariant holds after each step, and at the end it is claim 1. The key is normalized to , so the two directions of an edge go to the same entry.
Proof of 2. Line L5 appends to once for each corner of with . The indices of a face are distinct, so this happens exactly once when and never otherwise. Faces are processed in increasing order.
The queries. EDGE-FACES reads and drops the corner index, so by claim 1 it returns the faces with as an edge. FACE-NEIGHBORS visits the entry of each edge of and keeps each face the first time it appears. A face is returned if and only if some edge of has an incidence in , that is, if and only if and share an edge. The set makes each face appear at most once. BOUNDARY-EDGES keeps the keys whose list has length 1, which by claim 1 are the edges used by exactly one corner of one face.
Euler characteristic. The cell complex of the mesh has one 0-cell for each vertex index, one 1-cell for each distinct undirected edge, and one 2-cell for each face. By claim 1 the keys of are exactly the distinct edges, so is . A vertex that no face uses is a 0-cell by itself and adds 1, which is the Euler characteristic of a point.
Termination. BUILD runs line L4 once for each corner, that is times. Each query loops over a finite list. So every operation stops.
Complexity
Let be the number of corners. For a triangle mesh .
- BUILD does hash table insertions, so it takes expected time.
- EDGE-FACES takes expected time for faces on the edge.
- FACE-NEIGHBORS takes expected time proportional to the number of uses of the edges of , which is on a manifold mesh.
- VERTEX-FACES takes time proportional to its answer.
- BOUNDARY-EDGES and EULER take time, or for EULER if the sizes are kept.
- The space is : the positions, the faces, at most edge keys and uses.
The bare file form, without and , uses numbers for the positions and indices for the faces. It is one of the smallest forms with shared vertices. Each adjacency query on it scans all faces, in time.
Variants
- Triangle soup. Each face stores its own coordinates, with no shared indices. STL files use this form. It has no adjacency, and vertex welding is needed to make it an indexed face set.
- Fixed-size faces. For a triangle mesh, the faces are one array of indices. This is the index buffer of a graphics card.
- Corner attributes. OBJ and VRML give each corner its own index into separate normal and texture coordinate arrays, so a vertex can have different normals on the two sides of a crease.
- Edge-based structures. The corner table adds one array of opposite corners to a triangle index array. The doubly connected edge list, the half-edge form, and the winged-edge structure store the adjacency explicitly and allow local edits in constant time.
When to use it
Use it to store and exchange meshes, and to draw them. It is the input of almost every mesh algorithm, and it can hold any mesh, also a mesh with non-manifold edges, holes and flipped faces. Use the edge table when you need adjacency once, for example to find holes, to check that a mesh is closed, or to build a better structure. If a program walks over the mesh many times, or edits it, change to a corner table or a half-edge structure.
Pitfalls
- Indices from 0 or 1. OFF counts vertices from 0, and OBJ counts them from 1 and allows negative indices from the end. A wrong base moves every face by one vertex.
- Duplicate vertices. A file can have two vertices at the same position. The faces then do not share an edge, and the mesh looks closed but has holes in its topology. Weld first.
- Degenerate faces. A face can repeat an index, or have collinear vertices. The structure on this page rejects a repeated index. Collinear vertices give a zero normal and break later geometric tests.
- The edge count of the OFF header. Many writers put 0 there. Do not trust it. Count the keys of .
- Directed edge keys. A key with a direction puts the two faces of an edge in different entries, and every edge looks like a boundary edge.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/indexed-face-set/. The authors are listed in prov/A865QN.jsonl.
"""An indexed face set: vertex positions and faces given as lists of vertex indices.
The class adds an edge table (a hash map from each undirected edge to the
faces that use it) and a vertex-to-face table, so that the adjacency queries
take time proportional to the size of their answer. It also reads and writes
the OFF file format.
"""
from typing import Iterator, Sequence
Edge = tuple[int, int]
def edge_key(u: int, v: int) -> Edge:
"""The key of the undirected edge {u, v}."""
return (u, v) if u < v else (v, u)
class IndexedFaceSet:
"""Vertices and polygonal faces, with edge and vertex incidence tables."""
def __init__(self, vertices: Sequence[Sequence[float]], faces: Sequence[Sequence[int]]) -> None:
"""Build the tables. Each face needs at least 3 distinct vertex indices in range."""
n = len(vertices)
self.vertices: list[tuple] = [tuple(p) for p in vertices]
self.faces: list[tuple[int, ...]] = []
self.edges: dict[Edge, list[tuple[int, int]]] = {} # @line L1
self.vertex_face: list[list[int]] = [[] for _ in range(n)]
for f, face in enumerate(faces): # @line L2
face = tuple(face)
if len(face) < 3 or len(set(face)) != len(face) or min(face) < 0 or max(face) >= n:
raise ValueError(f"face {f} is not a valid polygon: {face}")
self.faces.append(face)
k = len(face)
for i in range(k):
u, v = face[i], face[(i + 1) % k] # @line L3
self.edges.setdefault(edge_key(u, v), []).append((f, i)) # @line L4
self.vertex_face[u].append(f) # @line L5
def edge_faces(self, u: int, v: int) -> list[int]:
"""The faces that use the edge {u, v}, with repeats if a face uses it twice."""
return [f for f, _ in self.edges.get(edge_key(u, v), [])] # @line L6
def face_edges(self, f: int) -> Iterator[Edge]:
face = self.faces[f]
k = len(face)
for i in range(k):
yield edge_key(face[i], face[(i + 1) % k])
def face_neighbors(self, f: int) -> list[int]:
"""The faces other than f that share an edge with f, each listed once."""
out: list[int] = []
seen = {f}
for e in self.face_edges(f): # @line L7
for g, _ in self.edges[e]:
if g not in seen:
seen.add(g)
out.append(g)
return out
def vertex_faces(self, v: int) -> list[int]:
"""The faces that have v as a vertex."""
return list(self.vertex_face[v])
def boundary_edges(self) -> list[Edge]:
"""The edges that exactly one face uses."""
return [e for e, uses in self.edges.items() if len(uses) == 1] # @line L8
def non_manifold_edges(self) -> list[Edge]:
"""The edges that three or more faces use."""
return [e for e, uses in self.edges.items() if len(uses) >= 3]
def euler_characteristic(self) -> int:
"""V - E + F of the cell complex. An unused vertex counts as a point."""
return len(self.vertices) - len(self.edges) + len(self.faces) # @line L9
def to_off(self) -> str:
"""The mesh in the OFF text format."""
lines = ["OFF", f"{len(self.vertices)} {len(self.faces)} {len(self.edges)}"]
lines += [" ".join(repr(c) for c in p) for p in self.vertices]
lines += [" ".join(str(x) for x in (len(face),) + face) for face in self.faces]
return "\n".join(lines) + "\n"
def _number(token: str) -> float:
try:
return int(token)
except ValueError:
return float(token)
def read_off(text: str) -> IndexedFaceSet:
"""Parse an OFF file. Comments start with #. The edge count of the header is ignored."""
tokens: list[str] = []
for line in text.splitlines():
tokens += line.split("#", 1)[0].split()
if not tokens or tokens[0] != "OFF":
raise ValueError("not an OFF file")
nv, nf = int(tokens[1]), int(tokens[2])
pos = 4
vertices = []
for _ in range(nv):
vertices.append(tuple(_number(t) for t in tokens[pos:pos + 3]))
pos += 3
faces = []
for _ in range(nf):
k = int(tokens[pos])
faces.append(tuple(int(t) for t in tokens[pos + 1:pos + 1 + k]))
pos += 1 + k
return IndexedFaceSet(vertices, faces)
test_indexed_face_set.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/indexed-face-set/. The authors are listed in prov/A865QN.jsonl.
import random
from indexed_face_set import IndexedFaceSet, read_off
# ---- brute force: scan every face for every query ----
def scan_edges(face):
k = len(face)
return [(face[i], face[(i + 1) % k]) for i in range(k)]
def brute_edge_faces(faces, u, v):
return [f for f, face in enumerate(faces) for a, b in scan_edges(face) if {a, b} == {u, v}]
def brute_neighbors(faces, f):
mine = {frozenset(e) for e in scan_edges(faces[f])}
return {g for g, face in enumerate(faces) if g != f and mine & {frozenset(e) for e in scan_edges(face)}}
def brute_vertex_faces(faces, v):
return [f for f, face in enumerate(faces) if v in face]
def brute_edge_set(faces):
return {frozenset(e) for face in faces for e in scan_edges(face)}
def rand_mesh(rng, n, nf):
faces = []
for _ in range(nf):
k = rng.choice((3, 3, 3, 4, 5))
faces.append(tuple(rng.sample(range(n), min(k, n))))
verts = [(rng.randint(-9, 9), rng.randint(-9, 9), rng.randint(-9, 9)) for _ in range(n)]
return verts, faces
# ---- tests ----
def test_page_example_square():
m = IndexedFaceSet([(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2), (0, 2, 3)])
assert m.edges[(0, 2)] == [(0, 2), (1, 0)]
assert m.edge_faces(2, 0) == [0, 1]
assert sorted(m.boundary_edges()) == [(0, 1), (0, 3), (1, 2), (2, 3)]
assert m.face_neighbors(0) == [1]
assert m.vertex_faces(0) == [0, 1]
assert m.euler_characteristic() == 1
def test_page_example_soup():
pts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 0, 0), (1, 1, 0), (0, 1, 0)]
m = IndexedFaceSet(pts, [(0, 1, 2), (3, 4, 5)])
assert m.face_neighbors(0) == []
assert len(m.boundary_edges()) == 6
assert m.euler_characteristic() == 2
def test_closed_meshes():
tet = IndexedFaceSet([(0, 0, 0)] * 4, [(0, 2, 1), (0, 1, 3), (1, 2, 3), (0, 3, 2)])
assert tet.euler_characteristic() == 2 and tet.boundary_edges() == []
cube = IndexedFaceSet([(0, 0, 0)] * 8, [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
(1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
assert cube.euler_characteristic() == 2 and cube.boundary_edges() == []
assert all(len(cube.face_neighbors(f)) == 4 for f in range(6))
a, b = 4, 5
faces = []
for i in range(a):
for j in range(b):
p, q = i * b + j, ((i + 1) % a) * b + j
r, s = ((i + 1) % a) * b + (j + 1) % b, i * b + (j + 1) % b
faces += [(p, q, r), (p, r, s)]
torus = IndexedFaceSet([(0, 0, 0)] * (a * b), faces)
assert torus.euler_characteristic() == 0 and torus.boundary_edges() == []
def test_non_manifold_edge():
# three triangles on one edge {0, 1}
m = IndexedFaceSet([(0, 0, 0)] * 5, [(0, 1, 2), (1, 0, 3), (0, 1, 4)])
assert m.non_manifold_edges() == [(0, 1)]
assert sorted(m.edge_faces(0, 1)) == [0, 1, 2]
def test_invalid_faces():
for bad in ([(0, 1)], [(0, 1, 1)], [(0, 1, 3)]):
try:
IndexedFaceSet([(0, 0, 0)] * 3, bad)
except ValueError:
continue
raise AssertionError(f"accepted {bad}")
def test_off_round_trip():
text = "OFF\n# a square\n4 2 0\n0 0 0\n1 0 0\n1.5 1 0\n0 1 -2.25\n3 0 1 2\n3 0 2 3\n"
m = read_off(text)
assert m.vertices[2] == (1.5, 1, 0) and m.faces == [(0, 1, 2), (0, 2, 3)]
m2 = read_off(m.to_off())
assert m2.vertices == m.vertices and m2.faces == m.faces
rng = random.Random(11)
verts = [(rng.random(), rng.uniform(-1e9, 1e9), rng.randint(-5, 5)) for _ in range(20)]
faces = [tuple(rng.sample(range(20), 3)) for _ in range(15)]
m3 = read_off(IndexedFaceSet(verts, faces).to_off())
assert m3.vertices == verts and m3.faces == faces
def test_against_brute_force_random():
rng = random.Random(2024)
for _ in range(600):
n = rng.randint(3, 9)
verts, faces = rand_mesh(rng, n, rng.randint(1, 10))
m = IndexedFaceSet(verts, faces)
for u in range(n):
for v in range(n):
if u != v:
assert sorted(m.edge_faces(u, v)) == sorted(brute_edge_faces(faces, u, v))
assert m.vertex_faces(u) == brute_vertex_faces(faces, u)
for f in range(len(faces)):
got = m.face_neighbors(f)
assert len(got) == len(set(got)) and set(got) == brute_neighbors(faces, f)
edges = brute_edge_set(faces)
counts = {e: sum(1 for face in faces for x in scan_edges(face) if frozenset(x) == e) for e in edges}
assert {frozenset(e) for e in m.boundary_edges()} == {e for e, c in counts.items() if c == 1}
assert {frozenset(e) for e in m.non_manifold_edges()} == {e for e, c in counts.items() if c >= 3}
assert m.euler_characteristic() == n - len(edges) + len(faces)
assert read_off(m.to_off()).faces == m.faces
History
The format of a vertex list and a face list of indices is as old as computer graphics. The name comes from the IndexedFaceSet node of Silicon Graphics' Open Inventor, which VRML took over in its 1.0 version in 1995. The VRML97 standard, ISO/IEC 14772-1:1997, defines the node with the fields coord and coordIndex, where the index ends a face. Botsch and others describe it as the face-based data structure, the simplest of the mesh data structures.
References
- Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez and Bruno Lévy, Polygon Mesh Processing, AK Peters, 2010, Chapter 2, Mesh Data Structures, Section 2.1, Face-Based Data Structures
- The Virtual Reality Modeling Language, ISO/IEC 14772-1:1997, Chapter 6, Node Reference, Section 6.23, IndexedFaceSet (the coord and coordIndex fields, and the ccw field for the vertex order)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag A865QN Edit this page History Report an error Markdown