render3d#
the core of the 3D engine: meshes, textured materials, scenes of instances (mirrored ones too), visibility on the GPU, glTF scenes on the GPU -- crate root lib/render3d/lib.rs
render3d -- the core of the 3D engine on lib/gpu (G5a to G5d; docs/RENDER3D.md): meshes in shared buffers,
a table of glTF's PBR materials with textures, scenes of instances, a camera, a sun, visibility on the GPU and one
instance list per mesh, side (mirrored instances turn their faces round) and alpha class (opaque without a discard
in its pipelines, MASK with one); (G5d) the camera's occlusion test against a depth pyramid in two phases. No draw
per object anywhere: a frame is a few compute dispatches and one indirect draw per list and phase (level Basis) or
one multi-draw per side, alpha class and phase for all of them (level Voll). The same WGSL on every path: compiled
ahead (shaders_spv.rs) on Vulkan, handed to the browser as text on WebGPU.
Renderer::new(&device, &RendererDesc) -> Result<Renderer> the pipelines and the pools of one colour format
renderer.add_mesh(&MeshData) -> Result<MeshId> positions, normals, uv, indices into the pools
renderer.add_texture(&TextureData) -> Result<TextureId> rgba into the array of its size class, mip levels
renderer.add_material(&Material) -> Result<MaterialId>, set_material(id, &Material)
renderer.set_size(w, h) a depth buffer the renderer keeps (or bring your own)
Scene::new(&renderer) -> Result<Scene>
scene.add(Instance { mesh, material, transform }) -> Result<InstanceId>, remove(id), set_transform(id, t),
set_material(id, m), set_mesh(id, m); set_camera(&Camera), set_sun(&Sun), set_origin(pos)
a frame:
scene.prepare(&mut renderer)?; waits for this slot's last frame, uploads what changed
renderer.record(&mut encoder, &scene, color, depth)?; depth None: the renderer's own
let id = queue.submit([encoder.finish()?])?; (or swapchain.present)
scene.submitted(id);
gltf::upload(&mut renderer, &document) -> Result<Imported> a jflib-gltf Document: meshes, textures,
materials, and its instances for a Scene (gltf.rs)
(G7f) renderer.remove_mesh(id), remove_material(id), remove_texture(id) their places are used again, the ids stay
invalid (store.rs); refused while a scene's instances, a material or a detail level use them
(G7f) renderer.add_material_desc(&MaterialDesc) glTF's BLEND (blended after the rest, sorted back to front
per instance on the GPU: sort.wgsl) and doubleSided (no culling of back faces, their normal turned round);
MaterialDesc::toon, the cartoon look (draw.wgsl)
(G7f) Camera::ortho, an orthographic camera; scene.set_viewmodel, add_viewmodel (a weapon before the camera, drawn
with its own lens in front of the world: the world's depth 0 ..= 0.5, its own 0.5 ..= 1); scene.set_outline (lines
from the depth buffer) and set_antialias (FXAA): post.rs, post.wgsl; scene.set_particles, add_emitter, emit,
set_time (billboards moved in a compute shader, sorted, one draw): particles.rs, particles.wgsl
Conventions: reverse Z (depth 1 at the near plane, compare Greater, clear with DEPTH_CLEAR; a far plane
of f64::INFINITY is the default), right-handed world, faces counter-clockwise from outside, light in the
units of KHR_lights_punctual, times the scene's exposure, tone mapped in the fragment shader (Khronos PBR
Neutral, or none), colours linear (an sRGB target encodes them; G5e2: for an 8-bit target without sRGB the fragment
shaders do, RendererDesc::encode_srgb). Positions are f64 on the CPU and f32 relative to the scene's
origin on the GPU.
Errors are gpu's: Invalid for ids and values this crate can judge, the rest from the backend.
render3d crate root#
/// what a depth attachment of this engine clears to (reverse Z: 0 is infinitely far)
DEPTH_CLEAR: f32 = 0.0
/// the most frames the CPU may record ahead of the GPU
FRAMES_MAX: usize = 3
/// (G5d) the most detail levels of a mesh
LODS_MAX: usize = 8
/// the WGSL sources and their embedded words (render3dtest: the embedding check)
CULL_WGSL: &str = include_str!("cull.wgsl")
SCATTER_WGSL: &str = include_str!("scatter.wgsl")
DRAW_WGSL: &str = include_str!("draw.wgsl")
/// (G5d) the depth pyramid of the occlusion test
HIZ_WGSL: &str = include_str!("hiz.wgsl")
/// (G7f) the blended instances sorted back to front
SORT_WGSL: &str = include_str!("sort.wgsl")
/// (G7f) outlines and FXAA; the particles
POST_WGSL: &str = include_str!("post.wgsl")
PARTICLES_WGSL: &str = include_str!("particles.wgsl")
CULL_VM_SPV: &[u32] = spv::CULL_VM
VS_FULL_SPV: &[u32] = spv::VS_FULL
FS_OUTLINE_SPV: &[u32] = spv::FS_OUTLINE
FS_FXAA_SPV: &[u32] = spv::FS_FXAA
CS_PARTICLES_SPV: &[u32] = spv::CS_PARTICLES
VS_PARTICLE_SPV: &[u32] = spv::VS_PARTICLE
FS_PARTICLE_SPV: &[u32] = spv::FS_PARTICLE
SORT_LOCAL_SPV: &[u32] = spv::SORT_LOCAL
SORT_GLOBAL_SPV: &[u32] = spv::SORT_GLOBAL
/// (G7f) the blended instances' vertex and fragment shaders
VS_BLEND_SPV: &[u32] = spv::VS_BLEND
FS_BLEND_SPV: &[u32] = spv::FS_BLEND
CULL_SPV: &[u32] = spv::CULL
CULL_EARLY_SPV: &[u32] = spv::CULL_EARLY
/// (G7f) the camera's culling without the occlusion test when the scene has blended instances
CULL_BLEND_SPV: &[u32] = spv::CULL_BLEND
CULL_LATE_SPV: &[u32] = spv::CULL_LATE
HIZ_DEPTH_SPV: &[u32] = spv::HIZ_DEPTH
HIZ_DOWN_SPV: &[u32] = spv::HIZ_DOWN
SCATTER_SPV: &[u32] = spv::SCATTER
VS_SPV: &[u32] = spv::VS
/// the main pass's fragment shader of opaque lists (no discard); FS_MASK_SPV: that of MASK lists
FS_SPV: &[u32] = spv::FS
FS_MASK_SPV: &[u32] = spv::FS_MASK
VS_DEPTH_SPV: &[u32] = spv::VS_DEPTH
VS_SHADOW_SPV: &[u32] = spv::VS_SHADOW
FS_SHADOW_SPV: &[u32] = spv::FS_SHADOW
struct RendererDescRenderer::new. Made withnewand changed field by field (it may grow)color: Format-- the format of the colour targetsframes_in_flight: usize-- frames the CPU may record ahead of the GPU (1 ..= FRAMES_MAX); G1 measured 2 to be enoughencode_srgb: bool-- (G5e2) an 8-bit colour format without sRGB (Rgba8Unorm, Bgra8Unorm, Rg8Unorm, R8Unorm): the fragment shaders encode the colours to sRGB, by the definition, as an sRGB target's hardware does (true, the default: what a window's swapchain or a view of lib/ui shows). false: the linear light as it is (tests that compare light, an app that encodes later). sRGB formats are encoded by the hardware and float formats stay linear either way
impl RendererDesc
const fn new(color: Format) -> RendererDescconst fn encodes_srgb(&self) -> boolthe fragment shaders encode sRGB with this description: encode_srgb and an 8-bit format without sRGBstruct MeshData<'a>a mesh's data: one normal and one uv per position, three indices per triangle, counter-clockwise from outside. Copied into the pools (a vertex is 32 bytes; 16-bit indices up to 65536 vertices, of which the GPU is fond); the renderer keeps no copy.positions: &'a [[f32; 3]]normals: &'a [[f32; 3]]uvs: &'a [[f32; 2]]indices: &'a [u32]
struct MeshId(pub u32)a mesh of a Renderer. (G7f) The low 24 bits are its place in the renderer's tables, the high 8 bits how often that place was used before (Renderer::remove_mesh): the id of a removed mesh stays invalid. A renderer that removes nothing numbers its meshes 0, 1, 2, ...struct Lod(G5d) a detail level of a mesh (Renderer::set_lods): an instance whose bounding sphere's projected diameter is less thanbelowof the view's height is drawn withmeshinstead; None: not drawn at all (contribution culling)mesh: Option<MeshId>below: f32
struct MaterialId(pub u32)a material of a Renderer. (G7f) As MeshId: a place and how often it was used before (Renderer::remove_material)enum AlphaClasshow a material's alpha is drawn, and so the lists and pipelines its instances take (docs/RENDER3D.md "Listen je Alpha-Modus"; Material::alpha_class, MaterialDesc::alpha_class)Opaque-- nothing is dropped: pipelines without a discard (the early depth test stays theirs)Mask-- glTF's MASK: fragments whose alpha is below the cutoff are droppedBlend-- (G7f) glTF's BLEND (MaterialDesc::blend): drawn after the others, sorted back to front per instance, blended (premultiplied alpha), the depth tested and not written; no shadows, not in the occlusion test's pyramid
struct Toon(G7f) the cartoon look of a material (MaterialDesc::toon; docs/RENDER3D.md "Cartoon-Material"): flat colours, the sun's and the lights' n.l in bands, a flat ambient light, a light rim on the silhouette. Metallic, roughness and the metallic-roughness texture are not used; the base colour (with its texture), the normal map, occlusion (on the ambient light), emission, MASK, BLEND and double-sided work as for PBR. Made withnewand changed field by field (it may grow). The values go to the GPU in bytes: softness, rim and rim_width in steps of 1/255bands: u32-- 1 ..= 16 levels of light: 0, 1 / (bands - 1), ..., 1 of the light's colour (the first step at the terminator n.l = 0, the others evenly up to n.l = 1); 1: no shading at all, the base colour under the full lightsoftness: f32-- 0 ..= 1: how soft a step is (0 hard; 1 a whole band wide)rim: f32-- 0 ..= 1: how bright the rim is (its colour is the light a white surface facing the sun gets)rim_width: f32-- 0 ..= 1: where the rim begins, as 1 - n.v (0: no rim)
impl Toon
const fn new(bands: u32) -> Toonbandslevels, hard steps, no rimstruct MeshInfowhere a mesh lies in the pools, and its bounding sphere in its own coordinatesfirst_index: u32indices: u32base_vertex: u32vertices: u32wide: bool-- its indices are 32 bits wide: more than 65536 verticescenter: [f64; 3]radius: f64
struct Materiala row of the material table: glTF's metallic-roughness material, shaded as glTF 2.0 Appendix B says (G5c; draw.wgsl). Fragments whose alpha is below alpha_cutoff are dropped. What reaches the target is opaque (alpha 1)base_color: [f32; 4]-- linear rgb and alpha (the texture's sRGB is decoded first)metallic: f32-- 0 ..= 1 (clamped in the shader, after the texture)roughness: f32emissive: [f32; 3]-- linear radiance (before the exposure)base_color_texture: Option<TextureRef>metallic_roughness_texture: Option<TextureRef>-- linear: roughness in g, metallic in b (times the factors)normal_texture: Option<TextureRef>-- linear, glTF's tangent space (+y up in the image); the tangent frame comes from the derivatives (docs/RENDER3D.md: how that differs from MikkTSpace); scale multiplies x and ynormal_scale: f32occlusion_texture: Option<TextureRef>-- linear, r: how much of the ambient (indirect) light reaches the surface, 1 + strength (r - 1)occlusion_strength: f32emissive_texture: Option<TextureRef>-- sRGB, times emissivealpha_cutoff: Option<f32>-- glTF's alpha mode MASK: fragments whose alpha is below it are not drawn (None: opaque). It decides the alpha class: an instance of a MASK material is in a list of MASK instances, drawn by pipelines with a discard
impl Material
const fn color(r: f32, g: f32, b: f32) -> Materiala dull material of one colourconst fn textured(t: TextureRef) -> Materiala dull material of a texture (white times the texture)const fn alpha_class(&self) -> AlphaClassthe lists and pipelines its instances take: Mask with an alpha_cutoff, else Opaque (blended: MaterialDesc)struct MaterialDesc(G7f) a material with what a Material cannot hold (it is not #[non_exhaustive], a field more would break code that writes all of them): glTF's alpha mode BLEND and doubleSided. Made withnew(orfroma Material) and changed field by field (it may grow); Renderer::add_material_desc, set_material_desc. Renderer::add_material(m) is add_material_desc(&MaterialDesc::new(m))material: Materialblend: bool-- glTF's BLEND: the instances are drawn after the opaque and MASK ones, sorted back to front per instance (by the distance of their bounding sphere's centre from the eye), over what is there: the shader multiplies its colour by the base colour's alpha (times the texture's), blended as premultiplied alpha (One, OneMinusSrcAlpha), in the target's code values; the depth is tested, not written. They cast no shadows and hide nothing from the occlusion test. Not together with an alpha_cutoff (Invalid)double_sided: bool-- glTF's doubleSided: back faces are not culled; they are lit with their normal turned round (the whole shading normal, as the glTF sample viewer turns the tangent frame). Both sides cast shadows (every material does)toon: Option<Toon>-- (G7f) the cartoon look in place of glTF's BRDF (None: PBR)
impl MaterialDesc
const fn new(material: Material) -> MaterialDescconst fn alpha_class(&self) -> AlphaClassthe lists and pipelines its instances take: Blend when blended, else the Material'sstruct Rendererthe pipelines of one colour format, the mesh pools and the material table of one device
impl Renderer
fn new(dev: &Device, desc: &RendererDesc) -> Result<Renderer>fn device(&self) -> &Devicefn desc(&self) -> &RendererDescwhat it was made with (G5e2: desc().encodes_srgb(), whether its fragment shaders encode sRGB)fn multi_draw(&self) -> boolthis device draws its lists with one multi-draw (level Voll)fn max_instances(&self) -> u32the most instances a scene can hold on this devicefn set_shadow_mask(&mut self, on: bool)(G5c) false: the shadow passes of MASK lists run without a fragment shader too and MASK materials cast full shadows (what that saves: docs/RENDER3D.md); true at first: their holes let the sun through. Opaque lists cast without a fragment shader either wayfn set_environment(&mut self, d: &EnvironmentData) -> Result<()>(G5c) the environment's light: a procedural sky or six faces, prefiltered on the CPU (the levels of a cube texture per roughness, 9 harmonics for the diffuse part); scenes take it with Scene::set_environment. The upload goes with the next submissionfn environment(&self) -> Option<&Environment>(G5c; tests, tools) the environment as the GPU holds itfn shadow_map(&self) -> &Texture(G5c; tests) the sun's shadow map: CASCADES_MAX layers of Depth32Float, in Layout::Sampled between framesfn add_mesh(&mut self, m: &MeshData) -> Result<MeshId>a mesh into the pools (they grow; nothing waits). The vertices must be there in equal numbers, the indices in threes and in range, positions finite.fn remove_mesh(&mut self, id: MeshId) -> Result<()>(G7f) a mesh goes: its id is invalid from now on, its vertices and indices are used again (once the frames that may still draw it are done, store.rs), its place gets the next mesh with a new id. Invalid for a mesh the renderer does not have, one that instances of a scene use (Scene::remove them first; a dropped scene uses nothing) and one that another mesh takes as a detail level (set_lods of that one first). Its own detail levels go with it. A scene prepared before the removal does not record (Invalid): it prepares againfn mesh_count(&self) -> u32(G7f) live meshesfn pool_use(&self) -> [(u32, u32, u32); 3](G7f; tests, tools) per pool (vertices, 16-bit, 32-bit indices): elements up to its end, its room, and the free elements below the end that removals left (ranges, handed out again before the end grows)fn mesh_info(&self, id: MeshId) -> Option<MeshInfo>fn set_lods(&mut self, mesh: MeshId, lods: &[Lod]) -> Result<()>(G5d) a mesh's detail levels: other meshes (or none) for its instances below a projected size, thresholds falling, at most LODS_MAX; empty: none. The visibility picks per instance from the camera's distance (the shadow cascades take the camera's pick, so a shadow matches its caster); the sphere culling takes for the mesh's instances grows to hold every level (cull_sphere). Scenes send all their instances again with their next frame. Invalid for meshes the renderer does not have and thresholds not finite, not above 0 or not fallingfn lods(&self, mesh: MeshId) -> &[Lod](G5d) a mesh's detail levels (empty: none)fn cull_sphere(&self, mesh: MeshId) -> Option<([f64; 3], f64)>(G5d) the sphere (centre, radius in the mesh's coordinates) the visibility takes for a mesh's instances: its own, grown to hold its detail levelsfn add_texture(&mut self, d: &TextureData) -> Result<TextureId>a texture into the array of its size class with all its mip levels (texture.rs: resampled when it is not 128, 256, 512, 1024 or 2048 square). The upload goes with the next submission. (G7f) A layer a removed texture left is used firstfn remove_texture(&mut self, id: TextureId) -> Result<()>(G7f) a texture goes: its id is invalid from now on, its layer is used again by the next texture of its class and colour space (the arrays do not shrink). Invalid for a texture the renderer does not have and one that a material names (set_material without it, or remove_material, first). A scene prepared before the removal does not record (Invalid): it prepares againfn texture_info(&self, id: TextureId) -> Option<TextureInfo>fn texture_count(&self) -> u32live texturesfn texture_bytes(&self) -> u64bytes of GPU memory the texture arrays takefn texture_array(&self, class: u32, srgb: bool) -> Option<&Texture>(tests) the array of a size class and colour space (layers: TextureInfo::layer), None without a texturefn add_material(&mut self, m: &Material) -> Result<MaterialId>a row of the table; its textures must be this renderer'sfn add_material_desc(&mut self, d: &MaterialDesc) -> Result<MaterialId>(G7f) a row of the table with glTF's BLEND and doubleSided (MaterialDesc); its textures must be this renderer's. The first blended or double-sided material makes the pipelines they needfn set_material(&mut self, id: MaterialId, m: &Material) -> Result<()>a row of the table; the next frame shows it. A new alpha class moves the material's instances to the lists of that class with their scenes' next prepare. (G7f) The material stays blended, double-sided and cartoon as it was (set_material_desc changes those)fn set_material_desc(&mut self, id: MaterialId, d: &MaterialDesc) -> Result<()>(G7f) a row of the table with glTF's BLEND and doubleSided; the next frame shows it. A new alpha class or side moves the material's instances to their new lists with their scenes' next preparefn remove_material(&mut self, id: MaterialId) -> Result<()>(G7f) a material goes: its id is invalid from now on, its textures lose a user, its place gets the next material with a new id. Invalid for a material the renderer does not have and one that instances of a scene use. A scene prepared before the removal does not record (Invalid): it prepares againfn material_count(&self) -> u32(G7f) live materialsfn has_material(&self, id: MaterialId) -> boolwhether the material is there (false once it was removed)fn alpha_class(&self, id: MaterialId) -> AlphaClassthe alpha class of a material (Opaque for one the renderer does not have)fn double_sided(&self, id: MaterialId) -> bool(G7f) a material is double-sided (false for one the renderer does not have)fn set_size(&mut self, w: u32, h: u32) -> Result<()>a depth buffer the renderer keeps, for frames recorded with depth None (sampled too: the occlusion test builds its pyramid from it)fn depth_texture(&self) -> Option<&Texture>(G5d; tests) the renderer's own depth buffer (set_size)fn pyramid(&self, depth: &TextureView) -> Option<&Texture>(G5d; tests) the occlusion test's pyramid of a depth attachment as the last frame with it built it: mip k - 1 holds level k (the smallest depth of 2^k x 2^k pixels), in Layout::Sampled; None when no record used it latelyfn record<'a>(&'a self, e: &mut CommandEncoder<'a>, s: &'a Scene, color: ColorAttachment<'a>, depth: Option<DepthAttachment<'a>>) -> Result<()>one frame of a prepared scene into e: its uploads, its culling, its render pass with a clear of colour and depth as the attachments say. depth None: the renderer's own (set_size), cleared. (G5d) With the occlusion test (Scene::set_occlusion, and a depth attachment with TextureUsage::SAMPLED) the pass is two: phase 1 with the attachments' load and theirbefore, phase 2 that keeps what phase 1 drew and ends in theirstoreandafter
render3d/dfg.rs#
Source: lib/render3d/dfg.rs
dfg -- the second sum of the split-sum approximation for draw.wgsl's BRDF (G5c; docs/RENDER3D.md "PBR"): a
table of (A, B) such that the specular light a white uniform environment reflects is f0 A + B, over n.v (x)
and roughness (y), 32 x 32 points from 0 to 1, read bilinearly by the fragment shader from a storage buffer
(no texture slot, the same exact weights on every path). Made ahead by dfg_table (render3dtest --gen-dfg
writes dfg_table.rs, --test shaders compares the embedded table with a fresh one): GGX importance sampling
of the half vector, 4096 points of the Hammersley set per entry, in f64. Karis' analytic fit was the
first choice; for this BRDF's separable Smith term it lies up to 0.19 from the integral (measured by
render3dtest --test pbr), the table within a few thousandths.
/// points of the table per axis
DFG_N: usize = 32
/// the embedded table: entry j * DFG_N + i holds (A, B) at n.v = i / (DFG_N - 1), roughness j / (DFG_N - 1)
DFG: [[f32; 2]; DFG_N * DFG_N] = { let mut out = [[0.0f32; 2]; DFG_N * DFG_N]; let mut k = ...
fn dfg_table() -> Vec<[f32; 2]>the table computed (what dfg_table.rs holds; slow: some 4 million samples)
render3d/env.rs#
Source: lib/render3d/env.rs
env -- the environment's light (G5c; docs/RENDER3D.md "Umgebungslicht"): diffuse through 9 spherical harmonics
(the irradiance's coefficients, in the lights' uniform block: no texture slot), specular through a cube texture
prefiltered per roughness (level k holds roughness k / (levels - 1)) read with the split-sum's table (dfg.rs).
The source is a procedural sky or the caller's six faces of linear radiance (RGBA f32); levels down to 4 x 4. Everything is made on
the CPU in f64 when it is set: level 0 is the source, every further level a GGX convolution with N = V = R
(importance sampling of the half vector, 128 points of the Hammersley set; a face source is read at the level
of its own box-filtered chain the sample's solid angle asks for), the harmonics from the source's texels
weighted by their solid angle (a sky through a 32 x 32 grid per face), times the cosine lobe's factors
(Ramamoorthi and Hanrahan). Uploaded as Rgba16Float with every level.
Faces in Vulkan's order: +x, -x, +y, -y, +z, -z; texel (i, j) of face f looks along the direction Vulkan's
face selection maps to it (env_dir).
/// texels a side of a sky's level 0
SKY_SIZE: u32 = 64
struct Skya procedural sky: linear radiance; smooth everywhere (a glow, no sharp sun disc)zenith: [f32; 3]horizon: [f32; 3]ground: [f32; 3]sun: [f64; 3]-- towards the sun's glow (any length), its colour at the centre, falling off as cos^8glow: [f32; 3]
impl Sky
const DEFAULT: Sky = Sky { zenith: [0.25, 0.45, 0.9], horizon: [0.8, 0.85, 0.9 ...fn radiance(&self, d: V3) -> [f64; 3]the radiance along a unit vectorenum EnvironmentData<'a>what Renderer::set_environment takesSky(Sky)Faces { size: u32, rgba: [&'a [f32]; 6] }-- six faces of size x size texels (a power of two, 4 ..= 1024), rows from the top, RGBA f32 linear radiance (alpha unused; RGBE, half floats and the like converted by the caller)
struct Environmentthe environment as the GPU holds it (tests, tools): each level's six faces, RGBA as f32 of the half floats uploaded, and the irradiance's harmonics (divided by pi: what a white matte surface shows)size: u32levels: Vec<Vec<[f32; 4]>>sh: [[f32; 3]; 9]
fn env_dir(f: usize, s: f64, t: f64) -> V3the unit vector of a point (s, t) in 0 ..= 1 of face f (Vulkan's face selection, inverted)fn env_face(d: V3) -> (usize, f64, f64)the face and (s, t) a unit vector falls on (Vulkan's face selection)fn to_half(v: f32) -> u16an f32 as IEEE half (nearest, ties to even; large values to infinity, which radiance never reaches here)fn from_half(h: u16) -> f32a half as f32
render3d/gltf.rs#
Source: lib/render3d/gltf.rs
gltf -- a jflib-gltf Document into a Renderer (G5b; docs/GLTF.md): each primitive as a mesh, each image as a
texture (once per image, colour space and filter: base colour and emissive sRGB, the others linear), each
material as a row, and the instances of a scene with their world matrices taken apart (gltf::decompose)
for Scene::add. (G7f) BLEND and doubleSided go through MaterialDesc. What the engine cannot show yet is counted in
notes: uv sets other than 0, world matrices with shear (drawn without it).
let doc = ::gltf::load(&bytes, &mut |uri| read(dir, uri), &::gltf::Limits::DEFAULT)?;
let imported = render3d::gltf::upload(&mut renderer, &doc, None)?;
for i in &imported.instances { scene.add(*i)?; }
struct Importedwhat upload made of a Documentmeshes: Vec<Vec<MeshId>>-- the renderer's mesh of each primitive: meshes[mesh][primitive]materials: Vec<MaterialId>-- the renderer's material of each of the document's, and glTF's default material for primitives withoutdefault_material: Option<MaterialId>textures: u32-- textures uploadedinstances: Vec<Instance>-- the scene's instances, for Scene::addsheared: u32-- instances whose world matrix has shear, which a Transform cannot hold (the largest |cos| between two axes above 1e-4); drawn without itlights: Vec<Light>-- (G5c) the scene's point and spot lights (KHR_lights_punctual), for Scene::set_lightssuns: Vec<Sun>-- (G5c) its directional lights as suns (ambient 0); a Scene has one sunnotes: Vec<String>-- what the engine leaves out (once each)
fn upload(r: &mut Renderer, doc: &g::Document, scene: Option<usize>) -> Result<Imported>the document's meshes, textures, materials, and the instances ofscene(None: the document's)
render3d/math.rs#
Source: lib/render3d/math.rs
math -- what the scene computes on the CPU, in f64 (no libm in no_std; the matrices are in scene.rs)
type V3 = [f64; 3]fn sqrt(x: f64) -> f64the square root (x <= 0: 0)fn tan(x: f64) -> f64the tangent of a small angle (a field of view below pi): sine over cosine by their seriesfn floor(x: f64) -> f64the largest integer not above x (|x| below 2^63)fn add(a: V3, b: V3) -> V3fn sub(a: V3, b: V3) -> V3fn mul(a: V3, k: f64) -> V3fn dot(a: V3, b: V3) -> f64fn cross(a: V3, b: V3) -> V3fn len(a: V3) -> f64fn norm(a: V3) -> V3a unit vector (zero stays zero)fn rotation(q: [f32; 4]) -> [V3; 3]the rotation matrix's columns of a quaternion (x, y, z, w; any length except 0)fn sincos(x: f64) -> (f64, f64)sine and cosine: reduced to -pi ..= pi, then their seriesfn ln(x: f64) -> f64the natural logarithm (x <= 0: -inf): x = m 2^e, ln m by the series of atanhfn exp(x: f64) -> f64e^x for |x| below 700: x = k ln 2 + r, the series of e^rfn pow(x: f64, y: f64) -> f64x^y for x > 0 (else 0)
render3d/particles.rs#
Source: lib/render3d/particles.rs
particles -- (G7f) billboards from a buffer (docs/RENDER3D.md "Partikel"): emitters on the CPU, a ring of particles on
the GPU, their motion in a compute shader (particles.wgsl), sorted back to front (sort.wgsl), one indirect draw.
A particle is born on the CPU (Scene::emit): its randomness comes from a hash of the emitter's seed and the particle's
serial number in that emitter, so the same calls give the same particles on every device and in every run. Its record
(64 bytes: place, birth in microseconds, velocity, life, sizes, colours, gravity and drag, flags) goes into the next places
of the ring (the oldest are overwritten), copied inside the frame's commands. Nothing changes it afterwards: the compute
shader evaluates its motion in closed form at its age every frame (constant gravity along -y and a linear drag), and
puts each living particle into the frame's list with the key of its distance; sort.wgsl sorts the list, one draw with six
vertices per particle draws it. No read-back, no state on the GPU besides the births.
enum ParticleBlend(G7f) how a particle is laid over the image (both through the premultiplied blend state: an additive particle returns alpha 0)Additive-- adds its light (fire, sparks, muzzle flashes)Alpha-- covers what is behind by its alpha, premultiplied (smoke, dust)
enum ParticleShape(G7f) the shape of a particle's billboardDisc-- a soft disc facing the camera (opacity 1 - r^2 from the middle to the rim)Streak-- the disc stretched along the particle's velocity on the screen by Emitter::stretch (sparks)
struct Emitter(G7f) an emitter of a Scene (Scene::add_emitter): what the particles it emits look like and how they move. Made withnewand changed field by field (it may grow). Ranges [a, b] are drawn uniformly per particleseed: u32-- the seed of its particles' randomness: particle k of this emitter (counted from its first emit) is the same in every run with the same callsblend: ParticleBlendshape: ParticleShapestretch: f32-- ParticleShape::Streak: how long the streak is per speed (seconds): its length is size + speed * stretchviewmodel: bool-- its particles live in the viewmodel's space (Scene::add_viewmodel; Scene::emit takes the camera's space: x right, y up, -z forward) and are drawn with the viewmodel, in front of the world (a muzzle flash at the weapon); gravity acts along the camera's -y. false: the world'slife: [f32; 2]-- seconds a particle lives (above 0)speed: [f32; 2]-- the speed at birth (world units per second), along a direction in a cone around Scene::emit's directionspread: f32-- the cone's half angle in radians (0: along the direction, pi: any direction)radius: f32-- particles are born within a ball of this radius around Scene::emit's pointsize: [f32; 2]-- the billboard's width at birth and at death (world units), linear in betweencolor: [[f32; 4]; 2]-- linear colour (radiance, before the exposure) and opacity at birth and at death, linear in betweengravity: f32-- acceleration downwards (along -y; negative: rising), world units per second squareddrag: f32-- linear drag (1 / seconds): the velocity falls by e^(-drag t) towards gravity / drag
impl Emitter
const fn new(seed: u32) -> Emitteradditive white discs of 0.1 that fade out over a second, at speed 1 straight along the directionstruct EmitterId(G7f) an emitter of a Scene; dead after Scene::remove_emitterslot: u32
fn hash(x: u32) -> u32the hash of the randomness (a PCG step and its output permutation, as in PCG-RXS-M-XS)fn motion(rec: &[u32; 16], t: f64) -> (V3, V3)a point and its velocity of a record at age t (seconds), in its own space, as particles.wgsl'smotioncomputes it: gravity along -y, drag k: v(t) = a + (v0 - a) e^(-k t) with a = g / k, p(t) = p0 + a t + (v0 - a)(1 - e^(-k t)) / k; without drag (k below 1e-4) p0 + v0 t + g t^2 / 2. In f64 (tests and tools)
/// the longest life of a particle (seconds): records older than this are dead (scene.rs zeroes them before their age
/// in 32-bit microseconds wraps at 4295 s)
LIFE_MAX: f32 = 4000.0
render3d/post.rs#
Source: lib/render3d/post.rs
post -- (G7f) what comes after the scene's passes (post.wgsl; docs/RENDER3D.md "Umrisse", "Kantenglättung") and the
particles' pipelines (particles.wgsl): outlines from the depth buffer, FXAA from an image of the scene's own. Per depth
attachment the renderer was given, in a chain a shared borrow can grow (as hiz.rs: Renderer::record takes &self): the
outline's bind group (that depth view) and FXAA's image (the attachment's size, the renderer's colour format) with its
group. Scene::prepare drops those not used lately.
struct Outline(G7f) lines on the edges of the depth buffer (Scene::set_outline): silhouettes and creases, drawn over the opaque image before blended instances and particles. Made withnewand changed field by field (it may grow)width: u32-- 1 ..= 8 pixels: on a silhouette's near side the line is this wide, across a crease about twicecolor: [f32; 4]-- linear colour and opacitycrease: f32-- how sharp a crease must be to get a line: the change of the surface's slope across it (tan of its angle to the view; 0.5 at first, about 30 degrees seen head on). Larger: fewer creases; jumps of the depth always get one
impl Outline
const fn new(width: u32, color: [f32; 4]) -> Outlinelineswidthpixels wide in this colour, creases from 0.5enum Antialias(G7f) anti-aliasing as a pass over the finished image (Scene::set_antialias)NoneFxaa-- FXAA 3.11, quality preset 12: the scene is drawn into an image of the renderer's (the target's size and format), FXAA writes it to the target. The target's old contents are replaced (Load::Keep becomes a clear)
render3d/scene.rs#
Source: lib/render3d/scene.rs
scene -- a scene's instances, camera and sun (lib.rs has the overview, docs/RENDER3D.md the reasons)
On the CPU: one Slot per instance with its f64 position; free places on a list, used again first.
On the GPU, per slot: spheres (16 bytes, read by cull), list_of (4 bytes, read by cull only for what
is visible), instances (64 bytes, the finished matrix, read by the vertex shader). Per list (one per
mesh, side and alpha class in use: a mirrored instance, its scales' product negative, turns its faces round and
is drawn by the pipelines whose front faces are clockwise; an instance of a MASK material is drawn by the pipelines
with a discard): a draw record, a first place in the visible list. Which list an instance is in is settled by
prepare (the class is its material's, which the renderer holds). The draw records lie by width of indices, class
and side, so each combination is one multi-draw; a list's record is the fourth word of its entry in list_first.
Capacities double, a list keeps room for its instances, so frames with instances coming and going rewrite no list
layout.
What a frame sends (prepare, then Renderer::record copies it inside the frame's commands, behind the
barrier against the frame before): always the view and the lights of this frame's slot; the changed
slots through the scatter shader (a run of (slot, record) in the slot's own Upload buffer); more than
4096 changes and an eighth of the slots at once, a new origin, new capacities: everything, from a
temporary buffer. Queue::write_buffer would not do for this: its copies run ahead of the frame's
commands without a barrier against the frames still on the GPU.
(G7f) Removal (store.rs): a scene counts its instances per mesh and material and tells the renderer's shared table
when it has the first or no longer any of one (and when it goes); lists belong to a mesh's slot, so a removed mesh's
lists serve the next mesh in that slot. Lists per side, class and faces: double-sided materials have lists of their
own (drawn without culling). Blended instances (class Blend) have lists for their mesh like the others, without room in
the visible lists: the camera's culling puts them into one list for all of them (`blend`), sort.wgsl sorts it, one draw
draws it (lib.rs draw_blend).
struct Transformwhere an instance is: position in the world (f64), rotation (quaternion x, y, z, w), scale per axis. Negative scales mirror: an odd number of them turns the winding round, the instance goes to its mesh's lists of mirrored instances and keeps its outside in front. 0 on some of the axes leaves faces without a normal, they come out blackpos: [f64; 3]rot: [f32; 4]scale: [f32; 3]
impl Transform
const fn at(pos: [f64; 3]) -> Transformfn mirrored(&self) -> boolthe determinant is negative: the faces turn roundstruct Instancewhat Scene::add takesmesh: MeshIdmaterial: MaterialIdtransform: Transform
struct InstanceIdan instance of a Scene; dead after remove, also when its place has gone to another oneslot: u32-- the place in the instance arrays
struct Cameraa right-handed camera, perspective or (G7f) orthographic; reverse Zeye: [f64; 3]forward: [f64; 3]-- unit vectors: where it looks, and up (at right angles)up: [f64; 3]fov_y: f64-- the vertical field of view in radians (perspective), width / heightaspect: f64near: f64-- distances along forward; (G7f) an orthographic camera's near may be 0 or belowfar: f64-- f64::INFINITY: no far plane (perspective only: an orthographic camera needs a finite one)ortho: Option<f64>-- (G7f) Some(h): orthographic, the view h world units high and h * aspect wide, fov_y unused (top, front and side views, editors); depth falls linearly from 1 at near to 0 at far. Culling, the occlusion test, detail levels (the size of an instance is its sphere's diameter over h, at any distance) and the sun's shadows (the cascades split the view's box uniformly) work as for a perspective camera. None: perspective
impl Camera
fn look_at(eye: [f64; 3], target: [f64; 3], up: [f64; 3], fov_y: f64, aspect: f64, near: f64, far: f64) -> Cameraat eye looking at target;upsays which way is up on the screenfn ortho_at(eye: [f64; 3], target: [f64; 3], up: [f64; 3], height: f64, aspect: f64, near: f64, far: f64) -> Camera(G7f) an orthographic camera at eye looking at target, the viewheightworld units high; near and far along the view (far finite)struct Viewmodel(G7f) the viewmodel's lens (Scene::set_viewmodel): the instances of Scene::add_viewmodel (a weapon before the camera) are drawn with this field of view and depth range after the world, in front of all of it (the world's depth takes 0 ..= 0.5, the viewmodel's 0.5 ..= 1), lit by the scene's sun, shadows, lights and environment. Made withnewand changed field by field (it may grow)fov_y: f64-- the vertical field of view in radiansnear: f64-- its own near and far planes (finite, 0 < near < far), distances along the camera's forwardfar: f64
impl Viewmodel
const fn new(fov_y: f64, near: f64, far: f64) -> Viewmodelstruct Sunone sun and an ambient light, linear, in the units of KHR_lights_punctual: a white matte surface facing the sun shows color / pi, one under the ambient light alone shows ambient (before the exposure)direction: [f64; 3]-- towards the sun, any lengthcolor: [f32; 3]-- illuminance per channel (lux)ambient: [f32; 3]-- the radiance of a uniform environment around the scene
impl Sun
const DEFAULT: Sun = Sun { direction: [0.3, 0.8, 0.5], color: [0.75 * core::f3 ...a white matte face towards the sun shows 0.75 + 0.25 (0.75 pi lux, ambient 0.25)enum LightKind(G5c) a point or spot light (KHR_lights_punctual): no shadowsPointSpot { inner: f32, outer: f32 }-- cone angles from the axis in radians, 0 <= inner < outer <= pi / 2: full inside inner, nothing beyond outer
struct Light(G5c) a point or spot light of a Scenekind: LightKindpos: [f64; 3]direction: [f64; 3]-- a spot light's axis, the way it shines (any length but 0)color: [f32; 3]-- linear colour, and the intensity in candela: color * intensity / d^2 reaches a surface d awayintensity: f32range: Option<f32>-- where it ends, KHR_lights_punctual's window clamp(1 - (d / range)^4, 0, 1); None: never
impl Light
const fn point(pos: [f64; 3], color: [f32; 3], intensity: f32, range: Option<f32>) -> Lighta point light of colour times intensity at posenum Tonemapwhat the fragment shader does with the light it computed (times the exposure)Neutral-- Khronos PBR Neutral: base colours stay up to 0.76, highlights are compressed towards whiteNone-- none: linear values, clamped by the target's format (HDR targets such as Rgba16Float keep them)
struct UploadInfowhat prepare sent for this framechanged: u32-- slots through the scatter shaderfull: bool-- every slot, from a temporary bufferlists: bool-- the lists' layout changedbytes: u64-- everything prepare wrote for the GPU, view and lights included
struct ListKind(G7f) what ListInfo cannot say (it is not #[non_exhaustive]): more about a list, in the order of Scene::listsdouble_sided: bool-- its instances' materials are double-sided: drawn without culling, back faces lit with their normal turned round
struct ListInfoa list of the scenemesh: MeshIdmirrored: bool-- its instances are mirrored (drawn with clockwise front faces)class: AlphaClass-- the alpha class of its instances' materials (drawn with or without a discard)count: u32-- the instances of this mesh, side and class, and the room for them in the visible list (G7f: none for blended instances, they go into the blended instances' list)capacity: u32room: u32-- (G5d) the instances that may land here: its own and those of meshes that take it as a detail levelfirst: u32-- its first place in the visible listrecord: u32-- its draw record (draws_buffer, late_buffers, cascade_buffers: 5 u32 each); the records lie by width of indices, class and side
struct FrameStatswhat a finished frame measured (Scene::set_stats)frame: u64-- counts the scene's frames from 0visible: u64-- instances the compute shader found visible (with the occlusion test: drawn in phase 1 or 2)late: u64-- (G5d) of them, those phase 2 of the occlusion test drew (0 without it)stamps: Option<[f64; 4]>-- the GPU's clock (ms) at the start, after the uploads, after the camera's culling (phase 1), after the frame (no timestamps here: None)cascades: [[f64; 2]; CASCADES_MAX]-- (G5c) per cascade of the sun, ms: its culling, its depth pass (0 for cascades not drawn)draw: f64-- (G5c) the main render pass, ms (G5d: both phases' passes)occlusion: [f64; 3]-- (G5d) the occlusion test, ms: building the pyramid, phase 2's culling, phase 2's pass (0 without it)
struct Sceneinstances, camera and sun of one scene of a Renderer
impl Scene
fn new(r: &Renderer) -> Result<Scene>fn add(&mut self, i: Instance) -> Result<InstanceId>a new instance, on a place that came free if there is one (its list: with the next prepare)fn add_viewmodel(&mut self, i: Instance) -> Result<InstanceId>(G7f) an instance of the viewmodel (Scene::set_viewmodel; without one it is not drawn): its transform is in the camera's space (x right, y up, -z forward, as glTF's cameras), it follows the camera, is drawn with the viewmodel's lens in front of the world, lit by the scene's sun, shadows and lights (it casts no shadows and hides nothing from the occlusion test). set_transform, set_material, set_mesh and remove work as for the others. Its material may not be blended (prepare: Invalid)fn remove(&mut self, id: InstanceId) -> Result<()>the instance goes; its place comes free (and its list loses it with the next prepare)fn set_transform(&mut self, id: InstanceId, t: &Transform) -> Result<()>a new transform; one that mirrors where the old did not (or the other way round) moves the instance to its mesh's list of the other side, as set_mesh does (with the next prepare)fn transform(&self, id: InstanceId) -> Result<Transform>fn set_material(&mut self, id: InstanceId, m: MaterialId) -> Result<()>a material of another alpha class moves the instance to the list of that class with the next prepare (until then a frame shows the old material: it goes up with prepare too)fn set_mesh(&mut self, id: InstanceId, m: MeshId) -> Result<()>the instance's list of the new mesh, with the next preparefn len(&self) -> u32instances alivefn is_empty(&self) -> boolfn set_camera(&mut self, c: &Camera)fn camera(&self) -> &Camerafn set_sun(&mut self, s: &Sun)fn set_exposure(&mut self, e: f32)what the light is multiplied by before the tone mapper (1 at first; not finite: 1)fn exposure(&self) -> f32fn set_tonemap(&mut self, t: Tonemap)Tonemap::Neutral at firstfn set_shadows(&mut self, s: Option<&Shadows>) -> Result<()>(G5c) the sun's shadows, None (at first) for none; Invalid for values out of rangefn shadows(&self) -> Option<Shadows>fn set_environment(&mut self, k: Option<f32>)(G5c) Some(k): the renderer's environment (Renderer::set_environment) times k lights the scene in place of Sun::ambient (until it has one, Sun::ambient does); None (at first): Sun::ambientfn set_lights(&mut self, lights: &[Light]) -> Result<()>(G5c) the point and spot lights (all of them: they go up with the next frame); Invalid for values out of range, and nothing changes thenfn lights(&self) -> &[Light]fn cascades(&self) -> &[Cascade](G5c; tests, tools) the cascades the last prepare computedfn cascade_buffers(&self, k: usize) -> Option<(&Buffer, &Buffer)>(G5c; tests, tools) a cascade's draw records and visible list after a frame's cullingfn set_origin(&mut self, origin: [f64; 3])the point of the world that is (0, 0, 0) on the GPU. Keep it near the camera: f32 has seven digits. Moving it uploads every instance oncefn origin(&self) -> [f64; 3]fn set_culling(&mut self, on: bool)false: every live instance is drawn (a test's comparison, a debugging aid)fn set_occlusion(&mut self, on: bool)(G5d) the camera's occlusion test against a depth pyramid in two phases (docs/RENDER3D.md "Verdeckung"): true at first. It runs when the depth attachment can be sampled (the renderer's own can) and culling is onfn occlusion(&self) -> boolfn late_buffers(&self) -> (&Buffer, &Buffer)(G5d; tests, tools) phase 2's draw records and visible list after a frame (laid out as draws_buffer and visible_buffer, which hold phase 1's with the occlusion test)fn set_stats(&mut self, on: bool)FrameStats of each frame: the instances found visible (a small copy per frame), the GPU's timesfn upload_info(&self) -> UploadInfowhat the last prepare sentfn lists(&self) -> Vec<ListInfo>the lists as the last prepare settled them, in order (list i is what list_of holds for its instances; its draw record: ListInfo::record)fn list_kinds(&self) -> Vec<ListKind>(G7f) more about the lists, in the order of lists(): double-sided or notfn blend_buffer(&self) -> &Buffer(G7f; tests, tools) the blended instances' list after a frame: a VkDrawIndirectCommand (vertices per instance, the instances), then per instance 4 u32: the bits of !(distance squared from the eye; f32), its slot, the draw record of its list (lists().record), the list's flags (1: 32-bit indices, 2: double-sided, 4: mirrored); sorted, farthest first. Its draw: blend_drawn()fn blend_drawn(&self) -> bool(G7f) the last prepare found blended instances that may be drawn (a list of them has room)fn draws_buffer(&self) -> &Buffer(tests, tools) the camera's draw records after a frame's culling: 5 u32 per list at ListInfo::record, instance_count secondfn visible_buffer(&self) -> &Buffer(tests, tools) the camera's visible list after a frame's culling: slots, a list's at ListInfo::firstfn set_viewmodel(&mut self, v: Option<&Viewmodel>) -> Result<()>(G7f) the viewmodel's lens (None at first: its instances are not drawn, the world's depth is as it was); Invalid for values out of range. With one the world's depth takes 0 ..= 0.5 (halved: the image stays the same but where two depths tie, as GPUs interpolate depth in steps of their own), the viewmodel's 0.5 ..= 1fn viewmodel(&self) -> Option<Viewmodel>fn viewmodel_buffers(&self) -> Option<(&Buffer, &Buffer)>(G7f; tests, tools) the viewmodel's draw records and visible list after a frame (as draws_buffer, visible_buffer)fn set_outline(&mut self, o: Option<&Outline>) -> Result<()>(G7f) lines on the edges of the depth buffer, over the opaque image (None at first); Invalid for values out of range. They need a depth attachment with TextureUsage::SAMPLED (the renderer's own has it): record says Invalid otherwisefn outline(&self) -> Option<Outline>fn set_antialias(&mut self, a: Antialias)(G7f) anti-aliasing over the finished image (Antialias::None at first)fn antialias(&self) -> Antialiasfn set_particles(&mut self, capacity: u32) -> Result<()>(G7f) room for this many particles (0, at first: none); a new capacity starts with none alive. Unsupported beyond what a binding reachesfn particle_capacity(&self) -> u32(G7f) the particles' room (0: none)fn set_time(&mut self, t: f64)(G7f) the particles' clock in seconds (the game's time; 0 at first): births and ages are read from it, so the same times give the same frames. It should not go backfn time(&self) -> f64fn add_emitter(&mut self, e: &Emitter) -> Result<EmitterId>(G7f) an emitter: what its particles look like and how they move; Invalid for values out of rangefn set_emitter(&mut self, id: EmitterId, e: &Emitter) -> Result<()>(G7f) a new description (its next particles take it; the living keep theirs); its serial numbers go onfn remove_emitter(&mut self, id: EmitterId) -> Result<()>(G7f) the emitter goes (its living particles stay until they die)fn emit(&mut self, id: EmitterId, at: [f64; 3], dir: [f64; 3], count: u32) -> Result<()>(G7f)countparticles of an emitter, born now (Scene::set_time) at a point in a cone around a direction (the world's, or for a viewmodel emitter the camera's space). They take the next places of the ring, the oldest are overwritten. Invalid without room for particles (set_particles) or for values not finitefn clear_particles(&mut self)(G7f) every particle dies nowfn particle_buffer(&self) -> Option<&Buffer>(G7f; tests, tools) the particles' list after a frame: a VkDrawIndirectCommand (6 vertices per particle, the particles alive), then per particle 4 u32: its key (farthest first), its place in the ring, 0, 0; sorted. None without roomfn particle_records(&self) -> Option<&Buffer>(G7f; tests, tools) the ring of records (particles.rs: 16 u32 each; particles::motion reads one)fn particle_epoch(&self) -> f64(G7f; tests, tools) the epoch of the particles' clock: a record's birth counts microseconds from itfn wait_slot(&mut self) -> Result<()>wait for the frame that last used this frame's slot, so its data can be written (the window's acquire has usually done so). prepare does it too; call it first to tell the wait from the work. The browser cannot wait, and needs not: its writes go in queue orderfn take_stats(&mut self) -> Vec<FrameStats>the finished frames' stats since the last callfn collect_stats(&mut self)after Device::wait_idle: the stats of what was still in flightfn prepare(&mut self, r: &mut Renderer) -> Result<()>the frame's data for Renderer::record: waits for this slot's last frame, sends what changedfn submitted(&mut self, id: SubmitId)the frame went to the GPU: Queue::submit's or Swapchain::present's answer
render3d/shadow.rs#
Source: lib/render3d/shadow.rs
shadow -- the sun's cascaded shadow maps (G5c; docs/RENDER3D.md "Schatten"): one Depth32Float array of
CASCADES_MAX layers owned by the Renderer, group 2 of the main pass with a linear comparison sampler, and the
cascades' geometry on the CPU in f64.
A cascade covers a slice of the camera's view (splits between uniform and logarithmic) by the bounding
sphere of the slice: its radius depends only on the camera's field of view and the splits, so turning the
camera changes nothing in the map's scale; its centre is snapped to the map's texel grid in the light's
basis, in world coordinates (f64, not relative to the origin), so moving the camera moves the map by whole
texels only. Light space: z towards the sun, x and y from a fixed reference (world y, or x for a sun
overhead). Depth is reverse Z (the near plane, towards the sun, at 1), the planes of the visibility
test are the box's four sides and its far side; there is no near plane: casters between the sun and the
cascade stay in the list and are flattened onto the near plane by the vertex shader (pancaking).
The map stays in Layout::Sampled between frames: a cascade's pass takes its layer from Sampled to
DepthTarget and back (the pass's own barriers: the last frame's fragment reads before the depth writes, the
depth writes before this frame's fragment reads).
/// the most cascades of the sun
CASCADES_MAX: usize = 4
struct Shadowsthe sun's shadows: cascaded shadow maps (Scene::set_shadows)cascades: u32-- 1 ..= CASCADES_MAXsize: u32-- texels a side of each cascade's map (16 ..= 8192)distance: f64-- how far along the view shadows reach (the last cascade's far end)split: f64-- how the slices are split: 0 uniform, 1 logarithmicreach: f64-- how far towards the sun beyond a cascade's sphere casters keep their depth; nearer the sun they are flattened onto the near plane and still cast (a triangle crossing that plane gets a wrong depth)
impl Shadows
const DEFAULT: Shadows = Shadows { cascades: 4, size: 2048, distance: 100.0, split ...4 cascades of 2048 texels up to 100 from the eye, split 0.75, reach 100: the default for level Vollconst BASIS: Shadows = Shadows { cascades: 2, size: 1024, ..Shadows::DEFAULT }(G5e3) 2 cascades of 1024 texels, the rest as DEFAULT (up to 100, split 0.75, reach 100): the default for level Basis (the browser, older and weak GPUs, phones), half the shadows' GPU time or less, coarser texels near the camera (docs/RENDER3D.md)const fn for_level(level: Level) -> Shadows(G5e3) the default for a device of this level: BASIS on Basis, DEFAULT on Voll (Shadows::for_level(dev.level()))struct Cascadea cascade as the CPU computed it for a frame (Scene::cascades)near: f64-- the slice of the view it covers (distances along the camera's forward)far: f64center: [f64; 3]-- its sphere's centre after snapping (world coordinates), its radius, one texel in world unitsradius: f64texel: f64axes: [[f64; 3]; 3]-- the light's basis: x and y of the map, z towards the sunz_far: f64-- the depth range along z (world, absolute): far side, near sidez_near: f64
render3d/texture.rs#
Source: lib/render3d/texture.rs
texture -- the textures of a Renderer (G5b; docs/RENDER3D.md "Texturen"): one texture array per size class
and colour space, chosen per instance through its material in the fragment shader (a switch over the five
classes), one repeating trilinear sampler for everything. The same binding model on Vulkan Voll, Basis and
WebGPU, from the same WGSL: lib/wgsl has no binding arrays and WebGPU none in its core.
Classes are squares of 128, 256, 512, 1024 and 2048 texels with every mip level. A texture of another
size goes into the class of its next power of two (128 at least, 2048 at most), resampled on the CPU:
nearest for textures drawn with a nearest filter (a small one is repeated texel for texel), else
bilinear upwards and a box downwards, in linear light for sRGB. The mip levels are 2 x 2 box filters on
the CPU, sRGB decoded by a table, averaged, encoded again (exactly rounded through a table of thresholds).
Wrap modes and nearest filtering happen in the shader (draw.wgsl: wrap_coord), exactly, because the
classes are powers of two.
An array grows by doubling its layers: a new texture, the old layers copied through a buffer, the old one
dropped once the GPU is done with it. Uploads go through Queue::write_texture (staged before the next
submission, after a barrier from Sampled: frames still reading the array finish first).
(G7f) Removing a texture: its id becomes invalid (store.rs: a slot and a generation), its layer goes on its array's
list of free layers and the next texture of that class and colour space takes it (the barrier from Sampled above is
what makes that safe against frames in flight). Refused while a material names it: each texture counts the material
rows that do.
/// the size classes: 128 << k texels square
CLASSES: usize = 5
CLASS_MIN: u32 = 128
CLASS_MAX: u32 = CLASS_MIN << (CLASSES - 1)
struct TextureData<'a>what add_texture takes: rows from the top, 4 bytes per texel, r g b a with straight alphawidth: u32height: u32rgba: &'a [u8]srgb: bool-- colour (base colour, emissive): sRGB; data (metallic-roughness, normals, occlusion): linearnearest: bool-- it is drawn with a nearest filter: a resampling to its class keeps the texels (else bilinear)
struct TextureId(pub u32)a texture of a Renderer. (G7f) As MeshId: a place and how often it was used before (Renderer::remove_texture)struct TextureInfowhere a texture liesclass: u32-- its class (0 ..), the class's size, its layer in the class's arraysize: u32layer: u32srgb: boolwidth: u32-- the size it was given; resampled: it was not the class's sizeheight: u32resampled: bool
enum WrapRepeatClampMirror
enum MipNone-- level 0 onlyNearestLinear
struct Samplinghow a material samples a texture (glTF's samplers)mag_nearest: boolmin_nearest: boolmip: Mipwrap_u: Wrapwrap_v: Wrap
impl Sampling
const LINEAR: Sampling = Sampling { mag_nearest: false, min_nearest: false, mip: M ...repeating, trilinear: the sampler's own path in the shaderconst NEAREST: Sampling = Sampling { mag_nearest: true, min_nearest: true, mip: Mip ...repeating, nearest texels of the nearest levelstruct TextureRefa texture of a material: which, sampled how (uv set 0)texture: TextureIdsampling: Sampling
fn class_of(w: u32, h: u32) -> u32the class of a texture of w x h: its next power of two, 128 ..= 2048fn mip_chain(d: &TextureData) -> Vec<Vec<u8>>what add_texture uploads, without a device (tools, measurements): the texels resampled to their class's size, then each mip level down to 1 x 1; rows of 4 bytes per texel. Empty when the data is too short