Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.2

0.9.2 / 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, parallel
import ownership
import brep
## The B-rep a CadModel holds (brep/), and its interop type.
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 geometry import NurbsSurface, copied, push_decimal, surface_spline
from brep import boundary_lines, hull_lines, encode_brep, decode_brep, boundary_key
from luce_geocore.kernel import GeometryWriter, GeometryReader, dtype_float64, dtype_int32, Attribute, Domain, DataType
from luce_geocore.core.shared import Column
from luce_geocore.core.growing import Growing
from meshing import planar_grid, nurbs_grid
import strings
import thread

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():
        if self.points.length > 0: free(self.points) in memory.heap
        if self.weights.length > 0: free(self.weights) in memory.heap
        if self.ku.length > 0: free(self.ku) in memory.heap
        if self.kv.length > 0: free(self.kv) in memory.heap

## A CAD model: independent faces (B-spline patches and planar polygons,
## each with its trim rectangle) and at most one B-rep, under one
## placement. Copies share their B-rep; edits return new models.
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

    ## For modeling: the B-rep (none for independent faces only), and the
    ## placement over it.
    pub func brep() -> const BrepModel*?:
        if let value = self.boundary: return value.value()
        return none

    pub func brep_placement() -> Matrix4:
        return self.placement

    ## A new model, held by reference, of B-rep `solid` (shared with it).
    pub static func of_brep(solid: 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()
        try result.value().attach_brep(solid)
        return result

    pub func independent_faces() -> i64:
        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 ""

    ## The name modeling gave the face ("" for none; docs/MODELING.md).
    pub func face_name(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_name(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

    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 p = try copied[Vector3](points)
        errdefer:
            if p.length > 0: free(p) in memory.heap
        let w = try copied[f64](weights)
        errdefer:
            if w.length > 0: free(w) in memory.heap
        let u = try copied[f64](ku)
        errdefer:
            if u.length > 0: free(u) in memory.heap
        let v = try copied[f64](kv)
        self.faces[self.count] = Face(p, 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)

## `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)

## 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)