Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.5

0.9.5 / src / modeling / profile.lucb

## Sketch profiles: a sketch's curves (luce-geocore's curves family, on the
## set's sketch plane) read exactly as lines, circular arcs and B-splines,
## split where they meet and traced into the faces of their arrangement
## (arrangement.lucb), as Fusion's sketch profiles are. A polyline's
## segments are lines; a NURBS whose spans are rational quadratic circular
## arcs (a Sketch's arcs and circles) is those arcs, merged; any other NURBS
## is a B-spline edge.
import interop
import memory
import strings
import ownership
from luce_std import math
from luce_geocore.geocore import Vector3, Matrix4, invalid, GeometrySet
from luce_geocore.core.growing import Growing
from luce_geocore.kernel import Curves, CurveType, KnotMode, set_curves, sketch_plane_of, CurvesBuilder, empty_set, dispose_set, adopt_set, with_curves
from geometry import Surface, NurbsCurve, basis_derivatives, basis_jet, nurbs_basis, surface_normal_checked, project, evaluate, nearest_parameters, nurbs_normal, surface_point, chart_uv, normal_at, surface_distance, interpolate_cubic, edge_index, wrap, union_root, push_decimal, CadTolerances, surface_plane, surface_cylinder, surface_cone, surface_spline, surface_sphere, surface_torus, curve_line, curve_circle, curve_spline, curve_ellipse, nonzero
from brep import BrepModel, brep_model_type
from model import CadModel, cad_model_type
from solids import CadSolids
from luce_std import sort

## A rational quadratic span is a circular arc when its end weights are
## within this of 1.
let arc_end_weight_slack: f64 = 1e-5

## Profile edge kinds (ProfileEdge.kind).
pub let profile_line: i64 = 0
pub let profile_arc: i64 = 1
pub let profile_spline: i64 = 2

## An edge of a profile from `start` to `end` (points on the plane): kind 0
## a line, 1 a circular arc about `center` sweeping `sweep` radians about
## the plane's normal (positive counterclockwise; a full circle starts and
## ends at one point), 2 B-spline `spline` of the profile's store. It is
## piece `piece` of sketch curve `curve` (-1: made, not sketched), which
## names the faces it makes (naming.lucb).
pub struct ProfileEdge:
    pub var kind: i64
    pub var start: Vector3
    pub var end: Vector3
    pub var center: Vector3
    pub var radius: f64
    pub var sweep: f64
    pub var spline: i64
    pub var curve: i64 = -1
    pub var piece: i64 = 0

func line_edge(start: Vector3, end: Vector3) -> ProfileEdge:
    return ProfileEdge(0, start, end, Vector3(), 0.0, 0.0, -1)

## A B-spline's control net and knots, in a profile's store.
pub struct ProfileSpline:
    pub var first: usize
    pub var count: usize
    pub var knot_first: usize
    pub var degree: i64

## The profiles of a sketch: its plane, every loop's edges in order (loop l
## is edges[loop_offsets[l]..<loop_offsets[l + 1]], counterclockwise about
## the normal for a region's outer loop, clockwise for a hole) and the
## regions (region r's loops are region_loops[region_offsets[r]..<...],
## its outer loop first).
pub struct Profiles:
    pub var origin: Vector3
    pub var normal: Vector3
    pub var u: Vector3
    pub var v: Vector3
    pub var edges: Growing[ProfileEdge]
    pub var loop_offsets: Growing[usize]
    pub var region_loops: Growing[usize]
    pub var region_offsets: Growing[usize]
    pub var splines: Growing[ProfileSpline]
    pub var spline_points: Growing[Vector3]
    pub var spline_weights: Growing[f64]
    pub var spline_knots: Growing[f64]

    pub func close():
        self.edges.close()
        self.loop_offsets.close()
        self.region_loops.close()
        self.region_offsets.close()
        self.splines.close()
        self.spline_points.close()
        self.spline_weights.close()
        self.spline_knots.close()

    pub func loop_count() -> usize:
        return self.loop_offsets.count - 1

    pub func region_count() -> usize:
        return self.region_offsets.count - 1

    pub func loop_edges(loop: usize) -> const ProfileEdge[]:
        return self.edges.view()[self.loop_offsets.items[loop]..<self.loop_offsets.items[loop + 1]]

    pub func region(region: usize) -> const usize[]:
        return self.region_loops.view()[self.region_offsets.items[region]..<self.region_offsets.items[region + 1]]

    ## Spline `index`'s control points, weights and knots.
    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)

    ## A point of `edge` at `fraction` of the way along it: its ends exactly
    ## at 0 and 1.
    pub func edge_at(edge: const ProfileEdge*, fraction: f64) -> Vector3!:
        if fraction == 0.0: return edge.start
        if fraction == 1.0: return edge.end
        if edge.kind == profile_line: return edge.start.multiply_scalar(1.0 - fraction).add(edge.end.multiply_scalar(fraction))
        if edge.kind == profile_arc:
            let x = try edge.start.subtract(edge.center).normalized()
            let y = self.normal.cross(x)
            let angle = edge.sweep * fraction
            return edge.center.add(x.multiply_scalar(edge.radius * math.cos(angle))).add(y.multiply_scalar(edge.radius * math.sin(angle)))
        let (points, weights, knots, degree) = self.spline_net(edge.spline)
        let low = knots[(usize)degree]
        let high = knots[points.length]
        return try NurbsCurve.at(points, weights, degree, knots, low + (high - low) * fraction)

    ## Everything moved by `by` (the plane and every edge with it).
    pub func moved(by: Vector3):
        self.origin = self.origin.add(by)
        for at in 0..<self.edges.count:
            var edge = self.edges.items[at]
            edge.start = edge.start.add(by)
            edge.end = edge.end.add(by)
            edge.center = edge.center.add(by)
            self.edges.items[at] = edge
        for at in 0..<self.spline_points.count:
            self.spline_points.items[at] = self.spline_points.items[at].add(by)

    ## The part of spline `index` from fraction `low` to `high` of its
    ## domain, as a new spline: knots inserted there to full multiplicity
    ## (Boehm), the control points between kept.
    func spline_part(index: i64, low: f64, high: f64) -> i64!:
        let (points, weights, knots, degree) = self.spline_net(index)
        let p = (usize)degree
        var rows = Growing[f64]()
        defer rows.close()
        for at in 0..<points.length:
            let w = weights[at]
            try rows.push(points[at].x * w)
            try rows.push(points[at].y * w)
            try rows.push(points[at].z * w)
            try rows.push(w)
        var u = Growing[f64]()
        defer u.close()
        try u.assign(knots)
        var scratch = Growing[f64]()
        defer scratch.close()
        let a = knots[p]
        let b = knots[points.length]
        let u0 = a + (b - a) * low
        let u1 = a + (b - a) * high
        for value in [u0, u1]:
            if value <= a or value >= b: continue
            var times: usize = 0
            for k in u.view():
                if k == value: times += 1
            while times < p:
                try insert_knot(&rows, &u, &scratch, p, 4, value)
                times += 1
        let count = rows.count // 4
        # The point at u0 is control point (its last knot) - p; at u1, (its
        # first knot) - 1.
        var last_low: usize = p
        for k in 0..<u.count:
            if u.items[k] <= u0: last_low = k
        var first_high: usize = count
        var k = u.count
        while k > 0:
            k -= 1
            if u.items[k] >= u1: first_high = k
        let s = last_low - p
        let e = first_high - 1
        let first = self.spline_points.count
        let knot_first = self.spline_knots.count
        for at in s..<e + 1:
            let w = rows.items[at * 4 + 3]
            try self.spline_points.push(Vector3(rows.items[at * 4] / w, rows.items[at * 4 + 1] / w, rows.items[at * 4 + 2] / w))
            try self.spline_weights.push(w)
        for _ in 0..<p + 1: try self.spline_knots.push(u0)
        for knot in u.view():
            if knot > u0 and knot < u1: try self.spline_knots.push(knot)
        for _ in 0..<p + 1: try self.spline_knots.push(u1)
        try self.splines.push(ProfileSpline(first, e - s + 1, knot_first, degree))
        return (i64)self.splines.count - 1

    ## Plane coordinates of a point.
    func planar(p: Vector3) -> (f64, f64):
        let d = p.subtract(self.origin)
        return (d.dot(self.u), d.dot(self.v))

    ## Points along loop `loop` in plane coordinates, for orientation and
    ## containment (arcs every 10 degrees, splines 32 a span).
    func outline(loop: usize, out: Growing[Vector3]*) -> !:
        out.clear()
        for edge in self.loop_edges(loop):
            var steps: usize = 1
            if edge.kind == profile_arc: steps = (usize)math.max(2.0, math.ceil(math.abs(edge.sweep) / 0.1745))
            if edge.kind == profile_spline: steps = 32
            for at in 0..<steps:
                let (a, b) = self.planar(try self.edge_at(&edge, (f64)at / (f64)steps))
                try out.push(Vector3(a, b, 0.0))

    ## Reverse loop `loop` in place: edges in the other order, each reversed.
    func reverse_loop(loop: usize) -> !:
        let first = self.loop_offsets.items[loop]
        let last = self.loop_offsets.items[loop + 1]
        var low = first
        var high = last - 1
        while low < high:
            let swap = self.edges.items[low]
            self.edges.items[low] = self.edges.items[high]
            self.edges.items[high] = swap
            low += 1
            high -= 1
        for at in first..<last:
            try self.reverse_edge(at)

    func reverse_edge(at: usize) -> !:
        var edge = self.edges.items[at]
        let start = edge.start
        edge.start = edge.end
        edge.end = start
        if edge.kind == profile_arc:
            # The arc now starts at the old end.
            edge.sweep = -edge.sweep
        if edge.kind == profile_spline:
            edge.spline = try self.reversed_spline(edge.spline)
        self.edges.items[at] = edge

    ## A copy of spline `index` running the other way: points and weights
    ## reversed, knots mirrored.
    func reversed_spline(index: i64) -> i64!:
        let s = self.splines.items[(usize)index]
        let first = self.spline_points.count
        let knot_first = self.spline_knots.count
        for at in 0..<s.count:
            try self.spline_points.push(self.spline_points.items[s.first + s.count - 1 - at])
            try self.spline_weights.push(self.spline_weights.items[s.first + s.count - 1 - at])
        let knots = s.count + (usize)s.degree + 1
        let low = self.spline_knots.items[s.knot_first]
        let high = self.spline_knots.items[s.knot_first + knots - 1]
        for at in 0..<knots:
            try self.spline_knots.push(low + high - self.spline_knots.items[s.knot_first + knots - 1 - at])
        try self.splines.push(ProfileSpline(first, s.count, knot_first, s.degree))
        return (i64)self.splines.count - 1

## A profile of one loop (a blend's tool section) as its one region, the
## loop turned counterclockwise about the normal.
func single_region(result: Profiles*) -> !:
    var scratch = Growing[Vector3]()
    defer scratch.close()
    try result.outline(0, &scratch)
    if signed_area(scratch.view()) < 0.0: try result.reverse_loop(0)
    try result.region_offsets.push(0)
    try result.region_loops.push(0)
    try result.region_offsets.push(1)

## Twice the signed area of a closed outline (positive counterclockwise).
func signed_area(points: const Vector3[]) -> f64:
    var total = 0.0
    for at in 0..<points.length:
        let a = points[at]
        let b = points[(at + 1) % points.length]
        total += a.x * b.y - b.x * a.y
    return total

## Whether `point` is inside the closed outline (by its winding number).
func inside(points: const Vector3[], point: Vector3) -> bool:
    var turns = 0
    for at in 0..<points.length:
        let a = points[at]
        let b = points[(at + 1) % points.length]
        let side = (b.x - a.x) * (point.y - a.y) - (point.x - a.x) * (b.y - a.y)
        if a.y <= point.y:
            if b.y > point.y and side > 0.0: turns += 1
        elif b.y <= point.y and side < 0.0:
            turns -= 1
    return turns != 0

## The profiles of the curves in `set`, on its sketch plane: the faces of
## their arrangement (arrangement.lucb) that `chosen` names (face keys
## apart by `;`), or by default islands alternating from the outside in.
## `tolerance` joins curve ends and recognises arcs.
pub func profiles_of(set: const GeometrySet*, tolerance: f64, chosen: str = "") -> Profiles!:
    var result = try empty_profiles(set)
    errdefer result.close()
    var pieces = Growing[ProfileEdge]()
    defer pieces.close()
    try read_pieces(set, &result, &pieces, tolerance)
    try arrange(&result, &pieces, chosen, tolerance)
    if result.region_count() == 0:
        error(invalid, "the sketch has no closed profile: close its open curves, or choose a profile")
    return result

## No profiles yet, on the sketch plane of `set`.
func empty_profiles(set: const GeometrySet*) -> Profiles!:
    let plane = try sketch_plane_of(set)
    return Profiles(plane.origin, plane.normal, plane.u, plane.v, Growing[ProfileEdge](), Growing[usize](), Growing[usize](), Growing[usize](),
                    Growing[ProfileSpline](), Growing[Vector3](), Growing[f64](), Growing[f64]())

## Every curve of `set` as pieces onto `out`, each tagged with its curve
## and its place along it.
func read_pieces(set: const GeometrySet*, result: Profiles*, out: Growing[ProfileEdge]*, tolerance: f64) -> !:
    let curves = set_curves(set) else error(invalid, "Extrude needs a sketch: connect a Sketch with closed curves")
    for curve in 0..<curves.curve_count():
        let before = out.count
        _ = try read_curve(curves, curve, result, out, tolerance)
        for at in before..<out.count:
            out.items[at].curve = (i64)curve
            out.items[at].piece = (i64)(at - before)

## Curve `curve`'s pieces onto `out`; whether it is cyclic.
func read_curve(curves: const Curves*, curve: usize, result: Profiles*, out: Growing[ProfileEdge]*, tolerance: f64) -> bool!:
    let (first, count) = curves.range(curve)
    let settings = curves.settings(curve)
    if count < 2: return false
    if settings.kind == CurveType.poly:
        let segments = count if settings.cyclic else count - 1
        for at in 0..<segments:
            let a = curves.point(first + at)
            let b = curves.point(first + (at + 1) % count)
            if a.subtract(b).length() > tolerance: try out.push(line_edge(a, b))
        return settings.cyclic
    if settings.kind != CurveType.nurbs:
        error(invalid, "profiles read polylines and NURBS curves; convert Bezier and Catmull-Rom curves first")
    # Points, weights and knots exact (f64) where the sketch kept them.
    var points = Growing[Vector3]()
    defer points.close()
    var w = Growing[f64]()
    defer w.close()
    for at in 0..<count:
        try points.push(curves.point(first + at))
        try w.push(curves.weight_at(first + at))
    var knots = Growing[f64]()
    defer knots.close()
    let order = settings.order
    let custom = curves.custom_knots(curve)
    if settings.knot_mode == KnotMode.custom and custom.length == count + order:
        if let exact = curves.exact_knots(curve):
            for k in exact: try knots.push(k)
        else:
            for k in custom: try knots.push((f64)k)
    else:
        # Clamped uniform (endpoint) knots; uniform ones as they are.
        for at in 0..<count + order:
            if settings.knot_mode == KnotMode.uniform: try knots.push((f64)at)
            elif at < order: try knots.push(0.0)
            elif at >= count: try knots.push((f64)(count - order + 1))
            else: try knots.push((f64)(at - order + 1))
    if order == 3 and try arcs_of(points.view(), w.view(), knots.view(), result.normal, out, tolerance):
        return settings.cyclic
    if settings.cyclic:
        error(invalid, "a closed spline is not a profile yet; draw it open with its ends together")
    let spline_first = result.spline_points.count
    let knot_first = result.spline_knots.count
    for at in 0..<count:
        try result.spline_points.push(points.items[at])
        try result.spline_weights.push(w.items[at])
    for k in knots.view(): try result.spline_knots.push(k)
    try result.splines.push(ProfileSpline(spline_first, count, knot_first, (i64)order - 1))
    let low = knots.items[order - 1]
    let high = knots.items[count]
    let start = try NurbsCurve.at(points.view(), w.view(), (i64)order - 1, knots.view(), low)
    let end = try NurbsCurve.at(points.view(), w.view(), (i64)order - 1, knots.view(), high)
    try out.push(ProfileEdge(2, start, end, Vector3(), 0.0, 0.0, (i64)result.splines.count - 1))
    return false

## A quadratic NURBS whose every span is a circular arc (clamped knots with
## doubled interior ones), as arcs onto `out`, consecutive arcs of one
## circle merged; false (nothing added) when it is not.
func arcs_of(points: const Vector3[], weights: const f64[], knots: const f64[], normal: Vector3, out: Growing[ProfileEdge]*, tolerance: f64) -> bool!:
    if points.length < 3 or points.length % 2 != 1: return false
    let spans = (points.length - 1) // 2
    # Knots 0 0 0 1 1 2 2 ... n n n.
    if knots[0] != knots[1] or knots[1] != knots[2] or knots[knots.length - 1] != knots[knots.length - 2] or knots[knots.length - 2] != knots[knots.length - 3]: return false
    for span in 1..<spans:
        if knots[1 + 2 * span] != knots[2 + 2 * span]: return false
    var found = Growing[ProfileEdge]()
    defer found.close()
    for span in 0..<spans:
        let p0 = points[2 * span]
        let p1 = points[2 * span + 1]
        let p2 = points[2 * span + 2]
        if math.abs(weights[2 * span] - 1.0) > arc_end_weight_slack or math.abs(weights[2 * span + 2] - 1.0) > arc_end_weight_slack: return false
        let w = weights[2 * span + 1]
        if not (w > 0.0 and w < 1.0): return false
        # Symmetric tangents, and the weight is the cosine of half the sweep.
        let reach = p1.subtract(p0).length()
        if math.abs(reach - p1.subtract(p2).length()) > tolerance * 10.0: return false
        let half = math.acos(w)
        let middle = p0.add(p2).multiply_scalar(0.5)
        let chord = p2.subtract(p0).length() * 0.5
        let radius = chord / math.sin(half)
        let away = middle.subtract(p1)
        if away.length() <= tolerance: return false
        let center = middle.add(try away.normalized().multiply_scalar(radius * math.cos(half)))
        if math.abs(center.subtract(p0).length() - radius) > tolerance * 10.0 or math.abs(center.subtract(p2).length() - radius) > tolerance * 10.0: return false
        let turning = p0.subtract(center).cross(p2.subtract(center)).dot(normal)
        try found.push(ProfileEdge(1, p0, p2, center, radius, 2.0 * half * (1.0 if turning >= 0.0 else -1.0), -1))
    # Merge runs on one circle turning one way.
    var at: usize = 0
    while at < found.count:
        var arc = found.items[at]
        var next = at + 1
        while next < found.count:
            let candidate = found.items[next]
            if candidate.center.subtract(arc.center).length() > tolerance * 10.0 or math.abs(candidate.radius - arc.radius) > tolerance * 10.0 or (candidate.sweep > 0.0) != (arc.sweep > 0.0):
                break
            arc.sweep += candidate.sweep
            arc.end = candidate.end
            next += 1
        arc.radius = (arc.start.subtract(arc.center).length() + arc.end.subtract(arc.center).length()) * 0.5
        try out.push(arc)
        at = next
    return true