Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.3

0.9.3 / src / modeling / blend_fits.lucb

## Whether a blend fits its edge's faces (blend.lucb): how far it reaches
## into each face against how far the face goes, said with the size that
## would fit when it does not.

## How far along each face from edge `e` a blend of `size` reaches (a
## fillet's contact distance, a chamfer's own size).
func reach_of(w: const Shape*, e: usize, size: f64, round: bool) -> f64!:
    if not round: return size
    let (fa, fb) = try edge_faces(w, e)
    let along = try along_edge(w, e)
    let ua = try into_face(w, fa, e, along)
    let ub = try into_face(w, fb, e, along)
    let angle = math.acos(math.clamp(ua.dot(ub), -1.0, 1.0))
    return size / math.tan(angle * 0.5)

## How far into face `f` from edge `e` the blend's contact can reach before
## leaving it: over samples along the edge, the least distance to the
## face's boundary going straight in.
## On a cylinder along the edge (`around`), the step goes around its
## circle.
func room(w: const Shape*, e: usize, f: usize, limit: f64, around: bool = false) -> f64!:
    var least = limit
    for k in 1..<8: least = try room_at(w, e, f, least, (f64)k / 8.0, around)
    return least

## room at one `fraction` of the way along edge `e`: how far in face `f`
## goes from there, up to `limit`.
func room_at(w: const Shape*, e: usize, f: usize, limit: f64, fraction: f64, around: bool = false) -> f64!:
    let edge = w.edges.items[e]
    let least = limit
    let p = try w.edge_at(e, fraction)
    let t = edge.t0 + (edge.t1 - edge.t0) * fraction
    let along = (try w.tangent(edge.carrier, t)).multiply_scalar(1.0 if edge.t1 > edge.t0 else -1.0)
    let n = try w.face_normal(f, p)
    var side = try n.cross(try along.normalized()).normalized()
    # Which way is into the face: a quarter of the reach in, clear of
    # where a curved boundary's chart (its chords) is off the edge,
    # else (a face narrower than that) a hair in.
    let quarter = least * 0.25
    let ahead = try face_contains(w, f, try stepped(w, f, p, side, quarter, around), w.tolerance) == inside_face
    let behind = try face_contains(w, f, try stepped(w, f, p, side.multiply_scalar(-1.0), quarter, around), w.tolerance) == inside_face
    if behind and not ahead: side = side.multiply_scalar(-1.0)
    elif ahead == behind:
        let probe = try stepped(w, f, p, side, least * 1e-3 + w.tolerance * 100.0, around)
        if try face_contains(w, f, probe, w.tolerance) != inside_face: side = side.multiply_scalar(-1.0)
    # On a rim's cylinder the straight step runs along the axis, on the
    # face; one leaving the surface has left the face.
    let far = try stepped(w, f, p, side, least, around)
    if try face_contains(w, f, far, w.tolerance) != outside and try on_face_surface(w, f, far): return least
    var inside_at = 0.0
    var outside_at = least
    for _ in 0..<40:
        let middle = (inside_at + outside_at) * 0.5
        let q = try stepped(w, f, p, side, middle, around)
        if try on_face_surface(w, f, q) and try face_contains(w, f, q, w.tolerance) != outside: inside_at = middle
        else: outside_at = middle
    return inside_at

## `p` moved `distance` along `side` on face `f`: straight, or (around)
## that far around its cylinder's circle or its sphere's great circle.
func stepped(w: const Shape*, f: usize, p: Vector3, side: Vector3, distance: f64, around: bool) -> Vector3!:
    if not around: return p.add(side.multiply_scalar(distance))
    let s = w.surfaces.items[(usize)w.faces.items[f].surface]
    if s.kind == surface_sphere:
        let out = p.subtract(s.origin)
        return s.origin.add(turned_direction(out, try out.cross(side).normalized(), distance / s.radius))
    let axis_point = s.origin.add(s.z.multiply_scalar(p.subtract(s.origin).dot(s.z)))
    let r0 = p.subtract(axis_point)
    let turn = 1.0 if s.z.cross(r0).dot(side) > 0.0 else -1.0
    return axis_point.add(turned_direction(r0, s.z, turn * distance / s.radius))

func on_face_surface(w: const Shape*, f: usize, p: Vector3) -> bool!:
    let s = &w.surfaces.items[(usize)w.faces.items[f].surface]
    if s.kind == surface_spline: return true
    return surface_distance(s, p) <= w.tolerance * 10.0

## Parasolid's overlap limit for a fillet of `size` on straight edge `e`
## between flat faces: the longest stretch of the edge along which it fits
## both faces, as fractions along it (start, finish); (0, 1) when it fits
## all along, an error when nowhere.
func overlap_limits(w: const Shape*, e: usize, size: f64, round: bool) -> (f64, f64)!:
    let (fa, fb) = try edge_faces(w, e)
    let reach = try reach_of(w, e, size, round)
    let samples: usize = 64
    var best_start: i64 = -1
    var best_count: usize = 0
    var run_start: i64 = -1
    for k in 0..<samples + 1:
        let fraction = math.clamp((f64)k / (f64)samples, 1e-3, 1.0 - 1e-3)
        let fits = try fits_at(w, e, fa, fb, reach, fraction)
        if fits and run_start < 0: run_start = (i64)k
        if (not fits or k == samples) and run_start >= 0:
            let end = k + 1 if fits else k
            if end - (usize)run_start > best_count:
                best_count = end - (usize)run_start
                best_start = run_start
            run_start = -1
    if best_count == 0: error(invalid, "an overlap limit leaves this fillet nowhere it fits its faces")
    let first = (usize)best_start
    let last = first + best_count - 1
    var start = 0.0
    var finish = 1.0
    if first > 0: start = try fit_boundary(w, e, fa, fb, reach, (f64)(first - 1) / (f64)samples, (f64)first / (f64)samples)
    if last < samples: finish = try fit_boundary(w, e, fa, fb, reach, (f64)(last + 1) / (f64)samples, (f64)last / (f64)samples)
    # The faces' boundaries are found within their charts' tolerance: a
    # limit that near a body vertex (the corner where the face narrows) is
    # moved onto it, so no sliver of cap is left beside it.
    let a = try w.edge_at(e, 0.0)
    let span = (try w.edge_at(e, 1.0)).subtract(a)
    let length = span.length()
    for q in w.points.view():
        let at = q.subtract(a).dot(span) / (length * length)
        if start > 0.0 and math.abs(at - start) * length < reach * 1e-3: start = at
        if finish < 1.0 and math.abs(at - finish) * length < reach * 1e-3: finish = at
    return (start, finish)

## Whether a blend reaching `reach` into faces `fa` and `fb` fits both at
## `fraction` along edge `e`.
func fits_at(w: const Shape*, e: usize, fa: usize, fb: usize, reach: f64, fraction: f64) -> bool!:
    let limit = reach * 1.01 + w.tolerance * 100.0
    return (try room_at(w, e, fa, limit, fraction)) > reach + w.tolerance * 10.0 and (try room_at(w, e, fb, limit, fraction)) > reach + w.tolerance * 10.0

## Where between fractions `misfit` (no fit) and `fit` (a fit) the blend
## starts to fit, by bisection.
func fit_boundary(w: const Shape*, e: usize, fa: usize, fb: usize, reach: f64, misfit: f64, fit: f64) -> f64!:
    var bad = misfit
    var good = fit
    for _ in 0..<40:
        let middle = (bad + good) * 0.5
        if try fits_at(w, e, fa, fb, reach, middle): good = middle
        else: bad = middle
    return good

## How a blend runs off one of its edge's faces (fits_plan): `how` one of
## the spill kinds, `off` the face it runs off, `far` that face's edge
## where it does, `face` the face beyond (a ledge, the curved face it rolls
## onto; -1 none) and `depth` how far `off` goes in from the edge.
struct Spill:
    var how: i64
    var off: i64
    var far: i64
    var face: i64
    var depth: f64

## Spill kinds. Fits: no overflow. Notch: the tool unchanged, reaching past
## the face for the next one to trim (over a convex edge). Ledge: notch over
## a concave edge, the tool stopped at the ledge's plane, which covers the
## blend's end (cliff_cut). Cliff: Parasolid's cliff-edge blend, its section
## tangent to the other face and running through the edge where this one
## ends (cliff_profile). Rolled: smooth onto a curved face tangent to this
## one, the ball touching it instead (rolled_profile).
let spill_fits: i64 = 0
let spill_notch: i64 = 1
let spill_ledge: i64 = 2
let spill_cliff: i64 = 3
let spill_rolled: i64 = 4

let no_spill: Spill = Spill(spill_fits, -1, -1, -1, 0.0)

## A blend of `size` on edge `e` must reach less far than its faces go
## (all the way, a face would vanish): else an error saying so, and the
## size it must stay under.
func check_fits(w: const Shape*, e: usize, size: f64, round: bool, overflow: i64 = overflow_default, continuity: i64 = 1, blend_shape: BlendShape = plain_blend) -> !:
    _ = try fits_plan(w, e, size, round, overflow, continuity, blend_shape)

## check_fits, and how the blend runs off each of the edge's two faces
## (Spill): by the behaviours `overflow` allows, in Parasolid's order
## (smooth, cliff, notch). A face split along a line lets the ball roll on
## in its plane (flat_room); a curved face tangent to the face beyond it, a
## cylinder along the edge, takes the ball instead (rolled_spill); a cliff
## edge (the face's far edge, straight and parallel) holds the section's
## end (cliff_spill, circular sections only); notch leaves the blend as it
## is, the next face trimming it, or a ledge's plane covering its end.
## Without any (overflow 0) the blend must fit its faces.
func fits_plan(w: const Shape*, e: usize, size: f64, round: bool, overflow: i64 = overflow_default, continuity: i64 = 1, blend_shape: BlendShape = plain_blend) -> (Spill, Spill)!:
    let (fa, fb) = try edge_faces(w, e)
    # How far the blend reaches along each face: alike between planes (and
    # at rims), each its own between a plane and a cylinder (the
    # cylinder's along its circle).
    var reach_a = try reach_of(w, e, size, round)
    var reach_b = reach_a
    var around: i64 = -1
    let edge = w.edges.items[e]
    if w.carriers.items[(usize)edge.carrier].kind == curve_line:
        let cylinder = ruled_pair(w, e, fa, fb)
        if cylinder >= 0:
            around = cylinder
            let along = try along_edge(w, e)
            let p = try w.edge_at(e, 0.5)
            let plane = fb if (usize)cylinder == fa else fa
            let into_plane = try into_face(w, plane, e, along)
            let into_round = try into_face(w, (usize)cylinder, e, along)
            let (ta, tb, _) = try ruled_contacts(w, plane, (usize)cylinder, p, into_plane, into_round, size, round, try convex(w, e), size)
            let s = w.surfaces.items[(usize)w.faces.items[(usize)cylinder].surface]
            let axis_point = s.origin.add(s.z.multiply_scalar(p.subtract(s.origin).dot(s.z)))
            let arc = s.radius * math.acos(math.clamp(tb.subtract(axis_point).dot(p.subtract(axis_point)) / (s.radius * s.radius), -1.0, 1.0))
            reach_a = ta.subtract(p).length() if fa == plane else arc
            reach_b = arc if fa == plane else ta.subtract(p).length()
    # On a sphere about a rim the step runs round its meridian.
    let ball = sphere_rim(w, e, fa, fb)
    if ball >= 0: around = ball
    # A curved wall ruled away from a flat cap is followed along its rulings
    # (cap_blend.lucb, which checks its own room): a straight step across
    # it would leave it.
    # Between two curved faces the ball's own fit says when it is too large.
    if curved_pair(w, fa, fb): return (no_spill, no_spill)
    let smooth = round and (overflow & overflow_smooth) != 0
    let notch = round and (overflow & overflow_notch) != 0
    let cliffs = round and (overflow & overflow_cliff) != 0
    var room_a = reach_a * 2.0 if curved_wall(w, e, fa, fb) else try room(w, e, fa, reach_a * 1.01 + w.tolerance * 100.0, around == (i64)fa)
    var room_b = reach_b * 2.0 if curved_wall(w, e, fb, fa) else try room(w, e, fb, reach_b * 1.01 + w.tolerance * 100.0, around == (i64)fb)
    # A face split along a line goes on in its plane past it.
    if smooth and room_a <= reach_a + w.tolerance * 10.0: room_a = try flat_room(w, e, fa, room_a, reach_a * 1.01 + w.tolerance * 100.0)
    if smooth and room_b <= reach_b + w.tolerance * 10.0: room_b = try flat_room(w, e, fb, room_b, reach_b * 1.01 + w.tolerance * 100.0)
    let fits_a = room_a > reach_a + w.tolerance * 10.0
    let fits_b = room_b > reach_b + w.tolerance * 10.0
    if fits_a and fits_b: return (no_spill, no_spill)
    # Only one face may be run off: the blend needs the other to rest on.
    if not fits_a and not fits_b: return try spill_too_large(size, round, math.min(room_a / reach_a, room_b / reach_b))
    let off = fa if not fits_a else fb
    let depth = room_a if not fits_a else room_b
    var spill = no_spill
    # Smooth: onto a curved face tangent to the one it runs off.
    if smooth: spill = try rolled_spill(w, e, off, depth, size)
    # Cliff: tangent to the other face, through the edge where this one ends.
    if spill.how == spill_fits and cliffs: spill = try cliff_spill(w, e, off, depth, size, continuity, blend_shape)
    # Notch: running off one face over a convex edge into the next face,
    # which trims it (the study's rail classification, its same-convexity
    # case: a plate thinner than the radius): the edge's tool reaches past
    # that face, outside the body, and the booleans cut it at the next
    # face. Over a concave edge (a ledge below the face) the tool would
    # reach into the ledge: it stops at the ledge's plane, which then covers
    # the fillet there.
    if spill.how == spill_fits and notch:
        let (ledge, ledge_edge) = try face_across(w, e, off, depth, beyond_concave)
        if ledge >= 0: spill = Spill(spill_ledge, (i64)off, (i64)ledge_edge, ledge, depth)
        elif try overflows(w, e, off, depth): spill = Spill(spill_notch, (i64)off, -1, -1, depth)
        elif try notched_end(w, e, off, depth): spill = Spill(spill_notch, (i64)off, -1, -1, depth)
    if spill.how == spill_fits:
        if cliffs and not (continuity == 1 and blend_shape.plain()) and (try far_edge(w, e, off, depth)) >= 0: error(invalid, "a cliff-edge overflow takes a circular (G1) fillet: turn Cliff off or use G1")
        return try spill_too_large(size, round, depth / (reach_a if not fits_a else reach_b))
    if not fits_a: return (spill, no_spill)
    return (no_spill, spill)

## The error for a blend of `size` too large for its faces: it must be
## under `share` of it.
func spill_too_large(size: f64, round: bool, share: f64) -> (Spill, Spill)!:
    let most = size * share
    var buffer: u8[256]
    let text = try strings.format(buffer, f"a fillet radius of {rounded_text(size)} is too large for this edge's faces: it must be less than {rounded_text(most)}") if round else try strings.format(buffer, f"a chamfer of {rounded_text(size)} is too large for this edge's faces: it must be less than {rounded_text(most)}")
    let owned = try interop.copy_text(text)
    if let owner = owned.owner: _ = ownership.pool_object(owner)
    error(invalid, owned.value)

## Whether face `wall` is a curved wall ruled away from flat face `cap`
## along edge `e`: a cylinder or cone, or a sweep, that cap_blend follows.
func curved_wall(w: const Shape*, e: usize, wall: usize, cap: usize) -> bool:
    if not cap_candidate(w, e, cap, wall): return false
    return w.surfaces.items[(usize)w.faces.items[wall].surface].kind != surface_plane

## `value` to four significant places, for messages.
func rounded_text(value: f64) -> f64:
    if value == 0.0 or not math.is_finite(value): return value
    let scale = math.pow(10.0, 3.0 - math.floor(math.log10(math.abs(value))))
    return math.round(value * scale) / scale

## Whether a fillet on straight edge `e` between flat faces may run off flat
## face `f` (which goes `depth` in from the edge): it ends there in a
## straight convex edge parallel to `e` whose other face is flat and turns
## the same way, so that face trims the fillet's surface across it.
func overflows(w: const Shape*, e: usize, f: usize, depth: f64) -> bool!:
    return (try face_beyond(w, e, f, depth, beyond_convex)) >= 0

## Whether face `f` of convex straight edge `e` between flat faces narrows
## to `depth` along only part of the edge, there ending in a straight convex
## edge parallel to `e` whose other face is flat and turns the same way (a
## notch cut into the face beside one end: Fusion's notch there, the
## fillet unchanged and the notch's faces trimming it, probe 14's cube).
func notched_end(w: const Shape*, e: usize, f: usize, depth: f64) -> bool!:
    let (fa, fb) = try edge_faces(w, e)
    if not flat_pair(w, fa, fb) or not try convex(w, e): return false
    for k in 1..<16:
        let found = try far_edge(w, e, f, depth, (f64)k / 16.0)
        if found < 0: continue
        let far = (usize)found
        let (ga, gb) = try edge_faces(w, far)
        let next = gb if ga == f else ga
        if w.surfaces.items[(usize)w.faces.items[next].surface].kind != surface_plane: continue
        if face_outward(w, next).dot(face_outward(w, f)) > 1.0 - 1e-9: continue
        if try convex(w, far): return true
    return false

## Edges face_beyond looks for: convex, concave, or flat (the faces each
## side in one plane: a face split along a line).
let beyond_convex: i64 = 0
let beyond_concave: i64 = 1
let beyond_flat: i64 = 2

## The flat face across the straight edge of flat face `f` (parallel to
## straight convex edge `e`, of the kind `kind` asks) where a step `depth`
## into `f` square to `e` leaves it, else -1; and that edge.
func face_beyond(w: const Shape*, e: usize, f: usize, depth: f64, kind: i64) -> i64!:
    let (next, _) = try face_across(w, e, f, depth, kind)
    return next

func face_across(w: const Shape*, e: usize, f: usize, depth: f64, kind: i64) -> (i64, usize)!:
    if kind != beyond_flat and not try convex(w, e): return (-1, 0)
    let found = try far_edge(w, e, f, depth)
    if found < 0: return (-1, 0)
    let far = (usize)found
    let (ga, gb) = try edge_faces(w, far)
    let next = gb if ga == f else ga
    if w.surfaces.items[(usize)w.faces.items[next].surface].kind != surface_plane: return (-1, 0)
    let flat = face_outward(w, next).dot(face_outward(w, f)) > 1.0 - 1e-9
    if kind == beyond_flat: return ((i64)next, far) if flat else (-1, 0)
    if flat or (try convex(w, far)) != (kind == beyond_convex): return (-1, 0)
    return ((i64)next, far)

## Of straight edge `e` and flat face `f` beside it, the straight edge of
## `f` parallel to `e` where a step `depth` into `f` square to `e` (from
## `fraction` of the way along `e`, its middle by default) leaves the face;
## -1 when it leaves elsewhere.
func far_edge(w: const Shape*, e: usize, f: usize, depth: f64, fraction: f64 = 0.5) -> i64!:
    let edge = w.edges.items[e]
    if w.carriers.items[(usize)edge.carrier].kind != curve_line: return -1
    if w.surfaces.items[(usize)w.faces.items[f].surface].kind != surface_plane: return -1
    let along = try along_edge(w, e)
    let p = try w.edge_at(e, fraction)
    let side = try into_face(w, f, e, along)
    let q = p.add(side.multiply_scalar(depth))
    # The edge of `f` where the step leaves it.
    var nearest: i64 = -1
    var gap = 1.0e300
    for use in w.face_uses(f):
        let k = edge_index(use)
        if k == e: continue
        let other = w.edges.items[k]
        let t = try nearest_on(w, other.carrier, q, other.t0, other.t1)
        let d = (try w.at(other.carrier, t)).subtract(q).length()
        if d < gap:
            gap = d
            nearest = (i64)k
    if nearest < 0 or gap > w.tolerance * 1000.0 + depth * 1e-6: return -1
    let far = (usize)nearest
    if w.carriers.items[(usize)w.edges.items[far].carrier].kind != curve_line: return -1
    if math.abs((try along_edge(w, far)).dot(along)) < 1.0 - 1e-9: return -1
    return nearest

## Smooth overflow onto a curved face: where face `off` (flat, `depth` in
## from straight edge `e` between flat faces) ends in a straight edge
## parallel to `e` with a cylinder about a parallel axis beyond it, tangent
## to `off` there (an earlier round of the face's far edge), the ball
## touching the edge's other face and that cylinder (ruled_contacts), when
## its contacts lie on both faces. At an inside edge the ball rolls in the
## air, onto a wall's rounded top (Fusion's, probe 14: a wall 2 high, its
## top rounded 1.5, its foot filleted 3).
func rolled_spill(w: const Shape*, e: usize, off: usize, depth: f64, size: f64) -> Spill!:
    let (fa, fb) = try edge_faces(w, e)
    if not flat_pair(w, fa, fb): return no_spill
    let outer = try convex(w, e)
    let found = try far_edge(w, e, off, depth)
    if found < 0: return no_spill
    let far = (usize)found
    let (ga, gb) = try edge_faces(w, far)
    let next = gb if ga == off else ga
    let s = w.surfaces.items[(usize)w.faces.items[next].surface]
    let along = try along_edge(w, e)
    if s.kind != surface_cylinder or s.z.cross(along).length() > 1e-9: return no_spill
    # Tangent to `off` along the far edge: the plane at the radius from the
    # axis, the cylinder's normal there the plane's.
    let m = try w.edge_at(far, 0.5)
    if math.abs((try w.face_normal(next, m)).dot(face_outward(w, off)) - 1.0) > 1e-6: return no_spill
    let rest = fb if off == fa else fa
    let p = try w.edge_at(e, 0.5)
    let (ta, tb, _) = ruled_contacts(w, rest, next, p, try into_face(w, rest, e, along), Vector3(), size, true, outer, size) catch failure:
        if failure.code != invalid: error(failure.code, failure.message)
        recover (Vector3(), Vector3(1e300, 0.0, 0.0), Vector3())
    if tb.x > 1e299: return no_spill
    if not try rests_on(w, e, rest, ta.subtract(p).length()): return no_spill
    if try face_contains(w, next, tb, w.tolerance) == outside: return no_spill
    return Spill(spill_rolled, (i64)off, found, (i64)next, depth)

## Cliff overflow: where face `off` (flat, `depth` in from straight edge
## `e` between flat faces, convex or concave: an inside corner's wall lower
## than the fillet) ends in a straight edge parallel to `e`,
## Parasolid's cliff-edge blend, its circle tangent to the other face and
## through that edge (cliff_circle), when it touches the other face on it.
## Circular sections only.
func cliff_spill(w: const Shape*, e: usize, off: usize, depth: f64, size: f64, continuity: i64, blend_shape: BlendShape) -> Spill!:
    if continuity != 1 or not blend_shape.plain(): return no_spill
    let (fa, fb) = try edge_faces(w, e)
    if not flat_pair(w, fa, fb): return no_spill
    let found = try far_edge(w, e, off, depth)
    if found < 0: return no_spill
    let spill = Spill(spill_cliff, (i64)off, found, -1, depth)
    let p = try w.edge_at(e, 0.5)
    let (ta, _, _) = cliff_circle(w, e, &spill, p, size) catch failure:
        if failure.code != invalid: error(failure.code, failure.message)
        recover (Vector3(1e300, 0.0, 0.0), Vector3(), Vector3())
    if ta.x > 1e299: return no_spill
    let rest = fb if off == fa else fa
    if not try rests_on(w, e, rest, ta.subtract(p).length()): return no_spill
    return spill

## Whether flat face `f` beside edge `e` goes on past `reach` in from it.
func rests_on(w: const Shape*, e: usize, f: usize, reach: f64) -> bool!:
    return (try room(w, e, f, reach * 1.01 + w.tolerance * 100.0)) > reach + w.tolerance * 10.0

## A cliff-edge blend's circle at edge point `p` (spill `spill`): its
## contact on the other face, its end on the cliff edge and its center; an
## error when no circle of radius `size` tangent to that face passes
## through the cliff edge on the corner's side.
func cliff_circle(w: const Shape*, e: usize, spill: const Spill*, p: Vector3, size: f64) -> (Vector3, Vector3, Vector3)!:
    let (fa, fb) = try edge_faces(w, e)
    let rest = fb if (usize)spill.off == fa else fa
    let along = try along_edge(w, e)
    let ua = try into_face(w, rest, e, along)
    # The cliff edge's point in p's section plane.
    let on = try w.edge_at((usize)spill.far, 0.0)
    let q = on.subtract(along.multiply_scalar(on.subtract(p).dot(along)))
    let d = q.subtract(p)
    let qs = d.dot(ua)
    let lateral = d.subtract(ua.multiply_scalar(qs))
    let qt = lateral.length()
    if qt <= w.tolerance or qt >= 2.0 * size: error(invalid, "a cliff-edge blend's cliff is farther from its other face than the fillet's diameter")
    let na = lateral.multiply_scalar(1.0 / qt)
    let sc = qs + math.sqrt(size * size - (qt - size) * (qt - size))
    if sc <= w.tolerance: error(invalid, "a cliff-edge blend's circle touches its other face behind the edge")
    let center = p.add(ua.multiply_scalar(sc)).add(na.multiply_scalar(size))
    return (p.add(ua.multiply_scalar(sc)), q, center)

## How far a fillet on edge `e` can step into flat face `f` (`first`, short
## of `reach`) and on into the faces beyond it in its plane, across
## straight edges parallel to `e` (a face split along a line: the ball
## rolls on over the line).
func flat_room(w: const Shape*, e: usize, f: usize, first: f64, reach: f64) -> f64!:
    var total = first
    var step = first
    var face = f
    var edge = e
    for _ in 0..<8:
        if total > reach: return total
        let (next, far) = try face_across(w, edge, face, step, beyond_flat)
        if next < 0: return total
        step = try room(w, far, (usize)next, reach - total + w.tolerance * 100.0)
        total += step
        face = (usize)next
        edge = far
    return total

## Edge tool `tool` stopped at the plane of flat face `beyond` (a cliff's
## ledge, cliff): its part on the face's outward side kept.
func cliff_cut(w: const Shape*, tool: interop.Reference[CadModel], beyond: i64, name: str) -> interop.Reference[CadModel]!:
    let s = &w.surfaces.items[(usize)w.faces.items[(usize)beyond].surface]
    let out = face_outward(w, (usize)beyond)
    var no_points = Growing[Vector3]()
    defer no_points.close()
    var knots = Growing[f64]()
    defer knots.close()
    var plane = try Surface(surface_plane, s.origin, s.x, out.multiply_scalar(-1.0), 0.0, 0.0, no_points.view(), knots.view(), knots.view(), knots.view(), 0, 0, 0, 0)
    defer plane.close()
    let kept = (try behind_surface(tool.value(), &plane, name)) else return tool.clone()
    return kept