Skip to content
Merged
Prev Previous commit
Next Next commit
fix(render): clear depth for the Bruneton sky and test pixels
Aerial treats only a cleared depth of 1 as sky. The ray uses the inverse
view-projection, the scene sun, and the camera clip planes. draw_into
clears HDR and depth when Bruneton replaces SkyRenderer. The runtime
flag follows PresentationQuality, and a headless frame checks sky
against near and far geometry.

Co-authored-by: Andrew Brown <lazyxeon@users.noreply.github.com>
  • Loading branch information
cursoragent and lazyxeon committed Oct 21, 2026
commit bcc89aec80e65cc7cff29739640878256c7f87ec
7 changes: 4 additions & 3 deletions aravath_runtime/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1437,10 +1437,11 @@ fn smoke_test(volumetrics: bool) -> anyhow::Result<()> {
Err(err) => return Err(err),
};
startup::stage("headless renderer ready");
renderer.set_atmosphere_enabled(astraweave_render::PresentationQuality::default().atmosphere());
if renderer.atmosphere_enabled() {
let quality = astraweave_render::PresentationQuality::default();
renderer.set_atmosphere_enabled(quality.atmosphere());
if renderer.atmosphere_enabled() != quality.atmosphere() {
anyhow::bail!(
"atmosphere is on before a measured heavy-scene median. {}",
"atmosphere flag does not follow PresentationQuality. {}",
startup::log_locations()
);
}
Expand Down
8 changes: 5 additions & 3 deletions astraweave-render/shaders/atmosphere/aerial_perspective.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@ fn linearize_depth(d: f32) -> f32 {
}

fn reconstruct_world_pos(uv: vec2<f32>, depth: f32) -> vec3<f32> {
let ndc = vec4<f32>(uv * 2.0 - 1.0, depth, 1.0);
// uv.y 0 is the top of the texture. This view is Y-up, so NDC y is +1 there.
let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, depth, 1.0);
let world_h = params.inv_view_proj * ndc;
return world_h.xyz / world_h.w;
}
Expand All @@ -98,8 +99,9 @@ fn aerial_perspective_main(@builtin(global_invocation_id) gid: vec3<u32>) {
let scene_color = textureSampleLevel(t_scene, s_linear, uv, 0.0).rgb;
let depth_raw = textureLoad(t_depth, pixel, 0);

// Sky pixels take the Bruneton sky. The HDRI sky is not drawn in this mode.
if (depth_raw >= 0.9999) {
// Only the cleared far plane is sky. A looser cutoff treats distant
// geometry (about 333 m at zfar 500) as sky.
if (depth_raw == 1.0) {
let sky = textureLoad(t_sky, pixel, 0);
textureStore(t_output, pixel, vec4<f32>(sky.rgb, 1.0));
Comment on lines +104 to +106

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve transparent water when replacing sky pixels

When atmosphere is enabled and water is visible over the far-plane clear, this branch replaces the already-rendered water with t_sky. renderer.rs:8067-8077 records run_water_pass before Bruneton, while water.rs:584 disables water depth writes, so those water pixels still have depth 1.0; the previous shader preserved scene_color for them. Record Bruneton before transparent water/overlays or otherwise preserve their color.

Useful? React with 👍 / 👎.

return;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Expand Down
3 changes: 2 additions & 1 deletion astraweave-render/shaders/atmosphere/sky_render.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ fn ray_sphere_dist(origin_h: f32, cos_zenith: f32, sphere_r: f32) -> f32 {

fn pixel_to_ray(pixel: vec2<f32>) -> vec3<f32> {
let uv = pixel * params.inv_resolution;
let ndc = vec4<f32>(uv * 2.0 - 1.0, 1.0, 1.0);
// uv.y 0 is the top of the texture. This view is Y-up, so NDC y is +1 there.
let ndc = vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 1.0, 1.0);
let world_h = params.inv_view_proj * ndc;
let world_pos = world_h.xyz / world_h.w;
return normalize(world_pos - params.view_pos);
Expand Down
39 changes: 22 additions & 17 deletions astraweave-render/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,27 @@ pub struct SkyRenderer {
cached_cube_bg: Option<wgpu::BindGroup>,
}

/// Clear used by the HDRI sky pass. Debug builds use magenta so a missing
/// skybox is visible. Release builds use dark grey. Bruneton uses this same
/// clear when it replaces the sky pass.
pub(crate) fn hdri_sky_clear_color() -> wgpu::Color {
if cfg!(debug_assertions) {
wgpu::Color {
r: 1.0,
g: 0.0,
b: 1.0,
a: 1.0,
}
} else {
wgpu::Color {
r: 0.05,
g: 0.05,
b: 0.05,
a: 1.0,
}
}
}

impl SkyRenderer {
/// Create a new sky renderer
pub fn new(config: SkyConfig) -> Self {
Expand Down Expand Up @@ -575,23 +596,7 @@ impl SkyRenderer {
view: target_view,
resolve_target: None,
ops: wgpu::Operations {
// In debug builds use magenta so a missing skybox is
// immediately visible; in release use dark grey.
load: wgpu::LoadOp::Clear(if cfg!(debug_assertions) {
wgpu::Color {
r: 1.0,
g: 0.0,
b: 1.0,
a: 1.0,
}
} else {
wgpu::Color {
r: 0.05,
g: 0.05,
b: 0.05,
a: 1.0,
}
}),
load: wgpu::LoadOp::Clear(hdri_sky_clear_color()),
store: wgpu::StoreOp::Store,
},
})],
Expand Down
62 changes: 48 additions & 14 deletions astraweave-render/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5576,8 +5576,9 @@ fn vs(input: VSIn) -> VSOut {
self.atmosphere_on = enabled;
}

/// Bruneton sky plus aerial perspective. Off until a GTX 1660 Ti
/// heavy-scene `median_gpu_frame_ms` with `--atmosphere` is at or under 11.
/// Bruneton sky plus aerial perspective. Off until
/// `gpu_frame_budget --scene heavy --atmosphere` prints
/// `median_gpu_frame_ms` at or under 11 on a GTX 1660 Ti.
#[must_use]
pub fn atmosphere_enabled(&self) -> bool {
self.atmosphere_on
Expand Down Expand Up @@ -5651,12 +5652,24 @@ fn vs(input: VSIn) -> VSOut {
let queue = self.queue.clone();
let width = self.config.width.max(1);
let height = self.config.height.max(1);
let inv = self.cached_proj * self.cached_view;
let view_proj = self.cached_proj * self.cached_view;
let inv = view_proj.inverse();
let eye = glam::Vec3::new(
self.camera_ubo.camera_pos_pad[0],
self.camera_ubo.camera_pos_pad[1],
self.camera_ubo.camera_pos_pad[2],
);
let light = glam::Vec3::new(
self.camera_ubo.light_dir_pad[0],
self.camera_ubo.light_dir_pad[1],
self.camera_ubo.light_dir_pad[2],
);
let toward_sun = if light.length_squared() > 1e-6 {
-light.normalize()
} else {
glam::Vec3::Y
};
let (near, far) = clip_planes(self.cached_proj);

if self.atmosphere_on {
if self.atmosphere.is_none() {
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
Expand All @@ -5668,15 +5681,7 @@ fn vs(input: VSIn) -> VSOut {
));
}
if let Some(pass) = self.atmosphere.as_mut() {
pass.prepare_frame(
&queue,
inv,
eye,
glam::Vec3::Y,
glam::Vec3::NEG_Y,
0.1,
200.0,
);
pass.prepare_frame(&queue, inv, eye, toward_sun, -toward_sun, near, far);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
pass.execute(&device, enc, &hdr, depth, gen);
enc.copy_texture_to_texture(
pass.aerial_texture().as_image_copy(),
Expand Down Expand Up @@ -7673,8 +7678,37 @@ fn vs(input: VSIn) -> VSOut {
.as_ref()
.and_then(|resources| resources.hdr_equirect.clone());

// Bruneton is a sky mode, not a second layer on the HDRI sky.
if !self.atmosphere_on {
// Bruneton replaces the HDRI sky. The sky pass is also the clear of
// HDR and of scene depth, so that clear still has to run.
if self.atmosphere_on {
self.close_timing_gap(enc);
let sky_stamp = self.begin_named_stamp(enc, "sky");
{
let _clear = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("atmosphere depth and hdr clear"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &self.hdr_view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(crate::environment::hdri_sky_clear_color()),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_view.unwrap_or(&self.depth.view),
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
});
}
self.end_named_stamp(enc, sky_stamp);
self.open_timing_gap(enc, "after_sky");
} else {
self.close_timing_gap(enc);
let sky_stamp = self.begin_named_stamp(enc, "sky");
let sky_result = self.sky.render(
Expand Down
178 changes: 175 additions & 3 deletions astraweave-render/tests/gated_passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ fn submit(renderer: &mut Renderer, view: &wgpu::TextureView) {
}

#[test]
fn atmosphere_stays_off_until_measured() {
fn atmosphere_follows_the_measured_default() {
pollster::block_on(async {
let renderer = Renderer::new_headless(64, 64).await.expect("headless");
assert!(!renderer.atmosphere_enabled());
assert!(!astraweave_render::PresentationQuality::default().atmosphere());
let quality = astraweave_render::PresentationQuality::default();
assert_eq!(renderer.atmosphere_enabled(), quality.atmosphere());
// The `--atmosphere` cell is blank, so the default stays off.
assert!(!quality.atmosphere());
assert!(astraweave_render::PresentationQuality::Atmosphere.atmosphere());
});
}
Expand All @@ -61,3 +63,173 @@ fn gated_passes_submit_with_scene_depth() {
submit(&mut renderer, &view);
});
}

fn vertical_quad(renderer: &Renderer) -> astraweave_render::Mesh {
let vertices = [
[-0.5, -0.5, 0.0],
[0.5, -0.5, 0.0],
[0.5, 0.5, 0.0],
[-0.5, 0.5, 0.0],
];
let normals = [[0.0, 0.0, 1.0]; 4];
let indices = [0, 1, 2, 0, 2, 3];
renderer.create_mesh_from_arrays(&vertices, &normals, &indices)
}

fn sample(pixels: &[u8], width: u32, x: u32, y: u32) -> [i32; 3] {
let i = ((y * width + x) * 4) as usize;
[pixels[i] as i32, pixels[i + 1] as i32, pixels[i + 2] as i32]
}

fn channel_distance(a: [i32; 3], b: [i32; 3]) -> i32 {
(a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs()
}

fn draw_and_read(renderer: &mut Renderer, atmosphere: bool) -> Vec<u8> {
const WIDTH: u32 = 64;
const HEIGHT: u32 = 64;
renderer.set_atmosphere_enabled(atmosphere);
let device = renderer.device().clone();
let queue = renderer.queue().clone();
device.push_error_scope(wgpu::ErrorFilter::Validation);
let target = device.create_texture(&wgpu::TextureDescriptor {
label: Some("atmosphere readback"),
size: wgpu::Extent3d {
width: WIDTH,
height: HEIGHT,
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 | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("atmosphere frame"),
});
renderer
.draw_into(&view, None, &mut encoder)
.expect("draw_into");
let row_bytes = WIDTH * 4;
let padded =
row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("atmosphere pixels"),
size: u64::from(padded) * u64::from(HEIGHT),
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded),
rows_per_image: Some(HEIGHT),
},
},
wgpu::Extent3d {
width: WIDTH,
height: HEIGHT,
depth_or_array_layers: 1,
},
);
queue.submit(std::iter::once(encoder.finish()));
let _ = device.poll(wgpu::MaintainBase::Wait);
let err = pollster::block_on(device.pop_error_scope());
assert!(
err.is_none(),
"validation rejected the atmosphere frame: {err:?}"
);
let slice = buffer.slice(..);
let (tx, rx) = std::sync::mpsc::sync_channel(1);
slice.map_async(wgpu::MapMode::Read, move |result| {
let _ = tx.send(result);
});
let _ = device.poll(wgpu::MaintainBase::Wait);
rx.recv().expect("map callback").expect("map readback");
let mapped = slice.get_mapped_range();
let mut pixels = vec![0u8; (WIDTH * HEIGHT * 4) as usize];
for y in 0..HEIGHT as usize {
let src = y * padded as usize;
let dst = y * row_bytes as usize;
pixels[dst..dst + row_bytes as usize]
.copy_from_slice(&mapped[src..src + row_bytes as usize]);
}
drop(mapped);
buffer.unmap();
pixels
}

/// A cleared pixel is Bruneton sky. A near red quad stays red. A far red quad
/// stays geometry (depth is not the clear value) and aerial perspective
/// changes it relative to the same quad with the pass off.
#[test]
fn atmosphere_sky_differs_from_geometry_and_aerial_tints_distance() {
pollster::block_on(async {
const WIDTH: u32 = 64;
let mut renderer = Renderer::new_headless(WIDTH, WIDTH)
.await
.expect("headless");
renderer.set_debug_shading(1, false);
renderer.set_material_params([1.0, 1.0, 1.0, 1.0], 0.0, 1.0);
renderer.set_light_direction_override(glam::Vec3::NEG_Y, 1.0);
let eye = glam::Vec3::new(0.0, 10.0, 5.0);
let target = glam::Vec3::new(0.0, 10.0, -1.0);
let projection =
astraweave_camera::Projection::perspective(60.0_f32.to_radians(), 1.0, 0.1, 20_000.0);
let view = glam::Mat4::look_at_rh(eye, target, glam::Vec3::Y);
renderer.update_view(&astraweave_camera::RenderView::new(
view,
&projection,
eye,
(target - eye).normalize(),
));
let mesh = vertical_quad(&renderer);
renderer.add_model(
"near",
mesh.clone(),
&[astraweave_render::Instance::from_pos_scale_color(
glam::Vec3::new(-18.0, 10.0, -40.0),
glam::Vec3::new(12.0, 12.0, 1.0),
[1.0, 0.0, 0.0, 1.0],
)],
);
renderer.add_model(
"far",
mesh,
&[astraweave_render::Instance::from_pos_scale_color(
glam::Vec3::new(0.0, 10.0, -8_000.0),
glam::Vec3::new(4_000.0, 4_000.0, 1.0),
[1.0, 0.0, 0.0, 1.0],
)],
);

let off = draw_and_read(&mut renderer, false);
let on = draw_and_read(&mut renderer, true);
let near = sample(&on, WIDTH, 10, 32);
let far = sample(&on, WIDTH, 32, 32);
let sky = sample(&on, WIDTH, 60, 32);
let far_off = sample(&off, WIDTH, 32, 32);
assert!(
near[0] > near[1] + 40 && near[0] > near[2] + 40,
"near geometry should stay red, got {near:?}"
);
assert!(
channel_distance(sky, near) > 40,
"sky {sky:?} replaced or matched the near quad {near:?}"
);
assert!(
channel_distance(far, sky) > 40,
"far geometry {far:?} was replaced by the sky {sky:?}"
);
assert!(
channel_distance(far, far_off) > 20,
"aerial perspective did not change the far quad: on {far:?} off {far_off:?} sky {sky:?}"
);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
});
}