* Ambient occlusion: the radius follows what the frame draws (#9327) In an empty design the radius came from the model's box, which is empty, so a preview got the smallest radius and the depth map's precision showed as specks. It now comes from the box the depth range uses, and with nothing to draw there is no occlusion. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Ambient occlusion: the term drawn once and blurred by depth (#9327) The lit pass worked the term out for every fragment it shaded, under a pattern that changed from pixel to pixel, which read as grain. The term now has its own texture, drawn once for each pixel of the prepass, with a fixed 4 x 4 pattern, and a 4 x 4 blur that keeps to each pixel's plane takes the pattern out without crossing an edge. The lit pass reads the result. The prepass and the term share their pipelines and draw walk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,6 +35,7 @@ fn near_z(c: vec4<f32>) -> f32 {
|
||||
|
||||
@group(1) @binding(2) var acc_t: texture_2d<f32>;
|
||||
@group(2) @binding(0) var ao_depth: texture_2d<u32>;
|
||||
@group(2) @binding(1) var ao_map: texture_2d<f32>;
|
||||
|
||||
fn clipped(p: vec3<f32>) -> bool {
|
||||
return length(u.clip.xyz) > 0.5 && dot(u.clip.xyz, p) > u.clip.w;
|
||||
@@ -62,7 +63,7 @@ fn out_color(c: vec4<f32>) -> vec4<f32> {
|
||||
}
|
||||
|
||||
struct TOut {
|
||||
@builtin(position) pos: vec4<f32>,
|
||||
@invariant @builtin(position) pos: vec4<f32>,
|
||||
@location(0) n: vec3<f32>,
|
||||
@location(1) c: vec4<f32>,
|
||||
@location(2) wp: vec3<f32>,
|
||||
@@ -107,7 +108,7 @@ fn vs_tri_inst(
|
||||
/// stores every vertex's outputs: more of them cost more than the triangles' shared vertices
|
||||
/// save).
|
||||
struct FOut {
|
||||
@builtin(position) pos: vec4<f32>,
|
||||
@invariant @builtin(position) pos: vec4<f32>,
|
||||
@location(0) rp: vec3<f32>,
|
||||
@location(1) c: vec4<f32>,
|
||||
};
|
||||
@@ -209,6 +210,12 @@ fn fs_ao_depth_flat(i: FOut, @builtin(front_facing) front: bool) -> AoDepth {
|
||||
return opaque_depth(t, front);
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_ao_term_flat(i: FOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
|
||||
let t = flat_fragment(i, front);
|
||||
return ao_term(t, front);
|
||||
}
|
||||
|
||||
/// Opaque model surfaces: cut by the section plane/// Opaque model surfaces: cut by the section plane, the inside shows as a flat cap colour.
|
||||
@fragment
|
||||
fn fs_solid(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
|
||||
@@ -346,11 +353,88 @@ fn opaque_depth(i: TOut, front: bool) -> AoDepth {
|
||||
return AoDepth(depth, bitcast<u32>(depth));
|
||||
}
|
||||
|
||||
/// The term for an opaque surface's fragment, on the prepass's depth. A section's cut face has none.
|
||||
fn ao_term(i: TOut, front: bool) -> vec4<f32> {
|
||||
if (clipped(i.wp) || length(i.n) < 0.5) { discard; }
|
||||
if (!front && length(u.clip.xyz) > 0.5) { return vec4<f32>(1.0); }
|
||||
return vec4<f32>(occlusion_term(i));
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_ao_term(i: TOut, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {
|
||||
return ao_term(i, front);
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_ao_blur(@builtin(vertex_index) v: u32) -> @builtin(position) vec4<f32> {
|
||||
let p = vec2<f32>(f32((v << 1u) & 2u), f32(v & 2u));
|
||||
return vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
/// The depth map at `p`, reading 0 near and 1 far whichever way the buffer runs.
|
||||
fn map_depth(p: vec2<i32>) -> f32 {
|
||||
let at = clamp(p, vec2<i32>(0), vec2<i32>(textureDimensions(ao_depth)) - vec2<i32>(1));
|
||||
let d = bitcast<f32>(textureLoad(ao_depth, at, 0).x);
|
||||
return select(d, 1.0 - d, reversed());
|
||||
}
|
||||
|
||||
/// The raw term (`ao_map` in this pass) averaged over a 4 x 4 window, which holds every turn of
|
||||
/// [`ao_turn`]'s pattern once. A neighbour counts when it lies on this pixel's plane, the slope
|
||||
/// taken from the nearer side across each axis, so no surface's shade crosses an edge.
|
||||
@fragment
|
||||
fn fs_ao_blur(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let c = vec2<i32>(pos.xy);
|
||||
let d = map_depth(c);
|
||||
if (d >= 1.0) { return vec4<f32>(1.0); }
|
||||
let left = d - map_depth(c + vec2<i32>(-1, 0));
|
||||
let right = map_depth(c + vec2<i32>(1, 0)) - d;
|
||||
let above = d - map_depth(c + vec2<i32>(0, -1));
|
||||
let below = map_depth(c + vec2<i32>(0, 1)) - d;
|
||||
let dx = select(right, left, abs(left) < abs(right));
|
||||
let dy = select(below, above, abs(above) < abs(below));
|
||||
let tolerance = 1.5 * (abs(dx) + abs(dy)) + 1e-6;
|
||||
let last = vec2<i32>(textureDimensions(ao_map)) - vec2<i32>(1);
|
||||
var sum = 0.0;
|
||||
var weight = 0.0;
|
||||
for (var y = -2; y < 2; y = y + 1) {
|
||||
for (var x = -2; x < 2; x = x + 1) {
|
||||
let p = c + vec2<i32>(x, y);
|
||||
let s = map_depth(p);
|
||||
if (s < 1.0 && abs(s - (d + dx * f32(x) + dy * f32(y))) <= tolerance) {
|
||||
sum = sum + textureLoad(ao_map, clamp(p, vec2<i32>(0), last), 0).x;
|
||||
weight = weight + 1.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
return vec4<f32>(sum / max(weight, 1.0));
|
||||
}
|
||||
|
||||
/// A pixel's turn of the sample pattern: every 4 x 4 window holds each of 16 turns once.
|
||||
fn ao_turn(pos: vec2<f32>) -> f32 {
|
||||
let x = u32(pos.x) & 3u;
|
||||
let y = u32(pos.y) & 3u;
|
||||
let v = ((x ^ y) & 1u) << 3u | (y & 1u) << 2u | ((x ^ y) >> 1u) << 1u | (y >> 1u);
|
||||
return (f32(v) + 0.5) / 16.0;
|
||||
}
|
||||
|
||||
/// The lit pass's occlusion: the blurred term where this point falls in the map, whatever the
|
||||
/// window's viewport offset and supersampling.
|
||||
fn occlusion(i: TOut) -> f32 {
|
||||
let size = vec2<i32>(textureDimensions(ao_map));
|
||||
// The maps are 1 × 1 stand-ins until a frame draws into them (the product preview draws no
|
||||
// prepass, and AO off releases them): they tell nothing, so leave the surface unoccluded.
|
||||
if (u.ao.x <= 0.0 || length(i.n) < 0.5 || size.x < 2 || size.y < 2) { return 1.0; }
|
||||
let q = u.vp * vec4<f32>(i.wp, 1.0);
|
||||
if (q.w <= 0.0) { return 1.0; }
|
||||
let uv = vec2<f32>(q.x / q.w * 0.5 + 0.5, 0.5 - q.y / q.w * 0.5);
|
||||
return textureLoad(ao_map, clamp(vec2<i32>(uv * vec2<f32>(size)), vec2<i32>(0), size - vec2<i32>(1)), 0).x;
|
||||
}
|
||||
|
||||
// Cosine-weighted hemisphere samples, the pattern turned by a different angle at each pixel.
|
||||
// Projecting the sample and a point one radius toward the eye supplies a depth range in both
|
||||
// orthographic and perspective views; distant foreground geometry cannot cast a dark halo onto
|
||||
// a background surface.
|
||||
fn occlusion(i: TOut) -> f32 {
|
||||
fn occlusion_term(i: TOut) -> f32 {
|
||||
let radius = u.ao.x;
|
||||
if (radius <= 0.0 || length(i.n) < 0.5) { return 1.0; }
|
||||
var n = normalize(i.n);
|
||||
@@ -364,10 +448,9 @@ fn occlusion(i: TOut) -> f32 {
|
||||
if (size.x < 2 || size.y < 2) { return 1.0; }
|
||||
// The same offsets at every pixel made each sample darken its own shifted copy of a nearby
|
||||
// part's outline: faint ghosts of the part where the radius is large on screen (#4167),
|
||||
// stepped bands along contacts where it is small (#3407). Turned by interleaved gradient
|
||||
// noise (Jimenez 2014), neighbouring pixels sample different points and the copies break up
|
||||
// into an even grain.
|
||||
let turn = fract(52.9829189 * fract(dot(i.pos.xy, vec2<f32>(0.06711056, 0.00583715))));
|
||||
// stepped bands along contacts where it is small (#3407). Turned, neighbouring pixels sample
|
||||
// different points, the copies break up into grain, and the blur takes the grain out (#9327).
|
||||
let turn = ao_turn(i.pos.xy);
|
||||
let t = tangent * cos(turn * 6.28318531) + bitangent * sin(turn * 6.28318531);
|
||||
let b = cross(n, t);
|
||||
// One comparison for both depth directions: depths read as 0 near / 1 far (mirrored when
|
||||
|
||||
@@ -3599,7 +3599,7 @@ impl Renderer {
|
||||
};
|
||||
if phase == Phase::AfterSeeThrough {
|
||||
pass.set_bind_group(1, &res.access_bind, &[]);
|
||||
pass.set_bind_group(2, &res.ao.bind, &[]);
|
||||
pass.set_bind_group(2, &res.ao.maps.bind, &[]);
|
||||
Self::draw_over(res, pass, sk, h, pv, m, &tris, &lines);
|
||||
return;
|
||||
}
|
||||
@@ -3608,7 +3608,7 @@ impl Renderer {
|
||||
pass.set_bind_group(0, scene_bind(sk, &res.bind), &[]);
|
||||
lines(pass, &res.overlay, &sk.under);
|
||||
pass.set_bind_group(1, &res.access_bind, &[]);
|
||||
pass.set_bind_group(2, &res.ao.bind, &[]);
|
||||
pass.set_bind_group(2, &res.ao.maps.bind, &[]);
|
||||
pass.set_bind_group(0, scene_bind(m, &res.bind), &[]);
|
||||
let planned = |pass: &mut wgpu::RenderPass<'static>, p: &wgpu::RenderPipeline| {
|
||||
for d in m.planned.iter().filter(|d| d.class == TriClass::Opaque) {
|
||||
|
||||
+211
-119
@@ -1,68 +1,134 @@
|
||||
//! The optional AO depth prepass. Only opaque model and preview triangles participate: their
|
||||
//! depth is drawn once into a single-sample depth map the lit fragment samples for occlusion.
|
||||
//! The map is independent of the window's MSAA, and the depth runs the same way as the
|
||||
//! viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]).
|
||||
//! The optional AO passes. Only opaque model and preview triangles participate: their depth is
|
||||
//! drawn once into a single-sample depth map, and the occlusion term of the surface that depth
|
||||
//! holds is drawn into a texture of the same size and blurred by depth (#9327), which the lit
|
||||
//! fragment reads. The maps are independent of the window's MSAA, and the depth runs the same way
|
||||
//! as the viewport's own buffer (see [`super::depth_compare`] and [`super::far_depth`]).
|
||||
//! Depth testing chooses the nearest surface; an R32Uint colour attachment stores that depth's
|
||||
//! bits for portable integer texel reads. GLSL cannot load from a depth texture, and float
|
||||
//! colour attachments are not available on every GL adapter.
|
||||
|
||||
use super::{Batches, TriSource, color_layout, depth_compare, far_depth, instance_layout, planned_layout, shared_layout, tri_layout};
|
||||
|
||||
pub(super) struct Resources {
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
pub bind: wgpu::BindGroup,
|
||||
depth: wgpu::TextureView,
|
||||
values: wgpu::TextureView,
|
||||
size: [u32; 2],
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
planned_pipeline: wgpu::RenderPipeline,
|
||||
instanced_pipeline: wgpu::RenderPipeline,
|
||||
instanced_flat_pipeline: wgpu::RenderPipeline,
|
||||
const TERM_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R8Unorm;
|
||||
|
||||
/// What the opaque triangles are drawn with in one pass, by where they come from.
|
||||
struct OpaquePipelines {
|
||||
built: wgpu::RenderPipeline,
|
||||
planned: wgpu::RenderPipeline,
|
||||
instanced: wgpu::RenderPipeline,
|
||||
instanced_flat: wgpu::RenderPipeline,
|
||||
}
|
||||
|
||||
fn texture(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> (wgpu::TextureView, wgpu::TextureView, wgpu::BindGroup) {
|
||||
let texture = |label, format, usage| {
|
||||
device.create_texture(&wgpu::TextureDescriptor {
|
||||
/// The maps at their current size. Group 2 of the shader is the depth map and a term: `bind` has
|
||||
/// the blurred one for the lit pass, `blur_bind` the raw one for the blur.
|
||||
pub(super) struct Maps {
|
||||
pub bind: wgpu::BindGroup,
|
||||
blur_bind: wgpu::BindGroup,
|
||||
depth: wgpu::TextureView,
|
||||
values: wgpu::TextureView,
|
||||
raw: wgpu::TextureView,
|
||||
smooth: wgpu::TextureView,
|
||||
}
|
||||
|
||||
pub(super) struct Resources {
|
||||
pub layout: wgpu::BindGroupLayout,
|
||||
pub maps: Maps,
|
||||
size: [u32; 2],
|
||||
prepass: OpaquePipelines,
|
||||
term: OpaquePipelines,
|
||||
blur: wgpu::RenderPipeline,
|
||||
}
|
||||
|
||||
fn maps(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, size: [u32; 2]) -> Maps {
|
||||
let view = |label, format, usage| {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
};
|
||||
let drawn_and_read = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING;
|
||||
let depth = view("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
let values = view("sc_ao_values", wgpu::TextureFormat::R32Uint, drawn_and_read);
|
||||
let raw = view("sc_ao_raw", TERM_FORMAT, drawn_and_read);
|
||||
let smooth = view("sc_ao_smooth", TERM_FORMAT, drawn_and_read);
|
||||
let group = |label, term| {
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some(label),
|
||||
size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage,
|
||||
view_formats: &[],
|
||||
layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(term) },
|
||||
],
|
||||
})
|
||||
};
|
||||
let depth = texture("sc_ao_depth", wgpu::TextureFormat::Depth32Float, wgpu::TextureUsages::RENDER_ATTACHMENT).create_view(&Default::default());
|
||||
let values = texture("sc_ao_values", wgpu::TextureFormat::R32Uint, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING)
|
||||
.create_view(&Default::default());
|
||||
let bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("sc_ao_depth"),
|
||||
layout,
|
||||
entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }],
|
||||
});
|
||||
(depth, values, bind)
|
||||
Maps { bind: group("sc_ao_lit", &smooth), blur_bind: group("sc_ao_blur", &raw), depth, values, raw, smooth }
|
||||
}
|
||||
|
||||
/// A term map as a pass's target, cleared to no occlusion.
|
||||
fn term_target(view: &wgpu::TextureView) -> Option<wgpu::RenderPassColorAttachment<'_>> {
|
||||
Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::WHITE), store: wgpu::StoreOp::Store },
|
||||
})
|
||||
}
|
||||
|
||||
/// The opaque triangles of `batches`, as neither pass counts them in the performance overlay.
|
||||
fn draw_opaque(pass: &mut wgpu::RenderPass<'_>, pipelines: &OpaquePipelines, binds: [&wgpu::BindGroup; 2], batches: [&Batches; 2]) {
|
||||
for (batch, bind) in batches.into_iter().zip(binds) {
|
||||
pass.set_bind_group(0, bind, &[]);
|
||||
pass.set_pipeline(&pipelines.built);
|
||||
if let Some(tris) = &batch.tris {
|
||||
for (buffer, count) in &tris.parts {
|
||||
pass.set_vertex_buffer(0, buffer.slice(..));
|
||||
pass.draw(0..*count, 0..1);
|
||||
}
|
||||
}
|
||||
let uncounted = super::Tally::default();
|
||||
// The blocks' opaque triangles, for the same depth.
|
||||
for key in &batch.block_order {
|
||||
if let Some(block) = batch.blocks.get(key) {
|
||||
block.draw(pass, super::TriClass::Opaque, &uncounted);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&pipelines.planned);
|
||||
for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) {
|
||||
pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..));
|
||||
pass.set_vertex_buffer(1, draw.colors.slice(..));
|
||||
pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1);
|
||||
}
|
||||
for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) {
|
||||
draw.draw(pass, &pipelines.instanced, &pipelines.instanced_flat, &uncounted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Resources {
|
||||
/// The layout of the depth map's bind group, which the lit pipelines' layout includes.
|
||||
/// The layout of the maps' bind groups, which the lit pipelines' layout includes.
|
||||
pub fn layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
|
||||
let entry = |binding, sample_type| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false },
|
||||
count: None,
|
||||
};
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("sc_ao_depth"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Uint,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
label: Some("sc_ao_maps"),
|
||||
entries: &[entry(0, wgpu::TextureSampleType::Uint), entry(1, wgpu::TextureSampleType::Float { filterable: false })],
|
||||
})
|
||||
}
|
||||
|
||||
/// The prepass's pipelines and a 1 x 1 stand-in map, bound with `layout` ([`Resources::layout`]).
|
||||
/// The passes' pipelines and 1 x 1 stand-in maps, bound with `layout` ([`Resources::layout`]).
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
@@ -71,57 +137,82 @@ impl Resources {
|
||||
reversed: bool,
|
||||
) -> Self {
|
||||
let layout = layout.clone();
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
let prepass_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("sc_ao_prepass"),
|
||||
bind_group_layouts: &[Some(uniform)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let term_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("sc_ao_term"),
|
||||
bind_group_layouts: &[Some(uniform), None, Some(&layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let built = [Some(tri_layout())];
|
||||
let evaluated = [Some(planned_layout()), Some(color_layout())];
|
||||
let placed = [Some(shared_layout()), Some(instance_layout())];
|
||||
let pipeline = |source: TriSource| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("sc_ao_prepass"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some(source.entry()),
|
||||
buffers: match source {
|
||||
TriSource::Built => &built[..],
|
||||
TriSource::Planned => &evaluated[..],
|
||||
TriSource::Instanced | TriSource::InstancedFlat => &placed[..],
|
||||
let target = |format| [Some(wgpu::ColorTargetState { format, blend: None, write_mask: wgpu::ColorWrites::RED })];
|
||||
let opaque = |label, layout: &wgpu::PipelineLayout, fragment: &str, format, depth_write_enabled, compare| {
|
||||
let pipeline = |source: TriSource| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module,
|
||||
entry_point: Some(source.entry()),
|
||||
buffers: match source {
|
||||
TriSource::Built => &built[..],
|
||||
TriSource::Planned => &evaluated[..],
|
||||
TriSource::Instanced | TriSource::InstancedFlat => &placed[..],
|
||||
},
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(depth_compare(reversed, wgpu::CompareFunction::Less)),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some(&source.fragment("fs_ao_depth")),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::R32Uint,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::RED,
|
||||
})],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(depth_write_enabled),
|
||||
depth_compare: Some(depth_compare(reversed, compare)),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some(&source.fragment(fragment)),
|
||||
targets: &target(format),
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
OpaquePipelines {
|
||||
built: pipeline(TriSource::Built),
|
||||
planned: pipeline(TriSource::Planned),
|
||||
instanced: pipeline(TriSource::Instanced),
|
||||
instanced_flat: pipeline(TriSource::InstancedFlat),
|
||||
}
|
||||
};
|
||||
let planned_pipeline = pipeline(TriSource::Planned);
|
||||
let instanced_pipeline = pipeline(TriSource::Instanced);
|
||||
let instanced_flat_pipeline = pipeline(TriSource::InstancedFlat);
|
||||
let pipeline = pipeline(TriSource::Built);
|
||||
let (depth, values, bind) = texture(device, &layout, [1, 1]);
|
||||
Self { layout, bind, depth, values, size: [1, 1], pipeline, planned_pipeline, instanced_pipeline, instanced_flat_pipeline }
|
||||
let prepass = opaque("sc_ao_prepass", &prepass_layout, "fs_ao_depth", wgpu::TextureFormat::R32Uint, true, wgpu::CompareFunction::Less);
|
||||
// The term only where the prepass's depth is, so each pixel's term is worked out once.
|
||||
let term = opaque("sc_ao_term", &term_layout, "fs_ao_term", TERM_FORMAT, false, wgpu::CompareFunction::LessEqual);
|
||||
let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("sc_ao_blur"),
|
||||
layout: Some(&term_layout),
|
||||
vertex: wgpu::VertexState { module, entry_point: Some("vs_ao_blur"), buffers: &[], compilation_options: Default::default() },
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module,
|
||||
entry_point: Some("fs_ao_blur"),
|
||||
targets: &target(TERM_FORMAT),
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let maps = maps(device, &layout, [1, 1]);
|
||||
Self { layout, maps, size: [1, 1], prepass, term, blur }
|
||||
}
|
||||
|
||||
pub fn prepare(
|
||||
@@ -138,7 +229,7 @@ impl Resources {
|
||||
// Bound memory at large window sizes; normalized coordinates also handle downsampling.
|
||||
let size = target_size(enabled, size_px, device.limits().max_texture_dimension_2d);
|
||||
if size != self.size {
|
||||
(self.depth, self.values, self.bind) = texture(device, &self.layout, size);
|
||||
self.maps = maps(device, &self.layout, size);
|
||||
self.size = size;
|
||||
}
|
||||
if !enabled {
|
||||
@@ -147,7 +238,7 @@ impl Resources {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("sc_ao_prepass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &self.values,
|
||||
view: &self.maps.values,
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
@@ -156,7 +247,7 @@ impl Resources {
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth,
|
||||
view: &self.maps.depth,
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(far_depth(reversed)), store: wgpu::StoreOp::Store }),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
@@ -164,34 +255,35 @@ impl Resources {
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
for (batch, bind) in batches.into_iter().zip(binds) {
|
||||
pass.set_bind_group(0, bind, &[]);
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
if let Some(tris) = &batch.tris {
|
||||
for (buffer, count) in &tris.parts {
|
||||
pass.set_vertex_buffer(0, buffer.slice(..));
|
||||
pass.draw(0..*count, 0..1);
|
||||
}
|
||||
}
|
||||
// The depth prepass is left out of the performance overlay's counts, as before.
|
||||
let uncounted = super::Tally::default();
|
||||
// The blocks' opaque triangles, for the same depth.
|
||||
for key in &batch.block_order {
|
||||
if let Some(block) = batch.blocks.get(key) {
|
||||
block.draw(&mut pass, super::TriClass::Opaque, &uncounted);
|
||||
}
|
||||
}
|
||||
pass.set_pipeline(&self.planned_pipeline);
|
||||
for draw in batch.planned.iter().filter(|d| d.class == super::TriClass::Opaque) {
|
||||
pass.set_vertex_buffer(0, draw.mesh.vertices.slice(..));
|
||||
pass.set_vertex_buffer(1, draw.colors.slice(..));
|
||||
pass.set_index_buffer(draw.mesh.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.draw_indexed(0..draw.mesh.index_count, 0, 0..1);
|
||||
}
|
||||
for draw in batch.instanced.iter().filter(|d| d.look == super::InstanceLook::Opaque) {
|
||||
draw.draw(&mut pass, &self.instanced_pipeline, &self.instanced_flat_pipeline, &uncounted);
|
||||
}
|
||||
}
|
||||
draw_opaque(&mut pass, &self.prepass, binds, batches);
|
||||
drop(pass);
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("sc_ao_term"),
|
||||
color_attachments: &[term_target(&self.maps.raw)],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.maps.depth,
|
||||
depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Discard }),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_bind_group(2, &self.maps.bind, &[]);
|
||||
draw_opaque(&mut pass, &self.term, binds, batches);
|
||||
drop(pass);
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("sc_ao_blur"),
|
||||
color_attachments: &[term_target(&self.maps.smooth)],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
pass.set_pipeline(&self.blur);
|
||||
pass.set_bind_group(0, binds[0], &[]);
|
||||
pass.set_bind_group(2, &self.maps.blur_bind, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -456,6 +456,13 @@ fn scene_bounds(app: &SolveApp) -> solidcraft_engine::geom::Aabb3 {
|
||||
b
|
||||
}
|
||||
|
||||
/// The ambient occlusion radius (0: off): 4% of what the frame draws, the box the depth range uses,
|
||||
/// so a preview in an empty design has its own. Nothing to draw has no occlusion (#9327).
|
||||
fn ao_radius(app: &SolveApp) -> f32 {
|
||||
let size = scene_bounds(app).diagonal();
|
||||
if app.preferences.ambient_occlusion && app.ui.visual_style != 2 && size > 0.0 { (size * 0.04).clamp(1e-4, 1e6) as f32 } else { 0.0 }
|
||||
}
|
||||
|
||||
pub fn scene_radius(app: &SolveApp) -> f64 {
|
||||
let b = scene_bounds(app);
|
||||
let r = if b.is_empty() { 50.0 } else { b.diagonal() * 0.5 + b.center().dist(app.cam.target) };
|
||||
@@ -4443,11 +4450,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
|
||||
analysis_colors: crate::gpu::analysis_colors(&t.analysis),
|
||||
access: crate::access::map(app),
|
||||
outline: matches!(app.ui.visual_style, 0 | 3),
|
||||
ao_radius: if app.preferences.ambient_occlusion && app.ui.visual_style != 2 {
|
||||
(model_bounds(app).diagonal() * 0.04).clamp(1e-4, 1e6) as f32
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
ao_radius: ao_radius(app),
|
||||
eye: {
|
||||
let e = proj.cam.eye().to_f32();
|
||||
[e[0], e[1], e[2], if proj.cam.fov > 0.0 { 1.0 } else { 0.0 }]
|
||||
@@ -7273,6 +7276,9 @@ mod tests {
|
||||
s.execute("solid.box", &json!({"length": 300, "width": 300, "height": 4, "corner": [-150, -150, -4], "body_name": "plate"})).unwrap();
|
||||
s.execute("solid.box", &json!({"length": 30, "width": 160, "height": 16, "corner": [0, -80, 0], "operation": "new", "body_name": "block"}))
|
||||
.unwrap();
|
||||
// On one side of the view only, too far from the block to shade the rows measured below.
|
||||
s.execute("solid.box", &json!({"length": 20, "width": 20, "height": 16, "corner": [-110, 60, 0], "operation": "new", "body_name": "marker"}))
|
||||
.unwrap();
|
||||
let mut app = SolveApp::new(s, crate::Services::default());
|
||||
let (yaw, pitch) = solidcraft_engine::render::StandardView::Top.angles();
|
||||
app.cam = Camera { target: Vec3::new(-30.0, 0.0, 0.0), yaw, pitch, roll: 0.0, distance: 200.0, fov: 0.0, ..Default::default() };
|
||||
@@ -7333,8 +7339,31 @@ mod tests {
|
||||
}
|
||||
// The shader takes the count it is given (the moving frame is a different picture), and
|
||||
// spreads it over the same hemisphere: both darken the contact alike.
|
||||
assert_ne!(pictures[0], pictures[1], "8 samples draw another grain than 32");
|
||||
assert_ne!(pictures[0], pictures[1], "8 samples draw another picture than 32");
|
||||
assert!((beside[0] - beside[1]).abs() < 0.02, "the same darkening beside the block at 32 and 8 samples: {beside:?}");
|
||||
// No grain (#9327): where the plate darkens, neighbouring pixels agree at either count.
|
||||
let (from, to) = ((edge - reach) as usize, (edge - 4.0) as usize);
|
||||
for picture in &pictures {
|
||||
let grain = (y0..y1).flat_map(|y| (from..to).map(move |x| (lum(picture, x, y) - lum(picture, x + 1, y)).abs() / 3.0)).fold(0.0, f64::max);
|
||||
eprintln!("grain {grain:.2}");
|
||||
assert!(grain <= 2.0, "neighbouring pixels differ by {grain:.2} of 255");
|
||||
}
|
||||
for picture in &pictures {
|
||||
// Blurred by depth: the block's top right beside the edge stays as clear as without AO.
|
||||
for x in (edge + 1.0) as usize..=(edge + 3.0) as usize {
|
||||
let y = (y0 + y1) / 2;
|
||||
assert!((lum(picture, x, y) - lum(&off, x, y)).abs() <= 6.0, "the plate's shade crosses onto the block's top at {x}");
|
||||
}
|
||||
// The map is read the right way up: the plate darkens beside the marker, not at its mirror image.
|
||||
let shade = |p: Vec3| {
|
||||
let (x, y, _) = at(p);
|
||||
lum(picture, x as usize, y as usize) / lum(&off, x as usize, y as usize).max(1.0)
|
||||
};
|
||||
let (beside, mirror) = (shade(Vec3::new(-100.0, 58.0, 0.0)), shade(Vec3::new(-100.0, -58.0, 0.0)));
|
||||
assert!(beside < 0.99 && (mirror - 1.0).abs() < 0.004, "beside the marker {beside:.4}, at its mirror image {mirror:.4}");
|
||||
}
|
||||
// Off, nothing is read from the released maps: the plate is as bright beside the block as away from it.
|
||||
assert!((lum(&off, to, y0) - lum(&off, from, y0)).abs() <= 3.0, "AO off darkens nothing");
|
||||
}
|
||||
|
||||
/// Faded and see-through bodies are drawn from their plans where the renderer blends them
|
||||
|
||||
@@ -570,3 +570,25 @@ fn vertex_markers_follow_the_edges_display_mode() {
|
||||
assert!(front.iter().all(|(_, c)| Some(*c) == edge), "style {style}: markers in the edge colour");
|
||||
}
|
||||
}
|
||||
|
||||
/// The radius is 4% of what the frame draws (#9327): in an empty design a preview's box, not the
|
||||
/// floor that left the depth map's precision to show as specks; nothing drawn, or AO off, is off.
|
||||
#[test]
|
||||
fn the_ambient_occlusion_radius_follows_what_is_drawn() {
|
||||
use solidcraft_engine::geom::Aabb3;
|
||||
|
||||
let mut app = SolveApp::new(Session::default(), Services::default());
|
||||
app.preferences.ambient_occlusion = true;
|
||||
app.ui.visual_style = 0;
|
||||
assert_eq!(super::ao_radius(&app), 0.0, "nothing to occlude");
|
||||
app.preview.bounds = Aabb3 { min: Vec3::ZERO, max: Vec3::new(30.0, 40.0, 0.0) };
|
||||
assert_eq!(super::ao_radius(&app), 2.0, "the preview's box, its diagonal 50");
|
||||
app.preview.bounds = Aabb3::EMPTY;
|
||||
app.run("solid.box", json!({"length": 300, "width": 400, "height": 0.001})).unwrap();
|
||||
assert!((super::ao_radius(&app) - 20.0).abs() < 1e-3, "the body's box");
|
||||
app.ui.visual_style = 2;
|
||||
assert_eq!(super::ao_radius(&app), 0.0, "wireframe");
|
||||
app.ui.visual_style = 0;
|
||||
app.preferences.ambient_occlusion = false;
|
||||
assert_eq!(super::ao_radius(&app), 0.0, "off");
|
||||
}
|
||||
|
||||
@@ -33,12 +33,11 @@ only display preferences, without adding a modelling undo step or moving the cam
|
||||
The GPU viewport uses 32 hemisphere samples per shaded pixel against an opaque depth
|
||||
prepass (at most 2048 pixels on its longest side), the sample pattern turned by a
|
||||
different angle at each pixel. One pattern for every pixel drew faint shifted copies of
|
||||
nearby parts (#4167) and stepped bands along contacts (#3407); turned, they become an
|
||||
even fine grain, which 2× supersampling smooths further. While the view moves (orbit, pan,
|
||||
zoom, resize), frames take 8 samples on the same turned pattern, and the full 32 follow once
|
||||
the view has held still for 0.25 s, the settling time adaptive supersampling uses (#7165).
|
||||
The AO grain changes when the full count arrives, as the edges do when adaptive supersampling
|
||||
does. `ui.screenshot` waits for that full-quality frame (at most half a second). The radius follows
|
||||
nearby parts (#4167) and stepped bands along contacts (#3407); turned, they become a grain,
|
||||
which a 4 × 4 blur by depth takes out: the term has its own texture, worked out once for each
|
||||
pixel of the prepass (#9327). While the view moves (orbit, pan, zoom, resize), frames take 8
|
||||
samples, and the full 32 follow once the view has held still for 0.25 s, the settling time
|
||||
adaptive supersampling uses (#7165). `ui.screenshot` waits for that full-quality frame (at most half a second). The radius follows
|
||||
model size, and depth-range rejection avoids shadows from distant foreground objects.
|
||||
It supports orthographic and perspective cameras and respects section clipping.
|
||||
Wireframe, transparent bodies, overlays and surface-analysis colours are unaffected.
|
||||
|
||||
Reference in New Issue
Block a user