Luce packages
LuceLuce BaseLuciaOS

dymokomi/luced-3d

Source of release 0.11.9

0.11.9 / src / overlay_lines.lucb

## Viewport overlay lines gathered in Base: world-space endpoint pairs of
## CAD boundaries, control hulls and normal guides, polygon normal guides,
## and Edit kinds' guides (a sketch plane's grid). The Luce side hands over
## a whole CAD overlay, mesh or grid in one call; the points never pass
## through Luce lists. The worker publishes the lines (ComputeChannel.overlay,
## .hull), and without the worker they become a WireBatch directly.
import interop
import memory
from luce_std import math
from luce_geocore.geocore import Vector3, Matrix4, Bounds, Mesh, invalid, mesh_overlay_points
from luce_geocore.core.growing import Growing
from luce_3d.graphics import WireBatch, wire_batch_type, WireRenderer, append_curve_segments
from luce_3d import graphics
from luce_gpu import gpu
from luce_cad.model import CadOverlay, CadPreviewSet
from luce_cad.measure import CadCheck, check_lines, check_labels
from luce_cad.cad_curves import curve_lines, curve_hulls
from luce_cad.cad_geometry import set_models
from luce_cad.sketch import CadSketch, CadShadows, sketch_samples, shadow_samples, projection_per_edge, sketch_trim_piece, sketch_offset_preview
from luce_geocore.geocore import GeometrySet, SceneKind, LightShape, Projection, Camera, Light
from luce_geocore.kernel import SceneObjects, scene_flattened

## The depth bias of lit strokes (draw_lit): four times the lines' own
## (WireRenderer's 1e-6), still far below a body's thickness.
let lit_bias: f64 = 0.000004

pub struct OverlayLines:
    var points: Growing[Vector3]
    ## The GPU batch made of the points (`batch`), and how many points it
    ## holds: points are only added, so it stands while that count does,
    ## and each draw of unchanged lines reuses it and its upload.
    var made: interop.Reference[WireBatch]?
    var made_count: usize

    pub func init():
        self.points = Growing[Vector3]()
        self.made = none
        self.made_count = 0

    ## Empty lines, owned by the caller.
    pub static func make() -> interop.Reference[OverlayLines]!:
        return try interop.Reference[OverlayLines].adopt(new OverlayLines() in memory.heap, overlay_lines_type, memory.heap)

    ## Segments held.
    pub func count() -> i64:
        return (i64)self.points.count // 2

    ## Point `index` (segment i's ends are points 2i and 2i + 1).
    pub func point(index: i64) -> Vector3!:
        if index < 0 or (usize)index >= self.points.count: error(invalid, "overlay point out of range")
        return self.points.items[(usize)index]

    ## Highlight helper strokes without rebuilding Luce endpoint lists.
    pub func draw(camera: interop.Reference[graphics.Camera], target: interop.View[gpu.RenderTarget], color: gpu.Color, width: f64 = 3.0) -> !:
        try WireRenderer.lines(self.points.view(), camera, target, color, width, writes_depth = false)

    ## Strokes lighting lines already drawn (a hovered or picked curve over
    ## its own line): nearer by `lit_bias`, so they cover that line whole.
    ## At one depth, the two lines' strips of different widths each won
    ## where rounding favored them: a lit line showed the plain one through
    ## it in blobs.
    pub func draw_lit(camera: interop.Reference[graphics.Camera], target: interop.View[gpu.RenderTarget], color: gpu.Color, width: f64) -> !:
        try WireRenderer.lines(self.points.view(), camera, target, color, width, bias = lit_bias, writes_depth = false)

    ## The same, for lines kept from frame to frame: drawn from their GPU
    ## batch, sent once.
    pub func draw_lit_kept(camera: interop.Reference[graphics.Camera], target: interop.View[gpu.RenderTarget], color: gpu.Color, width: f64) -> !:
        if self.points.count == 0: return
        let lines = try self.batch()
        defer lines.release()
        try lines.value().draw(camera, target, color, width, writes_depth = false, bias = lit_bias)

    ## The box around every endpoint (a zero box when there are none).
    pub func bounds() -> Bounds:
        if self.points.count == 0: return Bounds(Vector3(), Vector3())
        var low = self.points.items[0]
        var high = low
        for point in self.points.view():
            low = Vector3(math.min(low.x, point.x), math.min(low.y, point.y), math.min(low.z, point.z))
            high = Vector3(math.max(high.x, point.x), math.max(high.y, point.y), math.max(high.z, point.z))
        return Bounds(low, high)

    ## Part `part` of `overlay` (0 its boundaries, 1 its hull, 2 its normal
    ## guides) placed by `matrix`; a guide keeps its length.
    pub func add_cad(overlay: interop.Reference[CadOverlay], part: i64, matrix: Matrix4) -> !:
        let source = try overlay.get()
        let count = source.boundary_count() if part == 0 else (source.hull_count() if part == 1 else (source.net_count() if part == 3 else source.guide_count()))
        try self.points.reserve(self.points.count + (usize)count)
        if part == 2:
            for at in 0..<count // 2:
                let start = try source.guide(at * 2)
                let delta = (try source.guide(at * 2 + 1)).subtract(start)
                let placed = matrix.transform_point(start)
                self.points.items[self.points.count] = placed
                self.points.items[self.points.count + 1] = placed.add((try matrix.transform_normal(delta)).multiply_scalar(delta.length()))
                self.points.count += 2
            return
        for at in 0..<count:
            let point = (try source.boundary(at)) if part == 0 else ((try source.hull_point(at)) if part == 1 else (try source.net_point(at)))
            self.points.items[self.points.count] = matrix.transform_point(point)
            self.points.count += 1

    ## Part `part` of per-face previews (0 their boundaries, 2 their normal
    ## guides; they have no hull) placed by `matrix`.
    pub func add_preview(previews: interop.Reference[CadPreviewSet], part: i64, matrix: Matrix4) -> !:
        let source = try previews.get()
        if part == 1 or part == 3: return
        let count = source.boundary_count() if part == 0 else source.guide_count()
        try self.points.reserve(self.points.count + (usize)count)
        for at in 0..<(count if part == 0 else count // 2 * 2):
            let point = (try source.boundary(at)) if part == 0 else (try source.guide(at))
            if part == 2 and at % 2 == 1:
                let start = try source.guide(at - 1)
                let delta = point.subtract(start)
                self.points.items[self.points.count] = self.points.items[self.points.count - 1].add((try matrix.transform_normal(delta)).multiply_scalar(delta.length()))
            else:
                self.points.items[self.points.count] = matrix.transform_point(point)
            self.points.count += 1

    ## A normal guide per polygon of `mesh` placed by `matrix`.
    pub func add_face_guides(mesh: interop.Reference[Mesh], matrix: Matrix4) -> !:
        let guides = try mesh_overlay_points(try mesh.get(), matrix, true)
        defer:
            if guides.length > 0: free(guides) in memory.heap
        for point in guides: try self.points.push(point)

    ## A square grid on the plane through `origin` spanned by unit axes `u`
    ## and `v`: `divisions` cells across, `half` units each side of the
    ## origin (Edit Sketch's plane).
    pub func add_grid(origin: Vector3, u: Vector3, v: Vector3, half: f64, divisions: i64) -> !:
        if divisions < 1 or divisions > 1000 or not (half > 0.0): error(invalid, "a grid needs 1..1000 divisions and a positive size")
        try self.points.reserve(self.points.count + (usize)(divisions + 1) * 4)
        for line in 0..<divisions + 1:
            let t = -half + 2.0 * half * (f64)line / (f64)divisions
            try self.points.push(origin.add(u.multiply_scalar(t)).subtract(v.multiply_scalar(half)))
            try self.points.push(origin.add(u.multiply_scalar(t)).add(v.multiply_scalar(half)))
            try self.points.push(origin.add(v.multiply_scalar(t)).subtract(u.multiply_scalar(half)))
            try self.points.push(origin.add(v.multiply_scalar(t)).add(u.multiply_scalar(half)))

    ## Sketch `sketch`'s curves on the plane through `origin` with its x
    ## and y along `u` and `v`: `which` 0 the free ones, 1 the fully
    ## constrained (after CadSketch.analyze), 2 construction (and control
    ## point splines' nets), 3 entity `entity` alone (a hovered or selected
    ## one; a point draws nothing). With `unlinked`, 0 to 2 leave out
    ## projected curves (drawn apart, in their own color).
    pub func add_sketch(sketch: interop.Reference[CadSketch], origin: Vector3, u: Vector3, v: Vector3, which: i64, entity: i64 = -1, unlinked: bool = false) -> !:
        let s = try sketch.get()
        for at in 0..<s.entity_count():
            let kind = s.kind(at)
            # The origin's axes are drawn across the view apart.
            if kind == 0 or s.origin_part(at) >= 0: continue
            if unlinked and which != 3 and s.linked(at): continue
            if which == 2 and kind == 4 and not s.fit(at):
                for k in 1..<s.part_count(at):
                    let a = s.part(at, k - 1)
                    let b = s.part(at, k)
                    try self.add_segment(planar(origin, u, v, s.x(a), s.y(a)), planar(origin, u, v, s.x(b), s.y(b)))
            if which == 3:
                if at != entity: continue
            elif which == 2:
                if not s.construction(at): continue
            elif s.construction(at) or s.fixed(at) != (which == 1):
                continue
            if kind == 1:
                let a = s.part(at, 0)
                let b = s.part(at, 1)
                try self.add_segment(planar(origin, u, v, s.x(a), s.y(a)), planar(origin, u, v, s.x(b), s.y(b)))
                continue
            if kind > 3:
                # A spline, ellipse, conic or text: its samples joined (a
                # text's pieces apart, NaN between them).
                var samples = Growing[f64]()
                defer samples.close()
                try sketch_samples(s, at, 128, &samples)
                for k in 0..<samples.count // 2 - 1:
                    if math.is_nan(samples.items[2 * k]) or math.is_nan(samples.items[2 * k + 2]): continue
                    try self.add_segment(planar(origin, u, v, samples.items[2 * k], samples.items[2 * k + 1]), planar(origin, u, v, samples.items[2 * k + 2], samples.items[2 * k + 3]))
                continue
            let center = s.part(at, 0)
            let cx = s.x(center)
            let cy = s.y(center)
            var start = 0.0
            var sweep = 2.0 * math.pi
            if kind == 3:
                let first = s.part(at, 1)
                let last = s.part(at, 2)
                start = math.atan2(s.y(first) - cy, s.x(first) - cx)
                sweep = math.atan2(s.y(last) - cy, s.x(last) - cx) - start
                while sweep <= 0.0: sweep += 2.0 * math.pi
            try self.add_arc(origin, u, v, cx, cy, s.radius(at), start, sweep)

    ## The piece Trim would take from `curve` round sketch point (`x`, `y`).
    pub func add_trim_piece(sketch: interop.Reference[CadSketch], curve: i64, x: f64, y: f64, origin: Vector3, u: Vector3, v: Vector3) -> !:
        var points = Growing[f64]()
        defer points.close()
        try sketch_trim_piece(try sketch.get(), curve, x, y, &points)
        try self.add_plane_runs(points.view(), origin, u, v)

    ## What Offset would make of `curves` `distance` toward (`x`, `y`).
    pub func add_offset_preview(sketch: interop.Reference[CadSketch], curves: const i64[], distance: f64, x: f64, y: f64, origin: Vector3, u: Vector3, v: Vector3) -> !:
        var points = Growing[f64]()
        defer points.close()
        try sketch_offset_preview(try sketch.get(), curves, distance, x, y, &points)
        try self.add_plane_runs(points.view(), origin, u, v)

    ## Plane x, y pairs joined in runs (a NaN pair between runs).
    func add_plane_runs(points: const f64[], origin: Vector3, u: Vector3, v: Vector3) -> !:
        for k in 0..<points.length // 2 - 1:
            if math.is_nan(points[2 * k]) or math.is_nan(points[2 * k + 2]): continue
            try self.add_segment(planar(origin, u, v, points[2 * k], points[2 * k + 1]), planar(origin, u, v, points[2 * k + 2], points[2 * k + 3]))

    ## A body's edges cast on the plane through `origin` (axes `u`, `v`):
    ## every one of `shadows`, or edge `edge` alone.
    pub func add_shadows(shadows: interop.Reference[CadShadows], origin: Vector3, u: Vector3, v: Vector3, edge: i64 = -1) -> !:
        let p = try shadows.get()
        let samples = shadow_samples(p)
        let per = projection_per_edge()
        for e in 0..<samples.length // (2 * per):
            if edge >= 0 and (i64)e != edge: continue
            let run = samples[e * 2 * per..<(e + 1) * 2 * per]
            for k in 0..<per - 1:
                try self.add_segment(planar(origin, u, v, run[2 * k], run[2 * k + 1]), planar(origin, u, v, run[2 * k + 2], run[2 * k + 3]))

    ## The edges of `mesh` whose edge attribute `name` (a whole number)
    ## is `value`: a CAD pick mesh's edges of one model (`cad_edge_model`),
    ## lit as Combine's target is while its tool bodies are picked.
    pub func add_edges_where(mesh: interop.Reference[Mesh], name: str, value: i64) -> !:
        let source = try mesh.get()
        let column = source.find_attribute(name, 4)
        if column < 0: return
        for edge in 0..<try source.edge_count():
            if (i64)(try source.attribute_value(column, edge)) != value: continue
            try self.points.push(try source.point(try source.edge_point(edge, 0)))
            try self.points.push(try source.point(try source.edge_point(edge, 1)))

    ## A segment from `a` to `b`.
    pub func add_segment(a: Vector3, b: Vector3) -> !:
        try self.points.push(a)
        try self.points.push(b)

    ## Diagonal hatch lines `spacing` apart, at 45° on the plane through
    ## `origin` (axes `u`, `v`), across the triangles of `fills` (which lie
    ## on that plane), moved by `lift`: Fusion's hatch over a slice's cap.
    pub func add_hatch(fills: interop.Reference[Mesh], origin: Vector3, u: Vector3, v: Vector3, spacing: f64, lift: Vector3) -> !:
        if not (spacing > 0.0): return
        let mesh = fills.value()
        # Lines x - y = k step: `spacing` apart across them.
        let step = spacing * math.sqrt(2.0)
        var xs: f64[3] = [0.0, 0.0, 0.0]
        var ys: f64[3] = [0.0, 0.0, 0.0]
        var ss: f64[3] = [0.0, 0.0, 0.0]
        for face in 0..<mesh.face_count():
            if (try mesh.face_size(face)) != 3: continue
            for corner in 0..<(usize)3:
                let d = (try mesh.point(try mesh.face_point(face, (i64)corner))).subtract(origin)
                xs[corner] = d.dot(u)
                ys[corner] = d.dot(v)
                ss[corner] = xs[corner] - ys[corner]
            let low = math.min(ss[0], math.min(ss[1], ss[2]))
            let high = math.max(ss[0], math.max(ss[1], ss[2]))
            var k = math.ceil(low / step)
            while k * step <= high:
                let value = k * step
                k += 1.0
                # Where the line crosses the triangle's edges: two places.
                var found = 0
                var ax = 0.0
                var ay = 0.0
                var bx = 0.0
                var by = 0.0
                for edge in 0..<(usize)3:
                    let next = (edge + 1) % 3
                    let s0 = ss[edge]
                    let s1 = ss[next]
                    if (s0 < value) == (s1 < value) or s0 == s1: continue
                    let t = (value - s0) / (s1 - s0)
                    let x = xs[edge] + (xs[next] - xs[edge]) * t
                    let y = ys[edge] + (ys[next] - ys[edge]) * t
                    if found == 0:
                        ax = x
                        ay = y
                    else:
                        bx = x
                        by = y
                    found += 1
                if found == 2:
                    try self.add_segment(planar(origin, u, v, ax, ay).add(lift), planar(origin, u, v, bx, by).add(lift))

    ## An arc on the plane through `origin` (axes `u`, `v`) about plane
    ## point (`cx`, `cy`) of `radius`, from angle `start` sweeping `sweep`
    ## radians counterclockwise, in segments of at most 3 degrees.
    pub func add_arc(origin: Vector3, u: Vector3, v: Vector3, cx: f64, cy: f64, radius: f64, start: f64, sweep: f64) -> !:
        let count = (usize)math.max(1.0, math.min(512.0, math.ceil(math.abs(sweep) / (math.pi / 60.0))))
        var previous = planar(origin, u, v, cx + radius * math.cos(start), cy + radius * math.sin(start))
        for step in 1..<count + 1:
            let angle = start + sweep * (f64)step / (f64)count
            let next = planar(origin, u, v, cx + radius * math.cos(angle), cy + radius * math.sin(angle))
            try self.add_segment(previous, next)
            previous = next

    ## Line group `group` of a Check node's result (luce-cad's
    ## check_passed ... check_quills), placed by `matrix`.
    pub func add_check(check: interop.Reference[CadCheck], group: i64, matrix: Matrix4 = Matrix4()) -> !:
        for p in check_lines(check.value(), group): try self.points.push(matrix.transform_point(p))

    ## A Check node's edge labels (luce-cad's CheckLabel) as pairs, as
    ## check_label_pairs makes them.
    pub func add_check_labels(check: interop.Reference[CadCheck], matrix: Matrix4 = Matrix4()) -> !:
        try check_label_pairs(check.value(), matrix, &self.points)

    ## The evaluated curves of `set` (as CurveLines draws them), and its
    ## CAD curves (luce-cad's cad_curves).
    pub func add_curves(set: interop.Reference[GeometrySet]) -> !:
        try append_curve_segments(try set.get(), Matrix4(), &self.points, none)
        try curve_lines(try set.get(), set_models(try set.get()), Matrix4(), &self.points)

    ## `set`'s shown CAD curves, placed by `matrix` (a curve on a face
    ## lifted off it: luce-cad's curve_lines).
    pub func add_cad_curves(set: interop.Reference[GeometrySet], matrix: Matrix4 = Matrix4()) -> !:
        try curve_lines(try set.get(), set_models(try set.get()), matrix, &self.points)

    ## The control polygons of `set`'s shown CAD curves, placed by `matrix`
    ## (Edit CAD's CVs level draws them with the surfaces' nets).
    pub func add_cad_curve_hulls(set: interop.Reference[GeometrySet], matrix: Matrix4 = Matrix4()) -> !:
        try curve_hulls(try set.get(), matrix, &self.points)

    ## Every camera and light of `set` (and its instances) as viewport
    ## helpers, placed by `matrix`: a camera's frustum to one unit ahead with
    ## an up marker, a light's emitter outline with its direction.
    pub func add_scene(set: interop.Reference[GeometrySet], matrix: Matrix4 = Matrix4()) -> !:
        var objects = SceneObjects()
        defer objects.close()
        try scene_flattened(try set.get(), matrix, &objects)
        for index in 0..<objects.count():
            let item = objects.object(index)
            if item.kind == SceneKind.camera: try self.add_camera(item.camera, item.matrix)
            else: try self.add_light(item.light, item.matrix)

    ## A single camera/light helper, for object picking and selection bounds.
    pub func add_scene_object(set: interop.Reference[GeometrySet], index: i64) -> !:
        var objects = SceneObjects()
        defer objects.close()
        try scene_flattened(try set.get(), Matrix4(), &objects)
        if index < 0 or (usize)index >= objects.count(): error(invalid, "scene object out of range")
        let item = objects.object((usize)index)
        if item.kind == SceneKind.camera: try self.add_camera(item.camera, item.matrix)
        else: try self.add_light(item.light, item.matrix)

    ## Distance to a helper stroke within eight screen pixels, or -1.
    pub func pick(camera: interop.Reference[graphics.Camera], x: f64, y: f64, width: f64, height: f64) -> f64!:
        let p = try camera.value().projection(width / math.max(1.0, height))
        var best = 8.0
        var depth = -1.0
        for at in 0..<self.points.count // 2:
            let a = self.points.items[at * 2]
            let b = self.points.items[at * 2 + 1]
            let sa = p.screen(a, width, height)
            let sb = p.screen(b, width, height)
            if sa.z <= p.near or sb.z <= p.near: continue
            let dx = sb.x - sa.x
            let dy = sb.y - sa.y
            let t = math.clamp(((x - sa.x) * dx + (y - sa.y) * dy) / math.max(1e-12, dx * dx + dy * dy), 0.0, 1.0)
            let distance = math.hypot(x - sa.x - t * dx, y - sa.y - t * dy)
            if distance >= best: continue
            best = distance
            # The point on the stroke (perspective-correct) and its distance
            # along the view ray through it.
            let fraction = t if p.orthographic() else (t / sb.z) / ((1.0 - t) / sa.z + t / sb.z)
            let point = a.add(b.subtract(a).multiply_scalar(fraction))
            depth = point.subtract(p.eye_for(point)).length()
        return depth

    func segment(matrix: Matrix4, a: Vector3, b: Vector3) -> !:
        try self.points.push(matrix.transform_point(a))
        try self.points.push(matrix.transform_point(b))

    ## The closed outline through `corners`.
    func loop(matrix: Matrix4, corners: const Vector3[]) -> !:
        for at in 0..<corners.length: try self.segment(matrix, corners[at], corners[(at + 1) % corners.length])

    ## A circle of `radius` in the plane of unit axes `u` and `v`.
    func circle(matrix: Matrix4, center: Vector3, u: Vector3, v: Vector3, radius: f64) -> !:
        let steps: i64 = 32
        for step in 0..<steps:
            let a = 2.0 * math.pi * (f64)step / (f64)steps
            let b = 2.0 * math.pi * (f64)(step + 1) / (f64)steps
            try self.segment(matrix, center.add(u.multiply_scalar(radius * math.cos(a))).add(v.multiply_scalar(radius * math.sin(a))),
                             center.add(u.multiply_scalar(radius * math.cos(b))).add(v.multiply_scalar(radius * math.sin(b))))

    func add_camera(camera: Camera, matrix: Matrix4) -> !:
        # Perspective: the film back seen one unit ahead. Orthographic: the
        # apertures in tenths of a unit (USD's convention), one unit deep.
        let perspective = camera.projection == Projection.perspective
        let w = 0.5 * camera.horizontal_aperture / camera.focal_length if perspective else 0.05 * camera.horizontal_aperture
        let h = 0.5 * camera.vertical_aperture / camera.focal_length if perspective else 0.05 * camera.vertical_aperture
        let far: Vector3[4] = [Vector3(-w, -h, -1.0), Vector3(w, -h, -1.0), Vector3(w, h, -1.0), Vector3(-w, h, -1.0)]
        try self.loop(matrix, far)
        if perspective:
            for corner in far: try self.segment(matrix, Vector3(), corner)
        else:
            let near: Vector3[4] = [Vector3(-w, -h, 0.0), Vector3(w, -h, 0.0), Vector3(w, h, 0.0), Vector3(-w, h, 0.0)]
            try self.loop(matrix, near)
            for at in 0..<(usize)4: try self.segment(matrix, near[at], far[at])
        let up: Vector3[3] = [Vector3(-0.5 * w, h * 1.1, -1.0), Vector3(0.5 * w, h * 1.1, -1.0), Vector3(0.0, h * 1.5, -1.0)]
        try self.loop(matrix, up)

    func add_light(light: Light, matrix: Matrix4) -> !:
        let x = Vector3(1.0, 0.0, 0.0)
        let y = Vector3(0.0, 1.0, 0.0)
        let z = Vector3(0.0, 0.0, 1.0)
        var reach: f64 = 0.5
        if light.shape == LightShape.rect:
            let w = 0.5 * light.width
            let h = 0.5 * light.height
            let corners: Vector3[4] = [Vector3(-w, -h, 0.0), Vector3(w, -h, 0.0), Vector3(w, h, 0.0), Vector3(-w, h, 0.0)]
            try self.loop(matrix, corners)
            try self.segment(matrix, corners[0], corners[2])
            try self.segment(matrix, corners[1], corners[3])
            reach = math.max(0.25, math.max(w, h))
        elif light.shape == LightShape.disk:
            try self.circle(matrix, Vector3(), x, y, light.radius)
            reach = math.max(0.25, light.radius)
        elif light.shape == LightShape.sphere:
            try self.circle(matrix, Vector3(), x, y, light.radius)
            try self.circle(matrix, Vector3(), y, z, light.radius)
            try self.circle(matrix, Vector3(), z, x, light.radius)
            reach = math.max(0.25, light.radius)
        else:
            # Distant: three parallel rays with an arrowhead on the middle one.
            for offset in [-0.2, 0.0, 0.2]: try self.segment(matrix, Vector3(offset, 0.0, 0.0), Vector3(offset, 0.0, -1.0))
            try self.segment(matrix, Vector3(0.0, 0.0, -1.0), Vector3(-0.08, 0.0, -0.85))
            try self.segment(matrix, Vector3(0.0, 0.0, -1.0), Vector3(0.08, 0.0, -0.85))
            return
        # Which way it shines: down its local -Z.
        try self.segment(matrix, Vector3(), Vector3(0.0, 0.0, -reach))

    ## A GPU batch of the segments, made again only when segments were
    ## added since.
    pub func batch() -> interop.Reference[WireBatch]!:
        if let kept = self.made:
            if self.made_count == self.points.count: return kept.clone()
            kept.release()
            self.made = none
        let fresh = try interop.Reference[WireBatch].adopt(try new WireBatch(self.points.view()) in memory.heap, wire_batch_type, memory.heap)
        self.made = fresh.clone()
        self.made_count = self.points.count
        return fresh

    pub func close():
        if let kept = self.made: kept.release()
        self.made = none
        self.points.close()

## The endpoints of `lines`, for Base consumers (the worker channel).
## A check's labels as two point pairs each: the label's place (placed by
## `matrix`) and (level, order, value); then (group, 0, 0) and the origin.
## The viewport reads them back into text (check_labels.luc).
pub func check_label_pairs(check: const CadCheck*, matrix: Matrix4, out: Growing[Vector3]*) -> !:
    for label in check_labels(check):
        try out.push(matrix.transform_point(label.point))
        try out.push(Vector3((f64)label.level, (f64)label.order, label.value))
        try out.push(Vector3((f64)label.group, 0.0, 0.0))
        try out.push(Vector3())

pub func line_points(lines: const OverlayLines*) -> const Vector3[]:
    return lines.points.view()

pub let overlay_lines_type: interop.Type[OverlayLines] = interop.Type[OverlayLines]("OverlayLines", OverlayLines.close, closeable = true)

## Plane coordinates (`x`, `y`) on the plane through `origin` with axes
## `u` and `v`, as a world point.
func planar(origin: Vector3, u: Vector3, v: Vector3, x: f64, y: f64) -> Vector3:
    return origin.add(u.multiply_scalar(x)).add(v.multiply_scalar(y))