Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.1

0.9.1 / src / model / model.lucb

## Format-independent CAD model. Analytic control nets survive mesh generation.
## Independent patches and shared B-rep topology retain their analytic data.
import interop
import memory
from luce_std import math
import ownership
import brep
pub type BrepModel = brep.BrepModel
pub let brep_model_type = brep.brep_model_type
from luce_geocore.geocore import Mesh, MeshBuilder, MeshNormals, Vector3, Matrix4, invalid
from tessellation.surface import NurbsSurface
from patch_grid import planar_grid
import preview_set
from preview_set import PreviewPart, collect_preview
pub type CadPreviewSet = preview_set.CadPreviewSet
pub let cad_preview_set_type = preview_set.cad_preview_set_type
import cad_overlay
pub type CadOverlay = cad_overlay.CadOverlay
pub let cad_overlay_type = cad_overlay.cad_overlay_type
from brep import boundary_lines, hull_lines, encode_brep, decode_brep, boundary_key
from luce_geocore.kernel import GeometryWriter, GeometryReader, dtype_float64, dtype_int32
from luce_geocore.core.shared import Column
from luce_geocore.core.growing import Growing

struct Face:
    let points: Vector3[]
    let weights: f64[]
    let ku: f64[]
    let kv: f64[]
    let nu: i64
    let nv: i64
    let du: i64
    let dv: i64
    var u0: f64
    var u1: f64
    var v0: f64
    var v1: f64
    var reversed: bool

    func close():
        free(self.points) in memory.heap
        free(self.weights) in memory.heap
        free(self.ku) in memory.heap
        free(self.kv) in memory.heap

pub struct CadModel:
    ## Independent faces: the first `count` of `faces`, which grows by
    ## doubling (any number of faces).
    var faces: Face[]
    var count: usize
    var boundary: interop.Reference[BrepModel]? = none
    var placement: Matrix4

    pub func init() -> !:
        self.faces = try new Face[16] --- in memory.heap
        self.count = 0
        self.boundary = none
        self.placement = Matrix4()

    ## Number of analytic faces, independent of tessellation resolution.
    pub func face_count() -> i64:
        if let value = self.boundary:
            return (i64)self.count + value.value().face_count()
        return (i64)self.count

    pub func attach_brep(value: interop.Reference[BrepModel]) -> !:
        if let existing = self.boundary:
            error(invalid, "CAD model already has boundary topology")
        self.boundary = value.clone()

    pub func edge_count() -> i64:
        if let value = self.boundary:
            return value.value().edge_count()
        return 0

    ## Format-independent support type, including standalone NURBS patches.
    pub func face_surface_kind(face: i64) -> i64!:
        if face < 0 or face >= self.face_count():
            error(invalid, "CAD face index out of range")
        if let boundary = self.boundary:
            if face >= (i64)self.count:
                return try boundary.value().face_surface_kind(face - (i64)self.count)
        return 3

    ## Object hierarchy metadata is independent of surface representation.
    pub func face_path(face: i64) -> str!:
        if face < 0 or face >= self.face_count():
            error(invalid, "CAD face index out of range")
        if let boundary = self.boundary:
            if face >= (i64)self.count:
                return try boundary.value().face_path(face - (i64)self.count)
        return ""

    ## Extract analytic B-rep faces without tessellating or flattening metadata.
    pub func subset(selection: const i64[]) -> interop.Reference[CadModel]!:
        if self.count != 0:
            error(invalid, "CAD subsets currently require B-rep topology")
        let boundary = self.boundary else error(invalid, "CAD model has no B-rep")
        let part = try boundary.value().subset(selection)
        defer part.release()
        let result = try interop.Reference[CadModel].adopt(new CadModel() in memory.heap, cad_model_type, memory.heap)
        errdefer result.release()
        try result.value().attach_brep(part)
        result.value().placement = self.placement
        return result

    ## Return an independent transformed analytic model, retaining trim domains.
    pub func transformed(translation: Vector3, rotation: Vector3, scale: Vector3) -> interop.Reference[CadModel]!:
        if not translation.is_finite() or not rotation.is_finite() or not scale.is_finite() or math.abs(scale.x) < 0.000001 or math.abs(scale.y) < 0.000001 or math.abs(scale.z) < 0.000001:
            error(invalid, "CAD transform must be finite and nonsingular")
        return try self.placed(Matrix4.compose(translation, rotation, scale))

    ## An independent model placed by `matrix` (finite, nonsingular), with
    ## its trim domains; a B-rep keeps its columns under a new placement.
    pub func placed(matrix: Matrix4) -> interop.Reference[CadModel]!:
        if not matrix.is_finite() or math.abs(matrix.determinant()) < 0.000000000001:
            error(invalid, "CAD transform must be finite and nonsingular")
        let reflected = matrix.determinant() < 0.0
        let output = try interop.Reference[CadModel].adopt(new CadModel() in memory.heap, cad_model_type, memory.heap)
        errdefer output.release()
        for entry in self.faces[..<self.count]:
            let points = try new Vector3[entry.points.length] --- in memory.heap
            defer free(points) in memory.heap
            for index in 0..<points.length:
                points[index] = matrix.transform_point(entry.points[points.length - 1 - index if reflected and entry.nu == 0 else index])
            try output.value().append(points, entry.weights, entry.nu, entry.nv, entry.du, entry.dv, entry.ku, entry.kv)
            if entry.nu > 0:
                let index = output.value().count - 1
                try output.value().trim_rectangle((i64)index, entry.u0, entry.u1, entry.v0, entry.v1)
                output.value().faces[index].reversed = entry.reversed != reflected
        if let boundary = self.boundary:
            try output.value().attach_brep(boundary)
            output.value().placement = matrix.multiply(self.placement)
        return output

    ## Add a simple, coplanar outer boundary. Winding controls face orientation.
    ## Holes and shared topological edges are not supported by this first API.
    pub func add_planar(boundary: const Vector3[]) -> !:
        if boundary.length < 3:
            error(invalid, "CAD planar boundary requires at least 3 points")
        var normal = Vector3()
        for at in 0..<boundary.length:
            normal = normal.add(boundary[at].subtract(boundary[0]).cross(boundary[(at + 1) % boundary.length].subtract(boundary[0])))
        normal = try normal.normalized()
        for point in boundary:
            if not point.is_finite() or math.abs(point.subtract(boundary[0]).dot(normal)) > 0.000001:
                error(invalid, "CAD planar boundary must be finite and coplanar within 1e-6 source units")
        let checked = try planar_mesh(boundary)
        defer checked.release()
        var empty: f64[1]
        try self.append(boundary, empty[..<0], 0, 0, 0, 0, empty[..<0], empty[..<0])

    ## Preserve an exact rational control net and its full parameter domain.
    pub func add_nurbs(points: const Vector3[], weights: const f64[], nu: i64, nv: i64,
                       degree_u: i64, degree_v: i64, knots_u: const f64[], knots_v: const f64[]) -> !:
        try NurbsSurface.check(points, weights, nu, nv, degree_u, degree_v, knots_u, knots_v)
        try self.append(points, weights, nu, nv, degree_u, degree_v, knots_u, knots_v)

    ## Set an axis-aligned parameter-space trim on a NURBS face.
    ## This does not approximate the surface by clipping a pre-existing mesh.
    pub func trim_rectangle(face: i64, u0: f64, u1: f64, v0: f64, v1: f64) -> !:
        if face < 0 or (usize)face >= self.count:
            error(invalid, "CAD face index out of range")
        let entry = self.faces[(usize)face]
        if entry.nu == 0:
            error(invalid, "parameter trimming requires a NURBS face")
        try NurbsSurface.check_region(entry.ku, entry.kv, entry.nu, entry.nv, entry.du, entry.dv, u0, u1, v0, v1)
        self.faces[(usize)face].u0 = u0
        self.faces[(usize)face].u1 = u1
        self.faces[(usize)face].v0 = v0
        self.faces[(usize)face].v1 = v1

    ## The B-rep's control vertices (the cv domain; 0 without a B-rep).
    pub func cv_count() -> i64:
        if let boundary = self.boundary: return boundary.value().cv_count()
        return 0

    ## Faces the last tessellations took from the per-face cache.
    pub func reused_faces() -> i64:
        if let boundary = self.boundary: return boundary.value().reused_faces()
        return 0

    ## Where cv `index` is, placed as the model is (and as its surface's
    ## first face is).
    pub func cv_position(index: i64) -> Vector3!:
        let boundary = self.boundary else error(invalid, "CAD model has no B-rep")
        let shape = boundary.value()
        return self.placement.multiply(try shape.cv_placement(index)).transform_point(try shape.cv_position(index))

    ## A copy with cvs `ids` moved by `delta` (placed, as cv_position is):
    ## its B-rep shares every column but the cv positions, and its
    ## tessellation reuses every face whose inputs did not change.
    pub func with_cvs_moved(ids: const i64[], delta: Vector3) -> interop.Reference[CadModel]!:
        let placed = try new Vector3[ids.length] --- in memory.heap
        defer free(placed) in memory.heap
        for at in 0..<ids.length: placed[at] = (try self.cv_position(ids[at])).add(delta)
        return try self.with_cvs_placed(ids, placed)

    ## A copy with cvs `ids` at the placed `positions` (one per id).
    pub func with_cvs_placed(ids: const i64[], positions: const Vector3[]) -> interop.Reference[CadModel]!:
        let boundary = self.boundary else error(invalid, "CAD model has no B-rep")
        let shape = boundary.value()
        if ids.length != positions.length: error(invalid, "every moved control vertex needs a position")
        var placements = Growing[Matrix4]()
        defer placements.close()
        try shape.surface_placements(&placements)
        let inner = try new Vector3[ids.length] --- in memory.heap
        defer free(inner) in memory.heap
        for at in 0..<ids.length:
            let place = self.placement.multiply(placements.items[(usize)(try shape.cv_surface(ids[at]))])
            inner[at] = try unplaced(place, positions[at].subtract(place.translation))
        let moved = try shape.with_cvs_at(ids, inner)
        defer moved.release()
        return try self.with_brep(moved)

    ## This model with `shape` in place of its B-rep.
    func with_brep(shape: interop.Reference[BrepModel]) -> interop.Reference[CadModel]!:
        let result = try interop.Reference[CadModel].adopt(new CadModel() in memory.heap, cad_model_type, memory.heap)
        errdefer result.release()
        for entry in self.faces[..<self.count]:
            try result.value().append(entry.points, entry.weights, entry.nu, entry.nv, entry.du, entry.dv, entry.ku, entry.kv)
            let index = result.value().count - 1
            result.value().faces[index].u0 = entry.u0
            result.value().faces[index].u1 = entry.u1
            result.value().faces[index].v0 = entry.v0
            result.value().faces[index].v1 = entry.v1
            result.value().faces[index].reversed = entry.reversed
        try result.value().attach_brep(shape)
        result.value().placement = self.placement
        return result

    ## What its edges' drawn lines depend on (0: not known, draw them anew):
    ## a B-rep's edges and the model's placement. A copy with moved control
    ## vertices keeps the key; the viewport keeps its lines.
    pub func edges_key() -> i64:
        if self.count != 0: return 0
        let boundary = self.boundary else return 0
        var key = boundary_key(boundary.value())
        let m = self.placement
        let values: f64[12] = [m.x.x, m.x.y, m.x.z, m.y.x, m.y.y, m.y.z, m.z.x, m.z.y, m.z.z, m.translation.x, m.translation.y, m.translation.z]
        for value in values: key = (key ^ value.bits()) *% 0x100000001B3
        return (i64)(key >> 1) | 1

    ## Lines to draw over the model: its edges, its hull and a normal guide
    ## per face of `mesh` (its tessellation).
    pub func overlay(mesh: interop.Reference[Mesh]) -> interop.Reference[CadOverlay]!:
        let result = try interop.Reference[CadOverlay].adopt(new CadOverlay() in memory.heap, cad_overlay_type, memory.heap)
        errdefer result.release()
        let boundaries = cad_overlay.boundary_list(result.value())
        let hull = cad_overlay.hull_list(result.value())
        if let boundary = self.boundary:
            try boundary_lines(boundary.value(), self.placement, boundaries)
            try hull_lines(boundary.value(), self.placement, hull)
        for index in 0..<self.count:
            let entry = self.faces[index]
            let edges = try self.edge_count_in(none, (i64)index)
            for edge in 0..<edges:
                let chords = 1 if entry.nu == 0 else 64
                var previous = try self.edge_point_in(none, (i64)index, edge, 0.0)
                for step in 1..<chords + 1:
                    let next = try self.edge_point_in(none, (i64)index, edge, (f64)step / (f64)chords)
                    try boundaries.push(previous)
                    try boundaries.push(next)
                    previous = next
            for u in 0..<(usize)entry.nu:
                for v in 0..<(usize)entry.nv:
                    let here = self.placement.transform_point(entry.points[u * (usize)entry.nv + v])
                    if v + 1 < (usize)entry.nv:
                        try hull.push(here)
                        try hull.push(self.placement.transform_point(entry.points[u * (usize)entry.nv + v + 1]))
                    if u + 1 < (usize)entry.nu:
                        try hull.push(here)
                        try hull.push(self.placement.transform_point(entry.points[(u + 1) * (usize)entry.nv + v]))
        try cad_overlay.face_guides(mesh.value(), cad_overlay.guide_list(result.value()))
        return result

    ## The B-rep, resolved on the calling thread: preview workers may use the
    ## pointer but not the reference, whose owner belongs to this thread.
    func topology() -> BrepModel*?:
        if let value = self.boundary:
            return value.value()
        return none

    ## Produce a disposable display mesh; the analytic model is unchanged.
    pub func face_edge_count(face: i64) -> i64!:
        return try self.edge_count_in(self.topology(), face)

    pub func face_edge_point(face: i64, edge: i64, fraction: f64) -> Vector3!:
        return try self.edge_point_in(self.topology(), face, edge, fraction)

    pub func face_edge_linear(face: i64, edge: i64) -> bool!:
        return try self.edge_linear_in(self.topology(), face, edge)

    pub func face_edge_id(face: i64, edge: i64) -> i64!:
        return try self.edge_id_in(self.topology(), face, edge)

    pub func preview_face(face: i64, divisions: i64 = 8) -> interop.Reference[Mesh]!:
        return try self.preview_in(self.topology(), face, divisions)

    ## Every face's preview (see preview_face), meshed on the worker pool and
    ## merged into display batches in face order, with deduplicated analytic
    ## boundary polylines and a normal guide per face. Failed faces are
    ## counted and keep their boundaries.
    pub func preview(progress: interop.Callback[f64, unit]? = none) -> interop.Reference[CadPreviewSet]!:
        var job = PreviewJob(model = &self, topology = self.topology())
        return try collect_preview((usize)self.face_count(), (usize)self.edge_count(), make_preview_part, (void*)&job, progress)

    func edge_count_in(topology: BrepModel*?, face: i64) -> i64!:
        if face < 0 or face >= self.face_count_in(topology):
            error(invalid, "CAD face index out of range")
        if let boundary = topology:
            if face >= (i64)self.count:
                return try boundary.face_edge_count(face - (i64)self.count)
        return (i64)self.faces[(usize)face].points.length if self.faces[(usize)face].nu == 0 else 4

    func face_count_in(topology: BrepModel*?) -> i64:
        if let boundary = topology:
            return (i64)self.count + boundary.face_count()
        return (i64)self.count

    func edge_point_in(topology: BrepModel*?, face: i64, edge: i64, fraction: f64) -> Vector3!:
        let count = try self.edge_count_in(topology, face)
        if edge < 0 or edge >= count or fraction < 0.0 or fraction > 1.0 or not math.is_finite(fraction):
            error(invalid, "invalid CAD boundary sample")
        if let boundary = topology:
            if face >= (i64)self.count:
                return self.placement.transform_point(try boundary.face_edge_point(face - (i64)self.count, edge, fraction))
        let entry = self.faces[(usize)face]
        if entry.nu == 0:
            let a = entry.points[(usize)edge]
            let b = entry.points[(usize)((edge + 1) % count)]
            return a.add(b.subtract(a).multiply_scalar(fraction))
        let u = entry.u0 + (entry.u1 - entry.u0) * fraction
        let v = entry.v0 + (entry.v1 - entry.v0) * fraction
        return try NurbsSurface.at(entry.points, entry.weights, entry.nu, entry.nv, entry.du, entry.dv, entry.ku, entry.kv,
                                   u if edge == 0 or edge == 2 else (entry.u1 if edge == 1 else entry.u0), v if edge == 1 or edge == 3 else (entry.v0 if edge == 0 else entry.v1))

    func edge_linear_in(topology: BrepModel*?, face: i64, edge: i64) -> bool!:
        let count = try self.edge_count_in(topology, face)
        if edge < 0 or edge >= count:
            error(invalid, "CAD edge use index out of range")
        if let boundary = topology:
            if face >= (i64)self.count:
                return try boundary.face_edge_linear(face - (i64)self.count, edge)
        return self.faces[(usize)face].nu == 0

    func edge_id_in(topology: BrepModel*?, face: i64, edge: i64) -> i64!:
        let count = try self.edge_count_in(topology, face)
        if edge < 0 or edge >= count:
            error(invalid, "CAD edge use index out of range")
        if let boundary = topology:
            if face >= (i64)self.count:
                return try boundary.face_edge_id(face - (i64)self.count, edge)
        # Independent faces' edges follow the B-rep's, 2^32 ids per face.
        return (i64)CadModel.count_edges_in(topology) + face * 4294967296 + edge

    static func count_edges_in(topology: BrepModel*?) -> i64:
        if let boundary = topology:
            return boundary.edge_count()
        return 0

    func preview_in(topology: BrepModel*?, face: i64, divisions: i64) -> interop.Reference[Mesh]!:
        if face < 0 or face >= self.face_count_in(topology):
            error(invalid, "CAD preview face index out of range")
        if let boundary = topology:
            if face >= (i64)self.count:
                let part = try boundary.preview_face(face - (i64)self.count, divisions)
                defer part.release()
                return try part.value().placed(self.placement)
        let entry = self.faces[(usize)face]
        if entry.nu == 0:
            return try planar_mesh(entry.points)
        let part = try NurbsSurface.tessellate_region(entry.points, entry.weights, entry.nu, entry.nv, entry.du, entry.dv, entry.ku, entry.kv, entry.u0, entry.u1, entry.v0, entry.v1, divisions)
        defer part.release()
        var output = try MeshBuilder()
        defer output.close()
        try output.copy_points(part.value())
        for at in 0..<part.value().face_count():
            let count = try part.value().face_size(at)
            try output.face(count)
            for corner in 0..<count:
                try output.corner(try part.value().face_point(at, count - 1 - corner if entry.reversed else corner))
        let raw = try output.finish()
        defer raw.release()
        var groups: i64[1]
        # The NURBS grid comes from precise tessellation; publish it in f32.
        return try brep.published(try MeshNormals.generate(raw, groups[..<0]))

    ## Diagnostic B-rep face using global shared-edge/layout planning, unlike
    ## the independent preview. Other face jobs are not validated by this call.
    pub func planned_face(face: i64, segments: i64 = 16, edge_size: f64 = 0.0) -> interop.Reference[Mesh]!:
        if self.count != 0: error(invalid, "planned face diagnostics require B-rep topology")
        let boundary = self.boundary else error(invalid, "CAD model has no B-rep")
        let part = try boundary.value().planned_face(face, segments, edge_size)
        defer part.release()
        return try part.value().placed(self.placement)

    ## Whether `tessellate` can add curvature attributes: a B-rep model under a
    ## uniform-scale placement.
    pub func supports_curvature() -> bool:
        if self.count != 0 or self.boundary == none: return false
        let matrix = self.placement
        let scale = matrix.x.length()
        let tolerance = scale * 1e-9
        return math.abs(matrix.y.length() - scale) <= tolerance and math.abs(matrix.z.length() - scale) <= tolerance and math.abs(matrix.x.dot(matrix.y)) <= tolerance * scale and math.abs(matrix.y.dot(matrix.z)) <= tolerance * scale and math.abs(matrix.x.dot(matrix.z)) <= tolerance * scale

    ## `curvature`/`directions` add principal curvature corner attributes
    ## (BrepModel.mesh); B-rep models only, under a uniform-scale placement.
    ## `quick` lets a copy with moved cvs answer with its quick preview (a
    ## drag's frames; brep/quick.lucb).
    pub func tessellate(segments: i64 = 16, edge_size: f64 = 0.0, progress: interop.Callback[f64, unit]? = none, curvature: bool = false, directions: bool = false, quick: bool = false) -> interop.Reference[Mesh]!:
        if not math.is_finite(edge_size) or edge_size < 0.0:
            error(invalid, "edge size must be finite and nonnegative")
        if segments < 1 or segments > 64:
            error(invalid, "CAD tessellation segments must be 1..64")
        if self.face_count() == 0:
            error(invalid, "CAD model has no faces")
        let analysis = curvature or directions
        if analysis and self.count != 0:
            error(invalid, "curvature attributes require B-rep topology")
        # The common STEP path needs no second mesh rebuild, recoloring, BVH or
        # normal generation. Placement is applied only when nonidentity.
        if self.count == 0:
            if let boundary = self.boundary:
                let part = try boundary.value().mesh(segments, edge_size, progress, curvature, directions, quick)
                defer part.release()
                # An identity placement shares the mesh as it is.
                if self.placement.is_identity(): return part.clone()
                let placed = try part.value().placed(self.placement)
                if not analysis or self.placement.is_identity(): return placed
                defer placed.release()
                return try scaled_curvature(placed, self.placement, directions)
        # `cad_face` numbers faces as face_count() does: independent faces
        # first, then the B-rep's (after `count`).
        var output = try MeshBuilder()
        defer output.close()
        # The B-rep's polygon colors (white for the independent faces).
        var colors = Growing[f64]()
        defer colors.close()
        var has_colors = false
        if let boundary = self.boundary:
            let part = try boundary.value().mesh(segments, edge_size, progress)
            defer part.release()
            for point in 0..<part.value().point_count():
                _ = try output.point(self.placement.transform_point(try part.value().point(point)))
            let reversed = self.placement.determinant() < 0.0
            let groups = part.value().find_attribute("cad_face", 2)
            let cd = part.value().find_attribute("Cd", 2)
            has_colors = cd >= 0
            for face in 0..<part.value().face_count():
                let count = try part.value().face_size(face)
                if cd >= 0:
                    for component in 0..<3:
                        try colors.push(try part.value().attribute_value(cd, face, component))
                try output.face(count, (i64)self.count + (i64)(try part.value().attribute_value(groups, face, 0)))
                for corner in 0..<count:
                    try output.corner(try part.value().face_point(face, count - 1 - corner if reversed else corner))
        for face_id in 0..<self.count:
            let entry = self.faces[face_id]
            if entry.nu == 0 and edge_size == 0.0:
                try output.face((i64)entry.points.length, (i64)face_id)
                for point in entry.points:
                    try output.corner(try output.point(point))
                continue
            var resolution = segments
            if entry.nu > 0 and edge_size > 0.0:
                var span: f64 = 0.0
                for point in entry.points:
                    span = math.max(span, point.subtract(entry.points[0]).length())
                let needed = math.ceil(span / edge_size)
                if needed > 64.0:
                    error(invalid, "edge size exceeds independent NURBS grid budget; increase it")
                resolution = (i64)math.max((f64)segments, needed)
            let part = try planar_grid(entry.points, edge_size) if entry.nu == 0 else (try NurbsSurface.tessellate_region(entry.points, entry.weights, entry.nu, entry.nv, entry.du, entry.dv, entry.ku, entry.kv, entry.u0, entry.u1, entry.v0, entry.v1, resolution))
            defer part.release()
            let offset = (i64)output.np
            for point in 0..<part.value().point_count():
                _ = try output.point(try part.value().point(point))
            for face in 0..<part.value().face_count():
                let count = try part.value().face_size(face)
                try output.face(count, (i64)face_id)
                for corner in 0..<count:
                    try output.corner(offset + (try part.value().face_point(face, count - 1 - corner if entry.reversed else corner)))
        let raw = try output.finish()
        defer raw.release()
        for index in 0..<output.nf:
            if output.face_parents[index] < 0:
                output.face_parents[index] = self.face_count() + (i64)index
        let values = try new f64[output.nf] --- in memory.heap
        defer free(values) in memory.heap
        for index in 0..<output.nf:
            values[index] = (f64)output.face_parents[index]
        let tagged = try raw.value().with_attribute("cad_face", 2, 1, values, true)
        defer tagged.release()
        if has_colors:
            try colors.extend(output.nf * 3, 1.0)
            let colored = try tagged.value().with_attribute("Cd", 2, 3, colors.view())
            defer colored.release()
            return try MeshNormals.generate(colored, output.face_parents[..<output.nf])
        return try MeshNormals.generate(tagged, output.face_parents[..<output.nf])

    func append(points: const Vector3[], weights: const f64[], nu: i64, nv: i64, du: i64, dv: i64, ku: const f64[], kv: const f64[]) -> !:
        if self.count == self.faces.length:
            let grown = try new Face[self.faces.length * 2] --- in memory.heap
            memory.copy(grown, self.faces, self.count)
            free(self.faces) in memory.heap
            self.faces = grown
        let copied = try new Vector3[points.length] --- in memory.heap
        errdefer free(copied) in memory.heap
        for index in 0..<points.length:
            copied[index] = points[index]
        let w = try copy_values(weights)
        errdefer free(w) in memory.heap
        let u = try copy_values(ku)
        errdefer free(u) in memory.heap
        let v = try copy_values(kv)
        self.faces[self.count] = Face(copied, w, u, v, nu, nv, du, dv,
                                      ku[(usize)du] if nu > 0 else 0.0, ku[(usize)nu] if nu > 0 else 0.0,
                                      kv[(usize)dv] if nv > 0 else 0.0, kv[(usize)nv] if nv > 0 else 0.0, false)
        self.count += 1

    ## Release owned control nets and face storage.
    pub func close():
        for entry in self.faces[..<self.count]:
            entry.close()
        free(self.faces) in memory.heap
        if let boundary = self.boundary:
            boundary.release()
        self.boundary = none

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        if let boundary = self.boundary:
            boundary.trace(visit, context)

pub let cad_model_type: interop.Type[CadModel] = interop.Type[CadModel]("CadModel", CadModel.close, CadModel.trace, closeable = true)

## Curvature under a similarity placement: a uniform scale s divides it by s
## (a reflection keeps it, as corners reverse to keep normals outward), and
## directions turn with the placement.
func scaled_curvature(mesh: interop.Reference[Mesh], matrix: Matrix4, directions: bool) -> interop.Reference[Mesh]!:
    let scale = matrix.x.length()
    let tolerance = scale * 1e-9
    if math.abs(matrix.y.length() - scale) > tolerance or math.abs(matrix.z.length() - scale) > tolerance or math.abs(matrix.x.dot(matrix.y)) > tolerance * scale or math.abs(matrix.y.dot(matrix.z)) > tolerance * scale or math.abs(matrix.x.dot(matrix.z)) > tolerance * scale:
        error(invalid, "curvature analysis needs a uniform-scale CAD placement")
    let corners = (usize)mesh.value().vertex_count()
    let values = try new f64[corners * 3] --- in memory.heap
    defer free(values) in memory.heap
    var current = mesh.clone()
    defer current.release()
    for name in ["curvature.k1", "curvature.k2"]:
        let index = current.value().find_attribute(name, 1)
        if index < 0: continue
        for corner in 0..<corners: values[corner] = (try current.value().attribute_value(index, (i64)corner)) / scale
        let next = try current.value().with_attribute(name, 1, 1, values[..<corners], false, true)
        current.release()
        current = next
    for name in ["curvature.d1", "curvature.d2"]:
        let index = current.value().find_attribute(name, 1)
        if index < 0 or not directions: continue
        for corner in 0..<corners:
            let d = Vector3(try current.value().attribute_value(index, (i64)corner, 0), try current.value().attribute_value(index, (i64)corner, 1), try current.value().attribute_value(index, (i64)corner, 2))
            let turned = matrix.transform_direction(d).multiply_scalar(1.0 / scale)
            values[corner * 3] = turned.x
            values[corner * 3 + 1] = turned.y
            values[corner * 3 + 2] = turned.z
        let next = try current.value().with_attribute(name, 1, 3, values, false, true)
        current.release()
        current = next
    return current.clone()

## `delta` (placed, model space) in the B-rep's own space: the placement's
## linear part solved for it.
func unplaced(matrix: Matrix4, delta: Vector3) -> Vector3!:
    let determinant = matrix.determinant()
    if not math.is_finite(determinant) or math.abs(determinant) < 0.000000000001: error(invalid, "CAD placement is singular")
    # Cramer's rule over the columns x, y, z.
    let x = delta.dot(matrix.y.cross(matrix.z)) / determinant
    let y = matrix.x.dot(delta.cross(matrix.z)) / determinant
    let z = matrix.x.dot(matrix.y.cross(delta)) / determinant
    return Vector3(x, y, z)

struct PreviewJob:
    let model: const CadModel*
    let topology: BrepModel*?

## One face's preview on a pool worker, as luced-3d's per-patch preview did:
## 8 divisions for faces with many edges, else 16; then 4; then 16 again.
func make_preview_part(raw: void*?, face: usize, part: PreviewPart*):
    let job = (PreviewJob*)(raw else return)
    let index = (i64)face
    # Boundary sampling errors stopped the whole serial preview; they stay fatal.
    fill_boundaries(job, index, part) catch failure:
        part.fatal(failure.message)
        return
    let edges = job.model.edge_count_in(job.topology, index) catch failure:
        part.fatal(failure.message)
        return
    let mesh = fallback_preview(job, index, 8 if edges > 32 else 16) catch failure:
        part.fail(failure.message)
        return
    defer mesh.release()
    part.adopt(mesh) catch failure: part.fail(failure.message)

func fallback_preview(job: PreviewJob*, index: i64, divisions: i64) -> interop.Reference[Mesh]!:
    let first = job.model.preview_in(job.topology, index, divisions) catch failure:
        let coarse = job.model.preview_in(job.topology, index, 4) catch coarse_failure:
            return try job.model.preview_in(job.topology, index, 16)
        return coarse
    return first

## Each edge use's analytic polyline (64 chords when curved, as the display's
## full-circle resolution: a coarse chord sinks into the shaded mesh).
func fill_boundaries(job: PreviewJob*, face: i64, part: PreviewPart*) -> !:
    let model = job.model
    let uses = try model.edge_count_in(job.topology, face)
    try part.open_boundaries((usize)uses)
    for use in 0..<uses:
        let divisions = 1 if (try model.edge_linear_in(job.topology, face, use)) else 64
        try part.begin_use(try model.edge_id_in(job.topology, face, use))
        for step in 0..<divisions + 1:
            try part.boundary_point(try model.edge_point_in(job.topology, face, use, (f64)step / (f64)divisions))

func copy_values(values: const f64[]) -> f64[]!:
    let output = try new f64[values.length] --- in memory.heap
    for index in 0..<values.length:
        output[index] = values[index]
    return output

func planar_mesh(points: const Vector3[]) -> interop.Reference[Mesh]!:
    var builder = try MeshBuilder()
    defer builder.close()
    try builder.face((i64)points.length)
    for point in points:
        try builder.corner(try builder.point(point))
    return try builder.finish()

## A CAD model in a geometry file (element `cad_model`): its placement, its
## independent faces (children `f0`, `f1`, …: control net, dimensions,
## trim domain, reversal) and its B-rep (child `brep`, brep/codec.lucb).
## The writer borrows array bytes until the file is written: the model's
## own arrays are borrowed, temporaries are copied.
pub func encode_model(model: const CadModel*, writer: GeometryWriter*, path: str) -> !:
    try writer.crate.element(path, "cad_model")
    try writer.column("placement", dtype_float64, 1, 12, u8[]((u8*)&model.placement, 96))
    var base = try copied_path(path)
    defer base.close()
    var name = Growing[u8]()
    defer name.close()
    for index in 0..<model.count:
        let face = model.faces[index]
        try numbered(&name, "f", index)
        try writer.crate.element(try writer.child((str)base.view(), (str)name.view()), "cad_face")
        try writer.column("points", dtype_float64, face.points.length, 3, u8[]((u8*)face.points.data, face.points.length * 24))
        try writer.column("weights", dtype_float64, face.weights.length, 1, u8[]((u8*)face.weights.data, face.weights.length * 8))
        try writer.column("ku", dtype_float64, face.ku.length, 1, u8[]((u8*)face.ku.data, face.ku.length * 8))
        try writer.column("kv", dtype_float64, face.kv.length, 1, u8[]((u8*)face.kv.data, face.kv.length * 8))
        let dims: i32[4] = [(i32)face.nu, (i32)face.nv, (i32)face.du, (i32)face.dv]
        try writer.crate.copied_array("dims", dtype_int32, 4, u8[]((u8*)&dims[0], 16))
        let domain: f64[4] = [face.u0, face.u1, face.v0, face.v1]
        try writer.crate.copied_array("domain", dtype_float64, 4, u8[]((u8*)&domain[0], 32))
        try writer.crate.integer("reversed", 1 if face.reversed else 0)
    if let boundary = model.boundary:
        try encode_brep(boundary.value(), writer, try writer.child((str)base.view(), "brep"))

## A CAD model read back from element `path` and its children.
pub func decode_model(reader: GeometryReader*, path: str) -> interop.Reference[CadModel]!:
    let result = try interop.Reference[CadModel].adopt(new CadModel() in memory.heap, cad_model_type, memory.heap)
    errdefer result.release()
    let model = result.value()
    while let header = try reader.next_property():
        if header.name == "placement":
            var column = try reader.column[Matrix4](header)
            defer column.release()
            if column.count() == 1: model.placement = column.view()[0]
    var base = try copied_path(path)
    defer base.close()
    while let child = try reader.next_child((str)base.view()):
        if child.1 == "brep":
            let boundary = try decode_brep(reader, child.0)
            defer boundary.release()
            try model.attach_brep(boundary)
        elif child.1 == "cad_face":
            try decode_face(reader, model)
    return result

func decode_face(reader: GeometryReader*, model: CadModel*) -> !:
    var points: Column[Vector3]
    defer points.release()
    var weights: Column[f64]
    defer weights.release()
    var ku: Column[f64]
    defer ku.release()
    var kv: Column[f64]
    defer kv.release()
    var dims: Column[i32]
    defer dims.release()
    var domain: Column[f64]
    defer domain.release()
    var reversed = false
    while let header = try reader.next_property():
        let name = header.name
        if name == "points": points = try reader.column[Vector3](header)
        elif name == "weights": weights = try reader.column[f64](header)
        elif name == "ku": ku = try reader.column[f64](header)
        elif name == "kv": kv = try reader.column[f64](header)
        elif name == "dims": dims = try reader.column[i32](header)
        elif name == "domain": domain = try reader.column[f64](header)
        elif name == "reversed": reversed = (try reader.integer(header)) != 0
    let size = dims.view()
    let range = domain.view()
    if size.length != 4 or range.length != 4: error(invalid, "a saved CAD face lacks its dimensions")
    try model.append(points.view(), weights.view(), (i64)size[0], (i64)size[1], (i64)size[2], (i64)size[3], ku.view(), kv.view())
    let index = model.count - 1
    model.faces[index].u0 = range[0]
    model.faces[index].u1 = range[1]
    model.faces[index].v0 = range[2]
    model.faces[index].v1 = range[3]
    model.faces[index].reversed = reversed

## A copy of `path` (a writer's child paths are valid until its next call).
func copied_path(path: str) -> Growing[u8]!:
    var copy = Growing[u8]()
    try copy.assign(path.bytes)
    return copy

## `prefix` followed by `number` in decimal, into `out`.
pub func numbered(out: Growing[u8]*, prefix: str, number: usize) -> !:
    try out.assign(prefix.bytes)
    var digits: u8[24]
    var count: usize = 0
    var rest = number
    while true:
        digits[count] = (u8)(48 + rest % 10)
        count += 1
        rest = rest // 10
        if rest == 0: break
    while count > 0:
        count -= 1
        try out.push(digits[count])

## Every cv of `model` placed (as cv_position), appended to `out`.
pub func placed_cvs(model: const CadModel*, out: Growing[Vector3]*) -> !:
    if let boundary = model.boundary: try boundary.value().placed_cvs(model.placement, out)