Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

19.2 KB
Raw Blame
//! Cutout maps: what an alpha-tested material keeps of each of its triangles, made once, for the rays that only ask
//! whether something stands in their way.
//!
//! A cutout (`scene::mesh_class` 1) keeps of a triangle what its base texture's alpha says at or above the
//! material's cutoff. A ray finds that out with a read of the triangle's corners, its material and its texture at a
//! hit. A shadow ray needs less: is the point solid or a hole. A triangle's map answers that from two words: the
//! triangle is laid over with a lattice of 4^level cells, each about `CELL` texels of the texture across (`LEVELS`
//! levels at most), and a cell's state is two bits: nothing of it is there, all of it, or a part (less than half, or
//! half and more). The low bit is what a ray that reads no texture takes the cell for.
//!
//! The maps are a stream of the words' heap (heap.rs `Stream::Cutouts`):
//! - a run a section of a mesh drawn with a cutout material: a word a triangle, in the section's order: the map's
//!   first word in the stream and, in its low four bits, the map's level (1 ..= `LEVELS`), `WHOLE` (every cell is
//!   solid: no map), `NOTHING` (none is) or `NO_MAP`;
//! - the maps, sixteen cells a word, in `cell_of`'s order. Triangles with the same texture coordinates and material
//!   have one map (a tree's leaves are a few sprites, placed thousands of times: of Bistro's 285,355 cutout triangles
//!   3,195 have texture coordinates of their own).
//!
//! An instance's row of the section has where the run begins (`scene::Row`'s last word, `row_run`); a row without one
//! (a material with a function that may change its opacity, a section an edit made) is a cutout the kernel takes as
//! it did before there were maps.

use crate::scene::{GpuMaterial, Scene, ROW_CUTOUT, ROW_MATERIAL};
use glam::Vec2;
use rayon::prelude::*;
use std::collections::HashMap;

/// A cell's width in texels of the material's base texture, where the levels allow it; and the most levels (a cell
/// of a triangle 2048 texels wide is then 16 texels: its leaves' outlines, not their veins).
pub const CELL: f32 = 2.0;
pub const LEVELS: u32 = 7;

/// A triangle's word's low four bits when they are not a level.
pub const NO_MAP: u32 = 0;
pub const NOTHING: u32 = 14;
pub const WHOLE: u32 = 15;

/// A cell's state.
pub const CELL_EMPTY: u32 = 0;
pub const CELL_SOLID: u32 = 1;
pub const CELL_PART_EMPTY: u32 = 2;
pub const CELL_PART_SOLID: u32 = 3;

/// In a row's last word (`scene::Row`), above `scene::ROW_UNSAMPLED`: the section's run in the stream, plus one
/// (0: it has none).
pub const ROW_RUN_SHIFT: u32 = 1;

/// The run of a row, if it has one.
pub fn row_run(row: &crate::scene::Row) -> Option<u32> {
    (row[3] >> ROW_RUN_SHIFT).checked_sub(1)
}

/// The runs of the rows `mine` of an instance of `mesh` that an edit places: those of an instance the scene has of
/// that mesh, section by section where the material is the same (its maps are of the mesh's triangles and that
/// material, whichever instance asks). For a mesh whose triangles are the build's: one an edit wrote has other
/// triangles than the maps were made of, and its caller does not ask (live/edits.rs `EditState::remade`).
pub fn adopt_runs(mine: &mut [crate::scene::Row], mesh: u32, instances: &[crate::scene::Instance], rows: &[crate::scene::Row]) {
    if !mine.iter().any(|r| r[0] & ROW_CUTOUT != 0) {
        return;
    }
    let of = |i: &crate::scene::Instance| rows.get(i.rows as usize..i.rows as usize + mine.len());
    let Some(theirs) = instances.iter().filter(|i| i.mesh == mesh).filter_map(of).find(|o| o.iter().any(|r| row_run(r).is_some())) else { return };
    let low = (1 << ROW_RUN_SHIFT) - 1;
    for (m, o) in mine.iter_mut().zip(theirs) {
        if m[0] == o[0] {
            m[3] = m[3] & low | o[3] & !low;
        }
    }
}

/// What reads a cutout's alpha at a point of its texture: the material's opacity times its base texture's alpha,
/// bilinear between texel centres, repeated or clamped as the texture is.
pub struct Alpha<'a> {
    pub image: Option<&'a image::RgbaImage>,
    pub wrap: bool,
    pub opacity: f32,
    pub cutoff: f32,
}

impl Alpha<'_> {
    /// The texture's size in texels (one by one without a texture).
    pub fn texels(&self) -> Vec2 {
        self.image.map_or(Vec2::ONE, |i| Vec2::new(i.width() as f32, i.height() as f32))
    }

    /// Whether the material is there at `uv`: its alpha is at or above the cutoff (the kernel's `alpha_pass`).
    pub fn pass(&self, uv: Vec2) -> bool {
        let Some(img) = self.image else { return self.opacity >= self.cutoff };
        let (w, h) = (img.width() as i64, img.height() as i64);
        let p = uv * Vec2::new(w as f32, h as f32) - 0.5;
        let (x0, y0) = (p.x.floor(), p.y.floor());
        let (fx, fy) = (p.x - x0, p.y - y0);
        let at = |x: i64, y: i64| {
            let (x, y) = if self.wrap { (x.rem_euclid(w), y.rem_euclid(h)) } else { (x.clamp(0, w - 1), y.clamp(0, h - 1)) };
            img.get_pixel(x as u32, y as u32).0[3] as f32 / 255.0
        };
        let (x0, y0) = (x0 as i64, y0 as i64);
        let a = (at(x0, y0) * (1.0 - fx) + at(x0 + 1, y0) * fx) * (1.0 - fy) + (at(x0, y0 + 1) * (1.0 - fx) + at(x0 + 1, y0 + 1) * fx) * fy;
        a * self.opacity >= self.cutoff
    }
}

/// What a triangle's alpha left of it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kept {
    Whole,
    Nothing,
    Part,
}

/// The lattice's level for a triangle whose longest edge is `texels` long in its texture: cells about `cell` texels
/// across, `most` levels at most.
pub fn level_for(texels: f32, cell: f32, most: u32) -> u32 {
    if !(texels > cell) {
        return 0;
    }
    ((texels / cell).log2().ceil() as u32).min(most)
}

/// The cell of a lattice of `n` cells an edge that the point (u, v) of a triangle lies in (u towards its second
/// corner, v towards its third): row v, two cells a lattice square (the one at the square's origin, then the one
/// across its diagonal), a row holding 2 (n - row) - 1. The kernel's `cutout_cell` is the same.
pub fn cell_of(u: f32, v: f32, n: u32) -> u32 {
    let (x, y) = (u.clamp(0.0, 1.0) * n as f32, v.clamp(0.0, 1.0) * n as f32);
    let j = (y as u32).min(n - 1);
    let i = (x as u32).min(n - 1 - j);
    let across = (x - i as f32) + (y - j as f32) > 1.0 && i + j + 1 < n;
    j * (2 * n - j) + 2 * i + u32::from(across)
}

/// The state of cell `k` in a map's words.
pub fn cell_state(words: &[u32], k: u32) -> u32 {
    (words[(k / 16) as usize] >> ((k % 16) * 2)) & 3
}

/// The map of the triangle whose corners have the texture coordinates `uv`: its 4^level cells' states in
/// `cell_of`'s order. The alpha is read at the points of a lattice twice as fine: a cell has six of them, its
/// corners and its edges' middles, and they say whether it is all there or all gone. Of a cell that is a part, the
/// larger part is found at nine points more, the middles of its nine parts a third its width: five of nine, no tie.
/// (By the six alone, three of six for solid, a disc's cells came to 2 % more than its area; by the three middles,
/// two of three, to 5 % less where the disc was five cells across.)
pub fn map(uv: [Vec2; 3], alpha: &Alpha, level: u32) -> (Kept, Vec<u32>) {
    let n = 1usize << level;
    let m = 2 * n;
    // The fine lattice's points (i, j), i + j <= m, row by row.
    let row = |j: usize| j * (m + 1) - j * (j.max(1) - 1) / 2;
    let mut pass = vec![false; (m + 1) * (m + 2) / 2];
    let (e1, e2) = (uv[1] - uv[0], uv[2] - uv[0]);
    for j in 0..=m {
        for i in 0..=m - j {
            pass[row(j) + i] = alpha.pass(uv[0] + e1 * (i as f32 / m as f32) + e2 * (j as f32 / m as f32));
        }
    }
    let at = |i: usize, j: usize| pass[row(j) + i] as u32;
    let mut words = vec![0u32; (n * n).div_ceil(16)];
    let (mut solid, mut empty) = (0usize, 0usize);
    // How many of the nine points of the cell with the lattice corners a, b, c (fine lattice units) pass: its
    // thirds' six cells that stand as it does and three that stand the other way, each at its middle.
    let inside = |a: (f32, f32), b: (f32, f32), c: (f32, f32)| -> u32 {
        let at = |s: f32, t: f32| {
            let (x, y) = (a.0 + (b.0 - a.0) * s + (c.0 - a.0) * t, a.1 + (b.1 - a.1) * s + (c.1 - a.1) * t);
            alpha.pass(uv[0] + e1 * (x / m as f32) + e2 * (y / m as f32)) as u32
        };
        let mut count = 0;
        for q in 0..3 {
            for p in 0..3 - q {
                count += at((p as f32 + 1.0 / 3.0) / 3.0, (q as f32 + 1.0 / 3.0) / 3.0);
                if p + q < 2 {
                    count += at((p as f32 + 2.0 / 3.0) / 3.0, (q as f32 + 2.0 / 3.0) / 3.0);
                }
            }
        }
        count
    };
    let mut put = |k: usize, six: u32, corners: [(usize, usize); 3]| {
        let state = match six {
            0 => CELL_EMPTY,
            6 => CELL_SOLID,
            _ => {
                let c = corners.map(|(x, y)| (x as f32, y as f32));
                if inside(c[0], c[1], c[2]) >= 5 {
                    CELL_PART_SOLID
                } else {
                    CELL_PART_EMPTY
                }
            }
        };
        solid += usize::from(state == CELL_SOLID);
        empty += usize::from(state == CELL_EMPTY);
        words[k / 16] |= state << ((k % 16) * 2);
    };
    for j in 0..n {
        for i in 0..n - j {
            // The cell at the square's origin: corners (2i, 2j), (2i + 2, 2j), (2i, 2j + 2); the one across its
            // diagonal: (2i + 2, 2j + 2), (2i, 2j + 2), (2i + 2, 2j). Each with its three edges' middles.
            let (a, b) = (2 * i, 2 * j);
            let k = j * (2 * n - j) + 2 * i;
            put(k, at(a, b) + at(a + 2, b) + at(a, b + 2) + at(a + 1, b) + at(a, b + 1) + at(a + 1, b + 1), [(a, b), (a + 2, b), (a, b + 2)]);
            if i + j + 1 < n {
                put(k + 1, at(a + 2, b + 2) + at(a, b + 2) + at(a + 2, b) + at(a + 1, b + 2) + at(a + 2, b + 1) + at(a + 1, b + 1), [(a + 2, b + 2), (a, b + 2), (a + 2, b)]);
            }
        }
    }
    let kept = if solid == n * n {
        Kept::Whole
    } else if empty == n * n {
        Kept::Nothing
    } else {
        Kept::Part
    };
    (kept, words)
}

/// What of a material a map is made from: its base texture, how the texture coordinates are placed in it, its
/// opacity and its cutoff. `None`: no map can be made (a material function may change the opacity).
pub fn map_key(m: &GpuMaterial) -> Option<[u32; 7]> {
    (m.tex1[3] <= 0).then(|| [m.tex0[0] as u32, m.uv[0].to_bits(), m.uv[1].to_bits(), m.uv2[0].to_bits(), m.uv2[1].to_bits(), m.base_color[3].to_bits(), m.uv2[3].to_bits()])
}

/// The scene's cutout maps: the stream, and what each run was made from (`map_key`: a material edited since is no
/// longer the maps', live/edits.rs `forget_stale_maps`).
#[derive(Default)]
pub struct Maps {
    pub words: Vec<u32>,
    pub runs: HashMap<u32, [u32; 7]>,
}

/// The scene's cutout maps, each cutout row's run set in the row (`row_run`). After the rows are laid out (lib.rs
/// `prepare_as`); a row that had a run loses it when no map can be made for it now.
pub fn maps(sc: &mut Scene) -> Maps {
    let mut words: Vec<u32> = vec![];
    // A run a (mesh, section, material as `map_key`); a map a (texture coordinates, material); a map's words once.
    let mut runs: HashMap<(u32, u32, [u32; 7]), u32> = HashMap::new();
    let mut alike: HashMap<([u32; 6], [u32; 7]), u32> = HashMap::new();
    let mut shared: HashMap<Vec<u32>, u32> = HashMap::new();
    for k in 0..sc.instances.len() {
        let (mesh_k, first_row) = (sc.instances[k].mesh, sc.instances[k].rows as usize);
        let mesh = sc.meshes[mesh_k as usize];
        for si in 0..mesh.sect_count as usize {
            let Some(row) = sc.rows.get(first_row + si).copied() else { continue };
            let clear = row[3] & ((1 << ROW_RUN_SHIFT) - 1);
            sc.rows[first_row + si][3] = clear;
            if row[0] & ROW_CUTOUT == 0 {
                continue;
            }
            let Some(m) = sc.materials.get((row[0] & ROW_MATERIAL) as usize) else { continue };
            let Some(key) = map_key(m) else { continue };
            let sec = sc.sections[mesh.sect_first as usize + si];
            let run = match runs.get(&(mesh_k, si as u32, key)) {
                Some(&r) => r,
                None => {
                    let tex = (m.tex0[0] >= 0).then(|| sc.textures.get(m.tex0[0] as usize)).flatten();
                    let alpha = Alpha { image: tex.map(|t| &*t.rgba), wrap: tex.is_some_and(|t| t.wrap), opacity: m.base_color[3], cutoff: m.uv2[3] };
                    let (texels, repeat, offset) = (alpha.texels(), Vec2::new(m.uv[0], m.uv[1]), Vec2::new(m.uv2[0], m.uv2[1]));
                    let tris = (mesh.first + sec.first) as usize..(mesh.first + sec.first + sec.count) as usize;
                    let raw: Vec<[f32; 6]> = sc.pool_attrs[tris].iter().map(|a| [a.n0[3], a.n1[3], a.n2[3], a.uv[0], a.uv[1], a.uv[2]]).collect();
                    // The triangles whose map is not made yet, each once.
                    let mut todo: Vec<[f32; 6]> = vec![];
                    let mut queued: std::collections::HashSet<[u32; 6]> = Default::default();
                    for r in &raw {
                        let bits = r.map(f32::to_bits);
                        if !alike.contains_key(&(bits, key)) && queued.insert(bits) {
                            todo.push(*r);
                        }
                    }
                    let made: Vec<(Kept, u32, Vec<u32>)> = todo
                        .par_iter()
                        .map(|r| {
                            let uv = [Vec2::new(r[0], r[1]), Vec2::new(r[2], r[3]), Vec2::new(r[4], r[5])].map(|c| c * repeat + offset);
                            let edge = [uv[1] - uv[0], uv[2] - uv[1], uv[0] - uv[2]].iter().map(|e| (*e * texels).length()).fold(0.0f32, f32::max);
                            let level = level_for(edge, CELL, LEVELS);
                            let (kept, map) = map(uv, &alpha, level);
                            (kept, level, map)
                        })
                        .collect();
                    for (r, (kept, level, map)) in todo.iter().zip(made) {
                        let word = match kept {
                            Kept::Whole => WHOLE,
                            Kept::Nothing => NOTHING,
                            // (A triangle of one cell that is a part: what its low bit says.)
                            Kept::Part if level == 0 => [NOTHING, WHOLE][(cell_state(&map, 0) & 1) as usize],
                            Kept::Part => {
                                let at = *shared.entry(map).or_insert_with_key(|map| {
                                    let at = words.len() as u32;
                                    words.extend_from_slice(map);
                                    at
                                });
                                (at << 4) | level
                            }
                        };
                        alike.insert((r.map(f32::to_bits), key), word);
                    }
                    let run = words.len() as u32;
                    words.extend(raw.iter().map(|r| alike[&(r.map(f32::to_bits), key)]));
                    // (A map made before this run lies before it; one made for it too: the words above.)
                    runs.insert((mesh_k, si as u32, key), run);
                    run
                }
            };
            sc.rows[first_row + si][3] = clear | ((run + 1) << ROW_RUN_SHIFT);
        }
    }
    Maps { words, runs: runs.into_iter().map(|(k, run)| (run, k.2)).collect() }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn every_cell_of_a_lattice_is_reached_once() {
        for n in [1u32, 2, 4, 8, 16] {
            // (A point well inside each cell: a third of the way in from its corner, both ways.)
            let mut seen = vec![0u32; (n * n) as usize];
            for j in 0..n {
                for i in 0..n - j {
                    seen[cell_of((i as f32 + 0.3) / n as f32, (j as f32 + 0.3) / n as f32, n) as usize] += 1;
                    if i + j + 1 < n {
                        seen[cell_of((i as f32 + 0.7) / n as f32, (j as f32 + 0.7) / n as f32, n) as usize] += 1;
                    }
                }
            }
            assert!(seen.iter().all(|&c| c == 1), "n = {n}: {seen:?}");
        }
        // The triangle's corners and the middle of its far edge lie in cells of the lattice.
        for (u, v) in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.5, 0.5), (1.0, 1.0)] {
            assert!(cell_of(u, v, 8) < 64, "({u}, {v})");
        }
    }

    /// A texture with a disc of radius 0.3 about (0.4, 0.4).
    fn disc(size: u32) -> image::RgbaImage {
        image::RgbaImage::from_fn(size, size, |x, y| {
            let (dx, dy) = ((x as f32 + 0.5) / size as f32 - 0.4, (y as f32 + 0.5) / size as f32 - 0.4);
            image::Rgba([255, 255, 255, if dx * dx + dy * dy < 0.09 { 255 } else { 0 }])
        })
    }

    #[test]
    fn a_disc_keeps_its_area_and_its_place() {
        let img = disc(256);
        let alpha = Alpha { image: Some(&img), wrap: false, opacity: 1.0, cutoff: 0.5 };
        // A triangle over the texture and as much again: the disc lies inside it.
        let uv = [Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(0.0, 2.0)];
        for (level, tolerance) in [(5u32, 0.04f32), (7, 0.01)] {
            let n = 1u32 << level;
            let (kept, words) = map(uv, &alpha, level);
            assert_eq!(kept, Kept::Part);
            // The cells a ray takes for solid, against the disc's share of the triangle (its area is 2).
            let solid = (0..n * n).filter(|&k| cell_state(&words, k) & 1 == 1).count() as f32 / (n * n) as f32;
            let disc = std::f32::consts::PI * 0.09 / 2.0;
            assert!((solid / disc - 1.0).abs() < tolerance, "level {level}: {solid} of {disc}");
            // A point's cell says what the texture says there, away from the disc's rim.
            for (u, v, inside) in [(0.2, 0.2, true), (0.15, 0.2, true), (0.4, 0.4, false), (0.02, 0.6, false), (0.25, 0.15, true)] {
                let state = cell_state(&words, cell_of(u, v, n));
                assert_eq!(state, if inside { CELL_SOLID } else { CELL_EMPTY }, "level {level} at ({u}, {v})");
                assert_eq!(alpha.pass(uv[0] + (uv[1] - uv[0]) * u + (uv[2] - uv[0]) * v), inside);
            }
        }
    }

    #[test]
    fn a_solid_and_an_empty_triangle_have_no_map() {
        let img = image::RgbaImage::from_fn(8, 8, |x, _| image::Rgba([0, 0, 0, if x < 4 { 255 } else { 0 }]));
        let alpha = Alpha { image: Some(&img), wrap: false, opacity: 1.0, cutoff: 0.5 };
        assert_eq!(map([Vec2::new(0.1, 0.1), Vec2::new(0.3, 0.1), Vec2::new(0.1, 0.9)], &alpha, 3).0, Kept::Whole);
        assert_eq!(map([Vec2::new(0.7, 0.1), Vec2::new(0.9, 0.1), Vec2::new(0.7, 0.9)], &alpha, 3).0, Kept::Nothing);
        // Without a texture the opacity alone says.
        let plain = Alpha { image: None, wrap: false, opacity: 0.4, cutoff: 0.5 };
        assert_eq!(map([Vec2::ZERO, Vec2::X, Vec2::Y], &plain, 0).0, Kept::Nothing);
    }

    #[test]
    fn a_level_for_an_edge() {
        assert_eq!(level_for(1.0, 2.0, 7), 0);
        assert_eq!(level_for(2.0, 2.0, 7), 0);
        assert_eq!(level_for(3.0, 2.0, 7), 1);
        assert_eq!(level_for(64.0, 2.0, 7), 5);
        assert_eq!(level_for(2200.0, 2.0, 7), 7);
    }
}