Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(render): rebind Hi-Z on enable and restore alloc spread 4
The gate sat on the measured high sample and allowed a spread of 6.
Five lavapipe runs with validation on, and five with it off, each
recorded [119, 116, 115, 116, 115, 115]. Spread inside a run is 4.
The ceiling is 130, eleven above that sample and still under one
extra pass.

set_sample_hiz(true) drops any pyramid so the next draw_into copies
that frame's depth view, including when the size is unchanged.
The trace and phase-plan decision 2 describe that gate.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 20, 2026
commit f56b2fa46c78ee85f5962cc395c62ab0852bfbec
47 changes: 33 additions & 14 deletions astraweave-render/src/hiz_pyramid.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//! Shared Hi-Z (Hierarchical Depth) min-depth pyramid for screen-space tracing.
//! Shared Hi-Z (Hierarchical Depth) min-depth pyramid.
//!
//! Builds a min-depth mip chain from the depth buffer. Used by SSR and SSGI
//! to accelerate ray traversal by skipping empty space at coarse mip levels.
//! Builds a min-depth mip chain from a depth view. `Renderer::draw_into`
//! records it only when `sample_hiz` is set, and that build copies the depth
//! view from the frame that enabled it. Occlusion, SSR, and SSGI do not
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
//! sample the pyramid. SSGI reads scene depth.
//!
//! The pyramid stores the **minimum** depth in each 2×2 block, so the tracer
//! knows that if the ray depth is less than the stored min-depth at a given
//! mip level, there is no surface intersection in that region and the ray
//! can safely advance to the next cell.
//! The pyramid stores the **minimum** depth in each 2×2 block, so a future
//! tracer can skip a region whose ray depth is less than that minimum.

/// Min-depth Hi-Z pyramid for screen-space ray tracing (SSR, SSGI).
/// Min-depth Hi-Z pyramid. Nothing samples [`HizPyramid::view`] until a pass is wired to it.
pub struct HizPyramid {
copy_pipeline: wgpu::ComputePipeline,
downsample_pipeline: wgpu::ComputePipeline,
Expand All @@ -19,22 +19,26 @@ pub struct HizPyramid {
/// Per-mip views for downsample dispatch (single-mip views).
#[allow(dead_code)] // views must be kept alive for bind groups to remain valid
mip_views: Vec<wgpu::TextureView>,
/// Full mip-chain view for sampling in SSR/SSGI shaders.
/// Full mip-chain view. No pass samples this until one is wired to it.
full_view: wgpu::TextureView,
/// bind_groups[0]: copy — src depth → mip 0.
/// bind_groups[1..]: downsample — mip[i-1] → mip[i].
bind_groups: Vec<wgpu::BindGroup>,
mip_count: u32,
width: u32,
height: u32,
/// Depth view bound into the mip-0 copy. A later frame with a different
/// view, even at the same size, must build a new pyramid.
src_depth: wgpu::TextureView,
}

impl HizPyramid {
/// Create a new Hi-Z pyramid for the given resolution.
///
/// `src_depth_view` is a `texture_depth_2d` view (`Depth32Float`). The copy
/// stores it into mip 0 as `R32Float`. Downsample and SSR/SSGI read that
/// copy with `textureLoad`.
/// stores it into mip 0 as `R32Float`. Downsample reads that copy with
/// `textureLoad`. The view is kept so a later frame can tell whether this
/// pyramid still copies that source.
pub fn new(
device: &wgpu::Device,
width: u32,
Expand Down Expand Up @@ -211,19 +215,28 @@ impl HizPyramid {
mip_count,
width,
height,
src_depth: src_depth_view.clone(),
}
}

/// Returns the full mip-chain view for SSR/SSGI shader sampling.
/// Full mip-chain view. No pass samples this until one is wired to it.
pub fn view(&self) -> &wgpu::TextureView {
&self.full_view
}

/// The R32Float pyramid texture. SSR, SSGI, and occlusion sample [`Self::view`].
/// The R32Float pyramid texture. A consumer samples [`Self::view`].
pub fn texture(&self) -> &wgpu::Texture {
&self.hiz_texture
}

/// The mip-0 copy was bound from this depth view.
///
/// wgpu compares view identity, so a second view of the same texture is
/// a different source and needs its own pyramid.
pub fn copies_from(&self, view: &wgpu::TextureView) -> bool {
&self.src_depth == view
}

/// Number of mip levels in the pyramid.
pub fn mip_count(&self) -> u32 {
self.mip_count
Expand Down Expand Up @@ -274,7 +287,7 @@ impl HizPyramid {
height: u32,
src_depth_view: &wgpu::TextureView,
) {
if self.width == width && self.height == height {
if self.width == width && self.height == height && self.copies_from(src_depth_view) {
return;
}
*self = Self::new(device, width, height, src_depth_view);
Expand Down Expand Up @@ -348,5 +361,11 @@ mod tests {
let pyramid = HizPyramid::new(&device, 1920, 1080, &depth_view);
assert_eq!(pyramid.dimensions(), (1920, 1080));
assert_eq!(pyramid.mip_count(), 11);
assert!(pyramid.copies_from(&depth_view));
let other = depth_tex.create_view(&wgpu::TextureViewDescriptor::default());
assert!(
!pyramid.copies_from(&other),
"a second view of the same texture is a different copy source"
);
}
}
2 changes: 1 addition & 1 deletion astraweave-render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub mod graph_adapter; // runs a graph on Renderer frames
pub mod gtao; // Ground Truth Ambient Occlusion with visibility bitmask
pub mod hdr_pipeline; // HDR rendering pipeline orchestration (tonemap, color grading, post-FX chain)
pub mod hdri_catalog;
pub mod hiz_pyramid; // Shared Hi-Z min-depth pyramid for SSR/SSGI ray acceleration
pub mod hiz_pyramid; // Shared Hi-Z min-depth pyramid; draw_into records it only when sample_hiz is set
pub mod lumen; // Lumen Global Illumination orchestrator (Phase 5)
pub mod material; // shared authored materials API + GPU arrays
pub mod material_extended; // Phase PBR-E: Advanced materials (clearcoat, anisotropy, SSS, sheen, transmission)
Expand Down
43 changes: 34 additions & 9 deletions astraweave-render/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1048,10 +1048,11 @@ pub struct Renderer {
/// Named models for multi-model rendering (terrain, trees, rocks, etc.)
models: std::collections::HashMap<String, RenderModel>,
/// One Hi-Z pyramid. Built only when [`Self::sample_hiz`] is set, because
/// each mip is its own wgpu compute pass (#269).
/// each mip is its own wgpu compute pass (#269). [`Self::set_sample_hiz`]
/// drops it so the next frame copies that frame's depth view.
hiz: Option<crate::hiz_pyramid::HizPyramid>,
/// A recorded pass will sample [`crate::hiz_pyramid::HizPyramid::view`].
/// SSGI reads scene depth directly, so this stays false until that wiring exists.
/// Set with [`Self::set_sample_hiz`]. Default false: no pass samples
/// [`crate::hiz_pyramid::HizPyramid::view`]. SSGI reads scene depth.
sample_hiz: bool,
/// GL rejects `textureLoad` on `texture_depth_2d`, so the pyramid stays off.
hiz_depth_load: bool,
Expand Down Expand Up @@ -8255,12 +8256,12 @@ fn vs(input: VSIn) -> VSOut {
view
}

/// Copy this frame's depth into the shared Hi-Z pyramid.
/// Close the open pass-boundary timing gap.
///
/// The pyramid is presentation-only. Occlusion may consult it next frame.
/// It is not read back into the simulation. The first frame builds it;
/// later frames only dispatch the copy and the min-depth downsample.
/// Begin the `frame` pair when the device can write timestamps on the encoder.
/// Hi-Z is not this gap. [`Self::record_hiz`] builds the pyramid only when
/// [`Self::sample_hiz`] is set, and that build copies the depth view from
/// the `draw_into` that enabled it. Occlusion, SSR, and SSGI do not sample
/// the pyramid. It is not read back into the simulation.
///
/// Pass-boundary timestamps on Vulkan are `BOTTOM_OF_PIPE`. A pass that
/// does no draws can land both writes on the same tick. The encoder pair
Expand Down Expand Up @@ -8324,6 +8325,30 @@ fn vs(input: VSIn) -> VSOut {
}
}

/// Turn Hi-Z recording on or off.
///
/// The default is off. No pass samples [`crate::hiz_pyramid::HizPyramid::view`].
/// Turning the flag on drops any pyramid so the next [`Self::draw_into`]
/// copies the depth view from that call, including when the size matches
/// a view captured earlier. Turning it off drops the pyramid too.
pub fn set_sample_hiz(&mut self, enabled: bool) {
if self.sample_hiz != enabled {
self.hiz = None;
}
self.sample_hiz = enabled;
}

/// The pyramid from the last frame that recorded Hi-Z, if that flag is on.
pub fn hiz_pyramid(&self) -> Option<&crate::hiz_pyramid::HizPyramid> {
self.hiz.as_ref()
}

/// Build the Hi-Z pyramid when [`Self::sample_hiz`] is on.
///
/// The copy source is `depth_view`, or the renderer's own depth when the
/// caller passes `None`. A frame whose depth view is a different object
/// builds a new pyramid even when the size is unchanged. Each mip is its
/// own compute pass (#269). Nothing in `draw_into` samples the result.
fn record_hiz(
&mut self,
enc: &mut wgpu::CommandEncoder,
Expand All @@ -8342,7 +8367,7 @@ fn vs(input: VSIn) -> VSOut {
let rebuild = self
.hiz
.as_ref()
.map(|pyramid| pyramid.dimensions() != (width, height))
.map(|pyramid| pyramid.dimensions() != (width, height) || !pyramid.copies_from(&source))
.unwrap_or(true);
if rebuild {
self.hiz = Some(crate::hiz_pyramid::HizPyramid::new(
Expand Down
19 changes: 10 additions & 9 deletions astraweave-render/tests/frame_alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,17 @@ fn draw_into_allocates_nothing_after_warmup() {
eprintln!("draw_into alloc samples: {samples:?}");
let min = *samples.iter().min().unwrap();
let max = *samples.iter().max().unwrap();
// Measured after the unused Hi-Z chain stopped recording:
// [119, 116, 115, 116, 115, 115]. `draw_into` does not build the
// pyramid unless a pass samples `HizPyramid::view` (`sample_hiz`).
// Nothing does. The six mip passes were the jump to ~217. What
// remains is wgpu-core 25 `BasePass::new` for the passes that still
// record (shadows, sky, cloud shadow, main, post). Upstream still
// allocates that Vec per pass. Engine scratch stays at zero
// (`update_instances` above). A new recorded pass moves the band.
// Lavapipe, 64×64, validation on and off, five runs each:
// [119, 116, 115, 116, 115, 115]. Spread inside a run is 4.
// `draw_into` does not build the pyramid unless `sample_hiz` is set.
// The six mip passes were the jump to ~217 (about 18 allocations
// each). What remains is wgpu-core 25 `BasePass::new` for the passes
// that still record. Engine scratch stays at zero (`update_instances`
// above). Ceiling 130 is 11 above the high sample and still under
// one extra pass (119 + 18). Floor 100 is 15 under the low sample,
// so a dropped pass fails too.
assert!(
max <= 120 && min >= 100 && max - min <= 6,
max <= 130 && min >= 100 && max - min <= 4,
"draw_into allocs left the wgpu pass floor: {samples:?}"
);
});
Expand Down
116 changes: 116 additions & 0 deletions astraweave-render/tests/hiz_rebind.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//! Enabling `sample_hiz` rebuilds the pyramid against that frame's depth view.
//!
//! The copy bind group is fixed at `HizPyramid` creation. A later `draw_into`
//! with a different view of the same size must not keep the view captured
//! earlier.

use astraweave_render::Renderer;

fn color_target(device: &wgpu::Device) -> wgpu::TextureView {
let target = device.create_texture(&wgpu::TextureDescriptor {
label: Some("hiz rebind color"),
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
target.create_view(&wgpu::TextureViewDescriptor::default())
}

fn depth_target(device: &wgpu::Device, label: &str) -> (wgpu::Texture, wgpu::TextureView) {
let depth = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: 64,
height: 64,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth32Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = depth.create_view(&wgpu::TextureViewDescriptor::default());
(depth, view)
}

fn draw(renderer: &mut Renderer, color: &wgpu::TextureView, depth: Option<&wgpu::TextureView>) {
let device = renderer.device().clone();
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("hiz rebind"),
});
renderer
.draw_into(color, depth, &mut encoder)
.expect("draw_into");
drop(encoder);
}

#[test]
fn enabling_sample_hiz_rebinds_to_the_current_depth_view() {
pollster::block_on(async {
let mut renderer = Renderer::new_headless(64, 64)
.await
.expect("headless renderer");
if astraweave_render::gpu_fault::skip_without_depth_texture_load(
renderer.device(),
"enabling_sample_hiz_rebinds_to_the_current_depth_view",
) {
return;
}
let device = renderer.device().clone();
let color = color_target(&device);
let (_depth_a, view_a) = depth_target(&device, "depth a");
let (_depth_b, view_b) = depth_target(&device, "depth b");

draw(&mut renderer, &color, Some(&view_a));
assert!(
renderer.hiz_pyramid().is_none(),
"sample_hiz stays off until set, so no pyramid is captured at creation"
);

renderer.set_sample_hiz(true);
draw(&mut renderer, &color, Some(&view_a));
let pyramid = renderer
.hiz_pyramid()
.expect("enabling sample_hiz builds a pyramid");
assert!(
pyramid.copies_from(&view_a),
"the first enabled frame copies the depth view from that draw_into"
);
assert!(!pyramid.copies_from(&view_b));

draw(&mut renderer, &color, Some(&view_b));
let pyramid = renderer
.hiz_pyramid()
.expect("a same-size view still rebuilds");
assert!(
pyramid.copies_from(&view_b),
"a different depth view of the same size replaces the copy source"
);
assert!(!pyramid.copies_from(&view_a));

renderer.set_sample_hiz(false);
draw(&mut renderer, &color, Some(&view_a));
assert!(
renderer.hiz_pyramid().is_none(),
"turning sample_hiz off drops the pyramid"
);

renderer.set_sample_hiz(true);
draw(&mut renderer, &color, Some(&view_a));
let pyramid = renderer
.hiz_pyramid()
.expect("enabling again builds against the current view");
assert!(pyramid.copies_from(&view_a));
assert!(!pyramid.copies_from(&view_b));
});
}
4 changes: 3 additions & 1 deletion astraweave-render/tests/stream_fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,10 @@ fn fallback_frame_does_not_allocate_before_the_texture_is_resident() {
eprintln!("stream fallback draw_into alloc samples: {samples:?}");
let min = *samples.iter().min().unwrap();
let max = *samples.iter().max().unwrap();
// Same floor as `frame_alloc`: high sample 119, spread 4.
// Ceiling 130 leaves 11 of room and still fails one extra pass.
assert!(
max <= 120 && min >= 100 && max - min <= 6,
max <= 130 && min >= 100 && max - min <= 4,
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
"fallback frame left the wgpu pass floor: {samples:?}"
);

Expand Down
Loading
Loading