Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.4

0.9.4 / src / modeling / blend_tools.lucb

## Blend tools (blend.lucb): the solids the booleans take away or add for
## each blended edge. A corner profile (a chamfer's triangle, a fillet's
## circle or G2/G3 B-spline section) between the edge's faces, swept along
## a straight edge or turned about a rim's axis, reaching past an end only
## where nothing is there; concave edges' tools end flush with the face at
## each end. A plane meeting a cylinder along the edge has its own section
## (ruled_profile).

## The section of edge `e`'s blend at `p` (its start), swept along `along`:
## the corner profile between two planes, or between a plane and a
## cylinder along the edge (ruled_profile). A chamfer reaches `other` along
## the edge's second face when it is positive (chamfers.lucb's two-sided
## ones), else `size` like the first. A fillet running off a face
## (`spill`, blend_fits.lucb) rolls onto the curved face beyond it, or ends
## on the cliff edge.
func section_profile(w: const Shape*, e: usize, p: Vector3, along: Vector3, size: f64, round: bool, continuity: i64, other: f64 = -1.0, blend_shape: BlendShape = plain_blend, spill: Spill = no_spill) -> Profiles!:
    if spill.how == spill_rolled: return try rolled_profile(w, e, p, along, size, continuity, blend_shape, &spill)
    if spill.how == spill_cliff: return try cliff_profile(w, e, p, along, size, &spill)
    let (fa, fb) = try edge_faces(w, e)
    let ua = try into_face(w, fa, e, along)
    let ub = try into_face(w, fb, e, along)
    let cylinder = ruled_pair(w, e, fa, fb)
    if cylinder < 0: return try corner_profile(p, along, ua, ub, size, round, continuity, other, blend_shape)
    let plane = fb if (usize)cylinder == fa else fa
    let second = other if not round and other > 0.0 else size
    let on_plane = size if plane == fa else second
    let on_round = second if plane == fa else size
    return try ruled_profile(w, plane, (usize)cylinder, p, along, ua if plane == fa else ub, ub if plane == fa else ua, on_plane, round, try convex(w, e), on_round, continuity, blend_shape)

## The section of a blend between plane face `plane` and cylinder face
## `cylinder` (its axis along the edge), at edge point `p`: the region
## between the edge, the contacts and the blend (a fillet's circle touching
## the plane and the cylinder, its center where the plane and the cylinder
## moved by the radius meet; a chamfer's line `size` along the plane and
## `other` to the cylinder), closed back along the cylinder's own circle.
## `into_plane` and `into_round` are the directions into each face from
## the edge. A G2 or G3 fillet is a spline between the same contacts on the
## corner where the plane meets the cylinder's tangent there
## (fillet_section: Fusion's G2, following the cylinder's curvature at its
## contact; G3 its change too, nil on a circle), and a G1 fillet under a
## Tangency weight the conic on that corner (arc_section: Fusion's, its
## circle at weight 1). Each touches the cylinder only tangentially; the
## booleans meet the swept section with the cylinder along it in closed
## form (splines.lucb's along_sweep). With `rim` (a ball rolled on onto a
## cylinder beyond the edge's face, rolled_profile) the region closes back
## along the cylinder only to that point, then straight to `p`.
func ruled_profile(w: const Shape*, plane: usize, cylinder: usize, p: Vector3, along: Vector3, into_plane: Vector3, into_round: Vector3, size: f64, round: bool, outward: bool, other: f64, continuity: i64 = 1, blend_shape: BlendShape = plain_blend, rim: Vector3? = none) -> Profiles!:
    let s = w.surfaces.items[(usize)w.faces.items[cylinder].surface]
    let axis_point = s.origin.add(s.z.multiply_scalar(p.subtract(s.origin).dot(s.z)))
    let radius = s.radius
    let (ta, tb, center) = try ruled_contacts(w, plane, cylinder, p, into_plane, into_round, size, round, outward, other)
    var profile = Profiles(p, along, into_plane, along.cross(into_plane), Growing[ProfileEdge](), Growing[usize](), Growing[usize](), Growing[usize](),
                           Growing[ProfileSpline](), Growing[Vector3](), Growing[f64](), Growing[f64]())
    errdefer profile.close()
    try profile.loop_offsets.push(0)
    try profile.edges.push(line_edge(p, ta))
    if round and (continuity >= 2 or continuity == g1_spline or not blend_shape.plain()):
        let to_tb = tb.subtract(axis_point)
        let corner = try lines_meet(ta, into_plane, tb, s.z.cross(to_tb))
        let first = profile.spline_points.count
        let knot_first = profile.spline_knots.count
        if continuity >= 2:
            try fillet_section(ta, tb, corner, continuity, &profile.spline_points, &profile.spline_knots, blend_shape, Vector3(), to_tb.multiply_scalar(-1.0 / (radius * radius)))
        else:
            try arc_section(ta, tb, corner, &profile.spline_points, &profile.spline_weights, &profile.spline_knots, blend_shape)
        while profile.spline_weights.count < profile.spline_points.count: try profile.spline_weights.push(1.0)
        try off_cylinder(profile.spline_points.view()[first..], profile.spline_weights.view()[first..], profile.spline_knots.view()[knot_first..], axis_point, s.z, radius)
        try profile.splines.push(ProfileSpline(first, profile.spline_points.count - first, knot_first, 5))
        try profile.edges.push(ProfileEdge(2, ta, tb, Vector3(), 0.0, 0.0, (i64)profile.splines.count - 1))
    elif round:
        let leaving = ta.subtract(center)
        let arriving = tb.subtract(center)
        try profile.edges.push(ProfileEdge(1, ta, tb, center, size, math.atan2(along.dot(leaving.cross(arriving)), leaving.dot(arriving)), -1))
    else:
        try profile.edges.push(line_edge(ta, tb))
    let back = tb.subtract(axis_point)
    let turn_end = rim else p
    let home = turn_end.subtract(axis_point)
    try profile.edges.push(ProfileEdge(1, tb, turn_end, axis_point, radius, math.atan2(along.dot(back.cross(home)), back.dot(home)), -1))
    if rim != none: try profile.edges.push(line_edge(turn_end, p))
    try profile.loop_offsets.push(profile.edges.count)
    try single_region(&profile)
    return profile

## The section of a fillet on straight edge `e` between flat faces whose
## ball rolls on off one face onto the cylinder beyond it (`spill`,
## blend_fits.lucb's rolled_spill), at edge point `p`: ruled_profile between
## the other face and that cylinder, closed back along the cylinder to
## where the face meets it and along the face to the edge.
func rolled_profile(w: const Shape*, e: usize, p: Vector3, along: Vector3, size: f64, continuity: i64, blend_shape: BlendShape, spill: const Spill*) -> Profiles!:
    let (fa, fb) = try edge_faces(w, e)
    let rest = fb if (usize)spill.off == fa else fa
    let start = try w.edge_at((usize)spill.far, 0.0)
    let rim = start.subtract(along.multiply_scalar(start.subtract(p).dot(along)))
    return try ruled_profile(w, rest, (usize)spill.face, p, along, try into_face(w, rest, e, along), Vector3(), size, true, try convex(w, e), size, continuity, blend_shape, rim)

## The section of a cliff-edge blend on straight edge `e` (`spill`,
## blend_fits.lucb's cliff_spill) at edge point `p`: from the edge along the
## other face to the circle's contact, round the circle to the cliff edge,
## and back along the face run off.
func cliff_profile(w: const Shape*, e: usize, p: Vector3, along: Vector3, size: f64, spill: const Spill*) -> Profiles!:
    let (ta, q, center) = try cliff_circle(w, e, spill, p, size)
    let (fa, fb) = try edge_faces(w, e)
    let rest = fb if (usize)spill.off == fa else fa
    let ua = try into_face(w, rest, e, along)
    var profile = Profiles(p, along, ua, along.cross(ua), Growing[ProfileEdge](), Growing[usize](), Growing[usize](), Growing[usize](),
                           Growing[ProfileSpline](), Growing[Vector3](), Growing[f64](), Growing[f64]())
    errdefer profile.close()
    try profile.loop_offsets.push(0)
    try profile.edges.push(line_edge(p, ta))
    let leaving = ta.subtract(center)
    let arriving = q.subtract(center)
    try profile.edges.push(ProfileEdge(1, ta, q, center, size, math.atan2(along.dot(leaving.cross(arriving)), leaving.dot(arriving)), -1))
    try profile.edges.push(line_edge(q, p))
    try profile.loop_offsets.push(profile.edges.count)
    try single_region(&profile)
    return profile

## An error when a plane/cylinder fillet's section (degree 5: `points`,
## `weights`, `knots`) crosses the cylinder (through `axis_point` along
## `axis`, of `radius`) between its contacts: a section touching the
## cylinder at its end leaves it to one side, but a heavily weighted G3's
## inner points, along the cylinder's tangent, can carry it back across.
func off_cylinder(points: const Vector3[], weights: const f64[], knots: const f64[], axis_point: Vector3, axis: Vector3, radius: f64) -> !:
    var side = 0.0
    for k in 1..<(usize)64:
        let q = (try NurbsCurve.at(points, weights, 5, knots, (f64)k / 64.0)).subtract(axis_point)
        let gap = q.subtract(axis.multiply_scalar(q.dot(axis))).length() - radius
        if math.abs(gap) <= radius * 1e-9: continue
        if side == 0.0: side = gap
        elif (gap < 0.0) != (side < 0.0): error(invalid, "a fillet section weighted this heavily crosses the cylinder it meets: use a lower Tangency weight")

## A plane/cylinder blend's contacts at edge point `p`: on the plane, on
## the cylinder, and a fillet's center (see ruled_profile). A chamfer's
## contact on the cylinder is `other` straight from the edge (its chord:
## chamfers.lucb's measure).
func ruled_contacts(w: const Shape*, plane: usize, cylinder: usize, p: Vector3, into_plane: Vector3, into_round: Vector3, size: f64, round: bool, outward: bool, other: f64) -> (Vector3, Vector3, Vector3)!:
    let s = w.surfaces.items[(usize)w.faces.items[cylinder].surface]
    let axis_point = s.origin.add(s.z.multiply_scalar(p.subtract(s.origin).dot(s.z)))
    let radius = s.radius
    let n_plane = try w.face_normal(plane, p)
    # Away from the axis, the cylinder's outward normal at p, or toward it.
    let away = (try w.face_normal(cylinder, p)).dot(p.subtract(axis_point)) > 0.0
    var ta = Vector3()
    var tb = Vector3()
    var center = Vector3()
    if round:
        # The center: `size` from the plane (inside an outside corner, in
        # the air at an inside one), the cylinder's radius moved likewise.
        let toward = n_plane.multiply_scalar(-size if outward else size)
        let moved = radius - size if outward == away else radius + size
        if moved <= 0.0: error(invalid, "a fillet radius is larger than the cylinder it meets allows")
        let q = p.add(toward).subtract(axis_point)
        let b = q.dot(into_plane)
        let disc = b * b - (q.dot(q) - moved * moved)
        if disc < 0.0: error(invalid, "a fillet this large finds no circle touching both faces")
        let spread = math.sqrt(disc)
        # The nearer place along the plane into its face.
        var t = -b - spread
        if t <= 0.0: t = -b + spread
        center = p.add(toward).add(into_plane.multiply_scalar(t))
        ta = center.subtract(toward)
        tb = axis_point.add(try center.subtract(axis_point).normalized().multiply_scalar(radius))
    else:
        ta = p.add(into_plane.multiply_scalar(size))
        # `other` straight from the edge, on the cylinder's circle the way
        # into its face: a chord of 2 R sin(φ/2).
        if other >= 2.0 * radius: error(invalid, "a chamfer this large reaches across the cylinder it meets")
        let r0 = p.subtract(axis_point)
        let turn = 1.0 if s.z.cross(r0).dot(into_round) > 0.0 else -1.0
        tb = axis_point.add(turned_direction(r0, s.z, turn * 2.0 * math.asin(other / (2.0 * radius))))
    return (ta, tb, center)

## The tool that blends edge `e` from `start` to `end` (its chain's ends),
## a fillet of `size` radius when `round`, else a chamfer `size` along each
## face, as a closed solid.
## `body` holds rays against the solid's faces: the tool reaches past an
## end only where nothing is there (an outside corner), and stops flush
## where the solid goes on (a wall the edge runs into).
## An end marked exact (where a corner ball takes over) stops right there.
## Its blend face is named `name`. A two-sided chamfer reaches `other`
## along the second face (section_profile).
func edge_tool(w: const Shape*, e: usize, size: f64, round: bool, continuity: i64, start: Vector3, end: Vector3, exact_start: bool, exact_end: bool, body: ShapeRays*, name: str, other: f64 = -1.0, blend_shape: BlendShape = plain_blend, spill: Spill = no_spill) -> interop.Reference[CadModel]!:
    if w.carriers.items[(usize)w.edges.items[e].carrier].kind == curve_circle: return try rim_tool(w, e, size, round, continuity, exact_start, exact_end, body, name, other, blend_shape)
    let length = end.subtract(start).length()
    let along = try end.subtract(start).normalized()
    let (fa, fb) = try edge_faces(w, e)
    let ua = try into_face(w, fa, e, along)
    let ub = try into_face(w, fb, e, along)
    # Past each end by a margin, where the corner beyond is empty.
    let margin = size * 2.0 + length * 0.01
    let corner = try ua.add(ub).normalized().multiply_scalar(size * 0.25)
    let extent = math.max(length, size) * 4.0
    let before = 0.0 if exact_start or try body.inside(w, start.subtract(along.multiply_scalar(size * 0.5)).add(corner), extent) else margin
    let after = 0.0 if exact_end or try body.inside(w, end.add(along.multiply_scalar(size * 0.5)).add(corner), extent) else margin
    var profile = try section_profile(w, e, start.subtract(along.multiply_scalar(before)), along, size, round, continuity, other, blend_shape, spill)
    defer profile.close()
    let solid = try BrepModel.sized(w.tolerances, length + margin * 2.0)
    defer solid.release()
    try extrude_into(solid.value(), &profile, length + before + after, "")
    try name_tool(solid.value(), name)
    try name_caps(solid.value(), name)
    return try CadModel.of_brep(solid)

## The tool's two ends (its extrusion's floor and roof, its last faces)
## named `<name>/cap`: where the tool stops square inside the body (a
## limit), the end is left as a face of the result, the blend's cap.
func name_caps(b: BrepModel*, name: str) -> !:
    let count = b.face_count()
    if count < 2: return
    var buffer: u8[300]
    let cap = try strings.format(buffer, f"{name}/cap")
    try b.set_face_name(count - 2, cap)
    try b.set_face_name(count - 1, cap)

## The corner profile at `p` on an edge running `along`, between its faces'
## directions `ua` and `ub` (into each face): a chamfer's triangle `size`
## along each, or a fillet's region between them and its curve. A fillet of
## continuity 1 (G1) is the circle of radius `size` touching both faces; of
## 2 or 3 (G2, G3) a Bezier curve between the same contact points whose
## first three or four control points lie along each face, so its
## curvature (and for G3 its change) is zero where it meets them. Its
## middle edge is the blend's. A chamfer reaches `other` along `ub` when
## it is positive (a two-sided one), else `size`.
## A G1 fillet whose section is the circle's arc as a rational degree 5
## B-spline (setback.lucb's arc_section), not a circle: its ends then are
## the very curves a G1 setback corner's patch meets (continuity code 0).
pub let g1_spline: i64 = 0

func corner_profile(p: Vector3, along: Vector3, ua: Vector3, ub: Vector3, size: f64, round: bool, continuity: i64, other: f64 = -1.0, blend_shape: BlendShape = plain_blend) -> Profiles!:
    let angle = math.acos(math.clamp(ua.dot(ub), -1.0, 1.0))
    let reach = size / math.tan(angle * 0.5) if round else size
    let ta = p.add(ua.multiply_scalar(reach))
    let tb = p.add(ub.multiply_scalar(other if not round and other > 0.0 else reach))
    var profile = Profiles(p, along, ua, along.cross(ua), Growing[ProfileEdge](), Growing[usize](), Growing[usize](), Growing[usize](),
                           Growing[ProfileSpline](), Growing[Vector3](), Growing[f64](), Growing[f64]())
    errdefer profile.close()
    try profile.loop_offsets.push(0)
    try profile.edges.push(line_edge(p, ta))
    if round and (continuity > 1 or continuity == g1_spline):
        let first = profile.spline_points.count
        let knot_first = profile.spline_knots.count
        if continuity == g1_spline:
            try arc_section(ta, tb, p, &profile.spline_points, &profile.spline_weights, &profile.spline_knots, blend_shape)
        else:
            try fillet_section(ta, tb, p, continuity, &profile.spline_points, &profile.spline_knots, blend_shape)
        let count = profile.spline_points.count - first
        while profile.spline_weights.count < profile.spline_points.count: try profile.spline_weights.push(1.0)
        try profile.splines.push(ProfileSpline(first, count, knot_first, 5))
        try profile.edges.push(ProfileEdge(2, ta, tb, Vector3(), 0.0, 0.0, (i64)profile.splines.count - 1))
    elif round:
        let bisector = try ua.add(ub).normalized()
        let center = p.add(bisector.multiply_scalar(size / math.sin(angle * 0.5)))
        let leaving = ta.subtract(center)
        let arriving = tb.subtract(center)
        let sweep = math.atan2(along.dot(leaving.cross(arriving)), leaving.dot(arriving))
        try profile.edges.push(ProfileEdge(1, ta, tb, center, size, sweep, -1))
    else:
        try profile.edges.push(line_edge(ta, tb))
    try profile.edges.push(line_edge(tb, p))
    try profile.loop_offsets.push(profile.edges.count)
    try single_region(&profile)
    return profile

## A G2 or G3 fillet's section from contact `ta` to contact `tb`, whose
## legs run along the faces to the corner `p`: a degree 5 B-spline (the
## degree of every freeform element), its control points onto `points`
## and its knots onto `knots`. `blend_shape` carries Fusion's Tangency weight
## (0.1 to 2, 1 the default) and Parasolid's G2 depth, skew or softness
## (blend_shape.lucb's shaped_g2 then makes the G2 section).
## G2 is Fusion's own (Fusion 2705's blend faces read back as B-splines,
## probe of 2026-10-12, matched to 1e-14 at seven corner angles and nine
## weights): degree 4, two spans (knots 0, 1/2, 1), six points: each
## contact, then two along its leg, a and b from it,
##   a = r φ w / 8,   b = r sin φ / 4 + a (5 - 2 cos φ) / 3,
## for the turn φ from one leg to the other (π less the faces' angle), the
## radius r (each leg r tan(φ/2) long) and the weight w: w scales the speed
## at the contacts, the circle's arc length r φ at 1. Raised here to degree
## 5 exactly, the middle knot twice (still C3), so it is Fusion's curve.
## On a curved face the inner point moves off its leg by 8 a² κ / 3 toward
## the face's center of curvature in the section's plane, so the curvature
## matches the face's at the contact (Fusion's does too): `bend_a` and
## `bend_b` are κ times that unit direction at each contact (zero on a
## flat face; curvature_toward gives them).
## G3 (not in Fusion): three spans (knots at the thirds), eight points, the
## first four along each leg (fractions 0, 0.1, 0.2 and 0.6 of the way to
## the corner), so the curvature and its change are zero at each face. Its
## weight draws each fraction f to 1 - (1 - f)^w: above 1 toward the corner
## (hugging the faces longer, tighter in the middle), below toward the
## contacts, its first points' speed nearly w times as Fusion's G2's, its
## inner ones never past the corner.
## At a square corner with contacts a unit from it, G2's middle is 0.366
## from the corner and G3's 0.360, the circle's 0.414.
pub func fillet_section(ta: Vector3, tb: Vector3, p: Vector3, continuity: i64, points: Growing[Vector3]*, knots: Growing[f64]*, blend_shape: BlendShape = plain_blend, bend_a: Vector3 = Vector3(), bend_b: Vector3 = Vector3(), turn_a: f64 = 0.0, turn_b: f64 = 0.0) -> !:
    if blend_shape.offset != 0.0:
        try offset_section(ta, tb, p, continuity, blend_shape.offset, points, knots)
        return
    if continuity == 2:
        if blend_shape.shaped_g2(): try shaped_g2(ta, tb, p, blend_shape, points, knots, bend_a, bend_b)
        else: try fusion_g2(ta, tb, p, points, knots, blend_shape, bend_a, bend_b)
        return
    let leg_a = try g3_leg(ta, p, blend_shape, bend_a, turn_a)
    let leg_b = try g3_leg(tb, p, blend_shape, bend_b, turn_b)
    for k in 0..<(usize)4: try points.push(leg_a[k])
    for k in 0..<(usize)4: try points.push(leg_b[3 - k])
    for _ in 0..<(usize)6: try knots.push(0.0)
    try knots.push(1.0 / 3.0)
    try knots.push(2.0 / 3.0)
    for _ in 0..<(usize)6: try knots.push(1.0)

## A G2 or G3 section from contact `ta` to `tb` (legs meeting at `p`, both
## walls flat) that is the offset by `offset` of the plain section between
## the walls moved `offset` toward it (BlendShape.offset: a shell's inner
## round, its strip's offset surface): that section sampled, each point
## moved back by `offset` along its normal, and fitted in the plain one's
## layout (its knots), its points along each leg kept there (the first
## three at G2, four at G3: flat at the walls, as an offset of a section
## flat there is), the rest free, by least squares; within 1e-5 of the
## radius.
func offset_section(ta: Vector3, tb: Vector3, p: Vector3, continuity: i64, offset: f64, points: Growing[Vector3]*, knots: Growing[f64]*) -> !:
    let ea = try p.subtract(ta).normalized()
    let eb = try p.subtract(tb).normalized()
    # Each wall's normal toward the section (the other contact's side).
    let ua = try eb.subtract(ea.multiply_scalar(eb.dot(ea))).multiply_scalar(-1.0).normalized()
    let ub = try ea.subtract(eb.multiply_scalar(ea.dot(eb))).multiply_scalar(-1.0).normalized()
    let ta0 = ta.add(ua.multiply_scalar(offset))
    let tb0 = tb.add(ub.multiply_scalar(offset))
    # The moved legs' meeting point.
    let k = ea.dot(eb)
    let det = 1.0 - k * k
    if det < 1e-12: error(invalid, "a section's legs run along one line")
    let r = ta0.subtract(tb0)
    let s = (k * r.dot(eb) - r.dot(ea)) / det
    let p0 = ta0.add(ea.multiply_scalar(s))
    var base = Growing[Vector3]()
    defer base.close()
    try fillet_section(ta0, tb0, p0, continuity, &base, knots)
    let n = base.count
    let held = (usize)continuity + 1
    if n != 8 or knots.count != 14 or held > 4: error(invalid, "an offset section needs a G2 or G3 fillet's layout")
    var weights: f64[8] = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
    let plane = ea.cross(eb)
    # Unknowns: the steps along each leg of its held points but the contact
    # (held - 1 each), then the free middle points' coordinates.
    let loose = n - 2 * held
    let size = 2 * (held - 1) + 3 * loose
    var matrix: f64[100]
    var rhs: f64[10]
    for i in 0..<(usize)100: matrix[i] = 0.0
    for i in 0..<(usize)10: rhs[i] = 0.0
    var values: f64[12]
    var row: f64[10]
    var sign = 0.0
    let samples: usize = 200
    for q in 0..<samples + 1:
        let t = (f64)q / (f64)samples
        let at = try NurbsCurve.at(base.view(), weights[..<8], 5, knots.view(), t)
        let ahead = try NurbsCurve.at(base.view(), weights[..<8], 5, knots.view(), math.min(t + 1e-5, 1.0))
        let behind = try NurbsCurve.at(base.view(), weights[..<8], 5, knots.view(), math.max(t - 1e-5, 0.0))
        var normal = try plane.cross(ahead.subtract(behind)).normalized()
        if q == 0: sign = 1.0 if normal.dot(ua) > 0.0 else -1.0
        normal = normal.multiply_scalar(sign)
        let target = at.subtract(normal.multiply_scalar(offset))
        let first = nurbs_basis(knots.view(), (i64)n, 5, t, &values)
        var b: f64[8] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        for j in 0..<(usize)6:
            if first + j < n: b[first + j] = values[j]
        # What the fixed parts give, and each unknown's share, per axis.
        var rest = target.subtract(ta.multiply_scalar(b[0])).subtract(tb.multiply_scalar(b[n - 1]))
        for j in 1..<held:
            rest = rest.subtract(ta.multiply_scalar(b[j])).subtract(tb.multiply_scalar(b[n - 1 - j]))
        for axis in 0..<(usize)3:
            for i in 0..<size: row[i] = 0.0
            for j in 1..<held:
                let along_a = ea.x if axis == 0 else (ea.y if axis == 1 else ea.z)
                let along_b = eb.x if axis == 0 else (eb.y if axis == 1 else eb.z)
                row[j - 1] = b[j] * along_a
                row[held - 1 + j - 1] = b[n - 1 - j] * along_b
            for m in 0..<loose: row[2 * (held - 1) + m * 3 + axis] = b[held + m]
            let goal = rest.x if axis == 0 else (rest.y if axis == 1 else rest.z)
            for i in 0..<size:
                rhs[i] += row[i] * goal
                for j in 0..<size: matrix[i * size + j] += row[i] * row[j]
    try cholesky_solve(matrix[..<size * size], rhs[..<size], size)
    try points.push(ta)
    for j in 1..<held: try points.push(ta.add(ea.multiply_scalar(rhs[j - 1])))
    for m in 0..<loose: try points.push(Vector3(rhs[2 * (held - 1) + m * 3], rhs[2 * (held - 1) + m * 3 + 1], rhs[2 * (held - 1) + m * 3 + 2]))
    var j = held
    while j > 1:
        j -= 1
        try points.push(tb.add(eb.multiply_scalar(rhs[held - 1 + j - 1])))
    try points.push(tb)

## Fusion's G2 section (fillet_section): its six degree 4 points, then
## raised to degree 5 (eight points, knots 0 six times, 1/2 twice, 1 six
## times).
func fusion_g2(ta: Vector3, tb: Vector3, p: Vector3, points: Growing[Vector3]*, knots: Growing[f64]*, blend_shape: BlendShape, bend_a: Vector3, bend_b: Vector3) -> !:
    let la = p.subtract(ta)
    let lb = p.subtract(tb)
    let ea = try la.normalized()
    let eb = try lb.normalized()
    # The turn between the legs, and the radius their length gives.
    let phi = math.pi - math.acos(math.clamp(ea.dot(eb), -1.0, 1.0))
    let leg = (la.length() + lb.length()) * 0.5
    let r = leg / math.tan(phi * 0.5)
    let a = r * phi * blend_shape.weight / 8.0
    let b = r * math.sin(phi) / 4.0 + a * (5.0 - 2.0 * math.cos(phi)) / 3.0
    let off = 8.0 * a * a / 3.0
    let q: Vector3[6] = [ta, ta.add(ea.multiply_scalar(a)), ta.add(ea.multiply_scalar(b)).add(bend_a.multiply_scalar(off)),
                         tb.add(eb.multiply_scalar(b)).add(bend_b.multiply_scalar(off)), tb.add(eb.multiply_scalar(a)), tb]
    try points.push(q[0])
    try points.push(q[0].add(q[1].multiply_scalar(4.0)).multiply_scalar(0.2))
    try points.push(q[1].multiply_scalar(0.7).add(q[2].multiply_scalar(0.3)))
    try points.push(q[1].add(q[2].multiply_scalar(7.0)).add(q[3].multiply_scalar(2.0)).multiply_scalar(0.1))
    try points.push(q[2].multiply_scalar(2.0).add(q[3].multiply_scalar(7.0)).add(q[4]).multiply_scalar(0.1))
    try points.push(q[3].multiply_scalar(0.3).add(q[4].multiply_scalar(0.7)))
    try points.push(q[4].multiply_scalar(4.0).add(q[5]).multiply_scalar(0.2))
    try points.push(q[5])
    for _ in 0..<(usize)6: try knots.push(0.0)
    try knots.push(0.5)
    try knots.push(0.5)
    for _ in 0..<(usize)6: try knots.push(1.0)

## A G3 section's first four points from contact `t` along its leg to the
## corner `p` (fillet_section's fractions under `blend_shape`).
## On a curved face (`bend`: its curvature times the unit way toward its
## center of curvature in the section; `turn`: the curvature's change per
## length along the leg toward the corner) the third and fourth points move
## off the leg toward that center, so the section's curvature and its
## change at the contact are the face's: G3 on curved faces too. With the
## knots at the thirds the start's first three derivatives are 15 D0,
## 90 D1 - 180 D0 and 270 D2 - 1215 D1 + 1620 D0 (D_i = P_(i+1) - P_i).
## The first leg a1 = |D0| along the leg e, the curvature is 0.4 h2 / a1²
## for the third point's offset h2 toward the center n: h2 = 2.5 κ a1².
## Its change dκ/ds = (T_n / A² - 3 B_n B_e / A³) / A, for A = 15 a1 and
## B, T the second and third derivatives' parts along e and n, gives the
## fourth point's offset h3 from T_n = 270 h3 - 1485 h2.
func g3_leg(t: Vector3, p: Vector3, blend_shape: BlendShape, bend: Vector3, turn: f64) -> Vector3[4]!:
    let g3: f64[4] = [0.0, 0.1, 0.2, 0.6]
    let span = p.subtract(t)
    var leg: Vector3[4] = [t, Vector3(), Vector3(), Vector3()]
    for k in 1..<(usize)4: leg[k] = t.add(span.multiply_scalar(weighted_fraction(g3[k], blend_shape)))
    # Flat across at the contact (to rounding): the points stay on the leg.
    let kappa = bend.length()
    let length = span.length()
    if kappa * length <= 1e-12: return leg
    let e = span.multiply_scalar(1.0 / length)
    let n = try bend.subtract(e.multiply_scalar(bend.dot(e))).normalized()
    let a1 = weighted_fraction(g3[1], blend_shape) * length
    let a2 = weighted_fraction(g3[2], blend_shape) * length
    let big_a = 15.0 * a1
    let h2 = 2.5 * kappa * a1 * a1
    let b_n = kappa * big_a * big_a
    let b_e = 90.0 * (a2 - a1) - 180.0 * a1
    let t_n = big_a * big_a * big_a * turn + 3.0 * b_n * b_e / big_a
    let h3 = (t_n + 1485.0 * h2) / 270.0
    leg[2] = leg[2].add(n.multiply_scalar(h2))
    leg[3] = leg[3].add(n.multiply_scalar(h3))
    return leg

## A section control point's fraction `f` toward the corner under tangency
## weight `blend_shape` (fillet_section).
func weighted_fraction(f: f64, blend_shape: BlendShape) -> f64:
    if blend_shape.weight == 1.0: return f
    return 1.0 - math.pow(1.0 - f, blend_shape.weight)

## A concave edge's tool, added to the solid: the corner profile (in the
## air between its faces) swept from `start` to `end`, ending flush with
## the face at each end: exactly there when that face is square to the
## edge, else swept past and cut by the face's plane.
## An end marked exact (where a corner ball takes over) ends square there.
func concave_tool(w: const Shape*, e: usize, size: f64, round: bool, continuity: i64, start: Vector3, end: Vector3, exact_start: bool, exact_end: bool, name: str, other: f64 = -1.0, blend_shape: BlendShape = plain_blend, spill: Spill = no_spill) -> interop.Reference[CadModel]!:
    let length = end.subtract(start).length()
    let along = try end.subtract(start).normalized()
    let (fa, fb) = try edge_faces(w, e)
    let ua = try into_face(w, fa, e, along)
    let ub = try into_face(w, fb, e, along)
    let (n0, h0) = (along.multiply_scalar(-1.0), -along.dot(start)) if exact_start else try end_plane(w, start, fa, fb)
    let (n1, h1) = (along, along.dot(end)) if exact_end else try end_plane(w, end, fa, fb)
    let square = math.abs(n0.dot(along)) > 1.0 - 1e-9 and math.abs(n1.dot(along)) > 1.0 - 1e-9
    let margin = 0.0 if square else size * 4.0 + length * 0.1
    var profile = try section_profile(w, e, start.subtract(along.multiply_scalar(margin)), along, size, round, continuity, other, blend_shape, spill)
    defer profile.close()
    let solid = try BrepModel.sized(w.tolerances, length + margin * 2.0)
    defer solid.release()
    try extrude_into(solid.value(), &profile, length + margin * 2.0, "")
    try name_tool(solid.value(), name)
    let swept = try CadModel.of_brep(solid)
    if square: return swept
    defer swept.release()
    # Cut by the end faces' planes; the sides far off.
    let s1 = try ua.add(ub).normalized()
    let s2 = along.cross(s1)
    let far = (size * 8.0 + length) * 2.0
    let normals: Vector3[6] = [n0, s1, s2, n1, s1.multiply_scalar(-1.0), s2.multiply_scalar(-1.0)]
    let offsets: f64[6] = [h0, s1.dot(start) + far, s2.dot(start) + far, h1, -s1.dot(start) + far, -s2.dot(start) + far]
    let cell = try hexahedron(w.tolerances, normals[..<6], offsets[..<6], far)
    defer cell.release()
    return try combine(swept.value(), cell.value(), op_intersect)

## The plane of the face at the end of an edge between faces `fa` and `fb`
## (at its vertex at `point`): its outward normal and offset.
func end_plane(w: const Shape*, point: Vector3, fa: usize, fb: usize) -> (Vector3, f64)!:
    var vertex: i64 = -1
    for v in 0..<w.points.count:
        if w.points.items[v].subtract(point).length() <= w.tolerance * 10.0: vertex = (i64)v
    if vertex < 0: error(invalid, "a concave blend's end is not a corner of the body")
    var found: i64 = -1
    for f in 0..<w.faces.count:
        if f == fa or f == fb: continue
        for use in w.face_uses(f):
            let edge = w.edges.items[edge_index(use)]
            if edge.start == vertex or edge.end == vertex:
                if found >= 0 and found != (i64)f: error(invalid, "a concave blend must end at one flat face")
                found = (i64)f
    if found < 0 or w.surfaces.items[(usize)w.faces.items[(usize)found].surface].kind != surface_plane: error(invalid, "a concave blend must end at one flat face")
    let n = face_outward(w, (usize)found)
    return (n, n.dot(w.surfaces.items[(usize)w.faces.items[(usize)found].surface].origin))

## A tool's faces: the one its corner profile's middle edge made (the
## profile's order survives nesting: three edges reversed keep their
## middle) is the blend, named `name`; the rest go with the corner and
## stay unnamed.
func name_tool(b: BrepModel*, name: str) -> !:
    for face in 0..<b.face_count():
        try b.set_face_name(face, name if face == 1 else "")

## A rim's tool: the corner profile (a triangle `size` along each face,
## or the region between them and the circle of radius `size` touching
## both) turned about the rim's axis: a cone, or a torus. A whole circle's
## turns all the way; an arc's turns along it, reaching past an end where
## the corner beyond is empty and stopping at an exact one (a tangent
## joint with the next edge of a chain).
func rim_tool(w: const Shape*, e: usize, size: f64, round: bool, continuity: i64, exact_start: bool, exact_end: bool, body: ShapeRays*, name: str, other: f64 = -1.0, blend_shape: BlendShape = plain_blend) -> interop.Reference[CadModel]!:
    let edge = w.edges.items[e]
    let carrier = w.carriers.items[(usize)edge.carrier]
    let (fa, fb) = try edge_faces(w, e)
    let along = try along_edge(w, e)
    let p = try w.edge_at(e, 0.5)
    let ua = try into_face(w, fa, e, along)
    let ub = try into_face(w, fb, e, along)
    let normal = carrier.x.cross(carrier.y)
    let ball = sphere_rim(w, e, fa, fb)
    if ball >= 0 and not try convex(w, e): error(invalid, "an inside rim on a sphere (a dimple's) is not blended yet")
    if ball >= 0 and round: error(invalid, "a rim between a flat face and a sphere is filleted only along its whole loop (curved_blend)")
    let solid = try BrepModel.sized(w.tolerances, carrier.a + size * 4.0)
    defer solid.release()
    if edge.start == edge.end:
        var profile = try rim_profile(w, e, ball, p, along, ua, ub, size, round, continuity, other, blend_shape)
        defer profile.close()
        try revolve_into(solid.value(), &profile, carrier.origin, normal, (carrier.a + size) * 1e-7, "")
        try name_tool(solid.value(), name)
        return try CadModel.of_brep(solid)
    # The axis turning the way the edge runs.
    var a = normal
    if a.cross(p.subtract(carrier.origin)).dot(along) < 0.0: a = normal.multiply_scalar(-1.0)
    let sweep = math.abs(edge.t1 - edge.t0)
    # Past a free end, by a margin where the corner beyond is empty.
    let margin = math.min(math.pi * 0.25, size * 2.0 / carrier.a)
    let corner = try ua.add(ub).normalized().multiply_scalar(size * 0.25)
    let extent = (carrier.a + size) * 4.0
    let first = try w.edge_at(e, 0.0)
    let last = try w.edge_at(e, 1.0)
    let before = 0.0 if exact_start or try body.inside(w, turned_point(first, carrier.origin, a, -size * 0.5 / carrier.a).add(turned_direction(corner, a, -sweep * 0.5)), extent) else margin
    let after = 0.0 if exact_end or try body.inside(w, turned_point(last, carrier.origin, a, size * 0.5 / carrier.a).add(turned_direction(corner, a, sweep * 0.5)), extent) else margin
    # The profile where the tool starts: the middle's turned back.
    let back = -(sweep * 0.5 + before)
    var profile = try rim_profile(w, e, ball, turned_point(p, carrier.origin, a, back), turned_direction(along, a, back), turned_direction(ua, a, back), turned_direction(ub, a, back), size, round, continuity, other, blend_shape)
    defer profile.close()
    try revolve_into(solid.value(), &profile, carrier.origin, a, (carrier.a + size) * 1e-7, "", sweep + before + after)
    try name_tool(solid.value(), name)
    return try CadModel.of_brep(solid)

## A rim tool's section: a chamfer's on a sphere (face `ball`,
## sphere_rims.lucb), else the corner profile.
func rim_profile(w: const Shape*, e: usize, ball: i64, p: Vector3, along: Vector3, ua: Vector3, ub: Vector3, size: f64, round: bool, continuity: i64, other: f64, blend_shape: BlendShape) -> Profiles!:
    if ball < 0: return try corner_profile(p, along, ua, ub, size, round, continuity, other, blend_shape)
    let s = w.surfaces.items[(usize)w.faces.items[(usize)ball].surface]
    # The legs: `size` along ua, `other` (when positive) along ub.
    let second = other if other > 0.0 else size
    let (fa, _) = try edge_faces(w, e)
    if (usize)ball == fa: return try sphere_chamfer_profile(p, along, ub, ua, s.origin, s.radius, second, size)
    return try sphere_chamfer_profile(p, along, ua, ub, s.origin, s.radius, size, second)