Skip to content

CAD kernel foundations · Part eight

Discretising a B-rep

What a kernel turns an exact model into before it can be drawn, and how an edge becomes a polygon

Nothing that draws a shape can draw a B-rep. A graphics pipeline rasterises triangles and has no notion of a surface given by an equation or a boundary given by curves, so before a model can be displayed a kernel has to build a second, finite copy of it. In this article we look at what that copy is made of (a polygon for every edge, a triangulation for every face, and nothing of their own for the shells and solids above them) and how the edge polygons are computed from one relation about a circle, the sagitta. Part nine moves on to the faces.

What a mesh is

Once we have built a B-rep, the first thing we want is to look at it, but the hardware that draws it cannot draw what we built.

A graphics pipeline, from the earliest hardware to the one in front of you now, rasterises triangles. It has no notion of a surface given by an equation or of a boundary given by curves, and no way to ask a face where its edge is. Every real-time renderer, viewer, game engine and GPU driver takes the same input: a list of points, and a list of triples saying which of them form a flat facet. So before a B-rep can be displayed, something has to convert it into that form. That is the kernel’s job, because it is the only part of the stack that knows the exact surface.

A mesh is a discretisation: something continuous replaced by something finite, on purpose, with an error the caller is entitled to know.

The surface under a face is a function. Part three wrote the simplest ones out in full: give it two numbers and it returns a point, for any of the uncountably many pairs we could ask about. A triangulation discards nearly all of that. It keeps a finite list of points the function returned, and replaces everything between them with the flattest possible guess: a plane through three of them. Every decision in this article is about that substitution: how many points to keep, where to put them, and how far the guess may be from the true surface.

So a triangulation is a second representation of the shape, computed from the first, and it is only as good as the error bound quoted with it.

Display is the most obvious consumer and the least demanding one: a triangle a tenth of a millimetre off the true surface is invisible on a screen but catastrophic in a simulation mesh. The same triangulation is also what gets written to every exchange format that is not itself a B-rep, what collision tests and clash checks run against, what volumes and centres of mass are estimated from when exact integration is not wanted, and what a viewer picks against when we click a face. So a kernel that meshes badly does not only look bad: it gives wrong answers in four subsystems that have nothing to do with drawing.

Let’s state the job precisely. Given a face (a bounded region of a curved surface, described in the parameter rectangle of part five), produce a set of triangles whose vertices lie on the surface, which cover the face and nothing outside it, which approximate the surface within a stated deflection, and which match exactly the triangles of every neighbouring face along the edge the two share. The last of these four conditions is what turns a set of triangulated faces into a watertight model, and it constrains everything else.

Edge polygons and face triangulations

A B-rep has a hierarchy of entities: vertex, edge, face, shell, solid. Its discrete copy follows the same hierarchy, level by level, so let’s go through what each level becomes.

A vertex discretises to itself. It is already a point. There is nothing to approximate and nothing is stored.

An edge discretises to a polygon, in the sense of a polygonal chain and not a closed shape: a chain of straight segments whose corners lie on the curve. It is stored as a table of points, each with the curve parameter that produced it, so that anything downstream can go from a corner of the approximation back to the exact curve. That table is all a consumer ever sees of a curve that may be a spline of any degree, and on its own it is what a wireframe view draws.

A face discretises to a triangulation: a table of nodes, and a table of triangles, each triangle three indices into the node table. A node may carry the pair of parameters it was made from, which keeps the mesh attached to the surface underneath it, and a normal. The triangulation records the deflection it was built to and the settings it was built with, so that a later request can check whether the mesh already in hand is good enough instead of computing another. A face may hold several triangulations at once, at different deflections, but that is a caching decision and not something meshing requires.

Polygon mesh is the general name for a structure of this shape, and in general it need not be made of triangles; quadrilaterals are common in animation and in finite elements. Here it is triangles only, and the tables described above have no room for anything else. There is a reason for this: a triangle is the only polygon guaranteed to be flat. Four points sampled from a curved surface and rounded to floating point are not coplanar, so a quadrilateral would have no well-defined plane to intersect, to shade or to measure a deviation against. Every one of those downstream operations is written for three points.

The difficulty is between these two levels. An edge bounds two faces, so its polygon is stored three times: once as points in space, and once for each face as a list of indices into that face’s own node table. These lists are references to nodes the face’s triangulation already contains, not second copies of the points. The three can only agree if they all come from one chain, and section four shows how that is arranged. A seam edge, which bounds the same face twice, carries two such index lists for one curve, and in the kernel this description was read from there is a structure whose only purpose is to hold that pair.

Shells and solids have no discretisation of their own. There is no object that is “the mesh of this model”. A shape’s mesh is its faces’ triangulations, and what makes them one surface instead of a set of unconnected patches is the index lists along the edges they share. When we ask a kernel for the triangles of a solid, it walks the faces and concatenates their triangles.

This is also the form the graphics pipeline wants: nodes go into a vertex buffer, triangle indices into an index buffer, normals if they are present, and parameters as texture coordinates. This is no coincidence: drawing was the first consumer, and the storage still reflects it.

This arrangement is one option among others. Storing the tables on the faces is a choice, and the alternative is to build one buffer for the whole shape and keep nothing. That is smaller, has no three-way redundancy and nothing to keep in sync. But it cannot re-mesh one face after an edit without redoing the rest, cannot hold two deflections for two consumers, and makes each consumer redo work the previous one already did. The per-face tables are a cache, with the advantages and the problems of a cache. The agreement along the shared edge, on the other hand, is required whatever the storage.

The sagitta: chord error on a circle

Meshing rests on one relation about a circle. Everything later either builds on it or deals with the cases where it does not apply, so let’s derive it step by step.

Take a circular arc and join its two ends with a straight line. The arc bulges away from that line, most of all in the middle. The distance from the middle of the chord to the middle of the arc is the sagitta, Latin for arrow: in the archery picture the arc is the bow, the chord is the bowstring, and the sagitta is the arrow lying between them.

The derivation takes two lines. The centre of the circle is at distance R from every point of the arc, including its middle. It is at distance R cos(Δθ/2) from the middle of the chord, where Δθ is the angle the arc subtends, because the chord’s midpoint lies on the bisector and the half-angle is Δθ/2. Subtracting:

δ = R (1 − cos(Δθ/2))

and that is the largest distance between the arc and the chord that replaces it. In practice we want the inverse form (given an error budget, how large a step can we take):

Δθ = 2 arccos (1 − δ/R)

Δθ/2 R δ one step the arrow is the error Δθ/2 R δ/4 half the step a quarter of the error δ = R (1 − cos Δθ/2) halve the angle and the sagitta falls by four: the error goes as the square of the step drawn wide to be visible. At R = 10 and a deflection of 0.2 the relation returns 0.4007 rad
The sagitta. An arc is replaced by its chord; the arrow between them, from the middle of the chord to the middle of the arc, is the error of that substitution, and it is the quantity a caller sets when it sets a deflection. The centre is at R from the arc and at R cos(Δθ/2) from the chord, so the arrow is the difference of the two, which is the relation above. The right-hand arc is the same circle at half the angular step, and its arrow is a quarter as long: the error falls as the square of the step, which is why refining works and why it is expensive. The angle is drawn wide so that the arrow is visible; with the real numbers quoted below the panels, a step subtends 22 degrees and the arrow is two per cent of the radius.

Two consequences do most of the practical reasoning later. First, expanding the cosine for a small angle gives δ ≈ L²/(8R), with L the chord length: the error goes as the square of the step. Halve the step and the error falls to a quarter. This is why refining works, and also why it is expensive: a hundredfold gain in accuracy costs tenfold in points, in each direction. Second, the error goes as one over the radius, so a small fillet needs a much finer step than a large cylinder for the same tolerance, and a mesher that uses one step everywhere either wastes points on the flat parts or misses the tight ones.

These two lines are also what the kernel computes. They are one function in the library, which takes a radius, a deflection, an angular ceiling and a minimum size and returns a step, and both halves of the mesher call it. The points along a circular edge and the rows across a spherical face come from the same twenty lines, called twice with different arguments. Keep this in mind through the next section and part nine: the two look like separate machinery, but they share this function.

The relation is defined for a circle. A general surface has no single radius, which is why the elementary surfaces get their own treatment: for a sphere, a cylinder, a cone or a torus the kernel knows the exact radius, so the sagitta relation gives the exact step and not an estimate.

Used as it is, the relation misbehaves at both ends of the range of radii, so a real implementation clamps it at both.

angular ceiling π/2 Δθ radius minimum size angle sagitta Δθ = 2 arccos (1 − δ/R), clamped at both ends
The angular step given by the relation, against the radius, at a fixed deflection. Let’s read it from the right. A large radius is a nearly flat surface, and the relation asks for a small angle, but a small angle on a large circle is a long arc, so the step in millimetres grows even as the step in radians shrinks. Moving left, the radius tightens and the required angle grows; it would keep growing until a single step spanned most of the circle, and the angular ceiling stops that (the flat middle). Further left, the tightest radii would have the relation ask for points closer together than the caller said was useful, so a minimum size takes over and pushes the step back up. On that left-hand plateau the deflection is no longer met. It is abandoned on purpose, because keeping it would cost a million points, and this is why the two clamps are parameters and not constants.

An angular ceiling, for small radii. As the radius tightens, the required angle grows, and nothing in the formula stops it growing until one step spans most of the circle. A ceiling caps it, so that a tiny hole is still sampled as a polygon and not as a triangle. The ceiling is the second parameter a caller sets. It is an angle and not a length because it constrains curvature, not size.

A minimum size, for the other end. On the tightest radii the relation would ask for points closer together than anybody can use, often closer than the tolerance of the geometry they lie on, which makes them meaningless. A floor pushes the step back up. On that floor the promised deflection is no longer met, and that is deliberate: it is better to drop the promise openly than to keep it at the cost of a million points. The third parameter is where the caller sets that limit.

So a kernel that exposes the relation to its callers gives them three numbers (a deflection, an angle and a minimum size), and these are the relation and its two clamps. A kernel can also hide all of this and ask for a number of segments instead. That is easier to implement, and it tells the caller how much it will pay without telling it what accuracy it will get.

Discretising the edges first

Before any face is processed, every edge of the model is turned into a chain of points. This ordering is the reason a kernel’s meshes are watertight while a naive mesher’s are not.

Let’s start with the rule for a single edge. The relation of the last section needs a radius, and a general curve has a different radius at every point. So the discretiser handles three cases, and only the third is adaptive.

A line is given by its two ends. The chord of a straight line is the line itself, so no interior point can improve anything and none is added, whatever deflection was asked for. This is the argument that part nine makes for a plane and a cylinder, one dimension lower. A spline or a Bézier with only two poles is recognised as a line and treated the same way. So, at a higher cost, is a curve that turns out to be straight: the general walk probes it interval by interval, finds every tangent parallel to the first within one per cent of the angular budget, discards its work and starts again as a line.

A circle is given by one closed-form step. The relation is evaluated once, at the exact radius stored in the geometry, and the result is used all the way round. The angular range is divided by that step, the count is rounded up to a whole number, and the step is then reset to the range divided by that count. So every gap is identical, and the accuracy ends up slightly finer than requested, never coarser. Nothing is measured, and nothing needs to be, because on a circle the relation is exact.

Every other curve is walked. The first step still comes from the same relation, in its small-angle form, with the curve’s local radius of curvature in place of the radius: a chord of √(8δR), which is δ ≈ L²/(8R) from the last section solved for L. From there the walk corrects itself by measuring. At the midpoint of each candidate span it computes two ratios (the distance from that midpoint to the chord over the allowed deflection, and the angle between the two half-chords over half the allowed angle) and keeps the larger. Above one, the step shrinks and the span is tried again; well below one, the step grows. So the points are placed by prediction and then checked by measurement, which is a stricter standard than the interior of an analytic face is held to.

Note what is missing from this list. An ellipse, a parabola and a hyperbola are as analytic as a circle, and their curvature has a closed form too, but none of them gets a special case: only the circle does, and everything else goes to the walk. This is common in these catalogues, and there is a reason for it. The circle is the curve of constant curvature, the only case where a single evaluation of the relation gives the answer for the whole curve. For any other curve a closed form only gives a better first guess and the walk is still needed, so the walk gets written first and the special cases often never follow.

line 2 points a chord of a line is the line no step to choose error 0.000 circle 17 points one closed-form step, used all the way round every step 0.3927 rad error 0.192 ellipse 20 points no closed form: walked, then corrected steps 0.103 to 0.613 error 0.200 one deflection of 0.2 asked of all three
The same deflection of 0.2 applied to three edges, with three different results. The line is given by its two ends: the chord of a straight line is the line itself, so no interior point can improve anything, and the measured error is nil. The circle is given by one closed-form step: the relation of the last section, evaluated once at the exact radius stored in the geometry, then rounded up to a whole number of divisions and shared out evenly. Every gap is identical, and because rounding up gives slightly more resolution than requested, the error comes in just under budget. The ellipse, although just as analytic, gets neither: it goes to the walk, which starts from the local radius of curvature and then corrects itself by measuring. The points crowd where the curve turns and spread out where it is flat (a factor of six between the smallest gap and the largest), and the error sits right at the budget.

Two floors apply on top of that. There is a minimum number of points per edge whatever the geometry, and it is higher for the conics: four instead of two for a circle, an ellipse, a parabola or a hyperbola, because two points on a closed curve describe nothing. And the caller’s minimum size applies here too, so an edge shorter than the floor is not subdivided further.

A kernel ends up with several of these routines, because consumers want different guarantees and no single rule gives all of them. Points spaced equally along the curve are what sampling, fitting and a dimension’s leader line need, and they guarantee nothing about the error. Points spaced to a deflection are what drawing needs. Points spaced to a deflection and an angle are what meshing needs, because meshing cannot afford to cut a corner off.

The library the mesher’s routine belongs to has five of them, and which one a subsystem uses matters. Two distribute points by arc length, exactly or approximately. Two work to a deflection: one predicts the step from the second derivative and needs a C² curve, the other bisects and measures the midpoint and accepts any curve, at the cost of more points than necessary. The mesher uses none of these four. It uses the tangential-deflection routine, the only one with an angular criterion as well as a linear one, and the only one with the closed-form cases above.

The rest of the kernel does not use the same routine. The polygon that the face classifier of part seven builds for its ray casting is cut by the bisect-and-measure routine instead. So the same edge of the same model becomes a different chain of points depending on which subsystem asked for it. This is harmless as long as nobody assumes otherwise, and the lattice points of part nine are tested against the mesher’s own polygon, not the classifier’s.

Edges are held to a tighter standard than face interiors. Both budgets (distance and angle) are halved before the edge tessellator sees them, and halved again for an internal edge. Everything downstream is fitted to these points, and neither of the faces that share them can correct an error in them.

Two faces share an edge. Each has its own parameter rectangle, its own surface and its own pcurve for that edge. If each face tessellated its own copy of the edge, the two would produce points that are close but not equal, and the model would have slivers and gaps along every edge. The obvious fix, meshing both faces and then merging nearby vertices, turns every edge of the model into a tolerance problem.

The fix that works is to make the decision earlier. Tessellate the three-dimensional curve once, before either face is processed, producing a list of points on that curve and the parameters they lie at. Then, for each face in turn, evaluate that face’s pcurve at those same parameters. Each face gets a list of points in its own rectangle; the two lists have the same length and, mapped back to space, the same positions. They agree because there was only ever one tessellation, so no check is needed.

Everything downstream exists to protect this invariant. It is why the interior refinement pass never refines the boundary, however badly a boundary triangle misses the surface: moving a boundary point would move it in one face and not in the other. It is why a face that already has a triangulation has its edge polygons extracted instead of recomputed. And it is why an edge whose stored parametrisation disagrees with its curve (the same parameter gives different points on the curve and on the pcurve) needs a projection step with a monotonicity guard, because a parameter list that goes backwards produces a self-intersecting boundary polygon and a triangulation with no valid answer.

There is one more step between the edge and the triangulator. It is easy to miss because it fixes a mismatch between the two representations, not a fault in either. The polygon the triangulator sees is not the edge. It is the chain of straight segments joining consecutive points in the parameter rectangle, and the surface along one of those segments is not the curve: the two are only guaranteed to agree at the endpoints. On a plane this makes no difference, since a straight segment in the rectangle is exactly a straight line in space. On a curved surface the difference can exceed the whole budget.

So after the three-dimensional tessellation, each face’s copy gets a second pass. Take two consecutive points, take the midpoint of their two parameter pairs (the middle of the segment the triangulator will draw), and evaluate the surface there. Measure how far that point is from the chord joining the two points in space. If it is further than the budget allows, insert the curve’s own midpoint between them and repeat on both halves, up to a bounded depth. The new points are still points of the curve, so the invariant above holds; there are only more of them, where the straight segment in the rectangle was not accurate enough. Without this pass, a mesher produces faces whose edges are accurate but whose triangles next to those edges are not.

Then, before any triangle is created, the boundary is checked in the rectangle where it will be used: are the wires closed, and do they avoid crossing themselves? Where consecutive edges leave a gap, their ends are forced together in parameter space. Note that this repair is decided on three-dimensional connectivity and three-dimensional tolerances (no separate tolerance in u and v is computed for it). This is the usual pragmatic compromise, and a badly scaled surface is where it usually goes wrong.

That completes the edges. Every edge of the model is now a polygon: a chain of points on the curve, held to half the deflection the caller asked for, tessellated once and read by both faces that share it. What the faces do with it (how the inside of a curved face is filled, why that filling is decided in a flat parameter rectangle and not in space, and what joins the points up once they exist) is the subject of part nine.

Reading list

Sources

I. Stroud, Boundary Representation Modelling Techniques, Springer, 2006 (read directly). It gives the B-rep framing of the problem, and the reason faceting is treated as a derived representation with an error attached and not as a display concern.

Method

The sagitta figure is drawn at a deliberately wide angle, because a step of the size the relation returns subtends 22 degrees and its arrow would be two per cent of the radius, too small to see. Its geometry is the relation itself, and the numbers quoted under it are the run above.

The step figure in section three is the relation and its two clamps evaluated directly, with the two regime boundaries solved and not placed by eye.

The three-curve figure in section four is a dump of real output: a line, a circle of radius 10 and an ellipse of semi-axes 15.5 and 4.2, each handed to the library’s own curve discretiser at a deflection of 0.2 and the mesher’s default angular ceiling of 0.5 rad, and the points it returned are the points drawn. The error quoted under each panel is measured, not predicted: for every chord, the furthest the curve gets from it, sampled at forty stations along the span. The line comes back at nil, the circle at 0.192 against a budget of 0.2, the ellipse at 0.1998. The deflection was chosen so that the relation, and not the angular ceiling, is what governs: at 0.35 on the same circle the relation asks for 0.529 rad, the ceiling refuses anything above 0.5, and the ceiling is what answers.

The claim in section four that the mesher uses one discretisation strategy out of several, and that the classifier of part seven uses a different one, was established by reading which of them each subsystem includes, not by comparing output.

The behaviours described generically throughout (the single upstream tessellation of a shared curve, and the skipping of frontier links during refinement) were each read in the source of one production kernel. They are stated here without attribution because this series is about the problem rather than any one implementation of it.

Revision history

. Part numbers renumbered for the new part two, The Mathematics a Kernel Stands On.