HDR
This commit is contained in:
+261
-9
@@ -36,9 +36,9 @@ use crate::resources::{
|
||||
Camera, CullUniforms, FrameUniforms, Lights, Material, Mesh, ObjectUniform, ShadowUniform,
|
||||
};
|
||||
use crate::scene::Scene;
|
||||
use crate::core::hdr::ToneMapper;
|
||||
use crate::utils::conf::{
|
||||
GPU_DRIVEN_SHADER, GPU_WORKGROUP_SIZE, LOD_THRESHOLDS, MAX_ENTITIES, MAX_LOD_LEVELS,
|
||||
SHADOW_DEPTH_BIAS, SHADOW_MAP_SIZE, SHADOW_SCENE_CENTER, SHADOW_SCENE_RADIUS,
|
||||
GPU_DRIVEN_SHADER, GPU_WORKGROUP_SIZE, LOD_THRESHOLDS, MAX_ENTITIES, MAX_LOD_LEVELS, TONEMAP_SHADER,
|
||||
};
|
||||
use glam::{Mat4, Quat, Vec3, Vec4};
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -145,6 +145,30 @@ pub struct Renderer {
|
||||
/// Viewport height in pixels (Step 19, D9): the unit of the LOD projected-size test. Set from
|
||||
/// the initial surface size in `new` and refreshed by `resize_depth` on window resize.
|
||||
viewport_height: u32,
|
||||
/// Shadow mapping configuration (map size, biases, frustum). Set at construction time;
|
||||
/// `map_size` determines the shadow texture allocation, the rest are used per-frame.
|
||||
shadow_config: super::shadow::ShadowConfig,
|
||||
/// HDR pipeline (Étape 20). Present only when HDR is enabled via `AppBuilder::with_hdr`.
|
||||
/// When `None`, the main pass renders directly to the surface (LDR, zero overhead).
|
||||
hdr: Option<HdrPipeline>,
|
||||
}
|
||||
|
||||
/// Internal HDR pipeline state: offscreen `Rgba16Float` texture + tone mapping render pipeline.
|
||||
/// Allocated in `Renderer::new` when HDR is active; recreated on resize.
|
||||
struct HdrPipeline {
|
||||
/// Offscreen HDR color texture (`Rgba16Float`), sized to the surface.
|
||||
texture: wgpu::Texture,
|
||||
/// View of the HDR texture, used as the main pass color attachment.
|
||||
view: wgpu::TextureView,
|
||||
/// Tone mapping render pipeline (fullscreen triangle + ACES/Reinhard curve).
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
/// Bind group for the TM pass (HDR texture + sampler + uniform with exposure & viewport).
|
||||
/// The uniform buffer is owned by the bind group (freed when the bind group is replaced).
|
||||
bind_group: wgpu::BindGroup,
|
||||
/// Bind group layout for the TM pass (reused on resize to recreate the bind group).
|
||||
layout: wgpu::BindGroupLayout,
|
||||
/// Sampler for the HDR texture (linear, clamp).
|
||||
sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
@@ -156,7 +180,14 @@ impl Renderer {
|
||||
/// Returns a new Renderer instance sharing the same underlying GPU resources as Context.
|
||||
/// Called once at application startup during scene setup. The Renderer shares these resources via Arc;
|
||||
/// Context retains ownership and can continue using them after this call.
|
||||
pub fn new(context: &Context, format: wgpu::TextureFormat, width: u32, height: u32) -> Self {
|
||||
pub fn new(
|
||||
context: &Context,
|
||||
format: wgpu::TextureFormat,
|
||||
width: u32,
|
||||
height: u32,
|
||||
shadow_config: &super::shadow::ShadowConfig,
|
||||
hdr: Option<ToneMapper>,
|
||||
) -> Self {
|
||||
let queue: wgpu::Queue = context.queue.clone();
|
||||
let device: wgpu::Device = context.device.clone();
|
||||
let [frame_layout, object_layout] = create_uniform_bind_group_layouts(&device);
|
||||
@@ -206,7 +237,7 @@ impl Renderer {
|
||||
// Step 14 (DRAFT 3.2): shadow mapping resources — shadow map texture/view, comparison
|
||||
// sampler, group-3 bind group, shadow-light uniform buffer + group-0 bind group, and the
|
||||
// depth-only shadow pipeline. All allocated once here at the default resolution (D2/D8).
|
||||
let (shadow_texture, shadow_view) = create_shadow_map(&device, SHADOW_MAP_SIZE);
|
||||
let (shadow_texture, shadow_view) = create_shadow_map(&device, shadow_config.map_size);
|
||||
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("shadow comparison sampler"),
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
@@ -508,7 +539,7 @@ impl Renderer {
|
||||
}],
|
||||
});
|
||||
|
||||
let renderer = Self {
|
||||
let mut renderer = Self {
|
||||
queue,
|
||||
device,
|
||||
format,
|
||||
@@ -542,10 +573,14 @@ impl Renderer {
|
||||
lod_enabled: Cell::new(true),
|
||||
last_lod_levels: RefCell::new(Vec::new()),
|
||||
viewport_height: height,
|
||||
shadow_config: shadow_config.clone(),
|
||||
hdr: None,
|
||||
};
|
||||
// Seed the shared frame buffer with an identity camera + current unlit flag so the low-level
|
||||
// `render` path (which has no window/camera) sees coherent values before `render_scene` runs.
|
||||
renderer.write_default_frame_uniforms();
|
||||
// Étape 20: allocate the HDR pipeline (offscreen texture + TM pipeline) when enabled.
|
||||
renderer.hdr = hdr.map(|tm| create_hdr_pipeline(&renderer.device, &renderer.queue, width, height, tm, format));
|
||||
renderer
|
||||
}
|
||||
|
||||
@@ -585,6 +620,14 @@ impl Renderer {
|
||||
self.depth_view = depth_view;
|
||||
// Step 19 (D9): refresh the viewport height — the unit of the LOD projected-size test.
|
||||
self.viewport_height = height;
|
||||
// Étape 20: recreate the HDR texture + bind group at the new size (D10).
|
||||
if let Some(hdr) = &mut self.hdr {
|
||||
let (tex, view) = create_hdr_texture(&self.device, width, height);
|
||||
let bg = create_hdr_bind_group(&self.device, &hdr.layout, &hdr.sampler, &tex, width, height);
|
||||
hdr.texture = tex;
|
||||
hdr.view = view;
|
||||
hdr.bind_group = bg;
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the stored surface texture format after a surface reconfigure (ROADMAP Phase 4.4).
|
||||
@@ -619,7 +662,12 @@ impl Renderer {
|
||||
Some((index, vp)) => (
|
||||
index as u32,
|
||||
vp,
|
||||
Vec4::new(SHADOW_MAP_SIZE as f32, SHADOW_DEPTH_BIAS, 0.0, 0.0),
|
||||
Vec4::new(
|
||||
self.shadow_config.map_size as f32,
|
||||
self.shadow_config.depth_bias,
|
||||
self.shadow_config.slope_bias,
|
||||
0.0,
|
||||
),
|
||||
1,
|
||||
),
|
||||
None => (MAX_LIGHTS as u32, Mat4::IDENTITY, Vec4::ZERO, 0),
|
||||
@@ -679,8 +727,8 @@ impl Renderer {
|
||||
}
|
||||
crate::resources::LightType::Point => return None,
|
||||
};
|
||||
let r = SHADOW_SCENE_RADIUS;
|
||||
let target = Vec3::from(SHADOW_SCENE_CENTER);
|
||||
let r = self.shadow_config.scene_radius;
|
||||
let target = Vec3::from(self.shadow_config.scene_center);
|
||||
// Eye one scene-radius behind the target along the light path, so distance(target)=r and
|
||||
// every point in the box has depth within [near=0, far=r].
|
||||
let eye = target - dir * r;
|
||||
@@ -867,11 +915,17 @@ impl Renderer {
|
||||
// The matrix + draw-args are read via per-slot offsets; a culled/inactive slot's args
|
||||
// are zero, so its draw is a no-op. State changes (pipeline + texture bind group @2)
|
||||
// are hoisted out of the slot loop: one per DISTINCT material, not one per entity.
|
||||
// Étape 20: when HDR is active, the color attachment targets the offscreen HDR texture
|
||||
// instead of the surface; the TM pass (step 8) then copies it to the surface.
|
||||
let main_target = match &self.hdr {
|
||||
Some(h) => &h.view,
|
||||
None => view,
|
||||
};
|
||||
{
|
||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("scene render pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
view: main_target,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
@@ -952,6 +1006,30 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 8. Étape 20: tone mapping pass — renders a fullscreen triangle that reads the HDR
|
||||
// texture, applies exposure + tone mapping curve, and writes to the surface.
|
||||
// Only runs when HDR is active; the surface is the color target (no depth needed).
|
||||
if let Some(hdr) = &self.hdr {
|
||||
let mut tm_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("tone mapping pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
..Default::default()
|
||||
});
|
||||
tm_pass.set_pipeline(&hdr.pipeline);
|
||||
tm_pass.set_bind_group(0, &hdr.bind_group, &[]);
|
||||
tm_pass.draw(0..3, 0..1);
|
||||
}
|
||||
|
||||
self.queue.submit(std::iter::once(encoder.finish()));
|
||||
}
|
||||
|
||||
@@ -1429,6 +1507,180 @@ fn batch_slots<K: Eq + Hash + Clone>(keys: &[K]) -> Vec<Vec<usize>> {
|
||||
groups.into_iter().map(|(_, idxs)| idxs).collect()
|
||||
}
|
||||
|
||||
/// Allocates the offscreen HDR color texture (`Rgba16Float`) + view at the given size (Étape 20, D3).
|
||||
/// Used both at initial allocation and on resize.
|
||||
fn create_hdr_texture(device: &wgpu::Device, width: u32, height: u32) -> (wgpu::Texture, wgpu::TextureView) {
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("hdr texture"),
|
||||
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba16Float,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
});
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
(texture, view)
|
||||
}
|
||||
|
||||
/// Creates the tone mapping bind group: HDR texture (binding 0) + sampler (binding 1) + uniform (binding 2).
|
||||
/// The uniform contains exposure (1.0) and viewport size (pad.xy).
|
||||
fn create_hdr_bind_group(
|
||||
device: &wgpu::Device,
|
||||
layout: &wgpu::BindGroupLayout,
|
||||
sampler: &wgpu::Sampler,
|
||||
texture: &wgpu::Texture,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> wgpu::BindGroup {
|
||||
// Write the uniform: exposure = 1.0, pad.xy = viewport size.
|
||||
// WGSL uniform layout: f32 at offset 0 (4B), vec3<f32> at offset 16 (16B, aligned to 16).
|
||||
// Total = 32 bytes. We pack as 8 f32s: [exposure, 0, 0, 0, w, h, 0, 0].
|
||||
let uniform_data = [
|
||||
1.0f32, // exposure (offset 0)
|
||||
0.0, 0.0, 0.0, // padding to align vec3 to offset 16
|
||||
width as f32, height as f32, 0.0, // pad: vec3<f32> at offset 16
|
||||
0.0, // trailing pad to 32 bytes
|
||||
];
|
||||
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("tm uniform"),
|
||||
size: 32,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
{
|
||||
let mut w = uniform_buffer.slice(..).get_mapped_range_mut().expect("mapped buffer");
|
||||
w.copy_from_slice(bytemuck::cast_slice(&uniform_data));
|
||||
drop(w);
|
||||
uniform_buffer.unmap();
|
||||
}
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("tm bind group"),
|
||||
layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&texture.create_view(&wgpu::TextureViewDescriptor::default())),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &uniform_buffer,
|
||||
offset: 0,
|
||||
size: None,
|
||||
}),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates the full HDR pipeline (Étape 20): offscreen texture + TM pipeline + bind group.
|
||||
/// The pipeline uses the `TONEMAP_SHADER` with the entry point selected by the `ToneMapper` variant.
|
||||
fn create_hdr_pipeline(
|
||||
device: &wgpu::Device,
|
||||
_queue: &wgpu::Queue,
|
||||
width: u32,
|
||||
height: u32,
|
||||
tonemapper: ToneMapper,
|
||||
format: wgpu::TextureFormat,
|
||||
) -> HdrPipeline {
|
||||
// 1. Offscreen HDR texture + view.
|
||||
let (texture, view) = create_hdr_texture(device, width, height);
|
||||
|
||||
// 2. Sampler (linear, clamp).
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("hdr sampler"),
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// 3. Bind group layout: texture (0) + sampler (1) + uniform (2).
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("hdr bgl"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 4. Render pipeline: fullscreen triangle (no vertex buffer) + selected TM entry point.
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("tonemap shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(TONEMAP_SHADER.into()),
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("hdr pipeline layout"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("tone mapping pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some(tonemapper.entry_point()),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState::from(format))],
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
// 5. Bind group with the initial texture + viewport size.
|
||||
let bind_group = create_hdr_bind_group(device, &layout, &sampler, &texture, width, height);
|
||||
|
||||
HdrPipeline {
|
||||
texture,
|
||||
view,
|
||||
pipeline,
|
||||
bind_group,
|
||||
layout,
|
||||
sampler,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
Reference in New Issue
Block a user