mod bounds;
pub use bounds::SceneBoundsError;
use std::borrow::Cow;
use crcbl_hal::HalError;
use crcbl_shaders::cluster_dag::ClusterDag;
use crcbl_shaders::mesh;
use crcbl_shaders::meshlet::MeshClusters;
use crcbl_shaders::probe;
use crcbl_shaders::vertex::UvRange;
use glam::Mat4;
pub const PYRAMID_TINT: [f32; 4] = [0.15, 0.45, 1.0, 1.0];
pub const PYRAMID_ROUGHNESS: f32 = 0.25;
pub const PAGE_EXTENT: u32 = 2;
const PAGE_LAYER_BYTES: usize = (PAGE_EXTENT * PAGE_EXTENT) as usize * 4;
pub const CHECKER_LAYER: u32 = 0;
pub const CHECKER_TEXELS: [u8; PAGE_LAYER_BYTES] = [
0xFF, 0xFF, 0xFF, 0xFF, 0xB0, 0xB0, 0xB0, 0xFF, 0x70, 0x70, 0x70, 0xFF, 0x30, 0x30, 0x30, 0xFF, ];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Capacities {
pub vertices: u32,
pub indices: u32,
pub meshes: u32,
pub instances: u32,
pub materials: u32,
pub lights: u32,
pub probes: u32,
}
impl Default for Capacities {
fn default() -> Self {
Self {
vertices: 64 * 1024,
indices: 256 * 1024,
meshes: 1024,
instances: 16 * 1024,
materials: 1024,
lights: 1024,
probes: 0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PageKind {
BaseColor,
Normal,
MetallicRoughnessOcclusion,
Emissive,
}
impl PageKind {
pub const ALL: [Self; 4] = [
Self::BaseColor,
Self::Normal,
Self::MetallicRoughnessOcclusion,
Self::Emissive,
];
#[must_use]
pub const fn index(self) -> usize {
match self {
Self::BaseColor => 0,
Self::Normal => 1,
Self::MetallicRoughnessOcclusion => 2,
Self::Emissive => 3,
}
}
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::BaseColor => "base-colour",
Self::Normal => "normal",
Self::MetallicRoughnessOcclusion => "metallic-roughness-occlusion",
Self::Emissive => "emissive",
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Page<'a> {
extent: u32,
layers: Vec<Cow<'a, [u8]>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PageDesc<'a> {
pages: [Page<'a>; PageKind::ALL.len()],
}
impl<'a> PageDesc<'a> {
pub const WHITE: u8 = 0xFF;
pub const NEUTRAL_NORMAL: [u8; 4] = [0x80, 0x80, 0xFF, 0xFF];
#[must_use]
pub fn empty() -> Self {
Self::default()
}
pub fn set_extent(&mut self, kind: PageKind, extent: u32) {
assert!(extent > 0, "a page must have at least one texel a side");
let page = &mut self.pages[kind.index()];
assert!(
page.layers.is_empty(),
"the {} page already holds {} layer(s) authored at {} texels a side",
kind.label(),
page.layers.len(),
page.extent
);
page.extent = extent;
}
pub fn push_layer(&mut self, kind: PageKind, texels: impl Into<Cow<'a, [u8]>>) -> u32 {
let page = &mut self.pages[kind.index()];
assert!(
page.extent > 0,
"the {} page has no extent, so this layer's length would be measured against \
nothing: set_extent comes first",
kind.label()
);
let layer = u32::try_from(page.layers.len())
.unwrap_or_else(|_| unreachable!("a page of more layers than a u32 can name"));
page.layers.push(texels.into());
layer
}
#[must_use]
pub const fn extent(&self, kind: PageKind) -> u32 {
self.pages[kind.index()].extent
}
#[must_use]
pub fn layers(&self, kind: PageKind) -> &[Cow<'a, [u8]>] {
&self.pages[kind.index()].layers
}
pub(crate) fn check(&self) -> Result<(), HalError> {
for kind in PageKind::ALL {
let page = &self.pages[kind.index()];
if page.layers.is_empty() {
continue;
}
if page.extent == 0 {
return Err(HalError::InvalidDescriptor(format!(
"the {} page carries {} layer(s) at no extent, so there is no image for \
them to go into",
kind.label(),
page.layers.len()
)));
}
let texels = page.extent as usize * page.extent as usize * 4;
for (layer, bytes) in page.layers.iter().enumerate() {
if bytes.len() != texels {
return Err(HalError::InvalidDescriptor(format!(
"{} page layer {layer} carries {} bytes, and a {}×{} RGBA8 layer is \
{texels}",
kind.label(),
bytes.len(),
page.extent,
page.extent
)));
}
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ProbeUpdate {
#[default]
Authored,
EveryFrame,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ProbeGrid {
pub volume: probe::ProbeVolume,
pub update: ProbeUpdate,
pub probes: Vec<probe::GpuProbe>,
}
impl ProbeGrid {
pub(crate) fn check(&self) -> Result<(), HalError> {
let total = self.volume.total() as usize;
if total == self.probes.len() {
return Ok(());
}
Err(HalError::InvalidDescriptor(format!(
"the probe grid is {}×{}×{} over {} level(s), which is {total} \
probe(s), and the description carries {}",
self.volume.counts[0],
self.volume.counts[1],
self.volume.counts[2],
self.volume.level_count(),
self.probes.len()
)))
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Geometry<'a> {
Flat {
vertices: Cow<'a, [u8]>,
uv_range: UvRange,
indices: Cow<'a, [u32]>,
clusters: MeshClusters,
flags: u32,
},
Dag {
uv_range: UvRange,
levels: Vec<Cow<'a, [u8]>>,
dag: ClusterDag,
flags: u32,
},
}
impl Geometry<'_> {
#[must_use]
pub fn levels(&self) -> usize {
match self {
Self::Flat { .. } => 1,
Self::Dag { dag, .. } => dag.levels.len(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct MeshDesc<'a> {
pub label: Cow<'a, str>,
pub geometry: Geometry<'a>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SceneDesc<'a> {
pub meshes: Vec<MeshDesc<'a>>,
pub materials: Vec<mesh::GpuMaterial>,
pub page: PageDesc<'a>,
pub probes: ProbeGrid,
pub capacities: Capacities,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InstanceDesc {
pub mesh: usize,
pub material: usize,
pub transform: Mat4,
}
pub const DEMO_CUBE: usize = 0;
pub const DEMO_PYRAMID: usize = 1;
pub const DEMO_OPEN_BOX: usize = 2;
pub const DEMO_DUNES: usize = 3;
pub const DEMO_UNTINTED: usize = 0;
pub const DEMO_TINTED: usize = 1;
pub const DEMO_TEXTURED: usize = 2;
#[must_use]
pub fn demo() -> SceneDesc<'static> {
let mut page = PageDesc::empty();
page.set_extent(PageKind::BaseColor, PAGE_EXTENT);
let checker = page.push_layer(PageKind::BaseColor, &CHECKER_TEXELS[..]);
debug_assert_eq!(
checker, CHECKER_LAYER,
"the checker is this page's first and only layer"
);
SceneDesc {
meshes: vec![
MeshDesc {
label: Cow::Borrowed("cube"),
geometry: Geometry::Flat {
vertices: Cow::Owned(mesh::cube_vertex_bytes()),
uv_range: mesh::demo_uv_range(),
indices: Cow::Owned(mesh::cube_indices()),
clusters: crcbl_shaders::meshlet::cube_clusters(),
flags: 0,
},
},
MeshDesc {
label: Cow::Borrowed("pyramid"),
geometry: Geometry::Flat {
vertices: Cow::Owned(mesh::pyramid_vertex_bytes()),
uv_range: mesh::demo_uv_range(),
indices: Cow::Owned(mesh::pyramid_indices()),
clusters: crcbl_shaders::meshlet::pyramid_clusters(),
flags: 0,
},
},
MeshDesc {
label: Cow::Borrowed("open box"),
geometry: Geometry::Flat {
vertices: Cow::Owned(mesh::open_box_vertex_bytes()),
uv_range: mesh::demo_uv_range(),
indices: Cow::Owned(mesh::open_box_indices()),
clusters: crcbl_shaders::meshlet::open_box_clusters(),
flags: 0,
},
},
MeshDesc {
label: Cow::Borrowed("dunes"),
geometry: dunes_geometry(),
},
],
materials: vec![
mesh::GpuMaterial {
base_color_texture: mesh::GpuMaterial::NO_PAGE,
..mesh::GpuMaterial::UNTINTED
},
mesh::GpuMaterial {
base_color: PYRAMID_TINT,
roughness: PYRAMID_ROUGHNESS,
..mesh::GpuMaterial::UNTINTED
},
mesh::GpuMaterial {
base_color_texture: CHECKER_LAYER,
..mesh::GpuMaterial::UNTINTED
},
],
page,
probes: ProbeGrid::default(),
capacities: Capacities::default(),
}
}
fn dunes_geometry() -> Geometry<'static> {
let dag = crcbl_shaders::cluster_dag::dunes_dag();
let levels = dag
.levels
.iter()
.map(|level| {
let vertices: Vec<mesh::MeshVertex> = level
.positions
.iter()
.map(|&position| crcbl_shaders::dunes::vertex_at(position))
.collect();
Cow::Owned(mesh::vertex_bytes(&vertices))
})
.collect();
Geometry::Dag {
uv_range: crcbl_shaders::dunes::uv_range(),
levels,
dag,
flags: 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_demo_scene_shades_by_omission_through_an_untinted_row() {
let scene = demo();
assert_eq!(
usize::try_from(mesh::GpuInstance::default().material).expect("a table of three rows"),
DEMO_UNTINTED,
"the row a caller names by omission and the one it names by index are the same row"
);
assert_eq!(
scene.materials[mesh::GpuInstance::default().material as usize],
mesh::GpuMaterial {
base_color_texture: mesh::GpuMaterial::NO_PAGE,
..mesh::GpuMaterial::UNTINTED
},
"row 0 is what an instance with no material id names"
);
assert_ne!(scene.materials[0], scene.materials[1]);
assert_ne!(scene.materials[0], scene.materials[2]);
assert_eq!(
scene.materials[0].base_color, scene.materials[2].base_color,
"the texture pair must share a factor, or it is evidence about two columns"
);
}
#[test]
fn a_page_names_each_kind_apart_and_starts_naming_none() {
let page = PageDesc::empty();
for kind in PageKind::ALL {
assert_eq!(page.extent(kind), 0, "{} starts unsized", kind.label());
assert!(
page.layers(kind).is_empty(),
"{} starts empty",
kind.label()
);
}
page.check().expect("a description naming no page is legal");
let mut page = PageDesc::empty();
page.set_extent(PageKind::BaseColor, 4);
page.set_extent(PageKind::Normal, 2);
let colour = page.push_layer(PageKind::BaseColor, vec![0x11; 4 * 4 * 4]);
let normal = page.push_layer(PageKind::Normal, vec![0x22; 2 * 2 * 4]);
assert_eq!(
(colour, normal),
(0, 0),
"each kind numbers its own layers, and both start at zero"
);
assert_eq!(
(
page.extent(PageKind::BaseColor),
page.extent(PageKind::Normal)
),
(4, 2),
"one kind's extent says nothing about the other's"
);
assert_eq!(page.layers(PageKind::BaseColor)[0][0], 0x11);
assert_eq!(page.layers(PageKind::Normal)[0][0], 0x22);
page.check()
.expect("two kinds at two extents, each layer its own extent's worth");
}
#[test]
fn a_page_the_device_could_not_upload_is_refused() {
let good = || {
let mut page = PageDesc::empty();
for kind in PageKind::ALL {
page.set_extent(kind, 2);
}
page
};
for kind in PageKind::ALL {
let mut short = good();
short.push_layer(kind, vec![0x00; 4]);
let refusal = short
.check()
.expect_err("a layer of the wrong length would upload another layer's texels");
let HalError::InvalidDescriptor(said) = refusal else {
panic!("a description is refused as a description");
};
assert!(
said.contains(&format!("{} page layer 0 carries 4 bytes", kind.label())),
"the refusal must name the kind and the layer, and it said {said:?}"
);
let mut unsized_page = PageDesc::empty();
unsized_page.pages[kind.index()]
.layers
.push(Cow::Owned(vec![0x00; 2 * 2 * 4]));
let refusal = unsized_page
.check()
.expect_err("layers at no extent name an image that was never sized");
let HalError::InvalidDescriptor(said) = refusal else {
panic!("a description is refused as a description");
};
assert!(
said.contains(&format!(
"the {} page carries 1 layer(s) at no extent",
kind.label()
)),
"the refusal must name the kind, and it said {said:?}"
);
}
let mut whole = good();
for kind in PageKind::ALL {
whole.push_layer(kind, vec![0x00; 2 * 2 * 4]);
whole.push_layer(kind, vec![0x7B; 2 * 2 * 4]);
}
whole
.check()
.expect("two full-length layers on each kind is a page the renderer uploads");
}
#[test]
fn the_demo_page_is_one_checker_layer_and_no_normal_page() {
let page = demo().page;
assert_eq!(page.extent(PageKind::BaseColor), PAGE_EXTENT);
assert_eq!(
page.layers(PageKind::BaseColor).len(),
1,
"the demo page is the checker alone: nothing burns a layer any more"
);
assert_eq!(
page.layers(PageKind::BaseColor)[CHECKER_LAYER as usize].as_ref(),
&CHECKER_TEXELS[..]
);
assert_eq!(
demo().materials[DEMO_TEXTURED].base_color_texture,
CHECKER_LAYER,
"the textured row names the layer the page actually pushed"
);
assert_eq!(
page.extent(PageKind::Normal),
0,
"nothing in the demo scene names a normal map, so that page is one \
placeholder texel on the device"
);
page.check().expect("the demo page uploads as written");
}
#[test]
fn the_demo_scene_describes_the_residents_in_upload_order() {
let scene = demo();
let labels: Vec<&str> = scene
.meshes
.iter()
.map(|mesh| mesh.label.as_ref())
.collect();
assert_eq!(labels, ["cube", "pyramid", "open box", "dunes"]);
assert_eq!(
[DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES].map(|mesh| labels[mesh]),
["cube", "pyramid", "open box", "dunes"]
);
assert_eq!(
scene.meshes[..3]
.iter()
.map(|mesh| mesh.geometry.levels())
.collect::<Vec<_>>(),
[1, 1, 1],
"the flat residents are one mesh table entry each"
);
let Geometry::Dag { levels, dag, .. } = &scene.meshes[3].geometry else {
panic!("the dunes patch is the description's only DAG");
};
assert_eq!(
levels.len(),
dag.levels.len(),
"a level with no vertices would draw its clusters out of the level below"
);
for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
assert_eq!(
bytes.len(),
level.positions.len() * mesh::VERTEX_STRIDE,
"level {depth} carries one vertex per position"
);
}
assert!(
dag.levels.len() > 1,
"a one-level DAG is a flat mesh with extra steps, and would select nothing"
);
}
#[test]
fn the_default_capacities_are_the_ones_the_engine_shipped() {
assert_eq!(
Capacities::default(),
Capacities {
vertices: 64 * 1024,
indices: 256 * 1024,
meshes: 1024,
instances: 16 * 1024,
materials: 1024,
lights: 1024,
probes: 0,
}
);
assert_eq!(demo().capacities, Capacities::default());
}
#[test]
fn the_demo_scene_authors_no_probes() {
let scene = demo();
assert_eq!(scene.probes, ProbeGrid::default());
assert!(scene.probes.probes.is_empty());
assert_eq!(scene.probes.volume.total(), 0);
assert_eq!(scene.capacities.probes, 0);
scene
.probes
.check()
.expect("an empty grid uploads as written");
}
#[test]
fn a_grid_that_would_read_rows_it_does_not_carry_is_refused() {
let two = vec![probe::GpuProbe::ZERO; 2];
let claims_more = ProbeGrid {
update: ProbeUpdate::Authored,
volume: probe::ProbeVolume {
counts: [2, 2, 1],
..probe::ProbeVolume::default()
},
probes: two.clone(),
};
claims_more
.check()
.expect_err("a 2×2×1 grid carrying two probes would read rows it never wrote");
let claims_fewer = ProbeGrid {
update: ProbeUpdate::Authored,
volume: probe::ProbeVolume {
counts: [1, 1, 1],
..probe::ProbeVolume::default()
},
probes: two.clone(),
};
claims_fewer
.check()
.expect_err("a one-probe grid carrying two leaves one unreachable");
ProbeGrid {
update: ProbeUpdate::Authored,
volume: probe::ProbeVolume {
counts: [2, 1, 1],
inv_spacing: [1.0; 3],
origin: [0.0; 3],
levels: 1,
steps: probe::ProbeSteps::default(),
},
probes: two.clone(),
}
.check()
.expect("two probes on a 2×1×1 grid");
let clipmap = probe::ProbeVolume {
counts: [2, 1, 1],
inv_spacing: [1.0; 3],
origin: [0.0; 3],
levels: 2,
steps: probe::ProbeSteps::default(),
};
ProbeGrid {
update: ProbeUpdate::Authored,
volume: clipmap,
probes: two.clone(),
}
.check()
.expect_err("a two-level clipmap of two probes a level needs four rows");
ProbeGrid {
update: ProbeUpdate::Authored,
volume: clipmap,
probes: vec![probe::GpuProbe::ZERO; 4],
}
.check()
.expect("four rows fill a two-level clipmap of two probes a level");
}
}