Algorithmcore
CSG ray casting
Also called Roth ray casting of CSG.
Renders or measures a CSG solid by intersecting each ray with the primitives and combining the resulting in and out intervals by the Boolean operations of the tree.
- Time
- O(m + L h) worst
- Space
- O(L) extra
- Where
- L = the number of primitives; h = the height of the tree; m = the number of faces of all primitives
- Model
- Real RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Scott D. Roth, 1982
CSG ray casting finds where a ray meets a solid given by a CSG tree. It intersects the ray with each primitive, which gives for each leaf a list of parameter intervals where the ray is inside, and then combines the lists up the tree with the union, intersection and difference of intervals. The first interval end at or after the ray origin is the visible point, and the sum of the interval lengths is the length of the ray inside the solid. Roth made it the base of a solid modeler in 1982, and it is the one-dimensional case of set membership classification.
In plain words
Shoot a straight line through a CSG solid. For each basic shape, find where the line goes in and where it comes out. That gives, for each shape, a few stretches of the line that are inside it.
Now follow the recipe of the solid. For an added shape, join its stretches with the others. For a shape that is cut away, remove its stretches. For a shape that must be common to two parts, keep only the overlap. At the end you have the stretches of the line that are inside the whole solid.
The start of the first stretch in front of the eye is the point that you see, so one line per pixel draws a picture. The total length of the stretches, summed over a grid of parallel lines, estimates the volume. No surface of the solid is ever computed.
The problem
The input is a CSG tree whose leaves are primitives and whose inner nodes are , and , and a ray with . The output is the set of with in the solid, as a sorted list of disjoint closed intervals of positive length. Often only the first hit is needed: the least in that set. This page treats the whole line; a ray is the part with .
The algorithm
CAST(o, d, T) ▷ sorted disjoint closed intervals of t- 1
if T is a primitive then - 2
return the intervals of o + t d inside T, without those of length 0 - 3
A ← CAST(o, d, T.left), B ← CAST(o, d, T.right) - 4
return MERGE(A, B, T.op) MERGE(A, B, op)- 5
E ← the end points of A and B, sorted, without repeats - 6
for each pair e_j < e_{j+1} of consecutive points of E do - 7
if op(the midpoint is inside A, the midpoint is inside B) then - 8
add [e_j, e_{j+1}], joined with the last interval if that one ends at e_j FIRST-HIT(o, d, T)- 9
R ← CAST(o, d, T) - 10
for each [t0, t1] in R, in order do - 11
if t1 ≥ 0 then return max(t0, 0) - 12
return none
Line L2 depends on the primitive. For a convex polyhedron it is the slab method: each plane bounds from one side, at , and the interval is from the largest lower bound to the smallest upper bound. A sphere or another quadric gives a quadratic in and up to two interval ends (ray-sphere intersection). A torus gives a quartic. Only this step depends on the kind of surface, which is why Roth's method extends to new primitives with little work.
MERGE is the regularized set operation on the line. Between two consecutive end points, membership in and in is constant, so one midpoint decides each open piece. Line L8 makes the result closed and joins pieces that touch, so that no interval of length appears and no false end point stays between two touching pieces. A merge of the two sorted lists in one pass, with a flag for each list, needs no midpoints and gives the same result.
Example
Let and be two unit cubes that share the face , and let be a box that cuts a notch into the end of . The solid is . Cast the ray , , so the point at parameter has .
| node | intervals of |
|---|---|
At the union, . Both pieces and are inside, and line L8 joins them, so the shared face at leaves no trace. At the difference, sorted to . Only is inside and outside . The first hit is , the point on the left face of , and the ray is inside the solid for a length of .
Two more cases. For the lists and meet only at , so MERGE returns nothing: the touching cubes have an empty regularized intersection. The ray , meets only at , at the point on an edge. Line L2 gets the interval of length and drops it, so the ray misses .
Correctness
Assume that the ray does not lie in the plane or on the surface of a face of a primitive. Then the ray crosses the boundaries of the primitives at finitely many parameters, and each open piece between two consecutive crossings lies inside or outside each primitive. On such a piece the regularized solid is all of the piece or none of it, by the same argument as for set membership classification. MERGE evaluates the operation on each piece, so by induction on the tree CAST returns the closure of the union of the inside pieces, which is the set of with in the solid. The full proof gives the details and the case of a ray in a face plane.
Proof: CSG ray casting returns the regularized classification of the linefull
Let be a CSG tree whose leaves are bounded convex polyhedra with nonempty interior, and whose inner nodes are , and . Write for the solid of . Let with , and let . A nice list is a sorted list of disjoint closed intervals of positive length, no two of which share an end point.
Assumption. No face plane contains the line: for no are both and .
Let be the finite set of with and for some . A cell is a connected component of .
Lemma 1. Let be a cell. Then for each subtree of , either or . Write for true in the first case and false in the second. Then at each inner node, where op is or, and, or and-not.
Proof. Each function is affine. If , then has its only zero in , so it has a constant nonzero sign on . If , then is constant, and it is not zero by the assumption. Fix . There is a ball around on which every keeps the sign it has at . So or for each leaf. At an inner node with children whose sets each fill or miss it, the plain set operation gives or . The regularization does not change a set on the open set when that set is or there. So by induction is or , as the Boolean formula says. The signs are the same for all , so the choice is the same along the cell.
Lemma 2. Let be the union of the cells with true, and let . Then , the regularization of on the line, and is a finite subset of .
Proof. By Lemma 1, . The set is open and lies in , so . Conversely, lies in , and removing finitely many points from an open subset of does not change its closure. So . Finally .
The finite difference is real: a line through an edge where the solid touches itself along that edge only, or a line that grazes a vertex, meets in isolated points. The regularized classification of the line drops them, and the result is .
Theorem. Under the assumption, CAST returns a nice list whose union is , and FIRST-HIT returns , or none when this set is empty.
Proof. By induction on the tree.
Leaf. Line L2 takes as the largest over the planes with and as the smallest over the planes with , and returns the empty list if a plane with has the line outside. The open interval is then the set of where all strict inequalities hold, which is . If , the closure is . If , then is empty and so is . In both cases the output is a nice list for .
Inner node. By the induction hypothesis, and are nice lists for and . Let be the end points as in line L5. On an open piece there is no end point of or , so the piece lies in the interior of one interval of or misses all intervals of , and the same holds for . Every cell in the piece then has equal to the test "the midpoint is inside ", and the same for , because . By Lemma 1, line L7 computes for every cell in the piece. Outside both children are false, and op(false, false) is false for all three operations. So the true pieces cover up to finitely many points of , and the closure of their union is . Line L8 adds the closed pieces in order and joins a piece to the previous interval when they share an end, so the output is sorted, its intervals have positive length, and no two share an end point.
First hit. FIRST-HIT scans the nice list in increasing order. If an interval has , all earlier intervals lie in , and the least point of is . If no interval has , then is empty.
Termination. CAST visits each node of the tree once, and each MERGE loops once over a finite list.
A line in a face plane. If the assumption fails, Lemma 1 fails. On a cell the line can lie in the boundary of a primitive, and the leaf interval then reports the line as inside while the primitive lies on one side of the line only. For the touching cubes and and the line , in the shared face, both leaves give , so CAST returns for the intersection, while the regularized intersection is empty. Such a line needs the neighborhoods of set membership classification or a perturbation.
Complexity
The costs are in the real RAM with exact arithmetic on the ray parameters.
- Leaves. A convex polyhedron with faces costs , so all leaves cost . A convex primitive gives at most one interval.
- Inner nodes. A node has at most as many interval ends as the leaves below it have, so at most for convex leaves. A linear merge costs . Each leaf is below at most nodes, so all merges cost , which is for a tree of height and for a balanced tree.
- A picture. An image of pixels casts rays, for in all.
Practical renderers test each subtree against a bounding box first (axis-aligned bounding box, bounding volume hierarchy). An empty subtree under a union is skipped, and an empty left side of an intersection or a difference ends the work at that node.
Properties
- No boundary evaluation. The solid is rendered or measured from the tree alone. No surface of the result is ever built.
- Exact for the classification. With exact ray parameters, every interval end and every merge decision is exact. With quadrics the ends are roots of quadratics, and exact comparison needs algebraic numbers.
- The normal comes from one primitive. Each interval end is the end of one primitive interval, so the surface normal at a hit is the normal of that primitive. At an end that comes from a subtracted primitive, the normal must be reversed.
- Parallel. The rays are independent, so they can be cast at the same time.
Variants and improvements
- Volume and moments by rays. Cast a grid of parallel rays with spacing and add times the length inside the solid for each ray. This is a quadrature for the mass properties of the solid; its error depends on the grid, and random ray positions turn it into Monte Carlo integration.
- Ray representations and dexels. Storing the intervals of a fixed grid of rays gives a ray representation of the solid. It is used for fast display and for the simulation of machining.
- Ray tracing of CSG. A ray tracer adds reflected and refracted rays at each hit. Each of them is cast with the same CAST.
- Other surfaces. Any surface with a ray intersection routine can bound a primitive, such as implicit surfaces and signed distance functions.
When to use it
Use it to draw a CSG model without a boundary evaluation, for an interactive preview, or to estimate a volume or a center of mass of a CSG solid. It is also a robust way to test a point or a line against a CSG model, because each test involves only one primitive at a time. When the same model is drawn many times, or when exact faces are needed for machining or meshing, compute the boundary once with boundary evaluation.
Pitfalls
- Intervals of length zero. If line L2 keeps for a ray that grazes an edge, a later union shows a lone point as a hit, and a picture shows speckles along the silhouette edges. Drop such intervals at line L2 and at line L8.
- Touching intervals not joined. If line L8 adds and as two intervals, the shared face of two touching primitives stays as a false exit and entry at . The first hit is still right, but a count of surfaces, an x-ray picture or a later difference sees a face inside the solid.
- Rounded ray parameters. In floating point, the exit from and the entry into at a shared face are two separately rounded numbers. If the exit is a little larger, the intersection returns a sliver interval and a spurious surface. Compare with exact or filtered arithmetic (geometric robustness problem), or move the coincident faces apart in the model.
- A ray in a face plane. For the ray , in the shared face , both and give , so line L4 returns for , which is empty in space. The intervals on the line do not see from which side each solid touches the ray. Such rays form a set of measure zero, so a renderer can ignore them, but a point classifier cannot. Classify such a ray with neighborhoods, or perturb it.
- Normals of subtracted faces. At an interval end that comes from in , the normal of points into the material of the result. Reverse it, or the shading is wrong on every cut face.
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/csg-ray-casting/. The authors are listed in prov/K0WQSY.jsonl.
"""Roth's ray casting of a CSG solid, with exact rational ray parameters.
A primitive is a bounded convex polyhedron, given as a list of half-spaces
(a, b) that mean a . x <= b, with a a 3-vector. An inner node is a tuple
(op, left, right) with op in "union", "intersection" and "difference". A ray
is o + t d. Coordinates are int or Fraction.
The result of casting is a sorted list of disjoint closed intervals
(t0, t1), t0 < t1, of the parameter t on the whole line: the regularized
classification of the line against the solid. Intervals of length zero
(a ray that only grazes an edge or a vertex) are dropped.
"""
from fractions import Fraction
from typing import Optional, Sequence, Union
Num = Union[int, Fraction]
Vec3 = tuple[Num, Num, Num]
HalfSpace = tuple[Vec3, Num]
Primitive = list[HalfSpace]
Tree = Union[Primitive, tuple]
Intervals = list[tuple[Fraction, Fraction]]
OPS = {
"union": lambda a, b: a or b,
"intersection": lambda a, b: a and b,
"difference": lambda a, b: a and not b,
}
def _dot(a: Sequence[Num], b: Sequence[Num]) -> Num:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def _is_node(tree: Tree) -> bool:
return isinstance(tree, tuple) and len(tree) == 3 and isinstance(tree[0], str)
def ray_primitive(o: Vec3, d: Vec3, prim: Primitive) -> Intervals:
"""The interval of the line o + t d inside a bounded convex polyhedron."""
lo: Optional[Fraction] = None
hi: Optional[Fraction] = None
for a, b in prim:
s = _dot(a, d)
r = b - _dot(a, o)
if s == 0:
if r < 0:
return [] # the line is parallel to the plane and outside it
continue
t = Fraction(r) / s
if s > 0:
hi = t if hi is None or t < hi else hi
else:
lo = t if lo is None or t > lo else lo
if lo is None or hi is None:
raise ValueError("the primitive is not bounded along the ray")
return [(lo, hi)] if lo < hi else []
def _inside(intervals: Intervals, t: Fraction) -> bool:
return any(t0 < t < t1 for t0, t1 in intervals)
def merge(A: Intervals, B: Intervals, op: str) -> Intervals:
"""Combine two interval lists by a regularized operation on the line."""
f = OPS[op]
E = sorted({t for iv in A + B for t in iv}) # @line L5
out: Intervals = []
for e0, e1 in zip(E, E[1:]): # @line L6
m = (e0 + e1) / 2 # @line L7
if f(_inside(A, m), _inside(B, m)):
if out and out[-1][1] == e0: # @line L8
out[-1] = (out[-1][0], e1) # touching pieces join: no interval of length zero between
else:
out.append((e0, e1))
return out
def cast(o: Vec3, d: Vec3, tree: Tree) -> Intervals:
"""The intervals of the line o + t d inside the solid. Cost: O(k log k) per node for k end points."""
if not _is_node(tree): # @line L1
return ray_primitive(o, d, tree) # @line L2
op, left, right = tree
A, B = cast(o, d, left), cast(o, d, right) # @line L3
return merge(A, B, op) # @line L4
def first_hit(o: Vec3, d: Vec3, tree: Tree) -> Optional[Fraction]:
"""The least t >= 0 with o + t d in the solid, or None. It is 0 if o is in the solid."""
R = cast(o, d, tree) # @line L9
for t0, t1 in R: # @line L10
if t1 >= 0:
return max(t0, Fraction(0)) # @line L11
return None # @line L12
def box(x0: Num, y0: Num, z0: Num, x1: Num, y1: Num, z1: Num) -> Primitive:
"""The box [x0, x1] x [y0, y1] x [z0, z1] as six half-spaces."""
return [((1, 0, 0), x1), ((-1, 0, 0), -x0), ((0, 1, 0), y1), ((0, -1, 0), -y0),
((0, 0, 1), z1), ((0, 0, -1), -z0)]
test_csg_ray_casting.py 125 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/csg-ray-casting/. The authors are listed in prov/K0WQSY.jsonl.
import random
import unittest
from fractions import Fraction
from csg_ray_casting import box, cast, first_hit, merge
F = Fraction
def dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def is_node(t):
return isinstance(t, tuple) and len(t) == 3 and isinstance(t[0], str)
def leaves(tree):
return leaves(tree[1]) + leaves(tree[2]) if is_node(tree) else [tree]
def member(x, tree):
"""Point membership of the plain formula, with closed primitives."""
if not is_node(tree):
return all(dot(a, x) <= b for a, b in tree)
op, l, r = tree
p, q = member(x, l), member(x, r)
return {"union": p or q, "intersection": p and q, "difference": p and not q}[op]
def brute_intervals(o, d, tree):
"""Classify the midpoints between all plane crossings by 3D point membership."""
ts = set()
for prim in leaves(tree):
for a, b in prim:
s = dot(a, d)
if s != 0:
ts.add(F(b - dot(a, o)) / s)
ts = sorted(ts)
out = []
for t0, t1 in zip(ts, ts[1:]):
m = (t0 + t1) / 2
x = tuple(o[i] + m * d[i] for i in range(3))
if member(x, tree):
if out and out[-1][1] == t0:
out[-1] = (out[-1][0], t1)
else:
out.append((t0, t1))
return out
def in_a_face_plane(o, d, tree):
return any(dot(a, d) == 0 and dot(a, o) == b for prim in leaves(tree) for a, b in prim)
def random_primitive(rng):
lo = [rng.randint(0, 3) for _ in range(3)]
hi = [x + rng.randint(1, 3) for x in lo]
prim = box(lo[0], lo[1], lo[2], hi[0], hi[1], hi[2])
center = [F(lo[i] + hi[i], 2) for i in range(3)]
for _ in range(rng.randint(0, 2)):
a = tuple(rng.randint(-2, 2) for _ in range(3))
if a != (0, 0, 0):
prim.append((a, dot(a, center) + rng.randint(0, 2))) # a cut that keeps the center
return prim
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.25:
return random_primitive(rng)
op = rng.choice(["union", "union", "intersection", "difference"])
return (op, random_tree(rng, depth - 1), random_tree(rng, depth - 1))
A = box(0, 0, 0, 1, 1, 1)
B = box(1, 0, 0, 2, 1, 1)
C = box(F(3, 2), F(1, 4), F(1, 4), F(5, 2), F(3, 4), F(3, 4))
O, D = (-1, F(1, 2), F(1, 2)), (1, 0, 0)
class TestCsgRayCasting(unittest.TestCase):
def test_worked_example(self):
self.assertEqual(cast(O, D, A), [(1, 2)])
self.assertEqual(cast(O, D, B), [(2, 3)])
self.assertEqual(cast(O, D, ("union", A, B)), [(1, 3)])
self.assertEqual(cast(O, D, C), [(F(5, 2), F(7, 2))])
tree = ("difference", ("union", A, B), C)
self.assertEqual(cast(O, D, tree), [(1, F(5, 2))])
self.assertEqual(first_hit(O, D, tree), 1)
def test_touching_and_grazing(self):
self.assertEqual(cast(O, D, ("intersection", A, B)), [])
self.assertEqual(cast((1, -1, F(1, 2)), (-1, 1, 0), A), []) # touches only the edge x = y = 0
self.assertEqual(merge([(0, 1)], [(1, 2)], "union"), [(0, 2)])
self.assertEqual(merge([(0, 3)], [(1, 2)], "difference"), [(0, 1), (2, 3)])
self.assertEqual(merge([(0, 2)], [(0, 2)], "difference"), [])
def test_first_hit_inside_and_miss(self):
self.assertEqual(first_hit((F(1, 2), F(1, 2), F(1, 2)), (1, 0, 0), A), 0)
self.assertIsNone(first_hit((-1, 5, 5), (1, 0, 0), A))
self.assertIsNone(first_hit((3, F(1, 2), F(1, 2)), (1, 0, 0), A))
def test_random_against_point_membership(self):
rng = random.Random(1982)
done = hits = 0
while done < 600 or hits < 300:
tree = random_tree(rng, 3)
o = tuple(F(rng.randint(-8, 16), 2) for _ in range(3))
aim = tuple(F(rng.randint(1, 11), 2) for _ in range(3)) # aim into the scene
d = tuple(int(2 * (aim[i] - o[i])) for i in range(3))
if d == (0, 0, 0) or in_a_face_plane(o, d, tree):
continue
expect = brute_intervals(o, d, tree)
self.assertEqual(cast(o, d, tree), expect)
hit = next((max(t0, F(0)) for t0, t1 in expect if t1 >= 0), None)
self.assertEqual(first_hit(o, d, tree), hit)
done += 1
hits += bool(expect)
if __name__ == "__main__":
unittest.main()
History
Tilove's set membership classification of 1980 already classified line segments against a CSG tree. Scott Roth, at General Motors Research, made ray casting the base of a solid modeling system and published the method in 1982: it rendered line drawings and shaded pictures and computed volumes from the ray intervals.
References
- Scott D. Roth, Ray casting for modeling solids, Computer Graphics and Image Processing 18(2), 109 to 144, 1982, the whole paper (rays against primitives, the combination of the ray intervals by the tree, pictures and volumes)
- Robert B. Tilove, Set membership classification, a unified approach to geometric intersection problems, IEEE Transactions on Computers C-29(10), 874 to 883, 1980, the classification of a line segment against a CSG tree, of which the ray is the one-dimensional case
- Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the sections on CSG representations and the algorithms that evaluate them
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 K0WQSY Edit this page History Report an error Markdown