Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.7

0.11.7 / src / sketch_create.luc

## The Sketch editor's CREATE tools placed click by click (as Fusion's): what
## each makes once its clicks are in (finish), and what it would make with
## the cursor where it is (preview, the rubber band). A click's point is the
## point it snapped to, else a new one (on the curve it snapped to).
##
##   Line                 its ends (one drawn near level or upright is
##                        made so)
##   Midpoint Line        its middle, then an end
##   2-Point Rectangle    two corners (sides level and upright)
##   3-Point Rectangle    a side's two ends, then how wide (square corners)
##   Center Rectangle     its center, then a corner
##   Center Diameter Circle  its center, then a point on it
##   2-Point Circle       a diameter's ends
##   3-Point Circle       three points on it
##   3-Point Arc          its ends, then a point it passes through
##   Center Point Arc     its center, its start, its end (counterclockwise)
##   Circumscribed / Inscribed Polygon  its center, then a side's middle /
##                        a corner (six sides, all equal, on a construction
##                        circle)
##   Edge Polygon         one side's ends (six sides, to its left)
##   2-Tangent Circle     two lines, then where its side and size are (its
##                        radius the nearer line's distance from there)
##   3-Tangent Circle     three lines (the circle touching all three)
##   Tangent Arc          a line's or arc's end, then where it ends (it
##                        leaves the way that curve does)
##
## Slots are sketch_slots.luc's, splines, ellipses and conics
## sketch_freeform.luc's. Values locked in the value boxes while drawing
## (sketch_typing.luc) become the shape's dimensions in the same undo step
## (typed_dimensions).
from overlay_lines import OverlayLines
from sketch_editor import SketchEditor
from luce_cad.sketch import CadSketch
from sketch_kinds import line_kind
import sketch_kinds as k
from sketch_slots import slot_tools, finish_slot, preview_slot
from sketch_geometry import side_of, ended_curve, through, turn_to, across
from sketch_freeform import freeform_tools, finish_freeform, preview_freeform, curve_end
import sketch_origin
from luce_std import math

## How many sides the polygon tools make, unless typed.
let polygon_sides = 6

## Drawing tool `e.tool`'s clicks are in: make what it makes, as one undo.
pub func finish(e: SketchEditor) -> unit!:
    let sketch = e.sketch else return
    let c = e.clicks
    let tool = e.tool
    # What the shape makes from here on gets the typed dimensions.
    let first = sketch.entity_count()
    if tool == "Line":
        let a = e.made_point(0)
        let b = e.made_point(1)
        let line = sketch.add_line(a, b)
        if sketch.y(a) == sketch.y(b):
            _ = sketch.constrain(k.horizontal, line)
        elif sketch.x(a) == sketch.x(b):
            _ = sketch.constrain(k.vertical, line)
    elif tool == "Midpoint Line":
        let m = e.made_point(0)
        let end = e.made_point(1)
        let start = sketch.add_point(2.0 * c[0][0] - c[1][0], 2.0 * c[0][1] - c[1][1])
        let line = sketch.add_line(start, end)
        _ = sketch.constrain(k.midpoint, m, line)
    elif tool == "2-Point Rectangle":
        _ = rectangle(e, c[0], [c[1][0], c[0][1]], c[1], [c[0][0], c[1][1]], true)
    elif tool == "Center Rectangle":
        let a = [2.0 * c[0][0] - c[1][0], 2.0 * c[0][1] - c[1][1]]
        let corners = rectangle(e, a, [c[1][0], a[1]], c[1], [a[0], c[1][1]], true)
        # Its center: the middle of a construction diagonal.
        if corners.length == 4:
            let diagonal = sketch.add_line(corners[0], corners[2], true)
            _ = sketch.constrain(k.midpoint, e.made_point(0), diagonal)
    elif tool == "3-Point Rectangle":
        let (nx, ny, w) = across(c[0], c[1], c[2])
        _ = rectangle(e, c[0], c[1], [c[1][0] + nx * w, c[1][1] + ny * w], [c[0][0] + nx * w, c[0][1] + ny * w], false)
    elif tool == "Center Diameter Circle":
        _ = sketch.add_circle(e.made_point(0), math.hypot(c[1][0] - c[0][0], c[1][1] - c[0][1]))
    elif tool == "2-Point Circle":
        let center = sketch.add_point((c[0][0] + c[1][0]) * 0.5, (c[0][1] + c[1][1]) * 0.5)
        _ = sketch.add_circle(center, math.hypot(c[1][0] - c[0][0], c[1][1] - c[0][1]) * 0.5)
    elif tool == "3-Point Circle":
        let o = through(c[0], c[1], c[2]) else return
        _ = sketch.add_circle(sketch.add_point(o[0], o[1]), math.hypot(c[0][0] - o[0], c[0][1] - o[1]))
    elif tool == "3-Point Arc":
        let o = through(c[0], c[1], c[2]) else return
        let a = e.made_point(0)
        let b = e.made_point(1)
        # Counterclockwise from the end that has the third point on its way.
        let along = turn_to(o, c[0], c[2]) <= turn_to(o, c[0], c[1])
        _ = sketch.add_arc(sketch.add_point(o[0], o[1]), a if along else b, b if along else a)
    elif tool == "Center Point Arc":
        let center = e.made_point(0)
        let start = e.made_point(1)
        let r = math.hypot(c[1][0] - c[0][0], c[1][1] - c[0][1])
        let aim = math.atan2(c[2][1] - c[0][1], c[2][0] - c[0][0])
        let end = e.made_point(2) if e.click_snaps[2] >= 0 else sketch.add_point(c[0][0] + r * math.cos(aim), c[0][1] + r * math.sin(aim))
        if r > 0.0 and start != end:
            _ = sketch.add_arc(center, start, end)
    elif tool in ["Circumscribed Polygon", "Inscribed Polygon", "Edge Polygon"]:
        polygon(e)
    elif tool in ["2-Tangent Circle", "3-Tangent Circle"]:
        tangent_circle(e)
    elif tool == "Tangent Arc":
        tangent_arc(e)
    elif tool in slot_tools():
        finish_slot(e)
    elif tool in freeform_tools():
        finish_freeform(e)
    typed_dimensions(e, first)
    _ = sketch.solve()
    e.commit("Sketch line" if tool == "Line" else tool)

## A rectangle on corners `a`, `b`, `c`, `d` (in order): level and upright
## sides when `level`, else square corners kept by perpendicular and
## parallel sides. A corner clicked is that click's point. Its corners.
func rectangle(e: SketchEditor, a: list[float], b: list[float], c: list[float], d: list[float], level: bool) -> list[int]!:
    let sketch = e.sketch else return []
    if math.hypot(a[0] - c[0], a[1] - c[1]) <= 0.0:
        return []
    let p = [e.made_point(0), sketch.add_point(b[0], b[1]), e.made_point(1) if e.tool == "2-Point Rectangle" else sketch.add_point(c[0], c[1]), sketch.add_point(d[0], d[1])]
    if e.tool == "3-Point Rectangle":
        p[1] = e.made_point(1)
    if e.tool == "Center Rectangle":
        p[0] = sketch.add_point(a[0], a[1])
        p[2] = e.made_point(1)
    let lines = [sketch.add_line(p[0], p[1]), sketch.add_line(p[1], p[2]), sketch.add_line(p[2], p[3]), sketch.add_line(p[3], p[0])]
    if level:
        _ = sketch.constrain(k.horizontal, lines[0])
        _ = sketch.constrain(k.vertical, lines[1])
        _ = sketch.constrain(k.horizontal, lines[2])
        _ = sketch.constrain(k.vertical, lines[3])
    else:
        _ = sketch.constrain(k.perpendicular, lines[0], lines[1])
        _ = sketch.constrain(k.parallel, lines[0], lines[2])
        _ = sketch.constrain(k.parallel, lines[1], lines[3])
    return p

## A regular polygon, six sides unless Sides was typed, as Fusion makes
## one: one construction circle and luce-cad's Polygon constraint, which
## keeps it regular however it is dragged. Inscribed's circle runs through
## the corners (the click a corner), Circumscribed's touches the sides at
## their middles (the click a side's middle); a typed Radius is that
## circle's. Edge's is inscribed, on one side's two ends (to its left).
func polygon(e: SketchEditor) -> unit!:
    let sketch = e.sketch else return
    let c = e.clicks
    let n = int(e.typing.locked("Sides") else float(polygon_sides))
    var cx = c[0][0]
    var cy = c[0][1]
    var r = math.hypot(c[1][0] - cx, c[1][1] - cy)
    var start = math.atan2(c[1][1] - cy, c[1][0] - cx)
    let half = math.pi / float(n)
    if e.tool == "Circumscribed Polygon":
        # The click is a side's middle: corners half a side either way.
        r = r / math.cos(half)
        start -= half
    elif e.tool == "Edge Polygon":
        let side = math.hypot(c[1][0] - c[0][0], c[1][1] - c[0][1])
        r = side * 0.5 / math.sin(half)
        let mx = (c[0][0] + c[1][0]) * 0.5
        let my = (c[0][1] + c[1][1]) * 0.5
        let ux = (c[1][0] - c[0][0]) / side
        let uy = (c[1][1] - c[0][1]) / side
        let apothem = r * math.cos(half)
        cx = mx - uy * apothem
        cy = my + ux * apothem
        start = math.atan2(c[0][1] - cy, c[0][0] - cx)
    if r <= 0.0:
        return
    let center = e.made_point(0) if e.tool != "Edge Polygon" else sketch.add_point(cx, cy)
    let corners: list[int] = []
    for at in 0..<n:
        let angle = start + 2.0 * math.pi * float(at) / float(n)
        if e.tool == "Edge Polygon" and at < 2:
            corners.append(e.made_point(at))
        else:
            corners.append(sketch.add_point(cx + r * math.cos(angle), cy + r * math.sin(angle)))
    _ = sketch.add_polygon(center, corners, e.tool != "Circumscribed Polygon")

## What the tool would make with the cursor where it is.
pub func preview(e: SketchEditor, lines: OverlayLines) -> unit!:
    let c = e.clicks
    if c.length == 0:
        return
    let f = e.frame
    let p = e.cursor
    let all = c + [p]
    let tool = e.tool
    let first = c[0]
    if tool == "Line":
        lines.add_segment(f.at(c[-1][0], c[-1][1]), f.at(p[0], p[1]))
    elif tool == "Midpoint Line":
        lines.add_segment(f.at(2.0 * first[0] - p[0], 2.0 * first[1] - p[1]), f.at(p[0], p[1]))
    elif tool in ["2-Point Rectangle", "Center Rectangle"]:
        let a = first if tool == "2-Point Rectangle" else [2.0 * first[0] - p[0], 2.0 * first[1] - p[1]]
        loop(lines, e, [a, [p[0], a[1]], p, [a[0], p[1]]])
    elif tool == "3-Point Rectangle":
        if c.length == 1:
            lines.add_segment(f.at(first[0], first[1]), f.at(p[0], p[1]))
        else:
            let (nx, ny, w) = across(c[0], c[1], p)
            loop(lines, e, [c[0], c[1], [c[1][0] + nx * w, c[1][1] + ny * w], [c[0][0] + nx * w, c[0][1] + ny * w]])
    elif tool == "Center Diameter Circle":
        lines.add_arc(f.origin, f.u, f.v, first[0], first[1], math.hypot(p[0] - first[0], p[1] - first[1]), 0.0, 2.0 * math.pi)
    elif tool == "2-Point Circle":
        lines.add_arc(f.origin, f.u, f.v, (first[0] + p[0]) * 0.5, (first[1] + p[1]) * 0.5, math.hypot(p[0] - first[0], p[1] - first[1]) * 0.5, 0.0, 2.0 * math.pi)
    elif tool in ["3-Point Circle", "3-Point Arc"]:
        if c.length == 1:
            lines.add_segment(f.at(first[0], first[1]), f.at(p[0], p[1]))
        else:
            let o = through(all[0], all[1], all[2]) else return
            let r = math.hypot(all[0][0] - o[0], all[0][1] - o[1])
            if tool == "3-Point Circle":
                lines.add_arc(f.origin, f.u, f.v, o[0], o[1], r, 0.0, 2.0 * math.pi)
            else:
                let along = turn_to(o, all[0], all[2]) <= turn_to(o, all[0], all[1])
                let start_at = all[0] if along else all[1]
                let to = all[1] if along else all[0]
                lines.add_arc(f.origin, f.u, f.v, o[0], o[1], r, math.atan2(start_at[1] - o[1], start_at[0] - o[0]), turn_to(o, start_at, to))
    elif tool == "Center Point Arc":
        if c.length == 1:
            lines.add_segment(f.at(first[0], first[1]), f.at(p[0], p[1]))
        else:
            let r = math.hypot(c[1][0] - first[0], c[1][1] - first[1])
            let start = math.atan2(c[1][1] - first[1], c[1][0] - first[0])
            lines.add_arc(f.origin, f.u, f.v, first[0], first[1], r, start, turn_to(first, c[1], p))
    elif tool in ["Circumscribed Polygon", "Inscribed Polygon", "Edge Polygon"]:
        lines.add_segment(f.at(first[0], first[1]), f.at(p[0], p[1]))
    elif tool == "Tangent Arc":
        let arc = tangent_arc_of(e, p) else return
        lines.add_arc(f.origin, f.u, f.v, arc[0], arc[1], arc[2], arc[3], arc[4])
    elif tool in slot_tools():
        preview_slot(e, lines)
    elif tool in freeform_tools():
        preview_freeform(e, lines)

## A closed outline through `corners`.
func loop(lines: OverlayLines, e: SketchEditor, corners: list[list[float]]) -> unit!:
    let f = e.frame
    for at in 0..<corners.length:
        let a = corners[at]
        let b = corners[(at + 1) % corners.length]
        lines.add_segment(f.at(a[0], a[1]), f.at(b[0], b[1]))

## A circle touching two clicked lines (on the side of, and as big as the
## nearer line is far from, the third click) or three: its center X and
## radius r from s (n · X - c) = r for each line's unit normal n and
## offset c, the sign s the side the clicks are on.
func tangent_circle(e: SketchEditor) -> unit!:
    let sketch = e.sketch else return
    let count = 2 if e.tool == "2-Tangent Circle" else 3
    let lines: list[int] = []
    for at in 0..<count:
        let picked = e.click_snaps[at]
        if picked < 0 or sketch.kind(picked) != line_kind:
            e.say(f"{e.tool}: click on {count} lines")
            return
        lines.append(picked)
    # Where the circle is: the third click, or the middle of the clicks.
    var gx = 0.0
    var gy = 0.0
    for click in e.clicks:
        gx += click[0] / 3.0
        gy += click[1] / 3.0
    if count == 2:
        gx = e.clicks[2][0]
        gy = e.clicks[2][1]
    let rows: list[list[float]] = []
    for line in lines:
        let a = sketch.part(line, 0)
        let b = sketch.part(line, 1)
        let length = math.max(math.hypot(sketch.x(b) - sketch.x(a), sketch.y(b) - sketch.y(a)), 1e-300)
        let nx = -(sketch.y(b) - sketch.y(a)) / length
        let ny = (sketch.x(b) - sketch.x(a)) / length
        let c = nx * sketch.x(a) + ny * sketch.y(a)
        let s = 1.0 if nx * gx + ny * gy - c >= 0.0 else -1.0
        rows.append([s * nx, s * ny, s * c, math.abs(nx * gx + ny * gy - c)])
    var cx = 0.0
    var cy = 0.0
    var r = 0.0
    if count == 2:
        r = math.min(rows[0][3], rows[1][3])
        let d = rows[0][0] * rows[1][1] - rows[0][1] * rows[1][0]
        if math.abs(d) <= 1e-12:
            e.say("2-Tangent Circle needs two lines that are not parallel")
            return
        let b0 = r + rows[0][2]
        let b1 = r + rows[1][2]
        cx = (b0 * rows[1][1] - rows[0][1] * b1) / d
        cy = (rows[0][0] * b1 - b0 * rows[1][0]) / d
    else:
        # s n · X - r = s c for the three lines, by Cramer's rule.
        let m = [[rows[0][0], rows[0][1], -1.0], [rows[1][0], rows[1][1], -1.0], [rows[2][0], rows[2][1], -1.0]]
        let rhs = [rows[0][2], rows[1][2], rows[2][2]]
        let d = det3(m)
        if math.abs(d) <= 1e-12:
            e.say("No circle touches those three lines")
            return
        cx = det3(replaced(m, 0, rhs)) / d
        cy = det3(replaced(m, 1, rhs)) / d
        r = det3(replaced(m, 2, rhs)) / d
    if r <= 0.0:
        e.say("No circle touches those lines there")
        return
    let circle = sketch.add_circle(sketch.add_point(cx, cy), r)
    for line in lines:
        _ = sketch.constrain(k.tangent, line, circle, side = side_of(sketch, line, cx, cy))

## Tangent Arc's arc to `to`: [center x, center y, radius, start angle,
## counterclockwise sweep], from the end its first click snapped to, leaving
## the way the line or arc there does; none without such an end.
func tangent_arc_of(e: SketchEditor, to: list[float]) -> list[float]?!:
    let sketch = e.sketch else return none
    let start = e.click_snaps[0] if e.click_snaps.length > 0 else -1
    let from_curve = ended_curve(sketch, start)
    if from_curve < 0:
        return none
    let out = curve_end(sketch, from_curve, [sketch.x(start), sketch.y(start)])
    let px = sketch.x(start)
    let py = sketch.y(start)
    # Its center is off the way out, to the left (n) or right.
    let nx = -out.dy
    let ny = out.dx
    let h = (to[0] - px) * nx + (to[1] - py) * ny
    if math.abs(h) <= 1e-9:
        return none
    let radius = ((to[0] - px) * (to[0] - px) + (to[1] - py) * (to[1] - py)) / (2.0 * h)
    let cx = px + nx * radius
    let cy = py + ny * radius
    let at_start = math.atan2(py - cy, px - cx)
    let at_end = math.atan2(to[1] - cy, to[0] - cx)
    # To the left it turns counterclockwise from the start; to the right
    # counterclockwise from the end back to it.
    let first = at_start if radius > 0.0 else at_end
    let last = at_end if radius > 0.0 else at_start
    var sweep = last - first
    while sweep <= 0.0:
        sweep += 2.0 * math.pi
    return [cx, cy, math.abs(radius), first, sweep]

## Tangent Arc's clicks are in: the arc, touching the curve it leaves.
func tangent_arc(e: SketchEditor) -> unit!:
    let sketch = e.sketch else return
    let found = tangent_arc_of(e, e.clicks[1])
    if found == none:
        e.say("Tangent Arc starts at the end of a line or an arc")
        return
    let arc = found else return
    let start = e.click_snaps[0]
    let from_curve = ended_curve(sketch, start)
    let end = e.made_point(1)
    let center = sketch.add_point(arc[0], arc[1])
    let left = math.abs(math.atan2(sketch.y(start) - arc[1], sketch.x(start) - arc[0]) - arc[3]) <= 1e-9
    let made = sketch.add_arc(center, start if left else end, end if left else start)
    if sketch.kind(from_curve) == line_kind:
        _ = sketch.constrain(k.tangent, from_curve, made, side = side_of(sketch, from_curve, arc[0], arc[1]))
    else:
        # Two arcs: outside each other (radii added) or one inside the
        # other (the larger first, the smaller's radius taken away).
        let other = sketch.part(from_curve, 0)
        let apart = math.hypot(sketch.x(other) - arc[0], sketch.y(other) - arc[1])
        let r = sketch.radius(from_curve)
        if math.abs(apart - (r + arc[2])) <= math.abs(apart - math.abs(r - arc[2])):
            _ = sketch.constrain(k.tangent, from_curve, made, side = 1.0)
        elif r >= arc[2]:
            _ = sketch.constrain(k.tangent, from_curve, made, side = -1.0)
        else:
            _ = sketch.constrain(k.tangent, made, from_curve, side = -1.0)

func det3(m: list[list[float]]) -> float:
    return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])

## `m` with column `column` replaced by `values`.
func replaced(m: list[list[float]], column: int, values: list[float]) -> list[list[float]]:
    let result: list[list[float]] = []
    for row in 0..<3:
        let copy = m[row].copy()
        copy[column] = values[row]
        result.append(copy)
    return result

## The values locked in the value boxes as the shape's dimensions, as
## Fusion makes them, on what the tool made from entity `first` on: a
## line's Length and its Angle (from the sketch's x axis,
## sketch_origin.luc), a rectangle's Width and Height (a 3-point one's
## Length, Angle and Width) on its first two sides, a circle's Diameter, an
## arc's or a polygon's Radius and an arc's Sweep (an angle dimension on
## the arc). A polygon's Sides is no dimension: it is how many sides the
## polygon was made with, held equal round its circle. Typed values that
## would over-constrain what the shape snapped to are kept driven.
func typed_dimensions(e: SketchEditor, first: int) -> unit!:
    let sketch = e.sketch else return
    let t = e.typing
    if not t.any_locked():
        return
    let lines: list[int] = []
    var round = -1
    for at in first..<sketch.entity_count():
        let kind = sketch.kind(at)
        if kind == line_kind and not sketch.construction(at):
            lines.append(at)
        elif kind in [k.circle_kind, k.arc_kind] and round < 0:
            round = at
    let made: list[int] = []
    if lines.length > 0:
        if let length = t.locked("Length"):
            made.append(length_of_line(sketch, lines[0], length))
        if e.tool in ["Line", "3-Point Rectangle"]:
            if let angle = t.locked("Angle"):
                made.append(sketch.constrain(k.angle, e.origin_entity(sketch_origin.x_axis), lines[0], value = angle))
        if lines.length > 1:
            if let width = t.locked("Width"):
                made.append(length_of_line(sketch, lines[0] if e.tool != "3-Point Rectangle" else lines[1], width))
            if let height = t.locked("Height"):
                made.append(length_of_line(sketch, lines[1], height))
    # A polygon's radius is its construction circle's.
    for at in first..<sketch.entity_count():
        if e.tool.ends_with("Polygon") and sketch.kind(at) == k.circle_kind:
            round = at
    if round >= 0:
        if let diameter = t.locked("Diameter"):
            made.append(sketch.constrain(k.diameter, round, value = diameter))
        if let radius = t.locked("Radius"):
            made.append(sketch.constrain(k.radius, round, value = radius))
        if sketch.kind(round) == k.arc_kind:
            if let sweep = t.locked("Sweep"):
                made.append(sketch.constrain(k.sweep, round, value = sweep))
    if made.length == 0:
        return
    if not sketch.solve():
        for at in made:
            sketch.set_driven(at, true)

## Line `line`'s length held at `value`: its constraint.
func length_of_line(sketch: CadSketch, line: int, value: float) -> int!:
    return sketch.constrain(k.distance, sketch.part(line, 0), sketch.part(line, 1), value = value)