Algorithm Search⌘K

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
Properties
deterministicofflinerecursive
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 ∪∗\cup^*, ∩∗\cap^* and −∗-^*, and a ray o+tdo + t d with d≠0d \ne 0. The output is the set of t∈Rt \in \mathbb{R} with o+tdo + t d in the solid, as a sorted list of disjoint closed intervals of positive length. Often only the first hit is needed: the least t≥0t \ge 0 in that set. This page treats the whole line; a ray is the part with t≥0t \ge 0.

The algorithm

  1. CAST(o, d, T) ▷ sorted disjoint closed intervals of t
  2. 1if T is a primitive then
  3. 2return the intervals of o + t d inside T, without those of length 0
  4. 3A ← CAST(o, d, T.left), B ← CAST(o, d, T.right)
  5. 4return MERGE(A, B, T.op)
  6. MERGE(A, B, op)
  7. 5E ← the end points of A and B, sorted, without repeats
  8. 6for each pair e_j < e_{j+1} of consecutive points of E do
  9. 7if op(the midpoint is inside A, the midpoint is inside B) then
  10. 8add [e_j, e_{j+1}], joined with the last interval if that one ends at e_j
  11. FIRST-HIT(o, d, T)
  12. 9R ← CAST(o, d, T)
  13. 10for each [t0, t1] in R, in order do
  14. 11if t1 ≥ 0 then return max(t0, 0)
  15. 12return none

Line L2 depends on the primitive. For a convex polyhedron {x:ai⋅x≤bi}\{x : a_i \cdot x \le b_i\} it is the slab method: each plane bounds tt from one side, at t=(bi−ai⋅o)/(ai⋅d)t = (b_i - a_i \cdot o)/(a_i \cdot d), and the interval is from the largest lower bound to the smallest upper bound. A sphere or another quadric gives a quadratic in tt 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 AA and in BB 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 00 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 A=[0,1]3A = [0, 1]^3 and B=[1,2]×[0,1]2B = [1, 2] \times [0, 1]^2 be two unit cubes that share the face x=1x = 1, and let C=[3/2,5/2]×[1/4,3/4]2C = [3/2, 5/2] \times [1/4, 3/4]^2 be a box that cuts a notch into the end of BB. The solid is (A∪∗B)−∗C(A \cup^* B) -^* C. Cast the ray o=(−1,1/2,1/2)o = (-1, 1/2, 1/2), d=(1,0,0)d = (1, 0, 0), so the point at parameter tt has x=t−1x = t - 1.

node intervals of tt
AA [1,2][1, 2]
BB [2,3][2, 3]
A∪∗BA \cup^* B [1,3][1, 3]
CC [5/2,7/2][5/2, 7/2]
(A∪∗B)−∗C(A \cup^* B) -^* C [1,5/2][1, 5/2]

At the union, E={1,2,3}E = \{1, 2, 3\}. Both pieces (1,2)(1, 2) and (2,3)(2, 3) are inside, and line L8 joins them, so the shared face at t=2t = 2 leaves no trace. At the difference, E={1,3,5/2,7/2}E = \{1, 3, 5/2, 7/2\} sorted to 1,5/2,3,7/21, 5/2, 3, 7/2. Only (1,5/2)(1, 5/2) is inside A∪∗BA \cup^* B and outside CC. The first hit is t=1t = 1, the point (0,1/2,1/2)(0, 1/2, 1/2) on the left face of AA, and the ray is inside the solid for a length of 3/23/2.

Two more cases. For A∩∗BA \cap^* B the lists [1,2][1, 2] and [2,3][2, 3] meet only at t=2t = 2, so MERGE returns nothing: the touching cubes have an empty regularized intersection. The ray o=(1,−1,1/2)o = (1, -1, 1/2), d=(−1,1,0)d = (-1, 1, 0) meets AA only at t=1t = 1, at the point (0,0,1/2)(0, 0, 1/2) on an edge. Line L2 gets the interval [1,1][1, 1] of length 00 and drops it, so the ray misses AA.

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 tt with o+tdo + t d 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 TT be a CSG tree whose leaves are bounded convex polyhedra Pi={x:aij⋅x≤bij}P_i = \{x : a_{ij} \cdot x \le b_{ij}\} with nonempty interior, and whose inner nodes are ∪∗\cup^*, ∩∗\cap^* and −∗-^*. Write XTX_T for the solid of TT. Let ℓ(t)=o+td\ell(t) = o + t d with d≠0d \ne 0, and let IT={t:ℓ(t)∈XT}I_T = \{t : \ell(t) \in X_T\}. 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 i,ji, j are both aij⋅d=0a_{ij} \cdot d = 0 and aij⋅o=bija_{ij} \cdot o = b_{ij}.

Let ZZ be the finite set of tt with aij⋅ℓ(t)=bija_{ij} \cdot \ell(t) = b_{ij} and aij⋅d≠0a_{ij} \cdot d \ne 0 for some i,ji, j. A cell is a connected component of R∖Z\mathbb{R} \setminus Z.

Lemma 1. Let κ\kappa be a cell. Then for each subtree SS of TT, either ℓ(κ)⊆int⁡XS\ell(\kappa) \subseteq \operatorname{int} X_S or ℓ(κ)∩XS=∅\ell(\kappa) \cap X_S = \emptyset. Write ϕS(κ)\phi_S(\kappa) for true in the first case and false in the second. Then ϕS(κ)=op⁡(ϕS.left(κ),ϕS.right(κ))\phi_S(\kappa) = \operatorname{op}(\phi_{S.\text{left}}(\kappa), \phi_{S.\text{right}}(\kappa)) at each inner node, where op is or, and, or and-not.

Proof. Each function gij(x)=aij⋅x−bijg_{ij}(x) = a_{ij} \cdot x - b_{ij} is affine. If aij⋅d≠0a_{ij} \cdot d \ne 0, then gij(ℓ(t))g_{ij}(\ell(t)) has its only zero in ZZ, so it has a constant nonzero sign on κ\kappa. If aij⋅d=0a_{ij} \cdot d = 0, then gij(ℓ(t))g_{ij}(\ell(t)) is constant, and it is not zero by the assumption. Fix t∈κt \in \kappa. There is a ball UU around ℓ(t)\ell(t) on which every gijg_{ij} keeps the sign it has at ℓ(t)\ell(t). So U⊆int⁡PiU \subseteq \operatorname{int} P_i or U∩Pi=∅U \cap P_i = \emptyset for each leaf. At an inner node with children whose sets each fill UU or miss it, the plain set operation gives UU or ∅\emptyset. The regularization cl⁡(int⁡⋅)\operatorname{cl}(\operatorname{int} \cdot) does not change a set on the open set UU when that set is UU or ∅\emptyset there. So by induction XS∩UX_S \cap U is UU or ∅\emptyset, as the Boolean formula says. The signs are the same for all t∈κt \in \kappa, so the choice is the same along the cell. □\square

Lemma 2. Let WSW_S be the union of the cells κ\kappa with ϕS(κ)\phi_S(\kappa) true, and let JS=cl⁡WSJ_S = \operatorname{cl} W_S. Then JS=cl⁡(int⁡IS)J_S = \operatorname{cl}(\operatorname{int} I_S), the regularization of ISI_S on the line, and IS∖JSI_S \setminus J_S is a finite subset of ZZ.

Proof. By Lemma 1, IS∖Z=WSI_S \setminus Z = W_S. The set WSW_S is open and lies in ISI_S, so WS⊆int⁡ISW_S \subseteq \operatorname{int} I_S. Conversely, int⁡IS∖Z\operatorname{int} I_S \setminus Z lies in WSW_S, and removing finitely many points from an open subset of R\mathbb{R} does not change its closure. So cl⁡(int⁡IS)=cl⁡WS\operatorname{cl}(\operatorname{int} I_S) = \operatorname{cl} W_S. Finally IS∖JS⊆IS∖WS⊆ZI_S \setminus J_S \subseteq I_S \setminus W_S \subseteq Z. □\square

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 XSX_S in isolated points. The regularized classification of the line drops them, and the result is JSJ_S.

Theorem. Under the assumption, CAST(o,d,T)(o, d, T) returns a nice list whose union is JTJ_T, and FIRST-HIT returns min⁡(JT∩[0,∞))\min (J_T \cap [0, \infty)), or none when this set is empty.

Proof. By induction on the tree.

Leaf. Line L2 takes lolo as the largest τ=(b−a⋅o)/(a⋅d)\tau = (b - a \cdot o)/(a \cdot d) over the planes with a⋅d<0a \cdot d < 0 and hihi as the smallest over the planes with a⋅d>0a \cdot d > 0, and returns the empty list if a plane with a⋅d=0a \cdot d = 0 has the line outside. The open interval (lo,hi)(lo, hi) is then the set of tt where all strict inequalities hold, which is WPiW_{P_i}. If lo<hilo < hi, the closure is [lo,hi][lo, hi]. If lo≥hilo \ge hi, then WPiW_{P_i} is empty and so is JPiJ_{P_i}. In both cases the output is a nice list for JPiJ_{P_i}.

Inner node. By the induction hypothesis, AA and BB are nice lists for JleftJ_{\text{left}} and JrightJ_{\text{right}}. Let EE be the end points as in line L5. On an open piece (ej,ej+1)(e_j, e_{j+1}) there is no end point of AA or BB, so the piece lies in the interior of one interval of AA or misses all intervals of AA, and the same holds for BB. Every cell in the piece then has ϕleft(κ)\phi_{\text{left}}(\kappa) equal to the test "the midpoint is inside AA", and the same for BB, because Jleft∖Z=WleftJ_{\text{left}} \setminus Z = W_{\text{left}}. By Lemma 1, line L7 computes ϕT(κ)\phi_T(\kappa) for every cell in the piece. Outside [min⁡E,max⁡E][\min E, \max E] both children are false, and op(false, false) is false for all three operations. So the true pieces cover WTW_T up to finitely many points of ZZ, and the closure of their union is JTJ_T. 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 [t0,t1][t_0, t_1] has t1≥0t_1 \ge 0, all earlier intervals lie in t<0t < 0, and the least point of [t0,t1]∩[0,∞)[t_0, t_1] \cap [0, \infty) is max⁡(t0,0)\max(t_0, 0). If no interval has t1≥0t_1 \ge 0, then JT∩[0,∞)J_T \cap [0, \infty) is empty. ■\blacksquare

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 [0,1]3[0, 1]^3 and [1,2]×[0,1]2[1, 2] \times [0, 1]^2 and the line o=(1,−1,1/2)o = (1, -1, 1/2), d=(0,1,0)d = (0, 1, 0) in the shared face, both leaves give [1,2][1, 2], so CAST returns [1,2][1, 2] 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 kk faces costs O(k)O(k), so all leaves cost O(m)O(m). 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 2ℓ2 \ell for ℓ\ell convex leaves. A linear merge costs O(ℓ)O(\ell). Each leaf is below at most hh nodes, so all merges cost O(Lh)O(L h), which is O(L2)O(L^2) for a tree of height L−1L - 1 and O(Llog⁡L)O(L \log L) for a balanced tree.
  • A picture. An image of PP pixels casts PP rays, for O(P(m+Lh))O(P (m + L h)) 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 ss and add s2s^2 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 [1,1][1, 1] 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 [1,2][1, 2] and [2,3][2, 3] as two intervals, the shared face of two touching primitives stays as a false exit and entry at t=2t = 2. 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 AA and the entry into BB at a shared face are two separately rounded numbers. If the exit is a little larger, the intersection A∩∗BA \cap^* B 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 o=(1,−1,1/2)o = (1, -1, 1/2), d=(0,1,0)d = (0, 1, 0) in the shared face x=1x = 1, both AA and BB give [1,2][1, 2], so line L4 returns [1,2][1, 2] for A∩∗BA \cap^* B, 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 CC in A−∗CA -^* C, the normal of CC 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.

csg_ray_casting.pyI0RawGitHub
# 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

  1. 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)
  2. 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
  3. 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.

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