Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-geocore

Source of release 0.7.8

0.7.8 / src / geometries / shading / shading_cache.lucb

## Derived shading data of one geometry, computed on first use and shared by
## its snapshots: smooth normals for meshes without an authored N (per point,
## or per corner where a cusp splits a point; see smooth_normals.lucb) and the
## points' discrete principal curvatures (curvature.lucb). A mesh made by
## moving points keeps the previous geometry's cache as its source and redoes
## only the normals around the moved points.
import memory
import sync
from luce_std import sort
from core.float3 import Float3
from core.shared import Column
from geometries.shading.smooth_normals import Surface, point_normals, corner_normals, affected_points, refresh_points, refresh_corners
from geometries.shading.curvature import CurvatureShape, point_curvatures

pub struct ShadingCache:
    pub var owners: @usize = 1
    var lock: sync.Mutex
    var ready: @u32
    ## The smooth normals: all of them; or, while `patch` holds any, the
    ## normals of an earlier frame, shared, that `patch` overrides from
    ## element `patch_first` on (a drag's frames: the moved points'
    ## neighbourhood, not a copy of the whole column each move).
    var smooth: Column[Float3]
    var patch: Column[Float3]
    var patch_first: usize
    ## Whether `smooth` holds a normal per corner (true) or per point.
    var per_corner: bool
    ## A patched cache's identity: its column's parent and the elements that
    ## differ from it (a whole column says these itself).
    var patch_parent: u64
    var patch_changed: (usize, usize)
    ## Before this cache is built: the previous geometry's cache and the
    ## points that moved since.
    var source: ShadingCache*? = none
    var moved: u32[]
    ## k1 and k2 of every point.
    var curvature_ready: @u32
    var curvature: Column[f32]

    ## A cache for a mesh whose points `moved` over `previous`'s geometry.
    ## A built `previous` is its source. An unbuilt one passes on its own
    ## source with both moves (frames no one drew shade from the last built
    ## normals, not from scratch); without one this computes afresh.
    pub static func after(previous: ShadingCache*, moved: const u32[]) -> ShadingCache*!:
        let cache = try new ShadingCache() in memory.heap
        if moved.length == 0: return cache
        previous.lock.lock()
        var base = previous
        var earlier: const u32[] = moved[..<0]
        if previous.ready.load(.acquire) == 0:
            if previous.source == none:
                previous.lock.unlock()
                return cache
            base = previous.source else trap("a shading source vanished under its lock")
            earlier = previous.moved
        let copy = joined_points(earlier, moved) catch failure:
            previous.lock.unlock()
            free(cache) in memory.heap
            error(failure.code, failure.message)
        _ = base.owners.add(1, .relaxed)
        previous.lock.unlock()
        cache.source = base
        cache.moved = copy
        return cache

    ## The smooth normals as one array, per point or per corner
    ## (`corner_domain`): a patched cache joins its patch into a column of
    ## its own first (once). Published once, immutable after.
    pub func get(shape: const Surface*) -> const Float3[]!:
        try self.prepare(shape)
        if self.patch.is_empty(): return self.smooth.view()
        self.lock.lock()
        defer self.lock.unlock()
        if not self.patch.is_empty():
            # The joined column stands for this cache's normals: its parent
            # is the patched identity, unchanged, so GPU copies keep theirs.
            var whole = try Column[Float3].allocate(self.smooth.count())
            self.copy_range(0, whole.count(), whole.span())
            whole.set_parent(self.patch.id())
            whole.set_changed(0, 0)
            self.smooth.release()
            self.patch.release()
            self.smooth = whole
        return self.smooth.view()

    ## Build the normals (whole, or as a patch over a source's), without
    ## joining a patch: what ids, the domain and range reads need.
    pub func prepare(shape: const Surface*) -> !:
        if self.ready.load(.acquire) != 0: return
        self.lock.lock()
        defer self.lock.unlock()
        if self.ready.load(.acquire) != 0: return
        if let source = self.source:
            try self.update_from(source, shape)
        else:
            try self.compute(shape)
        self.ready.store(1, .release)
        self.drop_source()

    ## Normals `first..<end` into `output` (one each), from the column or
    ## through the patch; once prepared.
    pub func read(first: usize, end: usize, output: Float3[]):
        self.lock.lock()
        defer self.lock.unlock()
        self.copy_range(first, end, output)

    func copy_range(first: usize, end: usize, output: Float3[]):
        let all = self.smooth.view()
        memory.copy(output, all[first..<end], end - first)
        if self.patch.is_empty(): return
        let patch = self.patch.view()
        let low = first if first > self.patch_first else self.patch_first
        let patch_end = self.patch_first + patch.length
        let high = end if end < patch_end else patch_end
        if low < high: memory.copy(output[low - first..<high - first], patch[low - self.patch_first..<high - self.patch_first], high - low)

    ## How many normals there are.
    pub func count() -> usize:
        return self.smooth.count()

    pub func is_ready() -> bool:
        return self.ready.load(.acquire) != 0

    ## Whether the built normals are per corner (else per point).
    pub func corner_domain() -> bool:
        return self.per_corner

    ## The normals' identity (equal ids: equal normals) and the identity they
    ## were updated from (0: none), and what differs from that; meaningful
    ## once prepared.
    pub func id() -> u64:
        if not self.patch.is_empty(): return self.patch.id()
        return self.smooth.id()

    pub func parent() -> u64:
        if not self.patch.is_empty(): return self.patch_parent
        return self.smooth.parent()

    pub func changed() -> (usize, usize):
        if not self.patch.is_empty(): return self.patch_changed
        return self.smooth.changed()

    ## Every normal from scratch: per point, or per corner where a cusp splits
    ## some point's corners. Under the lock.
    func compute(shape: const Surface*) -> !:
        let points = shape.positions.length
        var point_column = try Column[Float3].allocate(points)
        errdefer point_column.release()
        let split = try new bool[points] --- in memory.heap
        defer free(split) in memory.heap
        if not point_normals(shape, point_column.span(), split):
            self.smooth = point_column
            self.per_corner = false
            return
        var corner_column = try Column[Float3].allocate(shape.corners.length)
        corner_normals(shape, point_column.view(), split, corner_column.span())
        point_column.release()
        self.smooth = corner_column
        self.per_corner = true

    ## `source`'s normals with those around the moved points redone, as a
    ## patch over the column `source` shares: the patch covers the moved
    ## points' elements and what `source`'s own patch covered, so a drag's
    ## frames cost their neighbourhood, not the mesh. Per point, a point that
    ## gained a cusp turns the storage per corner (once): the other points
    ## had none, so their corners copy their point's normal. Under the lock.
    func update_from(source: ShadingCache*, shape: const Surface*) -> !:
        let affected = try affected_points(shape, self.moved)
        defer free(affected) in memory.heap
        let range = changed_range(shape, affected, source.per_corner)
        var first = range.0
        var end = range.1
        if not source.patch.is_empty():
            let held_end = source.patch_first + source.patch.count()
            if range.0 == range.1:
                first = source.patch_first
                end = held_end
            else:
                first = first if first < source.patch_first else source.patch_first
                end = end if end > held_end else held_end
        var patch = try Column[Float3].allocate(end - first)
        errdefer patch.release()
        source.read(first, end, patch.span())
        if source.per_corner:
            refresh_corners(shape, affected, patch.span(), first)
        else:
            let split = try new bool[end - first + 1] --- in memory.heap
            defer free(split) in memory.heap
            memory.set(u8[]((u8*)split.data, split.length), 0)
            if refresh_points(shape, affected, patch.span(), split, first):
                # A cusp: every point's normal, then per corner.
                var points = try Column[Float3].allocate(source.count())
                errdefer points.release()
                source.read(0, points.count(), points.span())
                memory.copy(points.span()[first..<end], patch.view(), end - first)
                let whole = try new bool[points.count()] --- in memory.heap
                defer free(whole) in memory.heap
                memory.set(u8[]((u8*)whole.data, whole.length), 0)
                memory.copy(whole[first..<end], split[..<end - first], end - first)
                var corners = try Column[Float3].allocate(shape.corners.length)
                corner_normals(shape, points.view(), whole, corners.span())
                points.release()
                patch.release()
                self.smooth = corners
                self.per_corner = true
                return
        self.smooth = source.smooth.share()
        self.patch = patch
        self.patch_first = first
        self.patch_parent = source.id()
        self.patch_changed = range
        self.per_corner = source.per_corner

    ## k1 and k2 of every point, computed on first use.
    pub func curvatures(shape: const CurvatureShape*) -> const f32[]!:
        if self.curvature_ready.load(.acquire) == 0:
            self.lock.lock()
            defer self.lock.unlock()
            if self.curvature_ready.load(.acquire) == 0:
                var column = try Column[f32].allocate(shape.positions.length * 2)
                point_curvatures(shape, column.span())
                self.curvature = column
                self.curvature_ready.store(1, .release)
        return self.curvature.view()

    pub func has_curvatures() -> bool:
        return self.curvature_ready.load(.acquire) != 0

    ## The curvatures once `has_curvatures`.
    pub func built_curvatures() -> const f32[]:
        return self.curvature.view()

    pub func curvature_id() -> u64:
        return self.curvature.id()

    func drop_source():
        if let source = self.source:
            self.source = none
            release_shading(source)
        if self.moved.length > 0:
            free(self.moved) in memory.heap
            var empty: u32[]
            self.moved = empty

    ## Called by the last owner, after every reader.
    func close():
        self.smooth.release()
        self.patch.release()
        self.curvature.release()
        self.drop_source()

## The points of `a` and `b`, ascending, each once (a new heap list).
func joined_points(a: const u32[], b: const u32[]) -> u32[]!:
    let all = try new u32[a.length + b.length] --- in memory.heap
    errdefer free(all) in memory.heap
    memory.copy(all[..<a.length], a, a.length)
    memory.copy(all[a.length..], b, b.length)
    sort.stable(all, ascending)
    var kept: usize = 0
    for at in 0..<all.length:
        if at > 0 and all[at] == all[kept - 1]: continue
        all[kept] = all[at]
        kept += 1
    let unique = try new u32[kept] --- in memory.heap
    memory.copy(unique, all[..<kept], kept)
    free(all) in memory.heap
    return unique

func ascending(a: u32, b: u32) -> bool:
    return a < b

## Give up one owner of `cache`; the last frees it.
pub func release_shading(cache: ShadingCache*):
    if cache.owners.sub(1, .acq_rel) > 1: return
    cache.close()
    free(cache) in memory.heap

## The elements `affected` points own: themselves, or their corners.
func changed_range(shape: const Surface*, affected: const u32[], corners: bool) -> (usize, usize):
    if affected.length == 0: return (0, 0)
    if not corners: return ((usize)affected[0], (usize)affected[affected.length - 1] + 1)
    var first = shape.corners.length
    var end: usize = 0
    for point in affected:
        for at in (usize)shape.incident_offsets[(usize)point]..<(usize)shape.incident_offsets[(usize)point + 1]:
            let face = (usize)shape.incident_faces[at]
            let start = (usize)shape.offsets[face]
            let stop = (usize)shape.offsets[face + 1]
            first = start if start < first else first
            end = stop if stop > end else end
    return (first, end)