Algorithm Search⌘K

Algorithmresearch

B-rep reconstruction from segmented scans

Also called boundary model reconstruction.

Benko, Martin and Varady's pipeline that fits faces to segments, computes edges and vertex blends between them and stitches a consistent B-rep.

Time
Θ(m k + F³ + T m + T V + a V log V + F E) worst
Space
Θ(m + F² + V + E) extra
Where
E = the number of edges; F = the number of regions; T = the number of triangles of the adjacency graph; V = the number of vertices; a = the number of adjacent pairs; k = the largest number of points in the 27 grid cells around one cell; m = the number of points
Properties
deterministicnot exactiterative
Origin
Pál Benkő, Ralph R. Martin, Tamás Várady, 2001

B-rep reconstruction from segmented scans is the last step of reverse engineering: it turns a point cloud that is already cut into regions, one region per face, into a boundary representation with faces, edges, vertices and their connections. Benkő, Martin and Várady (2001) described the full procedure for conventional engineering parts. Each region gets a surface by geometric fitting; two faces are neighbors when their regions touch; the edge of two neighbors lies on the curve where their surfaces meet; a vertex lies where three or more faces meet; blends and vertex blends are fitted in the gaps between the faces; and the pieces are stitched into one closed model whose topology is consistent. This page gives the core of that procedure for parts with planar faces and sharp edges, where every step is exact: fit a plane to each region, find the adjacent pairs, intersect planes into edge lines and vertices, cut the lines into edges, and close the face loops. The output is checked with the Euler formula.

In plain words

A scanner gives many points on the surface of a part, and an earlier step has sorted them into groups, one group for each flat side. Now a CAD model must be built. First, a flat plane is laid through each group. Then the method looks for groups that come close to each other: these sides touch, so they share an edge. Two touching planes cross in a straight line, and the edge lies on that line. Where three touching sides meet, their planes cross in one point, a corner, if the scan really comes close to that point. The corners cut each line into edges, and the edges of a side close into a ring around it. In the end the method counts corners, edges and sides, to check that the model is a closed solid.

The problem

Input. Regions R1,…,RFR_1, \dots, R_F of points in space, where region RfR_f samples one planar face ff of a solid, as a segmentation into primitives gives them; a distance δ\delta such that points of two faces that share an edge come within δ\delta of each other; a distance η\eta such that every corner has points of each of its faces within η\eta.

Output. A boundary model: a plane nf⋅x=cfn_f \cdot x = c_f with a unit normal nfn_f for each face; the set AA of adjacent pairs of faces; vertices with the set of faces that meet at each; edges, each a pair of vertices with the two faces that meet along it; and for each face the cycle of its vertices around the boundary, or an empty loop if its edges do not close.

The algorithm

  1. BREP-FROM-SEGMENTS(R_1..R_F, δ, η)
  2. 1for each region R_f: P_f ← the plane that minimizes the sum of squared orthogonal distances to R_f
  3. 2A ← the pairs {j, k} with some p in R_j and q in R_k and |p − q| ≤ δ
  4. 3for each {j, k} in A: ℓ_jk ← the line P_j ∩ P_k (none if the planes are nearly parallel)
  5. 4for each triangle {j, k, l} of the graph A: v ← P_j ∩ P_k ∩ P_l; keep v if R_j, R_k and R_l each have a point within η of v
  6. 5merge kept vertices within η of each other; a merged vertex gets the union of the face sets
  7. 6for each {j, k} in A: sort the vertices whose faces include j and k along ℓ_jk; join them in consecutive pairs into edges
  8. 7for each face f: loop_f ← the cycle formed by the edges of f, or empty if they do not form one cycle
  9. 8return the planes, A, the vertices, the edges and the loops

Line L1. The plane goes through the centroid of the region, with the normal along the eigenvector of the smallest eigenvalue of the covariance matrix, as in principal component analysis. It minimizes the sum of the squared orthogonal distances, which is the geometric distance; for a plane with a unit normal the algebraic distance n⋅x−cn \cdot x - c is the same as the geometric one, so this fit has none of the bias of algebraic fits of curved primitives.

Line L2. The points go into a grid of cubes of side δ\delta with spatial hashing; two points within δ\delta lie in the same cube or in two cubes that touch, so each point is compared only with the points of 2727 cubes. This is a fixed-radius near neighbors search.

Lines L3 and L4. With d=nj×nkd = n_j \times n_k, the line Pj∩PkP_j \cap P_k has the direction dd and passes through x0=(cj(nk×d)+ck(d×nj))/∣d∣2x_0 = (c_j (n_k \times d) + c_k (d \times n_j)) / \lvert d \rvert^2, which satisfies both plane equations. The vertex of three planes solves the 3×33 \times 3 system with the rows nj,nk,nln_j, n_k, n_l; it is rejected when the determinant is near 00. The nearness test of line L4 keeps only the corners that the scan supports: three faces can be pairwise adjacent without a common corner, for example the three sides of a triangular prism, whose planes have no common point.

Lines L5 to L7. At a corner where four or more faces meet, several triangles give the same point, and line L5 joins them. A line can carry several edges of the same two faces when the faces touch at more than one place; consecutive vertices along the line, taken in pairs, give them. A face without holes has a boundary that is one cycle, which line L7 follows.

Example

The box [0,2]×[0,1]×[0,0.5][0, 2] \times [0, 1] \times [0, 0.5] is sampled at the centers of square cells of side s=0.1s = 0.1 on each face: 5050 points on each of the two faces x=0x = 0 and x=2x = 2, 100100 on y=0y = 0 and y=1y = 1, and 200200 on z=0z = 0 and z=0.5z = 0.5, 700700 points in all. The points nearest to an edge are at distance s/2s/2 from it on both faces, so the gap across an edge is s/2≈0.0707s / \sqrt 2 \approx 0.0707; opposite faces are at least 0.50.5 apart. So any δ\delta in [0.0707,0.5)[0.0707, 0.5) gives the true adjacency, and the run uses δ=η=0.15\delta = \eta = 0.15.

step result
L1 six planes, for example x=0x = 0 with the normal (1,0,0)(1, 0, 0), exact to the last digit
L2 1212 adjacent pairs: each face with the four faces that are not opposite to it
L3 1212 lines, for example y=0,z=0y = 0, z = 0 along the xx axis for the faces y=0y = 0 and z=0z = 0
L4 88 triangles of the graph, one from each of the pairs x=0x = 0 or 22, y=0y = 0 or 11, z=0z = 0 or 0.50.5; each corner has points within 0.07070.0707 on its three faces, so all 88 are kept
L5 no merge: the corners are at least 0.50.5 apart
L6 each line carries 22 corners, which give 11 edge: 1212 edges
L7 each face has a loop of 44 corners, for example (0,0,0),(0,1,0),(2,1,0),(2,0,0)(0,0,0), (0,1,0), (2,1,0), (2,0,0) on z=0z = 0

So V−E+F=8−12+6=2V - E + F = 8 - 12 + 6 = 2. The tests compare this result with the true box: the same 1212 adjacent pairs, the same 88 corners within 10−1210^{-12} with the same face sets, and the same 1212 edges with the same two faces each.

Rigid motions and noise. For 2020 boxes with random sides between 0.50.5 and 22, a random rotation and a random shift, sampled with s=0.1s = 0.1, δ=0.15\delta = 0.15 and η=0.2\eta = 0.2, and Gaussian noise of standard deviation σ\sigma on every coordinate, the code gave these results (seed 77):

σ\sigma boxes with the true adjacency, corners and edges largest corner error
00 2020 of 2020 2.2×10−152.2 \times 10^{-15}
0.0020.002 2020 of 2020 0.001950.00195
0.010.01 2020 of 2020 0.00950.0095
0.030.03 2020 of 2020 0.0270.027

These are measurements with the code of this page on these boxes, not a bound. The noise-free row agrees with the theorem below up to rounding; the other rows are not covered by it.

A concave edge. An L-shaped prism, the L [0,2]×[0,0.5]∪[0,0.5]×[0,1.5][0, 2] \times [0, 0.5] \cup [0, 0.5] \times [0, 1.5] extruded to the height 11, has 88 faces. The code finds 1212 corners, 1818 edges and 88 faces, loops of 66 corners on the two L-shaped faces and of 44 on the six sides, and V−E+F=2V - E + F = 2. The two faces at the concave edge are adjacent because their points come within s/2s / \sqrt 2 of each other inside the corner.

Correctness

The correctness file proves, in exact arithmetic, that the algorithm stops, and that it returns exactly the faces, the adjacency, the vertices, the edges and the face loops of a polyhedron when the data are exact and the two distances separate the right things:

  • every region lies on the plane of its face and has three points that are not on one line;
  • two faces that share an edge have points within δ\delta, and two faces that do not have none;
  • each vertex is simple, with exactly three faces, has points of each of its faces within η\eta, and is more than η\eta from every other vertex; for three pairwise adjacent faces without a common vertex, the planes have no common point or it is farther than η\eta from one of the regions;
  • two faces share at most one edge, faces are disks, and the thresholds of lines L3 and L4 are below the angles of the true edges and vertices.

Then the result has the same numbers of vertices, edges and faces as the polyhedron, so V−E+F=2V - E + F = 2 holds exactly when the polyhedron has no handles. The tests check this on random boxes (2020 of 2020 exact) and on the L-shaped prism. Not proved: anything for noisy data, where the corners move with the planes and δ\delta and η\eta can join or split faces and corners.

Proof: From exact samples of a polyhedron with simple vertices, the algorithm stops and returns its planes, adjacency, vertices, edges and face loopsfull

Setup. PP is a closed polyhedron with faces 1,…,F1, \dots, F. Each face ff is a polygon without holes in the plane Πf={x:nf⋅x=cf}\Pi_f = \{x : n_f \cdot x = c_f\} with ∣nf∣=1\lvert n_f \rvert = 1. An edge of PP is a segment between two distinct vertices and lies in exactly two faces. The input regions R1,…,RFR_1, \dots, R_F and the distances δ,η\delta, \eta satisfy:

  • H1. RfR_f lies on face ff and has three points that are not on one line.
  • H2. For faces j≠kj \ne k: some p∈Rjp \in R_j and q∈Rkq \in R_k have ∣p−q∣≤δ\lvert p - q \rvert \le \delta if and only if jj and kk share an edge.
  • H3. Every vertex vv is simple: exactly three faces contain it, and for each pair of them exactly one edge at vv lies in both. Two faces share at most one edge. Each of the three regions of the faces at vv has a point within η\eta of vv, and distinct vertices are more than η\eta apart.
  • H4. If three faces pairwise share an edge but no vertex lies on all three, then their planes have no unique common point, or that point is farther than η\eta from one of the three regions.
  • H5. At every edge between faces jj and kk, ∣nj×nk∣\lvert n_j \times n_k \rvert is at least the threshold of line L3, and at every vertex with faces j,k,lj, k, l, ∣det⁡(nj,nk,nl)∣\lvert \det(n_j, n_k, n_l) \rvert is at least the threshold of line L4.

Arithmetic is exact, and the 3×33 \times 3 symmetric eigenproblem of line L1 is solved exactly, as on the real RAM.

Lemma 1 (line L1). Under H1, line L1 returns the plane Πf\Pi_f, as (nf,cf)(n_f, c_f) or (−nf,−cf)(-n_f, -c_f).

Proof. Let cc be the centroid of RfR_f and C=∑p∈Rf(p−c)(p−c)TC = \sum_{p \in R_f} (p - c)(p - c)^\mathsf{T}. Every p−cp - c lies in the plane Πf\Pi_f moved to the origin, so (p−c)⋅nf=0(p - c) \cdot n_f = 0 and Cnf=0C n_f = 0. For a unit u⊥nfu \perp n_f, uTCu=∑((p−c)⋅u)2u^\mathsf{T} C u = \sum ((p - c) \cdot u)^2; if this were 00, every p−cp - c would be orthogonal to uu and to nfn_f, so all points would lie on the line through cc with the direction nf×un_f \times u, against H1. So CC is positive semidefinite, 00 is a simple eigenvalue with the eigenvectors ±nf\pm n_f, and all other eigenvalues are positive. The eigenvector of the smallest eigenvalue is ±nf\pm n_f, and the offset is ±nf⋅c=±cf\pm n_f \cdot c = \pm c_f, since cc lies in Πf\Pi_f. □\square

Lemma 2 (line L2). Line L2 returns exactly the pairs j<kj < k with p∈Rjp \in R_j, q∈Rkq \in R_k and ∣p−q∣≤δ\lvert p - q \rvert \le \delta. Under H2 this is the set of pairs of faces that share an edge.

Proof. The code puts each point pp in the cell (⌊p1/δ⌋,⌊p2/δ⌋,⌊p3/δ⌋)(\lfloor p_1 / \delta \rfloor, \lfloor p_2 / \delta \rfloor, \lfloor p_3 / \delta \rfloor) and compares each point with all points of the 2727 cells whose indices differ from its own by at most 11 in each coordinate. It adds a pair only after it tests the distance, so every pair it adds is close. Conversely, if ∣p−q∣≤δ\lvert p - q \rvert \le \delta with p∈Rjp \in R_j, q∈Rkq \in R_k, j<kj < k, then ∣pi−qi∣≤δ\lvert p_i - q_i \rvert \le \delta for each ii, so ⌊pi/δ⌋\lfloor p_i / \delta \rfloor and ⌊qi/δ⌋\lfloor q_i / \delta \rfloor differ by at most 11; when the code visits pp it compares it with qq and adds (j,k)(j, k), unless the pair is there already. □\square

From now on, by Lemmas 1 and 2, the planes are the planes of the faces and AA is the set of pairs of faces that share an edge.

Lemma 3 (line L3). For {j,k}∈A\{j, k\} \in A, line L3 returns a point and a direction of the line Πj∩Πk\Pi_j \cap \Pi_k, and every edge between jj and kk lies on this line.

Proof. Let d=nj×nkd = n_j \times n_k; by H5, d≠0d \ne 0 and the code does not return none. By the cyclic rule of the triple product, nj⋅(nk×d)=d⋅(nj×nk)=∣d∣2n_j \cdot (n_k \times d) = d \cdot (n_j \times n_k) = \lvert d \rvert^2 and nk⋅(d×nj)=d⋅(nj×nk)=∣d∣2n_k \cdot (d \times n_j) = d \cdot (n_j \times n_k) = \lvert d \rvert^2, while nj⋅(d×nj)=0n_j \cdot (d \times n_j) = 0 and nk⋅(nk×d)=0n_k \cdot (n_k \times d) = 0. So x0=(cj(nk×d)+ck(d×nj))/∣d∣2x_0 = (c_j (n_k \times d) + c_k (d \times n_j)) / \lvert d \rvert^2 has nj⋅x0=cjn_j \cdot x_0 = c_j and nk⋅x0=ckn_k \cdot x_0 = c_k. The direction dd is orthogonal to both normals, and two planes with independent normals meet in exactly one line, so the line is x0+Rdx_0 + \mathbb{R} d. An edge between jj and kk lies in both faces, so in both planes and on the line. □\square

Lemma 4 (lines L4 and L5). After line L5 the vertices are exactly the vertices of PP, each once, and the face set of each is the set of the three faces that contain it.

Proof. Take a vertex vv with faces j,k,lj, k, l. By H3, each pair of them shares an edge, so {j,k,l}\{j, k, l\} is a triangle of AA. By H5 the normals are independent and the system of line L4 has one solution, which is vv, since vv lies on the three planes. By H3 each of the three regions has a point within η\eta of vv. So line L4 keeps vv.

Take a triangle {j,k,l}\{j, k, l\} of AA that is not the face set of a vertex. If some vertex ww lay on all three faces, then by H3 its faces would be exactly j,k,lj, k, l, which is excluded. So H4 applies: either the planes have no unique common point, and line L4 gets none (when the determinant is 00 or below the threshold), or the point is farther than η\eta from one region, and line L4 drops it. So line L4 keeps no point from such a triangle.

So the kept points are the vertices of PP, each kept once, from the triangle of its own faces. In line L5, each new point is compared with the points kept before it; these are other vertices of PP, which by H3 are more than η\eta away, so no merge happens, and each vertex keeps the face set {j,k,l}\{j, k, l\}. □\square

Lemma 5 (line L6). Line L6 returns exactly the edges of PP, each once, with the pair of faces that contain it.

Proof. Take {j,k}∈A\{j, k\} \in A, and let ee be the edge between jj and kk, which exists by Lemma 2 and is unique by H3. Its two endpoints lie in both faces, so by Lemma 4 they are vertices whose face sets contain jj and kk. Conversely, let vv be a vertex whose face set contains jj and kk. By H3 some edge at vv lies in both jj and kk; by uniqueness it is ee, so vv is an endpoint of ee. So the list of line L6 has exactly the two endpoints of ee, which are distinct, the line of Lemma 3 exists, and the pairing gives the one edge (u,w,(j,k))(u, w, (j, k)) with the endpoints of ee. Every edge of PP lies in two faces that then share it, so every edge of PP arises from its pair in AA, and only once. □\square

Lemma 6 (line L7). For each face ff, line L7 returns the vertices of ff in the order of its boundary.

Proof. By Lemma 5, the edges whose face pair contains ff are exactly the edges of the polygon ff. A polygon without holes has a boundary that is one simple cycle of s≥3s \ge 3 edges, so in the graph of these edges every vertex has exactly two distinct neighbors, and the code does not return the empty loop. The walk starts at a vertex and each step moves to the neighbor of the current vertex other than the one it came from, so it follows the cycle in one direction, visits each of the ss vertices once, and returns to the start after ss steps. The list then has ss vertices, which is the number of vertices of the graph, and the code returns it. □\square

Theorem 1 (termination). On every input the algorithm stops.

Proof. Lines L1 to L6 are loops over finite sets: the regions, the points of 2727 cells for each point, the pairs in AA, the triples of faces, the kept vertices and the vertices on a line. In the code, the eigenproblem of line L1 uses at most a fixed number of Jacobi sweeps. In line L7, the walk starts only when every vertex of the edge graph of ff has exactly two neighbors. A finite graph in which every vertex has degree 22 is a disjoint union of cycles, and the component of the start is one cycle of some length s≥2s \ge 2, since an edge joins two distinct vertices. For s≥3s \ge 3 the walk follows the cycle as in Lemma 6 and is back at the start after ss steps. For s=2s = 2, the start aa has the neighbor bb twice and bb has aa twice; the walk goes to bb, where both neighbors are aa, and stops. So every walk stops after at most as many steps as the graph has vertices. □\square

Theorem 2 (correctness). Under H1 to H5 the algorithm returns the planes of the faces of PP, the pairs of faces of PP that share an edge, the vertices of PP with their faces, the edges of PP with their faces, and the boundary cycle of each face. In particular V−E+FV - E + F of the result equals that of PP, which is 2−2g2 - 2g for a polyhedron of genus gg whose faces are disks; so the check V−E+F=2V - E + F = 2 passes exactly when PP has no handles.

Proof. Lemmas 1 to 6 give the parts in turn, and Theorem 1 shows that the algorithm returns them. The counts of the result are the counts of PP. For a closed polyhedral surface whose faces are disks, V−E+F=2−2gV - E + F = 2 - 2g by the Euler-Poincaré formula. □\square

Corollary 1 (the box of the example). For the box [0,a]×[0,b]×[0,c][0, a] \times [0, b] \times [0, c] with a,b,c>0a, b, c > 0, sampled at the centers of cells of side ss that divide the sides, with s≤min⁡(a,b,c)/2s \le \min(a, b, c) / 2, s/2≤δ<min⁡(a,b,c)s / \sqrt 2 \le \delta < \min(a, b, c) and s/2≤η<min⁡(a,b,c)s / \sqrt 2 \le \eta < \min(a, b, c), the algorithm returns the 88 corners, the 1212 edges and the 66 faces of the box, with V−E+F=2V - E + F = 2.

Proof. Each face has at least 2×22 \times 2 cell centers, which are not on one line, so H1 holds. For two faces that share an edge, the two sample points nearest to the edge are at distance s/2s / 2 from it, orthogonally in the two faces, so they are s/2≤δs / \sqrt 2 \le \delta apart. Two opposite faces are at distance at least min⁡(a,b,c)>δ\min(a, b, c) > \delta. So H2 holds. Each corner is simple, each pair of its faces shares one edge, and two faces share at most one edge. The nearest point of each face to a corner is the center of the corner cell, at s/2≤ηs / \sqrt 2 \le \eta, and two corners are at least min⁡(a,b,c)>η\min(a, b, c) > \eta apart; so H3 holds. Three pairwise adjacent faces take one face from each pair of opposite faces, so they always have a common corner, and H4 holds with nothing to check. The normals are the unit vectors of the axes, so ∣nj×nk∣=1\lvert n_j \times n_k \rvert = 1 and ∣det⁡∣=1\lvert \det \rvert = 1, and H5 holds. Theorem 2 gives the claim, with g=0g = 0. □\square

What is not proved. Nothing is proved for noisy data. With noise, the planes of line L1 are only near the true planes, the vertices and edges move with them, and the choice of δ\delta and η\eta decides whether faces are joined and corners merged correctly; the page reports measurements for this, not a bound. Vertices with four or more faces, faces with holes, and curved faces are outside the hypotheses. In floating point, the corners of the example agree with the true corners within 10−1210^{-12} in the tests. ■\blacksquare

Complexity

Line L1 is Θ(m)\Theta(m), with 3×33 \times 3 eigenproblems. Line L2 compares each point with the points of 2727 cells, Θ(mk)\Theta(m k). Line L4 lists the triples of faces, Θ(F3)\Theta(F^3), and tests each of the TT triangles against the points of three regions, Θ(Tm)\Theta(T m) in the worst case; line L5 compares each new vertex with the VV kept ones, Θ(TV)\Theta(T V). Line L6 finds and sorts the vertices of each of the aa lines, Θ(aVlog⁡V)\Theta(a V \log V), and line L7 follows the edges of each face, Θ(FE)\Theta(F E). Together this is the bound in the front matter on the real RAM. For a part with bounded sampling density and faces of bounded degree, kk, TT, VV and EE are small and the work is dominated by Θ(m)\Theta(m) for the fits and the hashing and Θ(Tm)\Theta(T m) for the corner tests; a list of triangles from the adjacency lists, as in triangle counting, removes the F3F^3 term.

Properties

  • Topology from data. The adjacency, and with it the whole topology, comes from the distances between the regions, not from the planes; two planes that cross far from the part never make an edge.
  • Geometry from fits. Vertices and edges come from the fitted planes, so they are sharper and more accurate than the scan points near the edges, which are often missing or noisy.
  • Invariant. A rigid motion of the points moves the result with it, since every step uses distances and planes only.
  • Checkable. The Euler formula and the closed loops show at once whether the model is a valid closed solid.
  • Greedy merge. Line L5 joins each new vertex to the first kept vertex within η\eta, so with noise the merged vertices can depend on the order of the faces.

Variants and improvements

  • Curved faces. Benkő, Martin and Várady handle faces that are simple analytic surfaces, such as cylinders, cones and spheres, and swept surfaces, and the edges come from surface-surface intersection instead of plane intersection.
  • Blends. In real parts, sharp edges are often rounded. The procedure fits rolling-ball blends to the strips between the primary faces and fills the corners with vertex blends, so the edges are the boundaries of the blends, not plane intersections.
  • Constraints. Faces that should be parallel, perpendicular or coaxial are fitted together with constrained fitting, so that the model keeps the design intent and the corners are better placed.
  • Repair. Gaps and small slivers that remain are closed with B-rep healing, or kept with a local tolerance as in tolerant modeling.
  • Candidate selection. Later methods intersect all candidate planes and choose the faces of the result by optimization, for example PolyFit by Nan and Wonka (2017), and learning methods such as Point2CAD (Liu and others, 2024) reconstruct the topology of curved faces from point clouds. The reference data for such methods are B-rep models, for example of the ABC data set (Koch and others, 2019).

When to use it

Use it when the part is made of faces of known types, the scan covers all faces and a segmentation is available, for example from efficient RANSAC or variable-order fitting, and the goal is a CAD model that a modeler can edit. For organic shapes without clear faces, a mesh from surface reconstruction, such as Poisson reconstruction, is the better target.

Pitfalls

  • δ\delta too small or too large. Below the gap across an edge, s/2s / \sqrt 2 for samples of spacing ss, no faces are adjacent and nothing is built; the tests show this. Above the thickness of a thin wall, the two sides of the wall become adjacent.
  • η\eta too small. The corner lies outside the data, at about s/2s / \sqrt 2 from the nearest point or farther where the scan misses the edge; with a smaller η\eta no corner is kept, as the tests show.
  • Vertices of four or more faces. At the apex of a square pyramid, the two pairs of opposite faces also come within δ\delta of each other, and with noise the four planes meet in up to four nearby points, not one. Line L5 merges them only if they lie within η\eta; otherwise short false edges appear.
  • Nearly parallel neighbors. Two adjacent faces at a very flat angle meet in a line that moves far when the normals change a little, so a small fit error gives a large edge error.
  • Wrong segments. One face split into two regions gives two coplanar planes whose line is not defined, and two faces in one region give a bad plane. The method needs a good segmentation.
  • Holes and inner loops. A face with a hole has a boundary of several cycles, and line L7 then returns no loop; the full procedure needs loops with holes and the Euler formula with rings.

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.

brep_reconstruction_from_scans.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brep-reconstruction-from-scans/. The authors are listed in prov/RBGNXS.jsonl.

"""B-rep reconstruction of a polyhedral part from a segmented scan.

The input is a list of regions of 3D points, one region per face, as a
segmentation gives them. Each region is fitted by a plane; two faces are
adjacent when some of their points are close; adjacent faces meet in an edge
on the line where their planes meet; three faces that are pairwise adjacent
meet in a vertex where their planes meet, if the data come close to that
point. Edges are the segments between the vertices of their two faces, and
the edges of a face form its boundary loop. The result is checked with the
Euler formula V - E + F = 2 for a closed solid without holes.

Only planar faces with sharp edges are handled here: no curved faces, no
blends, and no faces with inner loops.
"""

from itertools import combinations
from math import sqrt
from typing import Dict, FrozenSet, List, Optional, Sequence, Set, Tuple

from re1lin import cross, dot, jacobi_eigen, norm, solve, sub

Vec3 = Tuple[float, float, float]
Plane = Tuple[Vec3, float]          # unit normal n and offset c of the plane n . x = c


def fit_plane(points: Sequence[Vec3]) -> Plane:
    """Least-squares plane (orthogonal distance): the centroid and the eigenvector of the smallest eigenvalue."""
    if len(points) < 3:
        raise ValueError("a plane needs at least three points")
    m = len(points)
    c = tuple(sum(p[k] for p in points) / m for k in range(3))
    cov = [[sum((p[a] - c[a]) * (p[b] - c[b]) for p in points) for b in range(3)] for a in range(3)]
    values, vectors = jacobi_eigen(cov)
    n = tuple(vectors[0])
    s = norm(n)
    n = (n[0] / s, n[1] / s, n[2] / s)
    return n, dot(n, c)


def adjacent_pairs(regions: Sequence[Sequence[Vec3]], delta: float) -> Set[Tuple[int, int]]:
    """Pairs (j, k), j < k, with a point of region j within delta of a point of region k (grid hashing)."""
    grid: Dict[Tuple[int, int, int], List[Tuple[int, Vec3]]] = {}
    for j, reg in enumerate(regions):
        for p in reg:
            grid.setdefault(tuple(int(p[a] // delta) for a in range(3)), []).append((j, p))
    pairs = set()
    d2 = delta * delta
    for cell, items in grid.items():
        near = [it for dx in (-1, 0, 1) for dy in (-1, 0, 1) for dz in (-1, 0, 1)
                for it in grid.get((cell[0] + dx, cell[1] + dy, cell[2] + dz), ())]
        for j, p in items:
            for k, q in near:
                if j < k and (j, k) not in pairs and dot(sub(p, q), sub(p, q)) <= d2:
                    pairs.add((j, k))
    return pairs


def plane_line(a: Plane, b: Plane, min_sin: float = 1e-3) -> Optional[Tuple[Vec3, Vec3]]:
    """The line where two planes meet, as (point, unit direction); None if they are nearly parallel."""
    (n1, c1), (n2, c2) = a, b
    d = cross(n1, n2)
    s = norm(d)
    if s < min_sin:
        return None
    u, v = cross(n2, d), cross(d, n1)
    x0 = tuple((c1 * u[k] + c2 * v[k]) / (s * s) for k in range(3))
    return x0, (d[0] / s, d[1] / s, d[2] / s)


def plane_vertex(a: Plane, b: Plane, c: Plane, min_det: float = 1e-6) -> Optional[Vec3]:
    """The point where three planes meet; None if their normals are nearly dependent."""
    if abs(dot(a[0], cross(b[0], c[0]))) < min_det:
        return None
    x = solve([list(a[0]), list(b[0]), list(c[0])], [a[1], b[1], c[1]])
    return tuple(x)


def _near(points: Sequence[Vec3], v: Vec3, eta: float) -> bool:
    e2 = eta * eta
    return any(dot(sub(p, v), sub(p, v)) <= e2 for p in points)


class BRep:
    """Faces (planes), vertices (points with their faces), edges (vertex pairs with their two faces) and loops."""

    def __init__(self):
        self.planes: List[Plane] = []
        self.adjacency: Set[Tuple[int, int]] = set()
        self.vertices: List[Vec3] = []
        self.vertex_faces: List[FrozenSet[int]] = []
        self.edges: List[Tuple[int, int, Tuple[int, int]]] = []     # (vertex a, vertex b, (face j, face k))
        self.loops: Dict[int, List[int]] = {}

    def euler(self) -> int:
        return len(self.vertices) - len(self.edges) + len(self.planes)


def reconstruct(regions: Sequence[Sequence[Vec3]], delta: float, eta: float) -> BRep:
    """Build a B-rep from segmented points, one region per planar face.

    delta: largest gap between points of two adjacent faces; eta: largest
    distance from a vertex to the points of its faces, and the merge distance
    of vertices. Precondition: every region has at least three points that do
    not lie on one line. Cost: Theta(m) expected for the adjacency on m points
    of bounded density, plus Theta(T m) for the T triangles of the adjacency
    graph, plus Theta(F^3) to list them.
    """
    B = BRep()
    B.planes = [fit_plane(reg) for reg in regions]                              # @line L1
    B.adjacency = adjacent_pairs(regions, delta)                                # @line L2
    lines = {pair: plane_line(B.planes[pair[0]], B.planes[pair[1]]) for pair in B.adjacency}  # @line L3
    found: List[Tuple[Vec3, Set[int]]] = []
    for j, k, l in combinations(range(len(regions)), 3):
        if (j, k) in B.adjacency and (j, l) in B.adjacency and (k, l) in B.adjacency:
            v = plane_vertex(B.planes[j], B.planes[k], B.planes[l])            # @line L4
            if v is None or not all(_near(regions[f], v, eta) for f in (j, k, l)):
                continue
            for w in found:                                                     # @line L5
                if norm(sub(w[0], v)) <= eta:
                    w[1].update((j, k, l))
                    break
            else:
                found.append((v, {j, k, l}))
    B.vertices = [v for v, _ in found]
    B.vertex_faces = [frozenset(fs) for _, fs in found]
    for (j, k) in sorted(B.adjacency):
        line = lines[(j, k)]
        on = [i for i, fs in enumerate(B.vertex_faces) if j in fs and k in fs]
        if line is None or len(on) < 2:
            continue
        on.sort(key=lambda i: dot(sub(B.vertices[i], line[0]), line[1]))
        for a in range(0, len(on) - 1, 2):                                      # @line L6
            B.edges.append((on[a], on[a + 1], (j, k)))
    for f in range(len(regions)):
        B.loops[f] = face_loop(B, f)                                            # @line L7
    return B                                                                    # @line L8


def face_loop(B: BRep, f: int) -> List[int]:
    """The vertices of face f in the order of its boundary cycle; [] if its edges do not form one cycle."""
    nbr: Dict[int, List[int]] = {}
    for a, b, (j, k) in B.edges:
        if f in (j, k):
            nbr.setdefault(a, []).append(b)
            nbr.setdefault(b, []).append(a)
    if not nbr or any(len(v) != 2 for v in nbr.values()):
        return []
    start = min(nbr)
    loop, prev, cur = [start], None, start
    while True:
        nxt = nbr[cur][0] if nbr[cur][0] != prev else nbr[cur][1]
        if nxt == start:
            break
        loop.append(nxt)
        prev, cur = cur, nxt
    return loop if len(loop) == len(nbr) else []
re1lin.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the re1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra for the re1 fitting pages.

Vectors are tuples or lists of numbers, matrices are lists of rows. The
elimination routines work with int, Fraction or float entries: with Fraction
they are exact. The Jacobi routine is float only. The helper holds no
fitting algorithm of any page.
"""

from fractions import Fraction
from math import atan2, cos, sin, sqrt
from typing import List, Optional, Sequence, Tuple

Vec = Sequence
Mat = List[List]


# ---- vectors ----


def dot(a: Vec, b: Vec):
    return sum(x * y for x, y in zip(a, b))


def add(a: Vec, b: Vec) -> tuple:
    return tuple(x + y for x, y in zip(a, b))


def sub(a: Vec, b: Vec) -> tuple:
    return tuple(x - y for x, y in zip(a, b))


def scale(s, a: Vec) -> tuple:
    return tuple(s * x for x in a)


def norm(a: Vec) -> float:
    return sqrt(float(dot(a, a)))


def cross(a: Vec, b: Vec) -> tuple:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


# ---- matrices ----


def zeros(n: int, m: int, z=0) -> Mat:
    return [[z] * m for _ in range(n)]


def transpose(a: Mat) -> Mat:
    return [list(r) for r in zip(*a)]


def mat_vec(a: Mat, x: Vec) -> list:
    return [dot(r, x) for r in a]


def mat_mul(a: Mat, b: Mat) -> Mat:
    bt = transpose(b)
    return [[dot(r, c) for c in bt] for r in a]


def gram(rows: Sequence[Vec]) -> Mat:
    """The matrix sum over the rows u of u u^T."""
    n = len(rows[0])
    g = zeros(n, n)
    for u in rows:
        for i in range(n):
            if u[i] == 0:
                continue
            for j in range(n):
                g[i][j] += u[i] * u[j]
    return g


# ---- elimination (exact with Fraction) ----


def solve(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
    """Solve a x = b for a square a by Gaussian elimination with partial pivoting.

    Returns None when a pivot has absolute value at most tol (singular
    matrix). With Fraction entries and tol = 0 the answer is exact.
    """
    n = len(a)
    m = [list(a[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[p][c]) <= tol:
            return None
        m[c], m[p] = m[p], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0:
                for k in range(c, n + 1):
                    m[r][k] -= f * m[c][k]
    x = [0] * n
    for r in range(n - 1, -1, -1):
        s = m[r][n] - sum(m[r][k] * x[k] for k in range(r + 1, n))
        x[r] = s / m[r][r]
    return x


def lstsq(a: Mat, b: Vec, tol: float = 0.0) -> Optional[list]:
    """Least squares solution of a x = b by the normal equations (a^T a) x = a^T b."""
    at = transpose(a)
    return solve(mat_mul(at, a), mat_vec(at, b), tol)


def nullspace(a: Mat) -> List[list]:
    """A basis of the null space of a, by reduced row echelon form. Exact for Fraction entries."""
    m = [[Fraction(x) for x in r] for r in a]
    rows, cols = len(m), len(m[0])
    piv = []
    r = 0
    for c in range(cols):
        p = next((i for i in range(r, rows) if m[i][c] != 0), None)
        if p is None:
            continue
        m[r], m[p] = m[p], m[r]
        inv = 1 / m[r][c]
        m[r] = [x * inv for x in m[r]]
        for i in range(rows):
            if i != r and m[i][c] != 0:
                f = m[i][c]
                m[i] = [x - f * y for x, y in zip(m[i], m[r])]
        piv.append(c)
        r += 1
        if r == rows:
            break
    free = [c for c in range(cols) if c not in piv]
    basis = []
    for f in free:
        v = [Fraction(0)] * cols
        v[f] = Fraction(1)
        for i, c in enumerate(piv):
            v[c] = -m[i][f]
        basis.append(v)
    return basis


def rank(a: Mat) -> int:
    return len(a[0]) - len(nullspace(a))


# ---- symmetric matrices (float) ----


def cholesky(a: Mat, rtol: float = 0.0) -> Mat:
    """Lower triangular l with l l^T = a, for a symmetric positive definite a.

    Raises ValueError when a pivot is at most rtol times the largest diagonal entry.
    """
    n = len(a)
    l = zeros(n, n, 0.0)
    big = max(abs(float(a[i][i])) for i in range(n))
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
            if i == j:
                if s <= rtol * big:
                    raise ValueError("matrix is not positive definite")
                l[i][i] = sqrt(s)
            else:
                l[i][j] = s / l[j][j]
    return l


def lower_solve(l: Mat, b: Vec) -> list:
    x = []
    for i in range(len(l)):
        x.append((b[i] - sum(l[i][k] * x[k] for k in range(i))) / l[i][i])
    return x


def upper_solve_t(l: Mat, b: Vec) -> list:
    """Solve l^T x = b for a lower triangular l."""
    n = len(l)
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (b[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
    return x


def jacobi_eigen(a: Mat, sweeps: int = 100, eps: float = 1e-15) -> Tuple[list, Mat]:
    """Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.

    Returns (values, vectors) with the values in ascending order and
    vectors[k] the unit eigenvector of values[k].
    """
    n = len(a)
    s = [[float(x) for x in r] for r in a]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(s[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off <= eps * eps * max(1.0, sum(s[i][i] ** 2 for i in range(n))):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if s[p][q] == 0.0:
                    continue
                th = 0.5 * atan2(2 * s[p][q], s[q][q] - s[p][p])
                c, sn = cos(th), sin(th)
                for k in range(n):
                    skp, skq = s[k][p], s[k][q]
                    s[k][p] = c * skp - sn * skq
                    s[k][q] = sn * skp + c * skq
                for k in range(n):
                    spk, sqk = s[p][k], s[q][k]
                    s[p][k] = c * spk - sn * sqk
                    s[q][k] = sn * spk + c * sqk
                for k in range(n):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
    order = sorted(range(n), key=lambda i: s[i][i])
    return [s[i][i] for i in order], [[v[k][i] for k in range(n)] for i in order]
test_brep_reconstruction_from_scans.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brep-reconstruction-from-scans/. The authors are listed in prov/RBGNXS.jsonl.

"""Tests: the fitted planes of a scanned box give the adjacency, the edges and the corners of the true box."""

import os
import random
import sys
from itertools import product
from math import sqrt

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from brep_reconstruction_from_scans import (  # noqa: E402
    BRep, adjacent_pairs, face_loop, fit_plane, plane_line, plane_vertex, reconstruct)

S = 0.1  # sample spacing


def face_grid(o, u, v, nu, nv, s=S):
    """Points at the centers of an nu by nv grid of cells of size s, from corner o along u and v."""
    return [tuple(o[k] + (i + 0.5) * s * u[k] + (j + 0.5) * s * v[k] for k in range(3))
            for i in range(nu) for j in range(nv)]


X, Y, Z = (1, 0, 0), (0, 1, 0), (0, 0, 1)


def box(a, b, c, s=S):
    """Six regions: faces x=0, x=a, y=0, y=b, z=0, z=c of the box [0,a] x [0,b] x [0,c]."""
    na, nb, nc = round(a / s), round(b / s), round(c / s)
    return [face_grid((0, 0, 0), Y, Z, nb, nc), face_grid((a, 0, 0), Y, Z, nb, nc),
            face_grid((0, 0, 0), X, Z, na, nc), face_grid((0, b, 0), X, Z, na, nc),
            face_grid((0, 0, 0), X, Y, na, nb), face_grid((0, 0, c), X, Y, na, nb)]


def true_box(a, b, c):
    """The true box: corners with their face sets, adjacency, and edges as (corner set, face pair)."""
    corners = {}
    for i, j, k in product((0, 1), repeat=3):
        corners[(i * a, j * b, k * c)] = frozenset((i, 2 + j, 4 + k))
    adjacency = {(f, g) for f in range(6) for g in range(f + 1, 6) if f // 2 != g // 2}
    edges = set()
    for f, g in adjacency:
        ends = frozenset(p for p, fs in corners.items() if f in fs and g in fs)
        edges.add((ends, (f, g)))
    return corners, adjacency, edges


def rotation(rng):
    q = [rng.gauss(0, 1) for _ in range(4)]
    s = sqrt(sum(x * x for x in q))
    w, x, y, z = (c / s for c in q)
    return [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
            [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
            [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]


def move(p, rm, t):
    return tuple(sum(rm[i][k] * p[k] for k in range(3)) + t[i] for i in range(3))


def dist(p, q):
    return sqrt(sum((p[k] - q[k]) ** 2 for k in range(3)))


def match(br: BRep, true_pts, tol):
    """Map each reconstructed vertex to the true corner within tol, or None if this fails."""
    m = {}
    for i, v in enumerate(br.vertices):
        near = [p for p in true_pts if dist(v, true_pts[p]) <= tol]
        if len(near) != 1:
            return None
        m[i] = near[0]
    return m if len(set(m.values())) == len(true_pts) == len(m) else None


def same_as_true_box(br: BRep, a, b, c, rm=None, t=(0, 0, 0), tol=1e-9):
    corners, adjacency, edges = true_box(a, b, c)
    rm = rm or [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    placed = {p: move(p, rm, t) for p in corners}
    m = match(br, placed, tol)
    if m is None or br.adjacency != adjacency:
        return False
    if any(br.vertex_faces[i] != corners[m[i]] for i in m):
        return False
    got = {(frozenset((m[x], m[y])), fj) for x, y, fj in br.edges}
    return len(br.edges) == 12 and got == edges and all(len(br.loops[f]) == 4 for f in range(6))


def test_box_worked_example():
    br = reconstruct(box(2.0, 1.0, 0.5), 1.5 * S, 1.5 * S)
    assert same_as_true_box(br, 2.0, 1.0, 0.5, tol=1e-12)
    assert (len(br.vertices), len(br.edges), len(br.planes)) == (8, 12, 6)
    assert br.euler() == 2
    assert br.loops[4] == [0, 2, 6, 4]


def test_random_rigid_boxes_noise_free():
    rng = random.Random(1)
    exact = 0
    for _ in range(20):
        a, b, c = (round(rng.uniform(0.5, 2.0), 1) for _ in range(3))
        rm, t = rotation(rng), [rng.uniform(-5, 5) for _ in range(3)]
        regs = [[move(p, rm, t) for p in r] for r in box(a, b, c)]
        br = reconstruct(regs, 1.5 * S, 2 * S)
        exact += same_as_true_box(br, a, b, c, rm, t, tol=1e-9) and br.euler() == 2
    assert exact == 20  # 20 of 20 trials


def test_random_noisy_boxes_measured():
    rng = random.Random(7)
    exact = 0
    for _ in range(20):
        a, b, c = (round(rng.uniform(0.5, 2.0), 1) for _ in range(3))
        rm, t = rotation(rng), [rng.uniform(-5, 5) for _ in range(3)]
        regs = [[tuple(x + rng.gauss(0, 0.002) for x in move(p, rm, t)) for p in r] for r in box(a, b, c)]
        br = reconstruct(regs, 1.5 * S, 2 * S)
        exact += same_as_true_box(br, a, b, c, rm, t, tol=0.005)
    assert exact == 20  # measured: 20 of 20, largest corner error 0.00195


def test_adjacency_matches_brute_force():
    rng = random.Random(3)
    for _ in range(10):
        regs = [[tuple(rng.uniform(0, 3) for _ in range(3)) for _ in range(rng.randint(5, 30))] for _ in range(6)]
        delta = rng.uniform(0.1, 0.6)
        brute = {(j, k) for j in range(6) for k in range(j + 1, 6)
                 if any(dist(p, q) <= delta for p in regs[j] for q in regs[k])}
        assert adjacent_pairs(regs, delta) == brute


def test_fit_plane_exact_on_plane_points():
    rng = random.Random(5)
    n = (2 / 3, -1 / 3, 2 / 3)
    u, v = (1 / sqrt(2), 0, -1 / sqrt(2)), (1 / sqrt(18), 4 / sqrt(18), 1 / sqrt(18))
    pts = [tuple(3 * n[k] + s * u[k] + t * v[k] for k in range(3))
           for s, t in ((rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(50))]
    m, c = fit_plane(pts)
    sign = 1 if m[0] > 0 else -1
    assert all(abs(sign * m[k] - n[k]) < 1e-12 for k in range(3))
    assert abs(sign * c - 3) < 1e-12


def test_line_and_vertex_of_planes():
    px, py, pz = ((1, 0, 0), 2.0), ((0, 1, 0), 3.0), ((0, 0, 1), -1.0)
    x0, d = plane_line(px, py)
    assert (x0[0], x0[1]) == (2.0, 3.0) and abs(abs(d[2]) - 1) < 1e-15
    assert plane_vertex(px, py, pz) == (2.0, 3.0, -1.0)
    assert plane_line(px, ((1, 0, 0), 5.0)) is None                       # parallel planes
    assert plane_vertex(px, py, ((0.6, 0.8, 0.0), 1.0)) is None           # three normals in one plane


def l_prism(a, b, t, h, s=S):
    """An L-shaped prism: the L is [0,a] x [0,t] united with [0,t] x [0,b], extruded from z=0 to z=h."""
    cap = [(x, y) for x, y in ((S * (i + 0.5), S * (j + 0.5)) for i in range(round(a / s)) for j in range(round(b / s)))
           if y < t or x < t]
    nh = round(h / s)
    return [[(x, y, 0.0) for x, y in cap], [(x, y, h) for x, y in cap],
            face_grid((0, 0, 0), X, Z, round(a / s), nh), face_grid((a, 0, 0), Y, Z, round(t / s), nh),
            face_grid((t, t, 0), X, Z, round((a - t) / s), nh), face_grid((t, t, 0), Y, Z, round((b - t) / s), nh),
            face_grid((0, b, 0), X, Z, round(t / s), nh), face_grid((0, 0, 0), Y, Z, round(b / s), nh)]


def test_l_prism_with_concave_edge():
    br = reconstruct(l_prism(2.0, 1.5, 0.5, 1.0), 1.5 * S, 1.5 * S)
    assert (len(br.vertices), len(br.edges), len(br.planes)) == (12, 18, 8)
    assert br.euler() == 2
    assert len(br.loops[0]) == 6 and len(br.loops[1]) == 6
    assert all(len(br.loops[f]) == 4 for f in range(2, 8))
    assert (4, 5) in br.adjacency                                          # the concave edge
    corner = [v for v in br.vertices if abs(v[0] - 0.5) < 1e-9 and abs(v[1] - 0.5) < 1e-9]
    assert len(corner) == 2


def test_delta_below_gap_finds_no_adjacency():
    br = reconstruct(box(2.0, 1.0, 0.5), 0.5 * S, 1.5 * S)                # gap across an edge is S / sqrt(2)
    assert br.adjacency == set() and br.vertices == [] and br.edges == []
    assert all(loop == [] for loop in br.loops.values())


def test_eta_below_gap_finds_no_vertex():
    br = reconstruct(box(2.0, 1.0, 0.5), 1.5 * S, 0.5 * S)                # a corner is S / sqrt(2) from its points
    assert len(br.adjacency) == 12 and br.vertices == []


def test_face_loop_rejects_open_boundary():
    br = reconstruct(box(2.0, 1.0, 0.5), 1.5 * S, 1.5 * S)
    br.edges = [e for e in br.edges if e[2] != (0, 2)]
    assert face_loop(br, 0) == [] and face_loop(br, 2) == []
    assert len(face_loop(br, 1)) == 4

History

Reverse engineering of CAD models from scans grew in the 1990s, and the survey of Várady, Martin and Cox (1997) set out the pipeline from points to segmentation, surface fitting and B-rep model building. Benkő, Martin and Várady (2001) described a full procedure for conventional engineering objects bounded by simple analytic surfaces, swept surfaces and blends, with the focus on boundary models that are accurate and topologically consistent, ready for CAD and manufacturing. The same group studied constrained fitting and the segmentation of smooth regions in the following years. Later work replaced fixed rules with optimization and learning, as in PolyFit and Point2CAD.

References

  1. Pál Benkő, Ralph R. Martin and Tamás Várady, Algorithms for reverse engineering boundary representation models, Computer-Aided Design 33(11), 2001, 839 to 851, the whole paper, which summarizes the phases of the approach, from segmentation and surface fitting to the creation of edges, blends and vertex blends and a topologically consistent B-rep (general locator; section numbers not confirmed)
  2. Tamás Várady, Ralph R. Martin and Jordan Cox, Reverse engineering of geometric models, an introduction, Computer-Aided Design 29(4), 1997, 255 to 268, the sections on segmentation and surface fitting and on the creation of B-rep models, with the adjacency of regions, the intersection of the fitted surfaces and the stitching of faces
  3. Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, Section 3.5.6, Euler characteristic (p. 43), for the check V − E + F = 2 of a closed solid without holes

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example