Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-3d

Source of release 0.9.3

0.9.3 / src / renderers / renderer.lucb

## Polygon meshes (Mesh.of) draw on device frames from retained GPU arrays
## keyed by their change ids (renderers/mesh_batch.lucb): lighting and the
## analysis shadings run in shaders, and a changed mesh uploads only the arrays
## that changed. Other geometry goes through the per-vertex interface, with
## world transforms and Lambert lighting cached per drawn geometry: a scene
## change keeps the prepared data of every object whose geometry, material,
## world transform and lights are unchanged. Standalone frames keep a CPU
## projection fallback for portable recording and tests.
from luce_gpu import gpu
import interop
from luce_std import math
import memory
import ownership
import core.object
import errors
from core.object import Object3D, ObjectNode, Light, LightKind
from luce_geocore import geocore
from luce_geocore.geocore import Geometry, Vector3, Matrix4, Selection
from luce_geocore.kernel import selection_bits, subdivided_display, mesh_dispose
from renderers.subdivision_draw import display_highlight, cage_face_of
from core.material import Material, Color, check_color
from cameras.perspective import PerspectiveCamera, Projection
from renderers.projection import projection_matrix
from renderers.retained import RetainedBatch
from renderers.picking import FacePicker
from luce_geocore.core.growing import Growing
from renderers.gpu_arrays import GpuArrays
from renderers.mesh_batch import MeshShading, FrameLighting, FaceHighlight, draw_polygon

struct Item:
    let object: interop.Interface[Object3D]
    let node: interop.Reference[ObjectNode]
    let world: Matrix4
    let geometry: interop.Interface[Geometry]?
    let polygon: interop.Reference[geocore.Mesh]?
    let material: interop.Interface[Material]?
    let illumination: Light
    let visible: bool

## Where the last frame placed a polygon mesh (by its positions' id), so a
## pick between frames draws it the same way.
struct Placement:
    let points: u64
    let world: Matrix4

struct Prepared:
    let points: Vector3[]
    let colors: Color[]
    let flat_colors: Color[]
    var smooth_gpu: RetainedBatch
    var flat_gpu: RetainedBatch
    # Retained, so its identity cannot be recycled while cached. Materials
    # match by value: scene rebuilds create equal ones.
    var geometry: interop.Interface[Geometry]? = none
    var tint: Color = Color(1.0, 1.0, 1.0)
    var lit: bool = false
    var world: Matrix4 = Matrix4()
    var lighting: u64 = 0
    # Scene changes survived unused; data outlives one change (a hide/show).
    var age: u32 = 0

pub struct Renderer:
    var items: Item[]
    var count: usize
    var vertices: gpu.Vertex[]
    var rendering: bool
    let static_scene: bool
    var prepared: Prepared[]
    var prepared_count: usize
    var prepared_epoch: u64
    # Prepared data from before the last scene change, reusable by identity.
    var spare: Prepared[]
    var spare_count: usize
    var lighting: u64
    var reuses: u64
    var lights: Light[]
    var light_count: usize
    var flat: bool = false
    var wire_width: f64 = 0.0
    # Polygon meshes: their GPU arrays, shading, and optional edge wires.
    var arrays: GpuArrays
    var shading: MeshShading
    var surfaces: bool = true
    var edge_width: f64 = 0.0
    var edge_color: Color = Color(0.0, 0.0, 0.0)
    var picker: FacePicker
    var highlight: FaceHighlight
    ## The cage highlight mapped onto a subdivided mesh's display faces.
    var display_highlight: FaceHighlight
    var placements: Growing[Placement]

    ## Objects whose prepared data survived a scene change (tests, profiling).
    pub func reused_count() -> i64:
        return (i64)self.reuses

    ## Display state only: switching normals never invalidates geometry buffers.
    pub func set_flat(value: bool):
        self.flat = value

    ## Surface shading of polygon meshes: 0 lit, 1 flat, 2 zebra, 3 isophotes,
    ## 4 normals, 5 unlit. Zebra and isophote stripes: `stripes` over a turn
    ## (or across the planar model), `duty` the dark share, around `axis`.
    ## Shading is draw state: changing it uploads nothing.
    pub func set_shading(mode: i64, stripes: f64 = 20.0, duty: f64 = 0.5, axis: Vector3 = Vector3(0.0, 1.0, 0.0), planar: bool = false, stripes_only: bool = false) -> !:
        if mode < 0 or mode > 6 or not (stripes >= 1.0 and stripes <= 256.0) or not (duty > 0.0 and duty < 1.0) or not axis.is_finite() or axis.length() < 0.000001:
            error(errors.invalid, "shading needs a mode 0..6, 1..256 stripes, a duty in (0,1) and a nonzero axis")
        let kind = self.shading.curvature
        let range = self.shading.curvature_range
        self.shading = MeshShading(mode = gpu.Shading((u8)mode), stripes = stripes, duty = duty, planar = planar, stripes_only = stripes_only, axis = try axis.normalized(), curvature = kind, curvature_range = range)

    ## The curvature map (shading mode 6): which value (0 mean, 1 Gaussian,
    ## 2 k1, 3 k2, 4 the larger |k|) and the value it spans (0: automatic,
    ## the 98th percentile of the mesh's values).
    pub func set_curvature(kind: i64, range: f64 = 0.0) -> !:
        if kind < 0 or kind > 4 or not (range >= 0.0 and range < 1.0e12):
            error(errors.invalid, "curvature needs a value kind 0..4 and a finite range, 0 for automatic")
        self.shading.curvature = kind
        self.shading.curvature_range = range

    ## Draw every polygon mesh's edges `width` logical pixels wide (0: none),
    ## from the same GPU arrays as its surfaces; `surfaces` false leaves only
    ## the wires.
    pub func set_edges(width: f64, color: Color, surfaces: bool = true) -> !:
        if not (width >= 0.0 and width <= 32.0): error(errors.invalid, "edge width must be finite and in 0..32")
        try check_color(color)
        self.edge_width = width
        self.edge_color = color
        self.surfaces = surfaces

    ## The face of `mesh` under (x, y) in a `width` x `height` view through
    ## `camera`, as the last frame placed it, or -1: an id pass on the GPU,
    ## reused until the mesh, its placement or the view changes. -2 when the
    ## last frame did not draw `mesh`'s points (a pick mesh of its own), and
    ## fails `unavailable` before a frame has drawn on a device: callers fall
    ## back to a CPU ray.
    pub func pick_face(mesh: interop.Reference[geocore.Mesh], camera: interop.Reference[PerspectiveCamera], x: f64, y: f64, width: f64, height: f64) -> i64!:
        if not self.arrays.has_device(): error(gpu.unavailable, "no frame has drawn on a GPU device")
        if not (width >= 1.0 and height >= 1.0 and width <= 16384.0 and height <= 16384.0): return -1
        let geometry = try mesh.get()
        var found: Matrix4? = none
        for placement in self.placements.view():
            if placement.points == geometry.points_id(): found = placement.world
        let world = found else return -2
        let projection = try camera.value().projection(width / height)
        # A subdivided cage is picked on the surface shown: the display's
        # faces, answered as the cage faces they came from.
        if let display = try subdivided_display(geometry):
            defer mesh_dispose(display)
            let face = try self.pick_mesh(display, world, projection, x, y, width, height)
            return try cage_face_of(display, face)
        return try self.pick_mesh(geometry, world, projection, x, y, width, height)

    func pick_mesh(geometry: const geocore.Mesh*, world: Matrix4, projection: Projection, x: f64, y: f64, width: f64, height: f64) -> i64!:
        var key = geometry.points_id() *% 0x9E3779B97F4A7C15 ^ geometry.triangles_id()
        let values: f64[25] = [world.x.x, world.x.y, world.x.z, world.y.x, world.y.y, world.y.z, world.z.x, world.z.y, world.z.z,
                               world.translation.x, world.translation.y, world.translation.z, projection.position.x, projection.position.y,
                               projection.position.z, projection.backward.x, projection.backward.y, projection.backward.z, projection.up.x,
                               projection.up.y, projection.up.z, projection.focal, projection.near, width, height]
        for value in values: key = (key ^ memory.read[u64]((void*)&value)) *% 0x100000001B3
        return try self.picker.face(&self.arrays, self.arrays.device_handle(), geometry, world, projection, key, x, y, (u32)width, (u32)height)

    ## Tint `faces` of `mesh` (and of later meshes with its topology, such as
    ## its Moves) with `color` at `weight` in the surface shading: a face
    ## selection costs one bit per face on the GPU, whatever its size. An
    ## empty list clears it.
    pub func set_face_selection(mesh: interop.Reference[geocore.Mesh], faces: const i64[], color: Color = Color(1.0, 0.5, 0.0), weight: f64 = 0.45) -> !:
        try check_color(color)
        if not (weight >= 0.0 and weight <= 1.0): error(errors.invalid, "selection tint weight must be in 0..1")
        let geometry = try mesh.get()
        try self.highlight.set(geometry.corners_id(), (usize)geometry.face_count(), faces, color, weight)

    ## Tint the faces of a face `selection` (luce-geocore); other component
    ## types clear the tint.
    pub func set_selected_faces(mesh: interop.Reference[geocore.Mesh], selection: interop.Reference[Selection], color: Color = Color(1.0, 0.5, 0.0), weight: f64 = 0.45) -> !:
        try check_color(color)
        if not (weight >= 0.0 and weight <= 1.0): error(errors.invalid, "selection tint weight must be in 0..1")
        let chosen = try selection.get()
        if chosen.domain() != 2:
            self.clear_face_selection()
            return
        let geometry = try mesh.get()
        let bits = selection_bits(chosen)
        try self.highlight.set_words(geometry.corners_id(), (usize)geometry.face_count(), bits.words, chosen.key(), color, weight)

    pub func clear_face_selection():
        self.highlight.words.clear()
        self.highlight.key = 0
        self.highlight.topology = 0

    ## GPU array uploads so far and their bytes (tests, benchmarks).
    pub func uploads() -> i64:
        return (i64)self.arrays.uploads

    pub func uploaded_bytes() -> i64:
        return (i64)self.arrays.uploaded

    ## Reserve the depth footprint of a coplanar screen-width wire overlay.
    ## Zero disables it. This is draw state; retained geometry stays unchanged.
    pub func set_wire_overlay(width: f64 = 0.0) -> !:
        if not (width >= 0.0 and width <= 32.0): error(errors.invalid, "wire overlay width must be finite and in 0..32")
        self.wire_width = width

    ## Opt-in immutable geometry/material cache. Scene transforms invalidate it
    ## automatically; owners call invalidate after custom material/geometry edits.
    pub func init(static_scene: bool = false) -> !:
        self.items = try new Item[1024] --- in memory.heap
        self.prepared = try new Prepared[1024] --- in memory.heap
        self.spare = try new Prepared[1024] --- in memory.heap
        self.spare_count = 0
        self.lighting = 0
        self.reuses = 0
        self.lights = try new Light[1024] --- in memory.heap
        self.static_scene = static_scene
        self.prepared_count = 0
        self.prepared_epoch = 0
        self.light_count = 0
        self.flat = false
        self.wire_width = 0.0
        self.arrays = GpuArrays()
        self.shading = MeshShading()
        self.surfaces = true
        self.edge_width = 0.0
        self.edge_color = Color(0.0, 0.0, 0.0)
        self.picker = FacePicker()
        self.highlight = FaceHighlight()
        self.display_highlight = FaceHighlight()
        self.placements = Growing[Placement]()
        self.count = 0
        var empty: gpu.Vertex[]
        self.vertices = empty
        self.rendering = false

    ## A frame retains the scene traversal while custom interfaces execute.
    ## Reusing the output buffer avoids per-mesh allocation after capacity grows.
    pub func render(scene: interop.Interface[Object3D], camera: interop.Reference[PerspectiveCamera],
                    target: interop.View[gpu.RenderTarget], fit_aspect: bool = false) -> interop.Outcome[unit]:
        if self.rendering:
            return errors.failure[unit](errors.busy, "the renderer cannot reenter a render pass")
        self.rendering = true
        defer self.finish()
        let native = target.get() catch failure:
            return errors.failure[unit](failure.code, failure.message)
        native.allow_vertices(8388608) catch failure:
            return errors.failure[unit](failure.code, failure.message)
        let extent = native.size() catch failure:
            return errors.failure[unit](failure.code, failure.message)
        let lens = camera.get() catch failure:
            return errors.failure[unit](failure.code, failure.message)
        let aspect: f64? = extent.width / extent.height if fit_aspect and extent.height > 0.0 else none
        let projection = lens.projection(aspect) catch failure:
            return errors.failure[unit](failure.code, failure.message)
        if extent.width <= 0.0 or extent.height <= 0.0:
            return errors.success[unit](())
        let version = object.epoch()
        self.gather(scene, Matrix4(), true, 0, 0) catch failure:
            return errors.failure[unit](failure.code, failure.message)
        if object.epoch() != version:
            return errors.failure[unit](errors.busy, "a scene changed during traversal")
        if not self.static_scene:
            self.invalidate()
        elif self.prepared_epoch != version:
            self.retire()
            self.prepared_epoch = version
        self.light_count = 0
        for item in self.items[..<self.count]:
            let light = item.illumination
            if item.visible and light.kind != LightKind.inactive:
                let direction = item.world.transform_direction(light.direction).normalized() catch failure:
                    return errors.failure[unit](failure.code, failure.message)
                self.lights[self.light_count] = Light(light.kind, light.color, light.intensity, direction)
                self.light_count += 1
        self.lighting = self.light_signature()
        var device = gpu.device_of(native) catch failure:
            if failure.code != gpu.unavailable: return errors.failure[unit](failure.code, failure.message)
            recover gpu.Device()
        defer device.destroy()
        if device.is_open():
            self.arrays.begin(device) catch failure:
                return errors.failure[unit](failure.code, failure.message)
        let lighting = self.frame_lighting()
        self.placements.clear()
        var drawable: usize = 0
        for index in 0..<self.count:
            let item = &self.items[index]
            if not item.visible:
                continue
            if let polygon = item.polygon if device.is_open() else none:
                let material = item.material else return errors.failure[unit](errors.invalid, "a renderable object has geometry without material")
                self.placements.push(Placement(polygon.value().points_id(), item.world)) catch failure:
                    return errors.failure[unit](failure.code, failure.message)
                self.draw_mesh(item, polygon, material, projection, &lighting, native) catch failure:
                    return errors.failure[unit](failure.code, failure.message)
                continue
            let geometry = item.geometry else continue
            let material = item.material else return errors.failure[unit](errors.invalid, "a renderable object has geometry without material")
            let rendered = self.draw(item, geometry, material, projection, target, drawable)
            drawable += 1
            if not rendered.is_success():
                return rendered
            rendered.release()
        if device.is_open(): self.arrays.trim()
        return errors.success[unit](())

    func draw_mesh(item: const Item*, polygon: interop.Reference[geocore.Mesh], material: interop.Interface[Material], projection: Projection,
                   lighting: const FrameLighting*, target: const gpu.RenderTarget*) -> !:
        try material.enter()
        defer material.leave()
        let appearance = material.value()
        let tint = appearance.color()
        try check_color(tint)
        var shading = self.shading
        if self.flat and shading.mode == gpu.Shading.lit: shading.mode = gpu.Shading.flat
        let cage = try polygon.get()
        let bias = self.wire_width * 0.7071067811865476 if self.surfaces else 0.0
        # A subdivided cage: its limit surface, the cage's wires over it.
        if let display = try subdivided_display(cage):
            defer mesh_dispose(display)
            if self.highlight.topology == cage.corners_id(): try display_highlight(&self.highlight, display, &self.display_highlight)
            else: self.display_highlight.words.clear()
            try draw_polygon(&self.arrays, target, display, item.world, projection, lighting, tint, appearance.is_lit(), &shading,
                             bias, self.surfaces, 0.0, self.edge_color, &self.display_highlight)
            if self.edge_width > 0.0:
                try draw_polygon(&self.arrays, target, cage, item.world, projection, lighting, tint, appearance.is_lit(), &shading,
                                 0.0, false, self.edge_width, self.edge_color, none)
            return
        try draw_polygon(&self.arrays, target, cage, item.world, projection, lighting, tint, appearance.is_lit(), &shading,
                         bias, self.surfaces, self.edge_width, self.edge_color, &self.highlight)

    ## Ambient lights summed, and the first four directional lights.
    func frame_lighting() -> FrameLighting:
        var lighting = FrameLighting()
        var red = 0.0
        var green = 0.0
        var blue = 0.0
        for light in self.lights[..<self.light_count]:
            if light.kind == LightKind.ambient:
                red += light.color.red * light.intensity
                green += light.color.green * light.intensity
                blue += light.color.blue * light.intensity
            elif light.kind == LightKind.directional and lighting.count < 4:
                lighting.directions[lighting.count] = light.direction
                lighting.colors[lighting.count] = Color(light.color.red * light.intensity, light.color.green * light.intensity, light.color.blue * light.intensity)
                lighting.count += 1
        lighting.ambient = Color(red, green, blue)
        return lighting

    func gather(source: interop.Interface[Object3D], parent: Matrix4, visible: bool, depth: usize, parent_id: u64) -> !:
        if depth >= 64 or self.count >= self.items.length:
            error(errors.limit, "a renderer supports at most 1024 objects and 64 levels")
        try source.enter()
        defer source.leave()
        let native = source.value()
        let node = native.node()
        defer node.release()
        let state = try node.get()
        if state.parent_id() != parent_id:
            error(errors.invalid, "an object returned an unstable node or belongs to another parent")
        for item in self.items[..<self.count]:
            if item.node.value().id() == state.id():
                error(errors.invalid, "a scene contains duplicate object identities")
        let world = parent.multiply(state.matrix())
        if not world.is_finite():
            error(errors.invalid, "world transform components overflowed")
        let geometry = native.geometry()
        defer release_geometry(geometry)
        let polygon = native.polygon()
        defer release_polygon(polygon)
        let material = native.material()
        defer release_material(material)
        let illumination = native.light()
        try check_color(illumination.color)
        if not (illumination.intensity >= 0.0 and illumination.intensity <= 100.0) or not illumination.direction.is_finite():
            error(errors.invalid, "a custom light returned invalid parameters")
        let shown = visible and state.is_visible()
        self.items[self.count] = Item(source.clone(), node.clone(), world, clone_geometry(geometry), clone_polygon(polygon), clone_material(material), illumination, shown)
        self.count += 1
        let length = state.child_count()
        var index: i64 = 0
        while index < length:
            let child = try state.child(index)
            defer child.release()
            try self.gather(child, world, shown, depth + 1, state.id())
            index += 1

    func reserve(count: usize) -> !:
        if count <= self.vertices.length:
            return
        let doubled = self.vertices.length * 2 if self.vertices.length <= 98304 else 196608
        let capacity = count if count > doubled else doubled
        let replacement = try new gpu.Vertex[capacity] --- in memory.heap
        if self.vertices.length > 0:
            free(self.vertices) in memory.heap
        self.vertices = replacement

    func draw(item: const Item*, geometry: interop.Interface[Geometry], material: interop.Interface[Material],
              projection: Projection, target: interop.View[gpu.RenderTarget], drawable: usize) -> interop.Outcome[unit]:
        geometry.enter() catch failure:
            return errors.failure[unit](failure.code, failure.message)
        defer geometry.leave()
        material.enter() catch failure:
            return errors.failure[unit](failure.code, failure.message)
        defer material.leave()
        let shape = geometry.value()
        let appearance = material.value()
        let count = shape.index_count()
        let vertices = shape.vertex_count()
        if count <= 0 or count > 100663296 or count % 3 != 0 or vertices <= 0 or vertices > 33554432:
            return errors.failure[unit](errors.invalid, "a custom geometry returned invalid buffer counts")
        let tint = appearance.color()
        check_color(tint) catch failure:
            return errors.failure[unit](failure.code, failure.message)
        let lit = appearance.is_lit()
        self.reserve((usize)count) catch failure:
            return errors.failure[unit](failure.code, failure.message)
        if drawable == self.prepared_count and self.reuse(item, geometry, tint, lit, drawable):
            self.prepared_count += 1
        elif drawable == self.prepared_count:
            let points = new Vector3[(usize)count] --- in memory.heap catch failure:
                return errors.failure[unit](failure.code, failure.message)
            let colors = new Color[(usize)count] --- in memory.heap catch failure:
                free(points) in memory.heap
                return errors.failure[unit](failure.code, failure.message)
            let flat_colors = new Color[(usize)count] --- in memory.heap catch failure:
                free(points) in memory.heap
                free(colors) in memory.heap
                return errors.failure[unit](failure.code, failure.message)
            self.prepared[drawable] = Prepared(points, colors, flat_colors, RetainedBatch(), RetainedBatch(), geometry.clone(), tint, lit, item.world, self.lighting)
            # On failure invalidate the partial cache before returning.
            self.prepared_count += 1
            let built = self.prepare(item, shape, tint, lit, vertices, &self.prepared[drawable])
            if not built.is_success():
                self.invalidate()
                return built
            built.release()
        let native = target.get() catch failure:
            return errors.failure[unit](failure.code, failure.message)
        var device = gpu.device_of(native) catch failure:
            if failure.code != gpu.unavailable: return errors.failure[unit](failure.code, failure.message)
            recover gpu.Device()
        defer device.destroy()
        if device.is_open():
            self.draw_retained(drawable, device, native, projection) catch failure:
                return errors.failure[unit](failure.code, failure.message)
            return errors.success[unit](())
        let cached = self.prepared[drawable]
        for offset in 0..<count:
            let relative = cached.points[(usize)offset].subtract(projection.position)
            let distance = -relative.dot(projection.backward)
            let color = cached.flat_colors[(usize)offset] if self.flat else cached.colors[(usize)offset]
            self.vertices[(usize)offset] = gpu.Vertex(
                x = (f32)(relative.dot(projection.right) * projection.focal / projection.aspect),
                y = (f32)(relative.dot(projection.up) * projection.focal),
                z = (f32)(projection.far * (distance - projection.near) / (projection.far - projection.near)),
                w = (f32)distance, red = (f32)color.red, green = (f32)color.green, blue = (f32)color.blue)
        native.triangles(self.vertices[..<(usize)count], true, self.wire_width * 0.7071067811865476) catch failure:
            return errors.failure[unit](failure.code, failure.message)
        return errors.success[unit](())

    func draw_retained(drawable: usize, device: gpu.Device, target: const gpu.RenderTarget*, projection: Projection) -> !:
        let cached = &self.prepared[drawable]
        let retained = &cached.flat_gpu if self.flat else &cached.smooth_gpu
        if not retained.is_open():
            for at in 0..<cached.points.length:
                let p = cached.points[at]
                let color = cached.flat_colors[at] if self.flat else cached.colors[at]
                self.vertices[at] = gpu.Vertex(x = (f32)p.x, y = (f32)p.y, z = (f32)p.z, red = (f32)color.red, green = (f32)color.green, blue = (f32)color.blue)
            try retained.upload(device, self.vertices[..<cached.points.length])
        let matrix = projection_matrix(projection)
        # Hardware slope is max(abs(dz/dx),abs(dz/dy)); sqrt(2) times
        # half the line width covers its perpendicular pixel footprint.
        try retained.draw(target, matrix, slope_bias = self.wire_width * 0.7071067811865476)

    func prepare(item: const Item*, shape: Geometry, tint: Color, lit: bool, vertices: i64, prepared: Prepared*) -> interop.Outcome[unit]:
        for offset in 0..<(i64)prepared.points.length:
            let indexed = shape.index(offset)
            defer indexed.release()
            let index = indexed.get() catch failure:
                return errors.failure[unit](failure.code, failure.message)
            if index < 0 or index >= vertices:
                return errors.failure[unit](errors.invalid, "a custom geometry returned an out-of-bounds index")
            let result = shape.vertex(index)
            defer result.release()
            let vertex = result.get() catch failure:
                return errors.failure[unit](failure.code, failure.message)
            if not vertex.position.is_finite() or not vertex.normal.is_finite():
                return errors.failure[unit](errors.invalid, "a custom geometry returned non-finite attributes")
            let world = item.world.transform_point(vertex.position)
            let vertex_tint = Color(tint.red * vertex.color.x, tint.green * vertex.color.y, tint.blue * vertex.color.z)
            check_color(vertex_tint) catch failure:
                return errors.failure[unit](failure.code, failure.message)
            var color = vertex_tint
            if lit:
                let normal = item.world.transform_normal(vertex.normal) catch failure:
                    return errors.failure[unit](failure.code, failure.message)
                color = self.illuminate(normal, vertex_tint) catch failure:
                    return errors.failure[unit](failure.code, failure.message)
            prepared.points[(usize)offset] = world
            prepared.colors[(usize)offset] = color
            prepared.flat_colors[(usize)offset] = vertex_tint
        if lit:
            for triangle in 0..<prepared.points.length // 3:
                let at = triangle * 3
                let normal = prepared.points[at + 1].subtract(prepared.points[at]).cross(prepared.points[at + 2].subtract(prepared.points[at])).normalized() catch failure:
                    # Custom geometry may intentionally contain zero-area
                    # triangles. They produce no pixels; keep cached shading.
                    continue
                for corner in 0..<(usize)3:
                    prepared.flat_colors[at + corner] = self.illuminate(normal, prepared.flat_colors[at + corner]) catch failure:
                        return errors.failure[unit](failure.code, failure.message)
        return errors.success[unit](())

    func illuminate(normal: Vector3, tint: Color) -> Color!:
        var illumination = Vector3()
        for light in self.lights[..<self.light_count]:
            var intensity = light.intensity
            if light.kind == LightKind.directional:
                intensity *= math.max(0.0, normal.dot(light.direction))
            illumination = illumination.add(Vector3(light.color.red, light.color.green, light.color.blue).multiply_scalar(intensity))
        return Color(math.min(1.0, tint.red * illumination.x), math.min(1.0, tint.green * illumination.y), math.min(1.0, tint.blue * illumination.z))

    ## Counts drop before the releases in these clean-ups: a last release can run a
    ## collection that traces this renderer, and it must not visit what is gone.
    func finish():
        let count = self.count
        self.count = 0
        self.rendering = false
        for item in self.items[..<count]:
            release_geometry(item.geometry)
            release_polygon(item.polygon)
            release_material(item.material)
            item.node.release()
            item.object.release()

    pub func close():
        self.finish()
        self.invalidate()
        free(self.prepared) in memory.heap
        free(self.spare) in memory.heap
        free(self.lights) in memory.heap
        free(self.items) in memory.heap
        self.picker.close()
        self.highlight.close()
        self.display_highlight.close()
        self.placements.close()
        self.arrays.close()
        if self.vertices.length > 0:
            free(self.vertices) in memory.heap

    ## Drop immutable draw data after a geometry/material mutation.
    pub func invalidate():
        let count = self.prepared_count
        self.prepared_count = 0
        self.prepared_epoch = 0
        for cached in self.prepared[..<count]:
            dispose(cached)
        self.drop_spare()

    ## After a scene change, keep prepared data aside for reuse by identity.
    ## Data unused across two changes is freed.
    func retire():
        let spare_count = self.spare_count
        let prepared_count = self.prepared_count
        self.spare_count = 0
        self.prepared_count = 0
        for index in 0..<spare_count:
            var cached = self.spare[index]
            cached.age += 1
            if cached.age >= 2:
                dispose(cached)
            else:
                self.spare[self.spare_count] = cached
                self.spare_count += 1
        for cached in self.prepared[..<prepared_count]:
            if self.spare_count == self.spare.length:
                dispose(cached)
                continue
            var entry = cached
            entry.age = 0
            self.spare[self.spare_count] = entry
            self.spare_count += 1

    ## Adopt a spare entry drawn from the same geometry object with an equal
    ## material under the same world transform and lights.
    func reuse(item: const Item*, geometry: interop.Interface[Geometry], tint: Color, lit: bool, drawable: usize) -> bool:
        for index in 0..<self.spare_count:
            let cached = self.spare[index]
            let shape = cached.geometry else continue
            let same_tint = cached.tint.red == tint.red and cached.tint.green == tint.green and cached.tint.blue == tint.blue
            if shape.owner != geometry.owner or not same_tint or cached.lit != lit or cached.lighting != self.lighting or not same_matrix(cached.world, item.world):
                continue
            self.prepared[drawable] = cached
            self.spare_count -= 1
            self.spare[index] = self.spare[self.spare_count]
            self.reuses += 1
            return true
        return false

    func drop_spare():
        let count = self.spare_count
        self.spare_count = 0
        for cached in self.spare[..<count]:
            dispose(cached)

    ## Prepared colors bake the lights in; a different set invalidates them.
    func light_signature() -> u64:
        var state: u64 = 0x9E3779B97F4A7C15
        for light in self.lights[..<self.light_count]:
            state = fold(state, (f64)(u8)light.kind)
            state = fold(fold(fold(state, light.color.red), light.color.green), light.color.blue)
            state = fold(state, light.intensity)
            state = fold(fold(fold(state, light.direction.x), light.direction.y), light.direction.z)
        return state

    func trace(visit: func(ownership.Object*, void*) -> unit, context: void*):
        for cached in self.prepared[..<self.prepared_count]:
            trace_prepared(cached, visit, context)
        for cached in self.spare[..<self.spare_count]:
            trace_prepared(cached, visit, context)
        for item in self.items[..<self.count]:
            item.object.trace(visit, context)
            item.node.trace(visit, context)
            if let geometry = item.geometry:
                geometry.trace(visit, context)
            if let polygon = item.polygon:
                polygon.trace(visit, context)
            if let material = item.material:
                material.trace(visit, context)

pub let renderer_type: interop.Type[Renderer] = interop.Type[Renderer]("Renderer", Renderer.close, Renderer.trace, closeable = true, main_thread = true)

func release_geometry(value: interop.Interface[Geometry]?):
    if let geometry = value:
        geometry.release()

func release_material(value: interop.Interface[Material]?):
    if let material = value:
        material.release()

func clone_geometry(value: interop.Interface[Geometry]?) -> interop.Interface[Geometry]?:
    if let geometry = value:
        return geometry.clone()
    return none

func release_polygon(value: interop.Reference[geocore.Mesh]?):
    if let mesh = value:
        mesh.release()

func clone_polygon(value: interop.Reference[geocore.Mesh]?) -> interop.Reference[geocore.Mesh]?:
    if let mesh = value:
        return mesh.clone()
    return none

func clone_material(value: interop.Interface[Material]?) -> interop.Interface[Material]?:
    if let material = value:
        return material.clone()
    return none

func dispose(cached: Prepared):
    var smooth = cached.smooth_gpu
    var flat = cached.flat_gpu
    smooth.close()
    flat.close()
    free(cached.flat_colors) in memory.heap
    free(cached.points) in memory.heap
    free(cached.colors) in memory.heap
    release_geometry(cached.geometry)

func trace_prepared(cached: const Prepared, visit: func(ownership.Object*, void*) -> unit, context: void*):
    if let geometry = cached.geometry:
        geometry.trace(visit, context)

func same_matrix(a: Matrix4, b: Matrix4) -> bool:
    return a.x == b.x and a.y == b.y and a.z == b.z and a.translation == b.translation

func fold(state: u64, value: f64) -> u64:
    var bits = value
    return (state ^ memory.read[u64](&bits)) *% 0x100000001B3