Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.2

0.9.2 / src / modeling / shape.lucb

## The modeling form of a B-rep: everything in world space (placements
## applied), each edge a parameter interval of a full curve (a carrier), so
## operations can split edges, find where curves meet and evaluate them
## anywhere. Read from a CadModel's B-rep, written back as a new BrepModel.

## A full curve: kind 0 a line (origin + x t, t a length), 1 a circle
## (origin + a (x cos t + y sin t)), 3 an ellipse (origin + x a cos t +
## y b sin t), 2 a B-spline of the shape's store (t its knot parameter).
pub struct Carrier:
    pub var kind: i64
    pub var origin: Vector3
    pub var x: Vector3
    pub var y: Vector3
    pub var a: f64
    pub var b: f64
    pub var spline: i64

## An edge: its carrier's interval from t0 to t1 (t1 < t0 runs backwards),
## between vertices start and end.
pub struct ShapeEdge:
    pub var carrier: i64
    pub var t0: f64
    pub var t1: f64
    pub var start: i64
    pub var end: i64

## A face: its surface, whether its normal is the surface's, its loops:
## uses[first..<first + count] (signed: +(edge + 1) forward), loop sizes
## sizes[loop_first..<loop_first + loops], the outer loop first; and its
## name (the shape's name `name`, -1 for none).
pub struct ShapeFace:
    pub var surface: i64
    pub var sense: bool
    pub var first: usize
    pub var count: usize
    pub var loop_first: usize
    pub var loops: usize
    pub var name: i64 = -1

## A B-spline of the shape's store: its control points and weights at
## first..<first + count, its knots from knot_first, its degree.
pub struct ShapeSpline:
    pub var first: usize
    pub var count: usize
    pub var knot_first: usize
    pub var degree: i64

## A solid in modeling form (see the file's header): points, carriers and
## their edge intervals, surfaces, faces and their loops, the spline store,
## face names, and each edge's two faces (sides).
pub struct Shape:
    pub var tolerance: f64
    pub var points: Growing[Vector3]
    pub var carriers: Growing[Carrier]
    pub var edges: Growing[ShapeEdge]
    pub var surfaces: Growing[Surface]
    pub var faces: Growing[ShapeFace]
    pub var uses: Growing[i64]
    pub var sizes: Growing[i64]
    pub var splines: Growing[ShapeSpline]
    pub var spline_points: Growing[Vector3]
    pub var spline_weights: Growing[f64]
    pub var spline_knots: Growing[f64]
    ## Face names: name n is name_bytes[name_offsets[n]..<name_offsets[n + 1]].
    pub var name_bytes: Growing[u8]
    pub var name_offsets: Growing[usize]
    ## Each edge's two faces, sides[2e] and sides[2e + 1] (-1 for none),
    ## indexed by index_sides (shape_of does): stale once faces change.
    pub var sides: Growing[i64]

    pub func close():
        self.points.close()
        self.carriers.close()
        self.edges.close()
        for surface in self.surfaces.view():
            var owned = surface
            owned.close()
        self.surfaces.close()
        self.faces.close()
        self.uses.close()
        self.sizes.close()
        self.splines.close()
        self.spline_points.close()
        self.spline_weights.close()
        self.spline_knots.close()
        self.name_bytes.close()
        self.name_offsets.close()
        self.sides.close()

    ## Name `n` ("" for -1).
    pub func name(n: i64) -> str:
        if n < 0: return ""
        return (str)self.name_bytes.view()[self.name_offsets.items[(usize)n]..<self.name_offsets.items[(usize)n + 1]]

    ## Face `f`'s name.
    pub func face_name(f: usize) -> str:
        return self.name(self.faces.items[f].name)

    ## A new name (-1 for "").
    pub func add_name(text: str) -> i64!:
        if text == "": return -1
        if self.name_offsets.count == 0: try self.name_offsets.push(0)
        for byte in text.bytes: try self.name_bytes.push(byte)
        try self.name_offsets.push(self.name_bytes.count)
        return (i64)self.name_offsets.count - 2

    pub func spline_net(index: i64) -> (const Vector3[], const f64[], const f64[], i64):
        let s = self.splines.items[(usize)index]
        return (self.spline_points.view()[s.first..<s.first + s.count], self.spline_weights.view()[s.first..<s.first + s.count],
                self.spline_knots.view()[s.knot_first..<s.knot_first + s.count + (usize)s.degree + 1], s.degree)

    ## Carrier `c` at parameter `t`.
    pub func at(c: i64, t: f64) -> Vector3!:
        let carrier = self.carriers.items[(usize)c]
        if carrier.kind == curve_line: return carrier.origin.add(carrier.x.multiply_scalar(t))
        if carrier.kind == curve_circle: return carrier.origin.add(carrier.x.multiply_scalar(carrier.a * math.cos(t))).add(carrier.y.multiply_scalar(carrier.a * math.sin(t)))
        if carrier.kind == curve_ellipse: return carrier.origin.add(carrier.x.multiply_scalar(carrier.a * math.cos(t))).add(carrier.y.multiply_scalar(carrier.b * math.sin(t)))
        let (points, weights, knots, degree) = self.spline_net(carrier.spline)
        let low = knots[(usize)degree]
        let high = knots[points.length]
        return try NurbsCurve.at_checked(points, weights, degree, knots, math.clamp(t, low, high))

    ## Carrier `c`'s derivative at `t` (by parameter).
    pub func tangent(c: i64, t: f64) -> Vector3!:
        let (_, d1, _) = try self.derivatives(c, t)
        return d1

    ## Carrier `c` at `t`, and its first and second derivatives, exactly.
    pub func derivatives(c: i64, t: f64) -> (Vector3, Vector3, Vector3)!:
        let carrier = self.carriers.items[(usize)c]
        if carrier.kind == curve_line: return (carrier.origin.add(carrier.x.multiply_scalar(t)), carrier.x, Vector3())
        if carrier.kind == curve_circle or carrier.kind == curve_ellipse:
            let b = carrier.a if carrier.kind == curve_circle else carrier.b
            let cx = carrier.x.multiply_scalar(carrier.a * math.cos(t))
            let sy = carrier.y.multiply_scalar(b * math.sin(t))
            let d1 = carrier.x.multiply_scalar(-carrier.a * math.sin(t)).add(carrier.y.multiply_scalar(b * math.cos(t)))
            return (carrier.origin.add(cx).add(sy), d1, cx.add(sy).multiply_scalar(-1.0))
        let (points, weights, knots, degree) = self.spline_net(carrier.spline)
        let low = knots[(usize)degree]
        let high = knots[points.length]
        return try NurbsCurve.derivatives_checked(points, weights, degree, knots, math.clamp(t, low, high))

    ## Edge `e` at `fraction` of its interval.
    pub func edge_at(e: usize, fraction: f64) -> Vector3!:
        let edge = self.edges.items[e]
        return try self.at(edge.carrier, edge.t0 + (edge.t1 - edge.t0) * fraction)

    ## The unit direction edge `e` leaves vertex end `which` (0 its start, 1
    ## its end) along, going into the edge.
    pub func leaving(e: usize, which: i64) -> Vector3!:
        let edge = self.edges.items[e]
        let t = edge.t0 if which == 0 else edge.t1
        let sign = 1.0 if (edge.t1 > edge.t0) == (which == 0) else -1.0
        return try self.tangent(edge.carrier, t).multiply_scalar(sign).normalized()

    pub func add_point(p: Vector3) -> i64!:
        try self.points.push(p)
        return (i64)self.points.count - 1

    pub func add_carrier(c: Carrier) -> i64!:
        try self.carriers.push(c)
        return (i64)self.carriers.count - 1

    pub func add_edge(edge: ShapeEdge) -> i64!:
        try self.edges.push(edge)
        return (i64)self.edges.count - 1

    ## A face of surface `surface` with `uses` in loops of `sizes`.
    pub func add_face(surface: i64, sense: bool, uses: const i64[], sizes: const i64[], name: i64 = -1) -> !:
        try self.faces.push(ShapeFace(surface, sense, self.uses.count, uses.length, self.sizes.count, sizes.length, name))
        for use in uses: try self.uses.push(use)
        for size in sizes: try self.sizes.push(size)

    ## Each edge's two faces into `sides`, from one pass over the uses: the
    ## first face using an edge, then the first other one (a seam, one
    ## face's both ways, has no second).
    pub func index_sides() -> !:
        self.sides.clear()
        try self.sides.fill(self.edges.count * 2, -1)
        for f in 0..<self.faces.count:
            for use in self.face_uses(f):
                let e = edge_index(use)
                if self.sides.items[e * 2] < 0: self.sides.items[e * 2] = (i64)f
                elif self.sides.items[e * 2 + 1] < 0 and self.sides.items[e * 2] != (i64)f: self.sides.items[e * 2 + 1] = (i64)f

    pub func face_uses(f: usize) -> const i64[]:
        let face = self.faces.items[f]
        return self.uses.view()[face.first..<face.first + face.count]

    pub func face_sizes(f: usize) -> const i64[]:
        let face = self.faces.items[f]
        return self.sizes.view()[face.loop_first..<face.loop_first + face.loops]

    ## The outward normal of face `f` at `p` (on its surface).
    pub func face_normal(f: usize, p: Vector3) -> Vector3!:
        let face = self.faces.items[f]
        let n = try normal_at(&self.surfaces.items[(usize)face.surface], p, self.tolerance)
        return n if face.sense else n.multiply_scalar(-1.0)

    ## A copy of spline net `points` (moved by `matrix`) in the store.
    func store_spline(points: const Vector3[], weights: const f64[], knots: const f64[], degree: i64, matrix: Matrix4) -> i64!:
        # Checked once here: evaluations skip it (NurbsCurve.at_checked).
        try NurbsCurve.check(points, weights, degree, knots)
        let first = self.spline_points.count
        let knot_first = self.spline_knots.count
        for at in 0..<points.length:
            try self.spline_points.push(matrix.transform_point(points[at]))
            try self.spline_weights.push(weights[at])
        for k in knots: try self.spline_knots.push(k)
        try self.splines.push(ShapeSpline(first, points.length, knot_first, degree))
        return (i64)self.splines.count - 1

## A shape with nothing in it, of tolerance `tolerance`.
pub func empty_shape(tolerance: f64) -> Shape:
    return Shape(tolerance, Growing[Vector3](), Growing[Carrier](), Growing[ShapeEdge](), Growing[Surface](), Growing[ShapeFace](),
                 Growing[i64](), Growing[i64](), Growing[ShapeSpline](), Growing[Vector3](), Growing[f64](), Growing[f64](), Growing[u8](), Growing[usize](), Growing[i64]())

## Surface coordinates of `p` on `s`: a plane's (x, y); an angle about the
## axis and a height (cylinder, cone); longitude and latitude (sphere); a
## B-spline's own parameters (an error when `p` is not on it within `tol`).
pub func surface_uv(s: const Surface*, p: Vector3, tol: f64) -> (f64, f64)!:
    if s.kind == surface_spline: return try spline_uv(s, p, tol)
    let uv = chart_uv(*s, p, Vector3(), false)
    return (uv.x, uv.y)

## Whether `s`'s first coordinate is an angle (it wraps).
pub func periodic(s: const Surface*) -> bool:
    return s.kind != surface_plane and s.kind != surface_spline

## The shape of `model` (its B-rep, placed). Independent faces are not
## solids: they are refused.
pub func shape_of(model: const CadModel*) -> Shape!:
    if model.independent_faces() > 0: error(invalid, "modeling needs a solid B-rep, not independent faces")
    let b = model.brep() else error(invalid, "modeling needs a solid B-rep")
    var shape = empty_shape(b.model_tolerance())
    errdefer shape.close()
    let top = model.brep_placement()
    # Vertices and edges are shared; faces may carry their own placement,
    # so a face whose placement differs from the first face's is refused.
    var placement = top
    if b.face_count() > 0:
        let first = try b.face_record(0)
        defer:
            var owned = first
            owned.close()
        placement = top.multiply(first.placement)
    let scale = placement.transform_direction(Vector3(1.0, 0.0, 0.0)).length()
    for v in 0..<b.vertex_count():
        _ = try shape.add_point(placement.transform_point(try b.vertex_at(v)))
    for e in 0..<b.edge_count():
        var curve = try b.edge_record(e)
        defer curve.close()
        if curve.kind == curve_line:
            let a = placement.transform_point(curve.points[0])
            let z = placement.transform_point(curve.points[1])
            let along = z.subtract(a)
            let c = try shape.add_carrier(Carrier(0, a, try along.normalized(), Vector3(), 0.0, 0.0, -1))
            _ = try shape.add_edge(ShapeEdge(c, 0.0, along.length(), curve.start, curve.end))
        elif curve.kind == curve_circle or curve.kind == curve_ellipse:
            let x = try placement.transform_direction(curve.x).normalized()
            let y = try placement.transform_direction(curve.y).normalized()
            let minor = curve.weights[0] * scale if curve.kind == curve_ellipse else curve.radius * scale
            let c = try shape.add_carrier(Carrier(curve.kind, placement.transform_point(curve.origin), x, y, curve.radius * scale, minor, -1))
            _ = try shape.add_edge(ShapeEdge(c, curve.angle, curve.angle + curve.sweep, curve.start, curve.end))
        else:
            let spline = try shape.store_spline(curve.points, curve.weights, curve.knots, curve.degree, placement)
            let c = try shape.add_carrier(Carrier(2, Vector3(), Vector3(), Vector3(), 0.0, 0.0, spline))
            _ = try shape.add_edge(ShapeEdge(c, curve.angle, curve.angle + curve.sweep, curve.start, curve.end))
    for s in 0..<b.surface_count():
        var record = try b.surface_record(s)
        defer record.close()
        var moved = Growing[Vector3]()
        defer moved.close()
        for p in record.points: try moved.push(placement.transform_point(p))
        let radius = record.radius * scale
        # A torus keeps its minor radius in `angle`.
        let angle = record.angle * scale if record.kind == surface_torus else record.angle
        # A B-spline's frame is unused (its control points place it).
        let x = placement.transform_direction(record.x)
        let z = placement.transform_direction(record.z)
        let spline = record.kind == surface_spline
        try shape.surfaces.push(try Surface(record.kind, placement.transform_point(record.origin), x if spline else try x.normalized(),
                                            z if spline else try z.normalized(), radius, angle, moved.view(), record.weights,
                                            record.ku, record.kv, record.nu, record.nv, record.du, record.dv))
    # A reflection turns every loop the other way about its (reflected)
    # normal: each loop runs backwards.
    let mirrored = placement.determinant() < 0.0
    var turned = Growing[i64]()
    defer turned.close()
    for f in 0..<b.face_count():
        var face = try b.face_record(f)
        defer face.close()
        let name = try shape.add_name(try b.face_name(f))
        if not mirrored:
            try shape.add_face(face.surface, face.sense, face.uses, face.sizes, name)
            continue
        turned.clear()
        var at: usize = 0
        for size in face.sizes:
            var k = (usize)size
            while k > 0:
                k -= 1
                try turned.push(-face.uses[at + k])
            at += (usize)size
        try shape.add_face(face.surface, face.sense, turned.view(), face.sizes, name)
    try shape.index_sides()
    return shape

## `shape` as a new B-rep: its points, edges, surfaces and faces as they are.
pub func brep_of(shape: const Shape*) -> interop.Reference[BrepModel]!:
    let output = try BrepModel.held(math.max(shape.tolerance, least_tolerance))
    errdefer output.release()
    let b = output.value()
    for p in shape.points.view(): _ = try b.add_vertex(p)
    for edge in shape.edges.view():
        let c = shape.carriers.items[(usize)edge.carrier]
        let forward = edge.t1 > edge.t0
        if c.kind == curve_line:
            _ = try b.add_line(edge.start, edge.end)
        elif c.kind == curve_circle:
            _ = try b.add_circle(edge.start, edge.end, c.origin, c.x.cross(c.y), c.x, c.a, forward)
        elif c.kind == curve_ellipse:
            _ = try b.add_ellipse(edge.start, edge.end, c.origin, c.x.cross(c.y), c.x, c.a, c.b, forward)
        else:
            let (points, weights, knots, degree) = shape.spline_net(c.spline)
            _ = try b.add_spline_edge(edge.start, edge.end, points, weights, degree, knots, forward)
    for s in shape.surfaces.view():
        if s.kind == surface_spline:
            _ = try b.add_spline_surface(s.points, s.weights, s.nu, s.nv, s.du, s.dv, s.ku, s.kv)
        else:
            _ = try b.add_surface(s.kind, s.origin, s.z, s.x, s.radius, s.angle)
    for f in 0..<shape.faces.count:
        let face = try b.add_face(shape.faces.items[f].surface, shape.face_uses(f), shape.face_sizes(f), shape.faces.items[f].sense)
        try b.set_face_name(face, shape.face_name(f))
    return output