Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.4

0.9.4 / src / modeling / api.lucb

## Luce's CAD modeling operations: features that make and change closed
## B-reps (see docs/MODELING.md for the plan and what each supports).

## A sketch plane on a body's face (CadModeling.face_frame): its origin and
## the directions of the sketch's x and y (the normal, x × y, out of the
## body); `found` false when there is no such flat face.
pub struct FaceFrame:
    pub var found: bool
    pub var origin: Vector3
    pub var u: Vector3
    pub var v: Vector3

## A line in space (CadModeling.edge_axis): a point on it and its
## direction; `found` false when there is none.
pub struct AxisLine:
    pub var found: bool
    pub var origin: Vector3
    pub var direction: Vector3

## The modeling features, as static functions on closed solids.
pub struct CadModeling:
    let reserved: u8 = 0

    ## The sketch in `set` (its curves on its sketch plane) as profiles:
    ## the faces `profiles` names (profile_keys' keys apart by `;`; empty:
    ## islands alternating from the outside in), faces next to each other
    ## joined, every region extruded `distance` along the plane's normal
    ## (negative: the other way) from `start` along it (a symmetric
    ## extrusion starts at minus half its distance): one closed solid
    ## each. Its faces are named for feature `tag` (naming.lucb).
    pub static func extruded(set: interop.Reference[GeometrySet], distance: f64, start: f64, tag: str, profiles: str = "", tolerances: CadTolerances = CadTolerances()) -> interop.Reference[CadModel]!:
        let source = try set.get()
        let size = try sketch_size(source)
        var p = try profiles_of(source, size * 0.0001, profiles)
        defer p.close()
        if start != 0.0: p.moved(p.normal.multiply_scalar(start))
        let solid = try BrepModel.sized(tolerances, size)
        defer solid.release()
        try extrude_into(solid.value(), &p, distance, tag)
        return try CadModel.of_brep(solid)

    ## `a` and `b` combined: `operation` 0 their union, 1 `a` without
    ## `b`, 2 their intersection (both closed solids).
    pub static func combined(a: interop.Reference[CadModel], b: interop.Reference[CadModel], operation: i64) -> interop.Reference[CadModel]!:
        if operation < 0 or operation > 2: error(invalid, "a boolean operation is 0 union, 1 subtract or 2 intersect")
        return try combine(a.value(), b.value(), operation, true)

    ## `model` with the edges `references` names (edge_references'; empty:
    ## every straight convex edge between two flat faces) chamfered
    ## `distance` along each face, the chamfers named for feature `tag`.
    ## Where three meet at a corner of flat faces, Fusion's Corner Type
    ## (chamfer_corners.lucb): `corner` 0 Chamfer (a flat face joins
    ## them), 1 Miter (they meet in a point), 2 Blend (set back, one flat
    ## face closing the corner, as Fusion's).
    pub static func chamfered(model: interop.Reference[CadModel], references: str, distance: f64, tag: str, chain: bool = true, corner: i64 = 1) -> interop.Reference[CadModel]!:
        try corner_kind(corner)
        return try blended(model.value(), references, distance, false, tag, 1, chain, true, corner)

    ## Fusion's Variable radius fillet (variable_fillet.lucb): the edges
    ## `reference` names (with their tangent chains when `chain`) filleted
    ## with `radii` at `positions` along the chain (0 its start, 1 its end;
    ## fractions of its length), Fusion's law between them (straight
    ## between two, a spline through more: radius_law.lucb) or, `smooth`,
    ## each held a moment at its point, of `continuity` (1 G1, 2 G2, 3 G3), named
    ## for feature `tag`: one straight edge between flat faces (square,
    ## slanted or open ends), a tangent chain round a flat face (run-outs at
    ## open ends), or a loop between two curved faces; `tangency` Fusion's
    ## Tangency weight (0.1 to 2), as filleted's.
    pub static func variable_filleted(model: interop.Reference[CadModel], reference: str, positions: const f64[], radii: const f64[], tag: str, smooth: bool = false, continuity: i64 = 1, chain: bool = true, tangency: f64 = 1.0, conic: i64 = 0, rho: f64 = 0.5, depth: f64 = -1.0, skew: f64 = 0.5, softness: f64 = -1.0) -> interop.Reference[CadModel]!:
        return try variable_filleted_edge(model.value(), reference, positions, radii, smooth, tag, continuity, chain, BlendShape(tangency, conic, rho, depth, skew, softness))

    ## Fusion's Full Round Fillet (full_round.lucb): `model`'s flat face
    ## `center` rounded away whole, the round tangent to it and to its
    ## sides (`side1`, `side2`; empty: the faces across its longest pair of
    ## parallel edges), of `continuity`, named for feature `tag`.
    pub static func full_round(model: interop.Reference[CadModel], center: str, tag: str, continuity: i64 = 1, side1: str = "", side2: str = "") -> interop.Reference[CadModel]!:
        if continuity < 1 or continuity > 3: error(invalid, "a fillet's continuity is G1, G2 or G3")
        return try full_rounded(model.value(), center, side1, side2, tag, continuity)

    ## Fusion's Chord Length (chord_length.lucb): the radius that makes the
    ## fillets of the edges `references` names (as filleted's) `chord`
    ## between where they leave the faces; refused when their faces meet at
    ## different angles.
    pub static func chord_radius(model: interop.Reference[CadModel], references: str, chord: f64, chain: bool = true) -> f64!:
        return try chord_radius_of(model.value(), references, chord, chain)

    ## `model` with the edges `references` names (as chamfered) filleted to
    ## `radius`, of `continuity` 1 (G1: circular), 2 (G2: curvature
    ## continuous) or 3 (G3: its change continuous too). With `chain` (as
    ## chamfered's), each edge brings the edges continuing it tangentially.
    ## With `setback` (Fusion's Corner type Setback), three G1 fillets
    ## meeting at a corner stop short of it and a patch blends them (G2 and
    ## G3 corners are always so); else a ball rounds it. `tangency` is
    ## Fusion's Tangency weight, 0.1 to 2 (blend_tools.lucb's
    ## fillet_section): 1 the plain section, more drawing the blend toward
    ## the corner, less toward its chord; a G1 fillet then is a conic.
    ## Parasolid's sections (blend_shape.lucb): `conic` rho_absolute,
    ## rho_relative or rho_middle with `rho` (G1), or a G2 section by `depth`
    ## (0 to 1, with `skew`) or `softness` (0 to 1); -1: unused. Limits
    ## (`limit_from`, `limit_to`, fractions along one straight edge): the
    ## blend runs between them, capped by the planes square to the edge
    ## there. `setback_ratio`: where fillets meet at a corner each stops at
    ## least that many radii from the vertex (Parasolid's setbacks; 0 as
    ## the corner needs), the corners setback patches. `overflow`: the
    ## overflow behaviours allowed where a blend runs off its face, a sum of
    ## overflow_smooth (1), overflow_cliff (2) and overflow_notch (4),
    ## tried in that order (blend_fits.lucb); 0 refuses a blend that does
    ## not fit its faces with the size that would (Parasolid's overflow
    ## off). The default is all three (Fusion's takes the cliff).
    ## Setback corners' shape (Alias's corner controls): `corner_shape` the
    ## curves on the faces as conics of that rho relative to the circle's
    ## (Corner Blend's Edge Shape; 0.5 the circle, Fusion's), and
    ## `corner_fullness` the patch's bulge from its boundary scaled (Ball
    ## Corner's Pivot Curve Length Ratio; 1 the fair fill's own, the
    ## default; 0 Fusion's: 1.27 at G1, 1.1 at G2 and G3).
    ## `limit_overlap` (Parasolid's overlap limit): one straight edge's
    ## fillet runs only along the longest stretch where it fits its faces,
    ## capped square there, rather than overflowing.
    pub static func filleted(model: interop.Reference[CadModel], references: str, radius: f64, tag: str, continuity: i64 = 1, chain: bool = true, setback: bool = false, tangency: f64 = 1.0, conic: i64 = 0, rho: f64 = 0.5, depth: f64 = -1.0, skew: f64 = 0.5, softness: f64 = -1.0,
                                limit_from: f64 = 0.0, limit_to: f64 = 1.0, setback_ratio: f64 = 0.0, overflow: i64 = overflow_default, corner_shape: f64 = 0.5, corner_fullness: f64 = 0.0, limit_overlap: bool = false) -> interop.Reference[CadModel]!:
        if not (corner_shape > 0.0 and corner_shape < 1.0): error(invalid, "a corner's edge shape is a rho from 0 to 1 (0.5 the circle)")
        if not (corner_fullness >= 0.0 and corner_fullness <= 4.0): error(invalid, "a corner's fullness is 0 (Fusion's) or more, at most 4 (1 the fair fill's own)")
        return try blended(model.value(), references, radius, true, tag, continuity, chain, true, 1, setback, BlendShape(tangency, conic, rho, depth, skew, softness), BlendLimits(limit_from, limit_to, setback_ratio, overflow, corner_shape, corner_fullness, limit_overlap))

    ## Parasolid's caps by faces or sheets: `model`'s edges `references`
    ## filleted to `radius` (as filleted's, at `continuity`), each blend
    ## stopping where it meets the surface of `cap`'s face `cap_face` (a
    ## face of the body itself or of a sheet), the part behind the face
    ## (against its normal; `flip`: in front of it) kept; the cut is the
    ## blend's cap (`<blend>/cap/...`), the edge sharp beyond it.
    pub static func capped_fillet(model: interop.Reference[CadModel], references: str, radius: f64, tag: str, cap: interop.Reference[CadModel], cap_face: str, flip: bool = false, continuity: i64 = 1, chain: bool = true) -> interop.Reference[CadModel]!:
        var t = try shape_of(cap.value())
        defer t.close()
        var found = Growing[usize]()
        defer found.close()
        try faces_named(&t, cap_face, &found)
        let face = t.faces.items[found.items[0]]
        let s = &t.surfaces.items[(usize)face.surface]
        # Behind the face: a plane's normal side taken away, a curved
        # surface's inside kept (its outward face's back), turned over by
        # the face's sense and `flip`.
        let behind = face.sense != flip
        var held = BlendCap(try Surface(s.kind, s.origin, s.x, s.z, s.radius, s.angle, s.points, s.weights, s.ku, s.kv, s.nu, s.nv, s.du, s.dv), behind if s.kind == surface_plane else not behind)
        defer held.surface.close()
        return try blended(model.value(), references, radius, true, tag, continuity, chain, true, 1, false, plain_blend, no_limits, &held)

    ## A fillet of several edge sets, each its own radius (Fusion's
    ## selection sets): `sets` the sets' edge references apart by `|`,
    ## set k filleted to `radii[k]`, at `continuity`; with `chain`, each
    ## edge's tangent chain at its radius. Where radii differ at a corner,
    ## a setback corner (fillet_sets.lucb).
    pub static func filleted_sets(model: interop.Reference[CadModel], sets: str, radii: const f64[], tag: str, continuity: i64 = 1, chain: bool = true) -> interop.Reference[CadModel]!:
        return try filleted_sets(model.value(), sets, radii, tag, continuity, chain)

    ## A fillet of `model`'s edges `references` (as filleted's) at
    ## `continuity`, kept between radii: a feature whose radius is being
    ## changed keeps it (made_for tells when its inputs changed) and asks
    ## it for each radius (FilletPlan.filleted).
    pub static func fillet_plan(model: interop.Reference[CadModel], references: str, continuity: i64, tag: str, chain: bool = true, tangency: f64 = 1.0, conic: i64 = 0, rho: f64 = 0.5, depth: f64 = -1.0, skew: f64 = 0.5, softness: f64 = -1.0) -> interop.Reference[FilletPlan]!:
        return try fillet_plan_of(model, references, continuity, tag, chain, BlendShape(tangency, conic, rho, depth, skew, softness))

    ## Identify blends (Parasolid's): the names of `model`'s faces that are
    ## constant rolling-ball blends, apart by `;`: cylinders and tori met
    ## tangentially by their two walls, and the corner balls between them
    ## (blend_find.lucb). Found from the geometry alone, an imported body's
    ## too once its faces are named.
    pub static func identified_blends(model: interop.Reference[CadModel]) -> interop.Owned[str]!:
        var w = try shape_of(model.value())
        defer w.close()
        var found = Growing[FoundBlend]()
        defer found.close()
        try found_blends(&w, &found)
        var out = Growing[u8]()
        defer out.close()
        for blend in found.view():
            if out.count > 0: try out.push(59)
            for byte in w.face_name(blend.face).bytes: try out.push(byte)
        return try interop.copy_text((str)out.view())

    ## The radius of `model`'s blend face `face` (identified_blends'); an
    ## error when the face is no blend.
    pub static func blend_radius(model: interop.Reference[CadModel], face: str) -> f64!:
        var w = try shape_of(model.value())
        defer w.close()
        var found = Growing[FoundBlend]()
        defer found.close()
        try found_blends(&w, &found)
        var picked = Growing[usize]()
        defer picked.close()
        try faces_named(&w, face, &picked)
        let at = blend_at(found.view(), picked.items[0])
        if at < 0: error(invalid, "the face is no constant rolling-ball blend")
        return found.items[(usize)at].radius

    ## References to `model`'s edges `edges` (B-rep edge numbers), apart by
    ## `;`: each the names of its two faces and where it is, so a feature
    ## finds the same edges after changes upstream renumber them.
    pub static func edge_references(model: interop.Reference[CadModel], edges: const i64[]) -> interop.Owned[str]!:
        var w = try shape_of(model.value())
        defer w.close()
        var text = Growing[u8]()
        defer text.close()
        try references_of(&w, edges, &text)
        return try interop.copy_text((str)text.view())

    ## How many of `model`'s edges `references` resolves to (an error when
    ## one is gone).
    pub static func resolved_count(model: interop.Reference[CadModel], references: str) -> i64!:
        var w = try shape_of(model.value())
        defer w.close()
        var edges = Growing[usize]()
        defer edges.close()
        try resolve_edges(&w, references, &edges)
        return (i64)edges.count

    ## `model` with its unnamed faces named `tag/f<i>` (i the face's
    ## number), as a feature that makes a body without naming its faces
    ## (a primitive) gives them.
    pub static func tagged(model: interop.Reference[CadModel], tag: str) -> interop.Reference[CadModel]!:
        var w = try shape_of(model.value())
        defer w.close()
        var name = Growing[u8]()
        defer name.close()
        for f in 0..<w.faces.count:
            if w.faces.items[f].name >= 0: continue
            try role_name(&name, tag, "f")
            try push_decimal(&name, (i64)f)
            w.faces.items[f].name = try w.add_name((str)name.view())
        return try shape_model(&w)

    ## `model` with `prefix` before each of its faces' names (every alias):
    ## a copy (a pattern's, a mirror's) distinct from its original.
    pub static func prefixed(model: interop.Reference[CadModel], prefix: str) -> interop.Reference[CadModel]!:
        var w = try shape_of(model.value())
        defer w.close()
        var name = Growing[u8]()
        defer name.close()
        for f in 0..<w.faces.count:
            try prefixed_name(w.face_name(f), prefix, &name)
            w.faces.items[f].name = try w.add_name((str)name.view())
        return try shape_model(&w)

    ## The closed curves of the sketch in `set` as profiles, every region
    ## turned a full turn about its plane's `axis` (0 the plane's u
    ## direction, 1 its v direction) through the plane's origin, into
    ## closed solids, or turned `angle` radians (toward the plane's normal)
    ## and closed by the profile at each end. The profile must lie on one
    ## side of the axis. Its faces are named for feature `tag`.
    pub static func revolved(set: interop.Reference[GeometrySet], axis: i64, tag: str, angle: f64 = 2.0 * math.pi, profiles: str = "", tolerances: CadTolerances = CadTolerances()) -> interop.Reference[CadModel]!:
        let source = try set.get()
        let size = try sketch_size(source)
        var p = try profiles_of(source, size * 0.0001, profiles)
        defer p.close()
        let solid = try BrepModel.sized(tolerances, size)
        defer solid.release()
        try revolve_into(solid.value(), &p, p.origin, p.u if axis == 0 else p.v, size * 0.000001, tag, angle)
        return try CadModel.of_brep(solid)

    ## The keys of the sketch's profiles in `set` (the smallest regions its
    ## curves bound, as Fusion's profiles), apart by `;`: each names its
    ## region by the curves round it and the way each runs, so it holds as
    ## dimensions change.
    pub static func profile_keys(set: interop.Reference[GeometrySet]) -> interop.Owned[str]!:
        let source = try set.get()
        var out = Growing[u8]()
        defer out.close()
        try face_keys(source, try sketch_size(source) * 0.0001, false, Vector3(), &out)
        return try interop.copy_text((str)out.view())

    ## The key of the profile holding world point `at` (on the sketch
    ## plane), or "" when none does: what a click picks.
    pub static func profile_at(set: interop.Reference[GeometrySet], at: Vector3) -> interop.Owned[str]!:
        let source = try set.get()
        var out = Growing[u8]()
        defer out.close()
        try face_keys(source, try sketch_size(source) * 0.0001, true, at, &out)
        return try interop.copy_text((str)out.view())

    ## The outlines of the sketch's profiles in `set` that `keys` names
    ## (apart by `;`), as closed curves on its plane, to draw them.
    pub static func profile_outlines(set: interop.Reference[GeometrySet], keys: str) -> interop.Reference[GeometrySet]!:
        let source = try set.get()
        var out = CurvesBuilder()
        defer out.close()
        try face_outlines(source, try sketch_size(source) * 0.0001, keys, &out)
        let made = try out.finish()
        let blank = try empty_set()
        defer dispose_set(blank)
        return try adopt_set(try with_curves(blank, made))

    ## The plane of `model`'s flat face named `name` (face_name's, any of its
    ## aliases): the face's own surface frame, turned so its normal leaves
    ## the body, for a sketch drawn on it. Names keep it the same face when
    ## features upstream change the body.
    pub static func face_frame(model: interop.Reference[CadModel], name: str) -> FaceFrame!:
        var w = try shape_of(model.value())
        defer w.close()
        for f in 0..<w.faces.count:
            let face = w.faces.items[f]
            if face.name < 0 or not (try names_meet(w.face_name(f), name)): continue
            let s = w.surfaces.items[(usize)face.surface]
            if s.kind != surface_plane: continue
            # The surface's z leaves the body when the face runs with it;
            # otherwise y turns over so x × y still leaves the body.
            return FaceFrame(true, s.origin, s.x, s.y if face.sense else s.y.multiply_scalar(-1.0))
        return FaceFrame(false, Vector3(), Vector3(1.0, 0.0, 0.0), Vector3(0.0, 1.0, 0.0))

    ## The name of `model`'s face `face` (a B-rep face number, as a pick
    ## mesh's cad_face says), the way face_frame finds it again.
    pub static func face_name_of(model: interop.Reference[CadModel], face: i64) -> interop.Owned[str]!:
        return try interop.copy_text(try model.value().face_name(face))

    ## The regions of the sketch's profiles in `set` that `keys` names
    ## (apart by `;`; empty: every profile), triangulated flat on its plane,
    ## to shade them; an empty mesh when it has no closed profile.
    pub static func profile_fills(set: interop.Reference[GeometrySet], keys: str = "") -> interop.Reference[Mesh]!:
        return try profile_fill_mesh(try set.get(), keys)

    ## Where an arrow on the sketch's profiles `keys` in `set` stands (empty:
    ## the closed shapes Extrude takes by default): a point inside them,
    ## their plane's normal and their area.
    pub static func profile_anchor(set: interop.Reference[GeometrySet], keys: str = "") -> ProfileAnchor!:
        return try anchor_of(try set.get(), keys)

    ## Whether `point` lies inside the closed solid `model` (rays through
    ## its exact faces, rays.lucb): what Extrude's automatic operation asks
    ## of a point halfway along it.
    pub static func inside(model: interop.Reference[CadModel], point: Vector3) -> bool!:
        var w = try shape_of(model.value())
        defer w.close()
        var low = Vector3(1.0e300, 1.0e300, 1.0e300)
        var high = Vector3(-1.0e300, -1.0e300, -1.0e300)
        for p in w.points.view():
            low = Vector3(math.min(low.x, p.x), math.min(low.y, p.y), math.min(low.z, p.z))
            high = Vector3(math.max(high.x, p.x), math.max(high.y, p.y), math.max(high.z, p.z))
        let size = math.max(1.0, high.subtract(low).length()) if w.points.count > 0 else 1.0
        var rays = try shape_rays(&w)
        defer rays.close()
        return try rays.inside(&w, point, size)

    ## How many profile regions the sketch in `set` has.
    pub static func profile_count(set: interop.Reference[GeometrySet]) -> i64!:
        let source = try set.get()
        var p = try profiles_of(source, try sketch_size(source) * 0.0001)
        defer p.close()
        return (i64)p.region_count()

    ## Shell: `model` hollowed to a wall `thickness` thick, its faces
    ## `faces` (names apart by `;`, as face_name_of gives; empty: a closed
    ## void inside) removed so the hollow opens there; the wall inside the
    ## body (`side` 0), outside it (1) or half each way (2). The inner
    ## wall's faces are named `<tag>/` and the face's name (shell.lucb).
    ## With `chain` (Fusion's Tangent chain), the faces meeting removed ones
    ## tangentially are removed too. Both ways with `outside` 0 or more is
    ## Fusion's Inside and Outside thickness: `thickness` inside,
    ## `outside_thickness` outside (negative: `thickness` half each way).
    pub static func shelled(model: interop.Reference[CadModel], faces: str, thickness: f64, tag: str, side: i64 = 0, chain: bool = false, outside_thickness: f64 = -1.0) -> interop.Reference[CadModel]!:
        var w = try shape_of(model.value())
        defer w.close()
        var removed = Growing[bool]()
        defer removed.close()
        try removed.fill(w.faces.count, false)
        if trimmed(faces) != "":
            var picked = Growing[usize]()
            defer picked.close()
            try faces_named(&w, faces, &picked)
            if chain: try grow_tangent(&w, &picked)
            for f in picked.view(): removed.items[f] = true
            # A body smooth all over (every edge rounded) is one tangent
            # chain: removing it all leaves no wall.
            if picked.count == w.faces.count:
                error(invalid, "a shell must keep some of the body's faces: Tangent chain takes every face here (the body is smooth all over); turn it off")
        return try shell_of(model, removed.view(), thickness, side, tag, outside_thickness)

    # -- Bodies: split, lumps, move and copy.

    ## Split Body by the plane through `origin` facing `normal`: the piece
    ## on the normal's side and the piece behind it, as two lumps of one
    ## model (lump_count, lump). The cut faces are `<tag>/to/f<i>`.
    pub static func split_by_plane(model: interop.Reference[CadModel], origin: Vector3, normal: Vector3, tag: str) -> interop.Reference[CadModel]!:
        let n = normal.normalized() catch failure: error(invalid, "a split plane needs a normal")
        let seed = Vector3(1.0, 0.0, 0.0) if math.abs(n.x) < 0.9 else Vector3(0.0, 1.0, 0.0)
        let x = try seed.subtract(n.multiply_scalar(seed.dot(n))).normalized()
        var no_points = Growing[Vector3]()
        defer no_points.close()
        var knots = Growing[f64]()
        defer knots.close()
        var plane = try Surface(surface_plane, origin, x, n, 0.0, 0.0, no_points.view(), knots.view(), knots.view(), knots.view(), 0, 0, 0, 0)
        defer plane.close()
        return try split_by_surface(model.value(), &plane, tag)

    ## Fusion's sketch Slice: what of `model` lies behind the plane through
    ## `origin` facing `normal`, the part in front cut away and the cut
    ## capped by faces named `<tag>/to/f<i>` (split_body.lucb); `model`
    ## itself when nothing of it is in front. An error when all of it is, or
    ## when the boolean fails.
    pub static func sliced(model: interop.Reference[CadModel], origin: Vector3, normal: Vector3, tag: str) -> interop.Reference[CadModel]!:
        let n = normal.normalized() catch failure: error(invalid, "a slice plane needs a normal")
        let seed = Vector3(1.0, 0.0, 0.0) if math.abs(n.x) < 0.9 else Vector3(0.0, 1.0, 0.0)
        let x = try seed.subtract(n.multiply_scalar(seed.dot(n))).normalized()
        var no_points = Growing[Vector3]()
        defer no_points.close()
        var knots = Growing[f64]()
        defer knots.close()
        var plane = try Surface(surface_plane, origin, x, n, 0.0, 0.0, no_points.view(), knots.view(), knots.view(), knots.view(), 0, 0, 0, 0)
        defer plane.close()
        let found = try behind_surface(model.value(), &plane, tag)
        let behind = found else return model.clone()
        return behind

    ## Split Body by the surface of `tool`'s face `face` (a plane, cylinder,
    ## cone, sphere or torus), extended past the face: the piece inside it
    ## (a plane: on its outward side) and the piece outside, as two lumps.
    ## With `extend` off (Fusion's Extend splitting tool), only where the
    ## face itself reaches; a B-spline face too (split_body.lucb).
    pub static func split_by_face(model: interop.Reference[CadModel], tool: interop.Reference[CadModel], face: str, tag: str, extend: bool = true) -> interop.Reference[CadModel]!:
        var t = try shape_of(tool.value())
        defer t.close()
        var found = Growing[usize]()
        defer found.close()
        try faces_named(&t, face, &found)
        let f = found.items[0]
        if not extend: return try split_by_face_only(model.value(), &t, f, tag)
        let s = &t.surfaces.items[(usize)t.faces.items[f].surface]
        if s.kind == surface_spline: error(invalid, "Split Body extends a plane, cylinder, cone, sphere or torus face; turn Extend splitting tool off to split by a B-spline face")
        if s.kind == surface_plane and not t.faces.items[f].sense:
            # The plane turned to face the way the face does.
            var no_points = Growing[Vector3]()
            defer no_points.close()
            var knots = Growing[f64]()
            defer knots.close()
            var turned = try Surface(surface_plane, s.origin, s.x, s.z.multiply_scalar(-1.0), 0.0, 0.0, no_points.view(), knots.view(), knots.view(), knots.view(), 0, 0, 0, 0)
            defer turned.close()
            return try split_by_surface(model.value(), &turned, tag)
        return try split_by_surface(model.value(), s, tag)

    ## Fillets of `radius` on the edges `references` names and, in the same
    ## feature, variable radius ones on the edges `variable` names
    ## (references apart by `;`, each one straight edge between flat faces):
    ## edge k's law is the next `counts[k]` of `positions` and `radii` (0
    ## its start, 1 its end; Fusion's law between them, or `smooth`). They
    ## meet at corners as constant fillets of `radius` do; a variable edge
    ## must have that radius at a corner it runs into, where its law is held
    ## flat (variable_corners.lucb).
    pub static func variable_filleted_edges(model: interop.Reference[CadModel], references: str, radius: f64, variable: str, positions: const f64[], radii: const f64[], counts: const i64[], tag: str, continuity: i64 = 1, smooth: bool = false, tangency: f64 = 1.0) -> interop.Reference[CadModel]!:
        return try variable_corner_fillets(model.value(), references, radius, variable, positions, radii, counts, tag, continuity, smooth, weighted_shape(tangency))

    ## The surface extension operator: the B-spline face named `face`'s
    ## surface carried on naturally past every side by `distance` (along its
    ## middle isoparms), as a one-face sheet facing and named as the face
    ## (surface_extend.lucb). An analytic face's surface goes on of itself
    ## (Untrim gives its natural extent): refused.
    pub static func extended_surface(model: interop.Reference[CadModel], face: str, distance: f64) -> interop.Reference[CadModel]!:
        return try extended_face(model.value(), face, distance)

    ## How many lumps (separate pieces) `model` has.
    ## `model` under the project's `tolerances` (a held body when the
    ## setting changes, or an import): its edges and vertices lying off
    ## their faces by more than its working tolerance made tolerant by as
    ## much; with `adopt` (an import taking the scene's tolerances) such
    ## edges found again where their faces' surfaces meet first, as far as
    ## they can be (rechecks.lucb).
    pub static func rechecked(model: interop.Reference[CadModel], tolerances: CadTolerances, adopt: bool = false) -> interop.Reference[CadModel]!:
        return try rechecked_model(model, tolerances, adopt)

    ## What `model`'s edges say against its tolerances: how many lie off
    ## their faces by more than the positional tolerance and the worst of
    ## them, how many are shorter than it (rechecks.lucb).
    pub static func tolerance_report(model: interop.Reference[CadModel]) -> ToleranceReport!:
        return try report_of(model.value())

    pub static func lump_count(model: interop.Reference[CadModel]) -> i64!:
        var w = try shape_of(model.value())
        defer w.close()
        var lumps = Growing[usize]()
        defer lumps.close()
        return (i64)(try lumps_of(&w, &lumps))

    ## Lump `at` of `model` as a body of its own.
    pub static func lump(model: interop.Reference[CadModel], at: i64) -> interop.Reference[CadModel]!:
        var w = try shape_of(model.value())
        defer w.close()
        var lumps = Growing[usize]()
        defer lumps.close()
        let count = try lumps_of(&w, &lumps)
        if at < 0 or (usize)at >= count: error(invalid, "the body has no such lump")
        return try lump_model(&w, lumps.view(), (usize)at)

    ## Move/Copy of a body: `model` turned `angle` radians about the line
    ## through `origin` along `axis`, then moved by `by`. A copy (the
    ## original kept) takes `prefix` before its faces' names, so features
    ## tell it from the original; empty for a move.
    pub static func moved_body(model: interop.Reference[CadModel], by: Vector3, origin: Vector3 = Vector3(), axis: Vector3 = Vector3(0.0, 1.0, 0.0), angle: f64 = 0.0, prefix: str = "") -> interop.Reference[CadModel]!:
        if not by.is_finite() or not origin.is_finite() or not math.is_finite(angle): error(invalid, "a move needs finite distances and angles")
        let a = axis.normalized() catch failure: error(invalid, "a rotation needs an axis")
        let x = Vector3(1.0, 0.0, 0.0).rotated_about(a, angle)
        let y = Vector3(0.0, 1.0, 0.0).rotated_about(a, angle)
        let z = Vector3(0.0, 0.0, 1.0).rotated_about(a, angle)
        let turned = origin.rotated_about(a, angle)
        let matrix = Matrix4(x, y, z, origin.subtract(turned).add(by))
        let placed = try model.value().placed(matrix)
        if prefix == "": return placed
        defer placed.release()
        return try CadModeling.prefixed(placed, prefix)

    # -- Extrude's extents (extents.lucb, extent_targets.lucb).

    ## The sketch's profiles in `set` (as extruded's) extruded on two sides
    ## of its plane moved `start` along the normal: `distance` along the
    ## normal and `other` against it, each side leaning in by its taper
    ## angle (radians; negative leans out: a cone from an arc, a slanted
    ## plane from a line). One side (`other` 0) may run either way; two
    ## sides take positive distances (symmetric: the same each way). Faces
    ## as extruded's; the part of a side below the plane, when the two
    ## sides' tapers differ, is `back<c>.<k>`.
    pub static func extruded_sides(set: interop.Reference[GeometrySet], distance: f64, other: f64, tag: str, taper: f64 = 0.0, other_taper: f64 = 0.0, start: f64 = 0.0, profiles: str = "", tolerances: CadTolerances = CadTolerances()) -> interop.Reference[CadModel]!:
        var levels = Growing[Level]()
        defer levels.close()
        try side_levels(distance, other, taper, other_taper, start, &levels)
        return try extruded_levels(tolerances, try set.get(), profiles, levels.view(), tag)

    ## Extent All: the profiles extruded past the whole of `model` along
    ## the normal (`direction` 1), against it (-1) or both ways (0), from
    ## the plane moved `start` along the normal (Start Offset).
    pub static func extruded_through(set: interop.Reference[GeometrySet], model: interop.Reference[CadModel], tag: str, direction: i64 = 1, taper: f64 = 0.0, profiles: str = "", start: f64 = 0.0) -> interop.Reference[CadModel]!:
        return try extruded_through_body(try set.get(), model.value(), tag, direction, taper, profiles, start)

    ## Extent To Object: the profiles extruded, from the plane moved `start`
    ## along the normal, toward `model`'s face named `face`, as Fusion's
    ## Extend says (extend_face ...): 0 until they meet its surface
    ## (extended past the face; a plane, cylinder, cone, sphere or torus),
    ## `offset` further on; 1 until they meet it and the faces next to it
    ## (refused when they would meet another face first, or run past them);
    ## 2 until they meet the body holding it; 3 through that body, ending
    ## at its last face. With `face` empty, 2 and 3 take the whole model.
    ## The face that stops it is named `<tag>/to/f<i>` (a plane parallel to
    ## the sketch: the end cap).
    pub static func extruded_to(set: interop.Reference[GeometrySet], model: interop.Reference[CadModel], tag: str, face: str = "", offset: f64 = 0.0, taper: f64 = 0.0, profiles: str = "", start: f64 = 0.0, extend: i64 = 0) -> interop.Reference[CadModel]!:
        return try extruded_to_target(try set.get(), model.value(), tag, face, offset, taper, profiles, start, extend)

    ## Start: Object, Fusion's: the profiles extruded from `model`'s face
    ## `face` (its surface moved `offset` along the way the extrusion runs)
    ## by `extent` (from_distance ...): `distance` along the normal, its
    ## sign the way (from a curved or slanted face, the end follows the
    ## face's shape moved on); to face `target` moved `target_offset` on;
    ## or through all (only `distance`'s sign counts). A face parallel to
    ## the sketch is a start offset, and takes a taper.
    pub static func extruded_from(set: interop.Reference[GeometrySet], model: interop.Reference[CadModel], tag: str, face: str, offset: f64 = 0.0, extent: i64 = 0, distance: f64 = 1.0, target: str = "", target_offset: f64 = 0.0, taper: f64 = 0.0, profiles: str = "") -> interop.Reference[CadModel]!:
        return try extruded_from_face(try set.get(), model.value(), tag, face, offset, extent, distance, target, target_offset, taper, profiles)

    ## The profiles turned about the line through `origin` along
    ## `direction`, which must lie in the sketch's plane (a sketch line, a
    ## body edge, a construction axis): as revolved's, a full turn or
    ## `angle` radians toward the plane's normal.
    pub static func revolved_about(set: interop.Reference[GeometrySet], origin: Vector3, direction: Vector3, tag: str, angle: f64 = 2.0 * math.pi, profiles: str = "", tolerances: CadTolerances = CadTolerances()) -> interop.Reference[CadModel]!:
        let source = try set.get()
        let size = try sketch_size(source)
        var p = try profiles_of(source, size * 0.0001, profiles)
        defer p.close()
        let axis = direction.normalized() catch failure: error(invalid, "a revolve's axis needs a direction")
        if math.abs(axis.dot(p.normal)) > 1e-9 or math.abs(origin.subtract(p.origin).dot(p.normal)) > size * 1e-7:
            error(invalid, "a revolve's axis must lie in the sketch's plane")
        let solid = try BrepModel.sized(tolerances, size)
        defer solid.release()
        try revolve_into(solid.value(), &p, origin, axis, size * 0.000001, tag, angle)
        return try CadModel.of_brep(solid)

    ## Revolve's To extent: the profiles turned about the line through
    ## `origin` along `direction` (in the sketch's plane), toward the
    ## plane's normal (`way` 1) or against it (-1), until they meet
    ## `model`'s face named `face` (its surface extended past the face; a
    ## plane, cylinder, cone, sphere or torus): the piece holding the
    ## profile, the face's cut named `<tag>/to/f<i>`. Refused when the turn
    ## comes round without meeting it.
    pub static func revolved_to(set: interop.Reference[GeometrySet], origin: Vector3, direction: Vector3, tag: str, model: interop.Reference[CadModel], face: str, way: f64 = 1.0, profiles: str = "") -> interop.Reference[CadModel]!:
        return try revolved_to_face(set, origin, direction, tag, model.value(), face, way, profiles)

    ## The axis of `model`'s edge `reference` (edge_references'): a line
    ## edge's line, a circular edge's axis (through its center, along its
    ## normal); `found` false for any other edge.
    pub static func edge_axis(model: interop.Reference[CadModel], reference: str) -> AxisLine!:
        var w = try shape_of(model.value())
        defer w.close()
        var edges = Growing[usize]()
        defer edges.close()
        try resolve_edges(&w, reference, &edges)
        let c = w.carriers.items[(usize)w.edges.items[edges.items[0]].carrier]
        if c.kind == curve_line: return AxisLine(true, c.origin, c.x)
        if c.kind == curve_circle: return AxisLine(true, c.origin, c.x.cross(c.y))
        return AxisLine(false, Vector3(), Vector3(0.0, 0.0, 1.0))

    ## Where a blend's radius arrow stands on `model`'s edge `reference`
    ## (edge_references'; several: the first): the edge's middle, and the
    ## way out of the corner between its faces (handles.lucb).
    pub static func edge_frame(model: interop.Reference[CadModel], reference: str) -> EdgeFrame!:
        var w = try shape_of(model.value())
        defer w.close()
        return try edge_frame_of(&w, reference)

    ## Fusion's Two distances and Distance and angle chamfers
    ## (chamfers.lucb): the edges `references` names (as chamfered)
    ## chamfered `distance` along their first face and `second` along the
    ## other, or, with `second` 0, leaving the first face at `angle`
    ## (radians). The first face is the one more chosen edges lie on (a tie:
    ## by name), `flip` swapping them. Every edge an equal chamfer takes:
    ## straight or curved, outside or inside, between flat or curved faces;
    ## distances run straight from the edge to each contact.
    pub static func chamfered_sides(model: interop.Reference[CadModel], references: str, distance: f64, second: f64, angle: f64, tag: str, chain: bool = true, flip: bool = false, corner: i64 = 1) -> interop.Reference[CadModel]!:
        try corner_kind(corner)
        return try sided_chamfer(model.value(), references, distance, second, angle, tag, chain, flip, corner)

    ## Fusion's Rule Fillet (rules.lucb): references to `model`'s blendable
    ## edges, convex ones when `rounds`, concave ones when `fillets`; with
    ## `faces` named (apart by `;`), only edges on one of them, and with
    ## `others` too, only edges between the two sets. An error when none.
    pub static func rule_edges(model: interop.Reference[CadModel], rounds: bool, fillets: bool, faces: str = "", others: str = "") -> interop.Owned[str]!:
        var w = try shape_of(model.value())
        defer w.close()
        var text = Growing[u8]()
        defer text.close()
        try rule_references(&w, rounds, fillets, faces, others, &text)
        return try interop.copy_text((str)text.view())

    ## Where Press Pull's arrow stands on `model`'s face `name` (as
    ## face_frame's): near the middle of the face, its outward normal.
    pub static func face_point(model: interop.Reference[CadModel], name: str) -> FacePoint!:
        var w = try shape_of(model.value())
        defer w.close()
        return try face_point_of(&w, name)

## A chamfer corner type, checked: 0 Chamfer, 1 Miter, 2 Blend.
func corner_kind(corner: i64) -> !:
    if corner < corner_chamfer or corner > corner_blend: error(invalid, "a chamfer's corner is 0 Chamfer, 1 Miter or 2 Blend")

## The extent of the sketch's curves (at least 1), which scales tolerances.
func sketch_size(set: const GeometrySet*) -> f64!:
    let curves = set_curves(set) else return 1.0
    var low = Vector3(1.0e300, 1.0e300, 1.0e300)
    var high = Vector3(-1.0e300, -1.0e300, -1.0e300)
    for at in 0..<curves.point_count():
        let p = curves.point(at)
        low = Vector3(math.min(low.x, p.x), math.min(low.y, p.y), math.min(low.z, p.z))
        high = Vector3(math.max(high.x, p.x), math.max(high.y, p.y), math.max(high.z, p.z))
    if curves.point_count() == 0: return 1.0
    return math.max(1.0, high.subtract(low).length())

## A model of shape `w`.
func shape_model(w: const Shape*) -> interop.Reference[CadModel]!:
    let b = try brep_of(w)
    defer b.release()
    return try CadModel.of_brep(b)