Combine tiled lights with bit masks (#147)

Pack a global and per-tile bit mask for surfaces and halos. OR the masks and visit set bits in light order to preserve the existing accumulation and eliminate the per-pixel merge of sorted lists.

Verified with the HD unit suite, including HLSL translation and the coverage oracle. On Vulkan with an RTX 3060, the controlled 96-light scene repeated at roughly 63 FPS versus 61 FPS with the previous lists and DLSS active.

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-24 19:23:14 +03:00
parent 4215e89994
commit 0f77eb5c26
3 changed files with 182 additions and 297 deletions
+45 -84
View File
@@ -15,14 +15,14 @@ struct Light {
@group(0) @binding(9) var shadow_sampler: sampler_comparison;
@group(0) @binding(10) var lightmap: texture_2d<f32>;
@group(0) @binding(11) var linear: sampler;
// First 5 words: the start and length of the surface list and of the halo list of the lights that
// cover the whole screen, and the mask of the spot lights whose cone can show anywhere. Then, per
// tile of 16x16 pixels: where its surface list and its halo list start in this array and how long
// they are (4 words), the mask of the spot lights whose cone can show in the tile (the 5th word),
// then the lists of light indices. A length of 0xffffffff means every light.
// Each block has surface masks, halo masks and a spot mask, in that order.
// Block zero covers the full screen; blocks 1 and later correspond to 16×16 tiles.
@group(0) @binding(12) var<storage, read> tiles: array<u32>;
// The words before the tile headers (`tiles.rs::GLOBAL_WORDS`).
const TILE_HEADER_WORDS: u32 = 5u;
fn tile_mask_base(px: vec2<i32>, mask_words: u32) -> u32 {
let tile = (u32(px.y) >> 4u) * u32(frame.shadow.w) + (u32(px.x) >> 4u);
return (tile + 1u) * (2u * mask_words + 1u);
}
// Ambient occlusion at half resolution: x the occlusion (1 open), y the distance it was taken at.
@group(0) @binding(13) var ao_tex: texture_2d<f32>;
// The water pass's depth: the nearest water surface (0 where there is none).
@@ -313,11 +313,8 @@ fn shade_surface(px: vec2<i32>, p: vec3<f32>, water: bool) -> vec3<f32> {
let sun = frame.sun.xyz;
let sun_on = frame.sun.w;
let atmosphere = frame.sky_sun.w > 0.5;
let count = u32(frame.params.x);
let tile = TILE_HEADER_WORDS + ((u32(px.y) >> 4u) * u32(frame.shadow.w) + (u32(px.x) >> 4u)) * 5u;
let surface_start = tiles[tile];
let surface_all = tiles[tile + 1u] == 0xffffffffu;
let surface_count = select(tiles[tile + 1u], count, surface_all);
let mask_words = (u32(frame.params.x) + 31u) / 32u;
let tile = tile_mask_base(px, mask_words);
let n = normalize(textureLoad(normal_tex, px, 0).xyz);
let albedo = textureLoad(albedo_tex, px, 0);
let lm = textureLoad(light_tex, px, 0).xy;
@@ -373,45 +370,28 @@ fn shade_surface(px: vec2<i32>, p: vec3<f32>, water: bool) -> vec3<f32> {
}
var light = max(base * sky_tint * frame.ambient.x, block * frame.ambient.y) * ao_ambient + direct;
// The spot lights whose cone reaches this tile.
let spot_mask = tiles[tile + 4u] | tiles[4u];
let spot_word = 2u * mask_words;
let spot_mask = tiles[tile + spot_word] | tiles[spot_word];
for (var j = 0; j < i32(frame.vfog.w); j++) {
if ((spot_mask >> u32(j)) & 1u) != 0u {
light += spot_light(j, p, n) * ao_lights;
}
}
// The mods' lights.
// The tile's own list and the whole screen's are both in light order and share no light: walking
// them merged visits the lights in the order the full loop does, so the sum is the same.
let gs_start = tiles[0];
let gs_count = select(0u, tiles[1], !surface_all);
var a = 0u;
var b = 0u;
for (var k = 0u; k < surface_count + gs_count; k++) {
// A list past the buffer's room is every light, in order: the whole screen's are among them.
var index = k;
if !surface_all {
if a >= surface_count {
index = tiles[gs_start + b];
b += 1u;
} else if b >= gs_count {
index = tiles[surface_start + a];
a += 1u;
} else if tiles[surface_start + a] < tiles[gs_start + b] {
index = tiles[surface_start + a];
a += 1u;
} else {
index = tiles[gs_start + b];
b += 1u;
}
// OR the two masks and walk their bits in the same order as the source lights.
for (var word = 0u; word < mask_words; word++) {
var bits = tiles[word] | tiles[tile + word];
while bits != 0u {
let index = word * 32u + firstTrailingBit(bits);
bits = bits & (bits - 1u);
let l = lights[index];
let to = l.pos.xyz - p;
let dist = length(to);
if dist >= l.pos.w { continue; }
let window = pow(clamp(1.0 - pow(dist / l.pos.w, 4.0), 0.0, 1.0), 2.0);
let falloff = l.color.w / (dist * dist + 1.0) * window;
let k = max(dot(n, to / max(dist, 0.001)) * 0.85 + 0.15, 0.0);
light += l.color.rgb * falloff * k * ao_lights;
}
let l = lights[index];
let to = l.pos.xyz - p;
let dist = length(to);
if dist >= l.pos.w { continue; }
let window = pow(clamp(1.0 - pow(dist / l.pos.w, 4.0), 0.0, 1.0), 2.0);
let falloff = l.color.w / (dist * dist + 1.0) * window;
let k = max(dot(n, to / max(dist, 0.001)) * 0.85 + 0.15, 0.0);
light += l.color.rgb * falloff * k * ao_lights;
}
// Metal keeps most of its diffuse look (there is no environment map to light it with).
var out = surface_rgb * (1.0 - metal * 0.65) * light + albedo.rgb * albedo.a * 1.5;
@@ -475,11 +455,8 @@ fn fs_light(in: FullOut) -> LightOut {
let view_s = normalize(ps);
let sun = frame.sun.xyz;
let sun_on = frame.sun.w;
let count = u32(frame.params.x);
let tile = TILE_HEADER_WORDS + ((u32(px.y) >> 4u) * u32(frame.shadow.w) + (u32(px.x) >> 4u)) * 5u;
let halo_start = tiles[tile + 2u];
let halo_all = tiles[tile + 3u] == 0xffffffffu;
let halo_count = select(tiles[tile + 3u], count, halo_all);
let mask_words = (u32(frame.params.x) + 31u) / 32u;
let halo_start = tile_mask_base(px, mask_words) + mask_words;
frag_px = in.position.xy;
let atmosphere = frame.sky_sun.w > 0.5;
var c = scene;
@@ -571,41 +548,25 @@ fn fs_light(in: FullOut) -> LightOut {
air_s += spot_beams(view_s, beam_len, ign(in.position.xy));
}
var halos = vec3<f32>(0.0);
// As the surface lights above: the tile's halo list merged with the whole screen's.
let gh_start = tiles[2];
let gh_count = select(0u, tiles[3], !halo_all);
var a = 0u;
var b = 0u;
for (var k = 0u; k < halo_count + gh_count; k++) {
var index = k;
if !halo_all {
if a >= halo_count {
index = tiles[gh_start + b];
b += 1u;
} else if b >= gh_count {
index = tiles[halo_start + a];
a += 1u;
} else if tiles[halo_start + a] < tiles[gh_start + b] {
index = tiles[halo_start + a];
a += 1u;
} else {
index = tiles[gh_start + b];
b += 1u;
}
for (var word = 0u; word < mask_words; word++) {
var bits = tiles[mask_words + word] | tiles[halo_start + word];
while bits != 0u {
let index = word * 32u + firstTrailingBit(bits);
bits = bits & (bits - 1u);
let l = lights[index];
// Nearest point of the view ray to the light, and the glow along the ray in front of it.
let t0 = dot(l.pos.xyz, view_s);
let hh = length(l.pos.xyz - view_s * t0) + 0.5;
let reach = l.pos.w * 0.5;
if hh > reach { continue; }
let a0 = atan((0.0 - t0) / hh);
let a1 = atan((far - t0) / hh);
// It fades out before its reach: no hard edge round a bright light.
let fade = 1.0 - smoothstep(reach * 0.25, reach, hh);
// Thicker air glows more round a light, but only so far: the mist at dusk and many fires
// at once would otherwise wash the picture out.
halos += l.color.rgb * l.color.w * (a1 - a0) / hh * 0.004 * (0.3 + min(density * 300.0, 0.9)) * fade;
}
let l = lights[index];
// Nearest point of the view ray to the light, and the glow along the ray in front of it.
let t0 = dot(l.pos.xyz, view_s);
let hh = length(l.pos.xyz - view_s * t0) + 0.5;
let reach = l.pos.w * 0.5;
if hh > reach { continue; }
let a0 = atan((0.0 - t0) / hh);
let a1 = atan((far - t0) / hh);
// It fades out before its reach: no hard edge round a bright light.
let fade = 1.0 - smoothstep(reach * 0.25, reach, hh);
// Thicker air glows more round a light, but only so far: the mist at dusk and many fires
// at once would otherwise wash the picture out.
halos += l.color.rgb * l.color.w * (a1 - a0) / hh * 0.004 * (0.3 + min(density * 300.0, 0.9)) * fade;
}
// However many blasts at once: a glow in the air, never a white wall.
air_s += halos / (1.0 + max(max(halos.r, halos.g), halos.b) / 1.2);
+4 -7
View File
@@ -24,7 +24,7 @@
//! - The sun is the light `frame::light_of` picks (moon at night), in `HdFrame.sun`.
//! - Bind groups are cached per (world views, lightmap) and per volumetric-history flip.
use super::frame::{HdLight, HdSpot};
use super::tiles::{TILE, tile_lists, tiles_buffer};
use super::tiles::{TILE, tile_masks, tiles_buffer};
use super::{
DEPTH, FLOAT, HDR, Hd, SAMPLER, SHADOW_ARRAY, SHADOW_SAMPLER, STORAGE, UNFILTERED, UNIFORM,
entries, module, stamp, target,
@@ -78,10 +78,9 @@ pub(super) struct Lighting {
/// Bind groups, keyed by the views they read; one per volumetric-history flip.
group: [Option<(LightKey, wgpu::BindGroup)>; 2],
lights: wgpu::Buffer,
/// The tiles' light lists (see `tile_lists`), sized for the screen, and the tiles per row.
/// The tiles' light masks (see `tile_masks`), sized for the screen, and the tiles per row.
tiles: wgpu::Buffer,
pub(super) tiles_x: u32,
tile_scratch: Vec<Vec<u16>>,
tile_words: Vec<u32>,
}
@@ -142,7 +141,6 @@ impl Lighting {
lights,
tiles: tiles_buffer(device, [1, 1]),
tiles_x: 1,
tile_scratch: Vec::new(),
tile_words: Vec::new(),
}
}
@@ -169,13 +167,12 @@ impl Lighting {
if n > 0 {
queue.write_buffer(&self.lights, 0, bytemuck::cast_slice(&lights[..n]));
}
// Written every frame, empty too: the shader reads the counts, not `params.x`.
tile_lists(
// Written every frame, including the spot masks when there are no point lights.
tile_masks(
view_proj,
&lights[..n],
spots,
size,
&mut self.tile_scratch,
&mut self.tile_words,
);
queue.write_buffer(&self.tiles, 0, bytemuck::cast_slice(&self.tile_words));
+133 -206
View File
@@ -1,56 +1,31 @@
//! Light tiles: for every 16x16 pixel tile of the world target, the short lists of the mods' point
//! lights that can reach it, so `fs_light` loops over a few lights instead of all of them.
//! Light masks for the 16×16 pixel tiles of the HD world target.
//!
//! Contract: a storage buffer of `u32`. First `GLOBAL_WORDS` (5) words: the start and length of the
//! surface list and of the halo list of the lights that cover the whole screen, and the mask of the
//! spot lights whose cone can show anywhere. Then, per tile, `TILE_WORDS` (5) words (surface list
//! start, surface length, halo list start, halo length, spot mask), then the index lists. A light
//! that covers the whole screen (its box crosses the camera's plane, or holds the camera) is in the
//! one global list of its kind, not in every tile's: the shader merges a tile's list with the global
//! one, both in light order, so the sum is the one of the full loop. The spot mask has bit `j` set
//! when spot light `j`'s cone can show in the tile (its bounds, apex and the square round its far
//! cap, projected); the spots light surfaces and draw their beams only where it is set. A length of
//! `EVERY_LIGHT` (0xffffffff) means "all lights" (the list overflowed `TILE_INDICES`). Light
//! positions are camera-relative and the cover test uses the *jittered* view-projection the world
//! was drawn with. Rebuilt on the CPU every frame (an empty one too: the shader reads the counts,
//! not `params.x`) and sized at `resize`.
//! The first block of words covers the whole screen and each tile has an identical block:
//! `ceil(light_count / 32)` words for surface lights, the same number for halos, then one
//! spot mask. A light whose projected bounds cross the camera plane goes in the first block
//! once. The shader ORs both masks and enumerates set bits in ascending light order.
//! Coverage uses the same jittered view-projection as the rendered world.
use super::frame::{HdLight, HdSpot};
use super::lighting::MAX_LIGHTS;
use glam::Mat4;
use std::sync::atomic::{AtomicBool, Ordering};
/// Words of a tile's header.
pub(super) const TILE_WORDS: usize = 5;
/// Words before the tile headers: the whole screen's two lists (start, length each) and spot mask.
pub(super) const GLOBAL_WORDS: usize = 5;
/// The side (pixels) of a tile of the screen with its own short list of lights.
pub(super) const TILE: u32 = 16;
/// The indices all the tile lists may hold together; a tile past it loops over every light. Five
/// hundred lights round the camera keep about 0.6 million; the whole screen's lists are not in it.
const TILE_INDICES: usize = 1 << 22;
/// A list length that means "every light": the list overflowed.
const EVERY_LIGHT: u32 = u32::MAX;
/// Where the whole screen's lists and mask lie in the buffer.
const GLOBAL_SURFACE: usize = 0;
const GLOBAL_HALO: usize = 2;
const GLOBAL_SPOTS: usize = 4;
/// Diagnostics only (`HORIZON_HD_LIGHT_TILES=0`, then the `light-tiles` control command): no
/// tile list, every pixel takes every light and every spot, the shader's whole-list path. A
/// still with and without it tells a wrong tile list from any other difference.
static UNTILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Diagnostics: use every light and spot in every tile.
static UNTILED: AtomicBool = AtomicBool::new(false);
/// The diagnostic runtime toggle: on is no tile list.
pub fn set_untiled(on: bool) {
UNTILED.store(on, std::sync::atomic::Ordering::Relaxed);
UNTILED.store(on, Ordering::Relaxed);
}
/// The global words, the tiles' headers and every index list for a screen of `size`.
pub(super) fn tiles_buffer(device: &wgpu::Device, size: [u32; 2]) -> wgpu::Buffer {
let tiles = (size[0].div_ceil(TILE).max(1) * size[1].div_ceil(TILE).max(1)) as usize;
let words = GLOBAL_WORDS + tiles * TILE_WORDS + TILE_INDICES + 2 * MAX_LIGHTS;
let stride = 2 * MAX_LIGHTS.div_ceil(32) + 1;
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HD light tiles"),
size: (words * std::mem::size_of::<u32>()) as u64,
label: Some("HD light masks"),
size: ((tiles + 1) * stride * std::mem::size_of::<u32>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
@@ -134,163 +109,98 @@ fn spot_hull(s: &HdSpot) -> [glam::Vec3; 5] {
]
}
/// Fills `words` with each 16x16 tile's two lists of the lights that can reach it, and the whole
/// screen's two (the contract at the top of this file). A length of `EVERY_LIGHT` stands for all
/// of `lights` (a list past the buffer's room). The surface list holds the lights whose sphere
/// can touch what the tile sees. The halo list holds the lights whose halo can reach a ray of
/// the tile: the shader adds a halo for the view *line* passing within half the radius of the
/// light, so a ray pointing away from a light behind it is lit too, and the mirrored sphere is
/// covered as well. Lights stay in order, so the sums are the ones of the full loop.
pub(super) fn tile_lists(
/// Populates the surface and halo masks. Halos illuminate a view line, so their masks also
/// include the mirrored sphere behind the camera. OR makes overlaps idempotent.
pub(super) fn tile_masks(
view_proj: &Mat4,
lights: &[HdLight],
spots: &[HdSpot],
size: [u32; 2],
scratch: &mut Vec<Vec<u16>>,
words: &mut Vec<u32>,
) {
let tx = size[0].div_ceil(TILE).max(1) as usize;
let ty = size[1].div_ceil(TILE).max(1) as usize;
let tiles = tx * ty;
// Two lists per tile, then the whole screen's two.
scratch.resize_with(tiles * 2 + 2, Vec::new);
scratch.truncate(tiles * 2 + 2);
scratch.iter_mut().for_each(Vec::clear);
let global = |list: usize| tiles * 2 + list;
let mut add = |list: usize, area: Cover, light: u16| match area {
let mask_words = lights.len().div_ceil(32);
let spot_word = 2 * mask_words;
let stride = spot_word + 1;
words.clear();
words.resize((tx * ty + 1) * stride, 0);
if UNTILED.load(Ordering::Relaxed) {
fill_global_masks(&mut words[..stride], lights.len());
return;
}
let from = |v: f32, n: usize| ((v / TILE as f32).floor().max(0.0) as usize).min(n - 1);
let mut set = |word: usize, bit: u32, area: Cover| match area {
Cover::Nothing => {}
Cover::Everywhere => scratch[global(list)].push(light),
Cover::Everywhere => words[word] |= bit,
Cover::Rect([x0, y0, x1, y1]) => {
let tile = TILE as f32;
if x1 < 0.0 || y1 < 0.0 || x0 >= size[0] as f32 || y0 >= size[1] as f32 {
return;
}
let from = |v: f32, n: usize| ((v / tile).floor().max(0.0) as usize).min(n - 1);
for y in from(y0, ty)..=from(y1, ty) {
for x in from(x0, tx)..=from(x1, tx) {
scratch[(y * tx + x) * 2 + list].push(light);
words[(y * tx + x + 1) * stride + word] |= bit;
}
}
}
};
for (i, l) in lights.iter().enumerate() {
let c = glam::Vec3::new(l.pos[0], l.pos[1], l.pos[2]);
add(0, cover(view_proj, c, l.pos[3], size), i as u16);
// The shader's halo reach: the line within `radius / 2 - 0.5` of the light.
let word = i / 32;
let bit = 1u32 << (i % 32);
set(word, bit, cover(view_proj, c, l.pos[3], size));
let reach = l.pos[3] * 0.5 - 0.5;
if reach > 0.0 || !reach.is_finite() {
let a = cover(view_proj, c, reach, size);
let b = cover(view_proj, -c, reach, size);
// Either sphere covering the whole screen names the light for every tile: once, in
// the global list, never in a tile's as well (the merge would light it twice).
if matches!(a, Cover::Everywhere) || matches!(b, Cover::Everywhere) {
add(1, Cover::Everywhere, i as u16);
set(mask_words + word, bit, Cover::Everywhere);
} else {
add(1, a, i as u16);
add(1, b, i as u16);
set(mask_words + word, bit, a);
set(mask_words + word, bit, b);
}
}
}
words.clear();
words.resize(GLOBAL_WORDS + tiles * TILE_WORDS, 0);
let mut global_spots = 0u32;
// The spots' masks: a bit per spot in every tile its cone's bounds can reach.
for (j, s) in spots.iter().take(32).enumerate() {
let tile = TILE as f32;
let area = cover_points(view_proj, &spot_hull(s), size);
let from = |v: f32, n: usize| ((v / tile).floor().max(0.0) as usize).min(n - 1);
match area {
Cover::Nothing => {}
Cover::Everywhere => global_spots |= 1 << j,
Cover::Rect([x0, y0, x1, y1]) => {
if x1 < 0.0 || y1 < 0.0 || x0 >= size[0] as f32 || y0 >= size[1] as f32 {
continue;
}
for y in from(y0, ty)..=from(y1, ty) {
for x in from(x0, tx)..=from(x1, tx) {
words[GLOBAL_WORDS + (y * tx + x) * TILE_WORDS + 4] |= 1 << j;
}
}
}
}
}
let mut room = TILE_INDICES;
for t in 0..tiles {
for list in 0..2 {
let ids = &mut scratch[t * 2 + list];
// Both the sphere and its mirror can name a light: once is enough.
ids.dedup();
let at = GLOBAL_WORDS + t * TILE_WORDS + list * 2;
if ids.len() > room {
words[at + 1] = EVERY_LIGHT;
} else {
room -= ids.len();
words[at] = words.len() as u32;
words[at + 1] = ids.len() as u32;
words.extend(ids.iter().map(|&i| u32::from(i)));
}
}
}
// The whole screen's lists: each of their lights once, in order.
for (which, list) in [(GLOBAL_SURFACE, 0), (GLOBAL_HALO, 1)] {
let ids = &scratch[global(list)];
words[which] = words.len() as u32;
words[which + 1] = ids.len() as u32;
words.extend(ids.iter().map(|&i| u32::from(i)));
}
words[GLOBAL_SPOTS] = global_spots;
if UNTILED.load(std::sync::atomic::Ordering::Relaxed) {
untile(words, tiles);
set(
spot_word,
1u32 << j,
cover_points(view_proj, &spot_hull(s), size),
);
}
}
/// The diagnostic's form of the lists: every tile's two lists are "all lights" and every spot
/// shows in every tile.
fn untile(words: &mut [u32], tiles: usize) {
for t in 0..tiles {
let at = GLOBAL_WORDS + t * TILE_WORDS;
words[at + 1] = EVERY_LIGHT;
words[at + 3] = EVERY_LIGHT;
words[at + 4] = u32::MAX;
fn fill_global_masks(global: &mut [u32], count: usize) {
let mask_words = count.div_ceil(32);
for word in 0..mask_words {
let bits = u32::MAX >> (32 - (count - word * 32).min(32));
global[word] = bits;
global[mask_words + word] = bits;
}
words[GLOBAL_SPOTS] = u32::MAX;
global[mask_words * 2] = u32::MAX;
}
#[cfg(test)]
mod tests {
use super::*;
/// What the shader walks for a tile: its own list merged with the whole screen's, in light order.
/// A list that fell back to every light is a failure here.
fn merged(words: &[u32], tile: usize, which: usize) -> Vec<u32> {
let list = |start: usize, len: usize| words[start..start + len].to_vec();
let at = GLOBAL_WORDS + tile * TILE_WORDS + which * 2;
assert_ne!(words[at + 1], EVERY_LIGHT, "tile {tile}, list {which}: past the room");
let own = list(words[at] as usize, words[at + 1] as usize);
let all = list(words[which * 2] as usize, words[which * 2 + 1] as usize);
let (mut i, mut j, mut out) = (0, 0, Vec::new());
while i < own.len() || j < all.len() {
let take_own = j >= all.len() || (i < own.len() && own[i] < all[j]);
if take_own {
out.push(own[i]);
i += 1;
} else {
out.push(all[j]);
j += 1;
fn list(words: &[u32], count: usize, block: usize, which: usize, global: bool) -> Vec<u32> {
let mask_words = count.div_ceil(32);
let at = block * (2 * mask_words + 1) + which * mask_words;
let mut indices = Vec::new();
for word in 0..mask_words {
let mut bits = words[at + word];
if global {
bits |= words[which * mask_words + word];
}
while bits != 0 {
indices.push(word as u32 * 32 + bits.trailing_zeros());
bits &= bits - 1;
}
}
out
}
/// The tile's own list, without the whole screen's.
fn own(words: &[u32], tile: usize, which: usize) -> Vec<u32> {
let at = GLOBAL_WORDS + tile * TILE_WORDS + which * 2;
words[words[at] as usize..words[at] as usize + words[at + 1] as usize].to_vec()
}
/// The whole screen's list of a kind.
fn global(words: &[u32], which: usize) -> Vec<u32> {
words[words[which * 2] as usize..words[which * 2] as usize + words[which * 2 + 1] as usize].to_vec()
indices
}
#[test]
@@ -308,22 +218,25 @@ mod tests {
light(0.0, 0.0, 10.0, 8.0),
light(1.0, 0.0, 0.0, 6.0),
];
let (mut scratch, mut words) = (Vec::new(), Vec::new());
tile_lists(&proj, &lights, &[], size, &mut scratch, &mut words);
let mut words = Vec::new();
tile_masks(&proj, &lights, &[], size, &mut words);
// The centre tile sees the first light and the one at the camera, in both lists.
let centre = 5 * 20 + 10;
assert_eq!(merged(&words, centre, 0), vec![0, 3]);
assert!(merged(&words, centre, 1).contains(&0) && merged(&words, centre, 1).contains(&3));
assert_eq!(list(&words, lights.len(), centre + 1, 0, true), vec![0, 3]);
assert!(
list(&words, lights.len(), centre + 1, 1, true).contains(&0)
&& list(&words, lights.len(), centre + 1, 1, true).contains(&3)
);
// A far corner sees only the one at the camera.
assert_eq!(merged(&words, 0, 0), vec![3]);
assert_eq!(list(&words, lights.len(), 1, 0, true), vec![3]);
// The light behind the camera shows in the halo list where the view points away.
assert!(merged(&words, centre, 1).contains(&2));
assert!(!merged(&words, 0, 0).contains(&2));
assert!(list(&words, lights.len(), centre + 1, 1, true).contains(&2));
assert!(!list(&words, lights.len(), 1, 0, true).contains(&2));
// The one at the camera covers the whole screen: once in the global list, in no tile's own.
assert_eq!(own(&words, centre, 0), vec![0]);
assert_eq!(own(&words, 0, 0), Vec::<u32>::new());
assert_eq!(global(&words, 0), vec![3]);
assert_eq!(words[GLOBAL_SPOTS], 0);
assert_eq!(list(&words, lights.len(), centre + 1, 0, false), vec![0]);
assert_eq!(list(&words, lights.len(), 1, 0, false), Vec::<u32>::new());
assert_eq!(list(&words, lights.len(), 0, 0, false), vec![3]);
assert_eq!(words[2], 0);
}
#[test]
@@ -346,10 +259,10 @@ mod tests {
// From the camera, wide: everywhere.
spot([0.0, 0.0, 0.0], [0.0, 0.0, -1.0], 80.0, 0.5),
];
let (mut scratch, mut words) = (Vec::new(), Vec::new());
tile_lists(&proj, &[], &spots, size, &mut scratch, &mut words);
let mut words = Vec::new();
tile_masks(&proj, &[], &spots, size, &mut words);
// The mask a tile's pixels see: its own and the whole screen's.
let mask = |tile: usize| words[GLOBAL_WORDS + tile * TILE_WORDS + 4] | words[GLOBAL_SPOTS];
let mask = |tile: usize| words[tile + 1] | words[0];
let centre = 5 * 20 + 10;
assert_eq!(mask(centre) & 1, 1);
assert_eq!(mask(0) & 1, 0);
@@ -357,7 +270,7 @@ mod tests {
assert_eq!(mask(centre) & 4, 0);
assert_eq!(mask(centre) & 8, 8);
assert_eq!(mask(0) & 8, 8);
assert_eq!(words[GLOBAL_SPOTS], 8);
assert_eq!(words[0], 8);
}
#[test]
@@ -365,39 +278,52 @@ mod tests {
let size = [320, 160];
let proj = Mat4::perspective_rh(1.0, 2.0, 0.05, 1000.0);
let lights = [
HdLight { pos: [0.0, 0.0, -20.0, 4.0], color: [1.0; 4] },
HdLight { pos: [30.0, 0.0, -5.0, 4.0], color: [1.0; 4] },
HdLight { pos: [1.0, 0.0, 0.0, 6.0], color: [1.0; 4] },
HdLight {
pos: [0.0, 0.0, -20.0, 4.0],
color: [1.0; 4],
},
HdLight {
pos: [30.0, 0.0, -5.0, 4.0],
color: [1.0; 4],
},
HdLight {
pos: [1.0, 0.0, 0.0, 6.0],
color: [1.0; 4],
},
];
let (mut scratch, mut words) = (Vec::new(), Vec::new());
tile_lists(&proj, &lights, &[], size, &mut scratch, &mut words);
let mut words = Vec::new();
tile_masks(&proj, &lights, &[], size, &mut words);
// Tiled: a corner tile has fewer lights than there are.
assert!(merged(&words, 0, 0).len() < lights.len());
untile(&mut words, 20 * 10);
// As the shader reads it: both lists of every tile are all the lights (its whole screen's
// are not added again), and every spot's bit is set.
for t in 0..20 * 10 {
let at = GLOBAL_WORDS + t * TILE_WORDS;
assert_eq!((words[at + 1], words[at + 3], words[at + 4]), (EVERY_LIGHT, EVERY_LIGHT, u32::MAX));
assert!(list(&words, lights.len(), 1, 0, true).len() < lights.len());
fill_global_masks(&mut words[..3], lights.len());
for tile in 0..20 * 10 {
for which in 0..2 {
assert_eq!(list(&words, lights.len(), tile + 1, which, true), [0, 1, 2]);
}
assert_eq!(words[(tile + 1) * 3 + 2] | words[2], u32::MAX);
}
assert_eq!(words[GLOBAL_SPOTS], u32::MAX);
let mut partial = [0u32; 5];
fill_global_masks(&mut partial, 33);
assert_eq!(partial, [u32::MAX, 1, u32::MAX, 1, u32::MAX]);
}
/// Five hundred lights round the camera, like a raid: every tile's merged list is exactly the
/// lights that can reach it, once and in order (what one list per tile held before the whole
/// screen's lights got their own), and no list falls back to every light.
/// Masks match the projected coverage on every tile and preserve accumulation order.
#[test]
fn a_raid_round_the_camera_lists_each_tile_its_lights_in_order_and_inside_the_room() {
fn large_light_set_matches_projected_coverage_in_order() {
let size = [1920u32, 1080];
let (tx, ty) = ((size[0] / TILE) as usize, (size[1] / TILE) as usize);
let (tx, ty) = (
size[0].div_ceil(TILE) as usize,
size[1].div_ceil(TILE) as usize,
);
let proj = Mat4::perspective_rh((70.0f32).to_radians(), 16.0 / 9.0, 0.05, 1000.0);
let mut x = 0x9e37_79b9_7f4a_7c15u64;
let mut rnd = move || {
x = x.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
x = x
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((x >> 33) as f32) / (1u64 << 31) as f32
};
// The mod's radii: tracers and small flames, geran and reentry and fires, blasts, flares
// and a blast's punch; all round the camera.
// A mix of small and large lights around the camera, with some covering the whole screen.
let lights: Vec<HdLight> = (0..500)
.map(|i| {
let radius = match i % 10 {
@@ -407,13 +333,18 @@ mod tests {
_ => 110.0 + rnd() * 146.0,
};
HdLight {
pos: [(rnd() - 0.5) * 600.0, rnd() * 120.0 - 30.0, (rnd() - 0.5) * 600.0, radius],
pos: [
(rnd() - 0.5) * 600.0,
rnd() * 120.0 - 30.0,
(rnd() - 0.5) * 600.0,
radius,
],
color: [1.0; 4],
}
})
.collect();
let (mut scratch, mut words) = (Vec::new(), Vec::new());
tile_lists(&proj, &lights, &[], size, &mut scratch, &mut words);
let mut words = Vec::new();
tile_masks(&proj, &lights, &[], size, &mut words);
let inside = |area: Cover, t: usize| match area {
Cover::Nothing => false,
@@ -422,7 +353,8 @@ mod tests {
if x1 < 0.0 || y1 < 0.0 || x0 >= size[0] as f32 || y0 >= size[1] as f32 {
return false;
}
let from = |v: f32, n: usize| ((v / TILE as f32).floor().max(0.0) as usize).min(n - 1);
let from =
|v: f32, n: usize| ((v / TILE as f32).floor().max(0.0) as usize).min(n - 1);
from(y0, ty) <= t / tx
&& t / tx <= from(y1, ty)
&& from(x0, tx) <= t % tx
@@ -449,28 +381,23 @@ mod tests {
}
// The mix has whole-screen lights, or the global lists would not be exercised.
assert!(whole_screen > 20, "{whole_screen} whole-screen covers");
let mut longest = 0;
for t in 0..tx * ty {
for which in 0..2 {
let expected: Vec<u32> = (0..lights.len() as u32)
.filter(|&i| {
let (s, a, b) = covers[i as usize];
if which == 0 { inside(s, t) } else { inside(a, t) || inside(b, t) }
if which == 0 {
inside(s, t)
} else {
inside(a, t) || inside(b, t)
}
})
.collect();
let got = merged(&words, t, which);
longest = longest.max(got.len());
let got = list(&words, lights.len(), t + 1, which, true);
assert_eq!(got, expected, "tile {t}, list {which}");
}
}
for which in 0..2 {
let g = global(&words, which);
assert!(g.windows(2).all(|w| w[0] < w[1]), "global list {which} is not in light order");
}
// The tile lists take a small part of the old room (1 << 19): the whole-screen lights no
// longer fill it a tile at a time.
let stored = words.len() - GLOBAL_WORDS - tx * ty * TILE_WORDS
- global(&words, 0).len() - global(&words, 1).len();
assert!(stored < 1 << 19, "{stored} tile indices; longest merged list {longest}");
let stride = 2 * lights.len().div_ceil(32) + 1;
assert_eq!(words.len(), (tx * ty + 1) * stride);
}
}