Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-cad

Source of release 0.9.2

0.9.2 / src / sketch / api.lucb

## Luce's sketch: a CadSketch holds a sketch while the editor works on it.
## It reads and writes the sketch's text (what the node keeps), adds and
## removes entities and constraints, edits dimensions, solves (and drags),
## says what is fully constrained or conflicting (after a change, not per
## drag frame), picks the entity nearest a point, and gives the curves
## Extrude reads. Coordinates are on the sketch plane, in millimeters.

pub struct CadSketch:
    var sketch: Sketch
    ## The freedom of the sketch as last analyzed (analyze).
    var freedom: Freedom?
    ## The last snap (snap).
    var snapped: SnapHit

    pub func close():
        self.sketch.close()
        self.forget()

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        _ = visit
        _ = context

    ## The sketch `text` describes (sketch/text.lucb); empty text is an
    ## empty sketch.
    pub static func parse(text: str) -> interop.Reference[CadSketch]!:
        var s = try read_sketch(text)
        errdefer s.close()
        return try interop.Reference[CadSketch].adopt(new CadSketch(s, none, SnapHit(0, 0.0, 0.0, -1, -1)) in memory.heap, cad_sketch_type, memory.heap)

    ## The sketch as text.
    pub func text() -> interop.Owned[str]!:
        var out = Growing[u8]()
        defer out.close()
        try write_sketch(&self.sketch, &out)
        return try interop.copy_text((str)out.view())

    pub func entity_count() -> i64:
        return (i64)self.sketch.entities.count

    pub func constraint_count() -> i64:
        return (i64)self.sketch.constraints.count

    ## Entity `at`: its kind (0 point, 1 line, 2 circle, 3 arc, 4 spline,
    ## 5 ellipse, 6 conic, 7 text), whether it is construction, and its
    ## parts: a text's anchor point; a
    ## line's start and end points; a circle's or arc's center point (`part`
    ## 0), an arc's start (1) and end (2) points; an ellipse's center and
    ## major axis point; a conic's start, end and apex; a spline's points in
    ## order (`part_count` of them).
    pub func kind(at: i64) -> i64:
        return (i64)(u8)self.sketch.entity(at).kind

    pub func construction(at: i64) -> bool:
        return self.sketch.entity(at).construction

    ## Point `which` of those entity `at` is drawn on: a line's start and
    ## end; a circle's center; an arc's center, start and end; a spline's
    ## points; an ellipse's center and major axis point; a conic's start,
    ## end and apex; a text's anchor.
    pub func part(at: i64, which: i64) -> i64:
        let e = self.sketch.entity(at)
        if which < 0 or which >= self.sketch.point_count(e): return -1
        return self.sketch.point_of(e, which)

    ## How many points entity `at` is drawn on (none for a point).
    pub func part_count(at: i64) -> i64:
        return self.sketch.point_count(self.sketch.entity(at))

    ## Whether spline `at` passes through its points (else they are its
    ## control net).
    pub func fit(at: i64) -> bool:
        return self.sketch.entity(at).fourth != 0

    ## Snap (`x`, `y`) within `reach` to what the sketch has (sketch/
    ## snapping.lucb): the kinds in `mask` (1 points, 2 middles, 4
    ## crossings, 8 curves), not entity `skip`; the kind it found (0 none).
    ## Where, and on what: snap_x, snap_y, snap_entity, snap_other.
    pub func snap(x: f64, y: f64, reach: f64, mask: i64, skip: i64 = -1) -> i64!:
        self.snapped = try snap_in(&self.sketch, x, y, reach, mask, skip)
        return self.snapped.kind

    pub func snap_x() -> f64:
        return self.snapped.x

    pub func snap_y() -> f64:
        return self.snapped.y

    pub func snap_entity() -> i64:
        return self.snapped.entity

    pub func snap_other() -> i64:
        return self.snapped.other

    ## How far (`x`, `y`) is from entity `at` (a point, or a curve).
    pub func distance(at: i64, x: f64, y: f64) -> f64:
        return distance_to(&self.sketch, self.sketch.entity(at), at, x, y)

    ## Which end of spline or conic `curve` is nearer curve `other`: +1
    ## its start, -1 its end (what Tangent and Curvature hold).
    pub func end_nearest(curve: i64, other: i64) -> f64:
        let e = self.sketch.entity(curve)
        let (start, _, _) = curve_end_points(&self.sketch, e, 1.0)
        let (end, _, _) = curve_end_points(&self.sketch, e, -1.0)
        let o = self.sketch.entity(other)
        let from_start = distance_to(&self.sketch, o, other, self.sketch.x(start), self.sketch.y(start))
        let from_end = distance_to(&self.sketch, o, other, self.sketch.x(end), self.sketch.y(end))
        return 1.0 if from_start <= from_end else -1.0

    ## The way control point spline `curve`'s end `side` turns to curve as
    ## circle or arc `other` does (Curvature's sign): +1 counterclockwise,
    ## -1 clockwise. Leaving an arc from its end it turns the arc's way
    ## (+1), from its start the other (-1); otherwise as it turns now.
    pub func curvature_turn(curve: i64, side: f64, other: i64) -> f64:
        let e = self.sketch.entity(curve)
        let (p0, p1, p2) = curve_end_points(&self.sketch, e, side)
        let o = self.sketch.entity(other)
        if o.kind == EntityKind.arc:
            if p0 == o.fourth: return 1.0
            if p0 == o.third: return -1.0
        if p2 < 0: return 1.0
        let cross = (self.sketch.x(p1) - self.sketch.x(p0)) * (self.sketch.y(p2) - self.sketch.y(p1)) - (self.sketch.y(p1) - self.sketch.y(p0)) * (self.sketch.x(p2) - self.sketch.x(p1))
        return 1.0 if cross >= 0.0 else -1.0

    ## Point `point`'s coordinates; circle or arc `curve`'s radius (an
    ## ellipse's minor radius, a conic's rho).
    pub func x(point: i64) -> f64:
        return self.sketch.x(point)

    pub func y(point: i64) -> f64:
        return self.sketch.y(point)

    pub func radius(curve: i64) -> f64:
        let scalar = self.sketch.scalar_of(self.sketch.entity(curve))
        return self.sketch.params.items[(usize)scalar] if scalar >= 0 else 0.0

    ## Constraint `at`: its kind (ConstraintKind's order), entities, value
    ## and whether it is driven.
    pub func constraint_kind(at: i64) -> i64:
        return (i64)(u8)self.sketch.constraints.items[(usize)at].kind

    pub func constraint_entity(at: i64, which: i64) -> i64:
        let k = self.sketch.constraints.items[(usize)at]
        return k.first if which == 0 else (k.second if which == 1 else k.third)

    pub func constraint_value(at: i64) -> f64:
        return self.sketch.constraints.items[(usize)at].value

    pub func driven(at: i64) -> bool:
        return self.sketch.constraints.items[(usize)at].driven

    pub func add_point(x: f64, y: f64, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_point(x, y, construction)

    pub func add_line(start: i64, end: i64, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_line(start, end, construction)

    pub func add_circle(center: i64, radius: f64, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_circle(center, radius, construction)

    pub func add_arc(center: i64, start: i64, end: i64, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_arc(center, start, end, construction)

    ## A spline on `points`: through them (`fit`) or on them as its control
    ## net, of degree 5 (less with fewer points).
    pub func add_spline(points: const i64[], fit: bool, degree: i64 = 5, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_spline(points, fit, degree, construction)

    ## A text at point `anchor` saying `content` in font file `font`
    ## (empty: the system's sans), its capitals `height` tall.
    pub func add_text(anchor: i64, height: f64, content: str, font: str = "", construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_text(anchor, height, content, font, construction)

    ## What text `at` says, and its font file.
    pub func text_content(at: i64) -> interop.Owned[str]!:
        return try interop.copy_text(self.sketch.text_content(self.sketch.entity(at)))

    pub func text_font(at: i64) -> interop.Owned[str]!:
        return try interop.copy_text(self.sketch.text_font(self.sketch.entity(at)))

    pub func add_ellipse(center: i64, major: i64, minor: f64, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_ellipse(center, major, minor, construction)

    pub func add_conic(start: i64, end: i64, apex: i64, rho: f64, construction: bool = false) -> i64!:
        self.forget()
        return try self.sketch.add_conic(start, end, apex, rho, construction)

    ## Project edge `edge` of `projection` into the sketch: its shadow,
    ## fixed and linked to the edge (sketch/projection.lucb).
    pub func project(projection: interop.Reference[CadProjection], edge: i64) -> i64!:
        self.forget()
        let p = try projection.get()
        if edge < 0 or edge >= p.edge_count(): error(invalid, "the projection has no such edge")
        let per = projection_per_edge()
        let run = p.samples.view()[(usize)edge * 2 * per..<((usize)edge + 1) * 2 * per]
        var reference = try p.reference(edge)
        defer reference.release()
        return try add_shadow(&self.sketch, run, reference.value)

    ## Cast the linked edges again from `model` onto the plane through
    ## `origin` (axes `u`, `v`); how many no longer find their edge.
    pub func relink(model: interop.Reference[CadModel], origin: Vector3, u: Vector3, v: Vector3) -> i64!:
        self.forget()
        return try relink_sketch(&self.sketch, model.value(), origin, u, v)

    ## How many curves are projected (linked to body edges).
    pub func link_count() -> i64:
        return (i64)self.sketch.links.count

    ## Set circle `curve`'s radius, an ellipse's minor radius or a conic's
    ## rho (unsolved).
    pub func set_radius(curve: i64, value: f64) -> !:
        self.forget()
        let e = self.sketch.entity(curve)
        let scalar = self.sketch.scalar_of(e)
        if scalar < 0: return
        if not self.sketch.scalar_fits(e, value): error(invalid, "a radius, height or minor radius is positive and a rho between 0 and 1")
        self.sketch.params.items[(usize)scalar] = value

    pub func set_construction(at: i64, construction: bool):
        self.sketch.entities.items[(usize)at].construction = construction

    ## A constraint of kind `kind` (ConstraintKind's order); its index.
    pub func constrain(kind: i64, first: i64, second: i64 = -1, third: i64 = -1, value: f64 = 0.0, side: f64 = 1.0, driven: bool = false) -> i64!:
        if kind < 0 or kind >= (i64)constraint_kind_count: error(invalid, "a sketch constraint kind is ConstraintKind's")
        self.forget()
        return try self.sketch.constrain(ConstraintKind((u8)kind), first, second, third, value, side, driven)

    ## Set dimension `at` to `value` (mm or radians), or make it driven.
    pub func set_value(at: i64, value: f64):
        self.forget()
        self.sketch.constraints.items[(usize)at].value = value

    pub func set_driven(at: i64, driven: bool):
        self.forget()
        self.sketch.constraints.items[(usize)at].driven = driven

    pub func remove(at: i64) -> !:
        self.forget()
        try remove_entity(&self.sketch, at)

    pub func unconstrain(at: i64) -> !:
        self.forget()
        try remove_constraint(&self.sketch, at)

    ## Move point `point` to (`x`, `y`), unsolved.
    pub func place(point: i64, x: f64, y: f64):
        self.sketch.place(point, x, y)

    ## Solve; whether it converged (unconverged, nothing moves).
    pub func solve() -> bool!:
        return (try solve_sketch(&self.sketch)).converged

    ## Drag point `point` toward (`x`, `y`): the sketch solved with the
    ## point held where it can be. Whether it converged; when not, the
    ## sketch stays as it was.
    pub func drag(point: i64, x: f64, y: f64) -> bool!:
        let at = self.sketch.entity(point).first
        return (try drag_sketch(&self.sketch, [at, at + 1], [x, y], 20)).converged

    ## Work out the freedom (degrees, fixed entities, redundant and
    ## conflicting constraints), kept until the next change.
    pub func analyze() -> !:
        self.forget()
        self.freedom = try freedom_of(&self.sketch)

    pub func degrees() -> i64:
        let f = self.freedom else return -1
        return f.degrees

    ## Whether entity `at` is fully constrained (after analyze).
    pub func fixed(at: i64) -> bool:
        let f = self.freedom else return false
        return f.fixed.items[(usize)at]

    pub func conflicting_count() -> i64:
        let f = self.freedom else return 0
        return (i64)f.conflicting.count

    pub func conflicting(at: i64) -> i64:
        let f = self.freedom else return -1
        return f.conflicting.items[(usize)at]

    pub func redundant_count() -> i64:
        let f = self.freedom else return 0
        return (i64)f.redundant.count

    ## Fusion's MODIFY tools (sketch/modify.lucb). Trim the piece of curve
    ## `curve` round (`x`, `y`) between its nearest crossings (the whole
    ## curve when nothing crosses it: later entities renumber, as removing
    ## does); extend its end nearest (`x`, `y`) to the next curve; break it
    ## at the crossings round (`x`, `y`).
    pub func trim(curve: i64, x: f64, y: f64) -> !:
        self.forget()
        try trim_curve(&self.sketch, curve, x, y)

    pub func extend(curve: i64, x: f64, y: f64) -> !:
        self.forget()
        try extend_curve(&self.sketch, curve, x, y)

    pub func break_apart(curve: i64, x: f64, y: f64) -> !:
        self.forget()
        try break_curve(&self.sketch, curve, x, y)

    ## Round (fillet) or cut (chamfer) the corner of two lines sharing a
    ## point: the new arc or line.
    pub func fillet(first: i64, second: i64, radius: f64) -> i64!:
        self.forget()
        return try fillet_corner(&self.sketch, first, second, radius)

    pub func chamfer(first: i64, second: i64, distance: f64) -> i64!:
        self.forget()
        return try chamfer_corner(&self.sketch, first, second, distance)

    ## Copies of the chain `curves` `distance` to the side of (`x`, `y`);
    ## how many curves were made (the last entities).
    pub func offset(curves: const i64[], distance: f64, x: f64, y: f64) -> i64!:
        self.forget()
        var made = Growing[i64]()
        defer made.close()
        try offset_chain(&self.sketch, curves, distance, x, y, &made)
        return (i64)made.count

    ## Move `entities` by (`dx`, `dy`), or copies of them (`copy`).
    pub func move(entities: const i64[], dx: f64, dy: f64, copy: bool = false) -> !:
        self.forget()
        var made = Growing[i64]()
        defer made.close()
        try move_entities(&self.sketch, entities, dx, dy, copy, &made)

    ## Mirror copies of `entities` about line `axis` (held symmetric to
    ## them); Circular Pattern: `count` round (`cx`, `cy`) over `angle`
    ## radians (a whole turn: evenly); Rectangular Pattern: `count` along
    ## (`dx`, `dy`) apart. How many curves were made.
    pub func mirror(entities: const i64[], axis: i64) -> i64!:
        self.forget()
        var made = Growing[i64]()
        defer made.close()
        try mirror_entities(&self.sketch, entities, axis, &made)
        return (i64)made.count

    pub func pattern_circular(entities: const i64[], cx: f64, cy: f64, count: i64, angle: f64) -> i64!:
        self.forget()
        var made = Growing[i64]()
        defer made.close()
        let all_round = math.abs(math.abs(angle) - 2.0 * math.pi) <= 1e-9
        let step = angle / (f64)count if all_round else angle / (f64)math.max(1.0, (f64)(count - 1))
        try pattern_round(&self.sketch, entities, cx, cy, count, step, &made)
        return (i64)made.count

    pub func pattern_rectangular(entities: const i64[], dx: f64, dy: f64, count: i64) -> i64!:
        self.forget()
        var made = Growing[i64]()
        defer made.close()
        try pattern_along(&self.sketch, entities, dx, dy, count, &made)
        return (i64)made.count

    ## Scale `entities` about (`cx`, `cy`) by `factor` (their dimensions
    ## too).
    pub func scale(entities: const i64[], cx: f64, cy: f64, factor: f64) -> !:
        self.forget()
        try scale_entities(&self.sketch, entities, cx, cy, factor)

    ## The entity nearest (`x`, `y`) within `reach`, points before curves
    ## (construction alike), or -1. `only` 1 picks points alone, 2 curves
    ## alone (a selection level's filter); 0 either.
    pub func pick(x: f64, y: f64, reach: f64, only: i64 = 0) -> i64:
        return nearest(&self.sketch, x, y, reach, only)

    ## The curves Extrude and Revolve read, on the plane through `origin`
    ## with the sketch's x and y along `u` and `v`.
    pub func curves(origin: Vector3, u: Vector3, v: Vector3) -> interop.Reference[GeometrySet]!:
        return try sketch_curves(&self.sketch, origin, u, v)

    func forget():
        if let f = self.freedom:
            var kept = f
            kept.close()
        self.freedom = none

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

## Points along spline, ellipse, conic or text `at` of `sketch`, as x, y
## pairs onto `out` (the editor draws them): `count` + 1 along the curve,
## or a text's pieces, 8 steps each, a NaN pair after each piece.
pub func sketch_samples(sketch: const CadSketch*, at: i64, count: usize, out: Growing[f64]*) -> !:
    try sample_curve(&sketch.sketch, sketch.sketch.entity(at), count, out)

## The piece Trim would take from curve `curve` of `sketch` round (`x`,
## `y`), as x, y pairs onto `out` (the editor shows it before the click).
pub func sketch_trim_piece(sketch: const CadSketch*, curve: i64, x: f64, y: f64, out: Growing[f64]*) -> !:
    try trim_piece(&sketch.sketch, curve, x, y, out)

## What Offset would make of `curves` `distance` toward (`x`, `y`): x, y
## pairs onto `out`, a NaN pair after each new curve.
pub func sketch_offset_preview(sketch: const CadSketch*, curves: const i64[], distance: f64, x: f64, y: f64, out: Growing[f64]*) -> !:
    try offset_preview(&sketch.sketch, curves, distance, x, y, out)