Decode the motion buffer per history grid in TAA/TAAU (#143)
The G-buffer's motion buffer is current-to-previous in jittered render pixels: both positions are projected with their frame's drawn matrix, so even a still surface writes the two frames' jitter difference. fs_taa (1:1) keeps its history on the jittered grid and needs that difference as written, but native TAAU resolves a full-size history on the stable output grid, so using the buffer raw shifted every still pixel's history lookup by the jitter difference — (+0.375, +0.5) output pixels at 1280x720 -> 1920x1080 on the first Halton(2,3) pair. State the contract explicitly (gfx/hd/mod.rs, taa.rs, frame.rs and the motion producers in terrain.wgsl / entity.wgsl) and pass the previous frame's jitter to the shaders (HdFrame.prev_jitter, HdScene::prev_jitter_px, Renderer::taa_prev). fs_taau now adds the current jitter and subtracts the previous one, so a still surface reads the same output pixel on every phase; fs_taa is unchanged. The DLSS backend receives the buffer and its flags unchanged — NGX's input contract is verified on that path separately (#137), not inferred here. Numerical tests cover every jitter phase at 1:1 and fractional scales: the still-surface lookup, the 1:1 correction, a moving camera (the motion path and the depth/camera fallback agree on one continuous surface), a moving model's known shift, the issue's worked numbers, and the jittered-depth unprojection. An ignored GPU smoke runs the real fs_taau A/B on a still finely patterned surface at 1280x720 -> 1920x1080: the old decode against the fixed one, the depth fallback (must agree with the fixed decode), and the spatial filter alone (the production lanczos gather's own sub-pixel error is the floor the temporal path must not add to). Co-Authored-By: Kimi Code <noreply@moonshot.ai>
This commit is contained in:
@@ -297,6 +297,9 @@ struct EntityGBufferOut {
|
||||
@location(2) light: vec4<f32>,
|
||||
@location(3) motion: vec2<f32>,
|
||||
}
|
||||
// The motion buffer's contract: current-to-previous in jittered render pixels (both matrices as
|
||||
// drawn, so a still surface writes the two frames' jitter difference). The temporal passes decode
|
||||
// it for their history grid (gfx/hd/taa.wgsl); DLSS receives it unchanged.
|
||||
fn motion_pixels(pos: vec3<f32>, previous: vec4<f32>) -> vec2<f32> {
|
||||
let current = globals.view_proj * vec4(pos, 1.0);
|
||||
if current.w <= 0.0 || previous.w <= 0.0 { return vec2<f32>(0.0); }
|
||||
|
||||
@@ -227,7 +227,8 @@ struct Globals {
|
||||
hd_wind: [f32; 4],
|
||||
/// AirDef fork: the sprite layers' material classes, 4 bits each (`hd::materials`).
|
||||
hd_materials: hd::MaterialTable,
|
||||
/// The previous frame's drawn (jittered) view-projection, for dense motion vectors.
|
||||
/// The previous frame's drawn (jittered) view-projection, for dense motion vectors: the
|
||||
/// buffer is current-to-previous in jittered render pixels, jitter difference included.
|
||||
prev_view_proj: [[f32; 4]; 4],
|
||||
/// xyz: the camera's translation since that frame.
|
||||
camera_delta: [f32; 4],
|
||||
@@ -643,9 +644,10 @@ pub struct Renderer {
|
||||
hd_shadow_visible: Vec<resident::Visible>,
|
||||
/// The far cascade as last drawn (matrix, camera, light) and the frames since.
|
||||
hd_far: Option<(Mat4, glam::DVec3, Vec3, u32)>,
|
||||
/// HD's TAA: frames jittered so far, and the last one's unjittered view-projection and camera.
|
||||
/// HD's TAA: frames jittered so far, and the last one's unjittered view-projection, camera,
|
||||
/// drawn (jittered) view-projection and jitter in render pixels.
|
||||
taa_frame: u32,
|
||||
taa_prev: Option<(Mat4, glam::DVec3, Mat4)>,
|
||||
taa_prev: Option<(Mat4, glam::DVec3, Mat4, [f32; 2])>,
|
||||
hd: Option<hd::Hd>,
|
||||
mod_params: (Vec<f32>, f32),
|
||||
/// Time the shader pack's passes on the GPU (F3, or `HORIZON_SHADER_PACK_TIMING`).
|
||||
@@ -4361,7 +4363,9 @@ impl Renderer {
|
||||
&& !self.pack_post.as_ref().is_some_and(|p| p.1.is_some())
|
||||
&& !self.native.as_ref().is_some_and(|n| n.post.is_some());
|
||||
// AirDef fork: HD's temporal anti-aliasing shifts the whole projection by a sub-pixel
|
||||
// offset each frame; `unjittered` is what the next frame reprojects with.
|
||||
// offset each frame; `unjittered` is what the next frame reprojects a stable history with.
|
||||
// The motion buffer keeps both frames' jitter (Globals.prev_view_proj is the previous
|
||||
// drawn matrix); each temporal consumer decodes it for its own history grid (gfx/hd).
|
||||
let unjittered = self.view_projection(frame);
|
||||
let taa = hd_wanted && hd::taa_enabled();
|
||||
let mut jitter_px = [0.0; 2];
|
||||
@@ -4379,7 +4383,7 @@ impl Renderer {
|
||||
};
|
||||
let taa_prev = std::mem::replace(
|
||||
&mut self.taa_prev,
|
||||
taa.then_some((unjittered, frame.camera, view_proj)),
|
||||
taa.then_some((unjittered, frame.camera, view_proj, jitter_px)),
|
||||
);
|
||||
// AirDef fork: a cut starts the temporal histories over (no ghost of the last shot).
|
||||
let taa_prev = if std::mem::take(&mut self.cut) {
|
||||
@@ -4620,6 +4624,7 @@ impl Renderer {
|
||||
jitter_px,
|
||||
prev_view_proj: taa_prev.map_or(unjittered, |p| p.0),
|
||||
prev_view_proj_jittered: taa_prev.map_or(view_proj, |p| p.2),
|
||||
prev_jitter_px: taa_prev.map_or(jitter_px, |p| p.3),
|
||||
camera_delta: taa_prev.map_or(Vec3::ZERO, |p| (frame.camera - p.1).as_vec3()),
|
||||
// The world's sun: vanilla turns the sky -90° about Y, so it crosses from east to west.
|
||||
sun: Vec3::new(-sun_angle.sin(), sun_angle.cos(), 0.0),
|
||||
|
||||
@@ -172,6 +172,10 @@ impl Dlss {
|
||||
self.world = world;
|
||||
self.out = out;
|
||||
self.convert.resize(device, world, out);
|
||||
// NGX receives the motion buffer as written: current-to-previous in jittered render
|
||||
// pixels, the current jitter passed separately as `jitter_offset`. Whether it wants the
|
||||
// jitter inside the vectors is its own input contract, verified on this path separately
|
||||
// (#137) — not inferred here, and these flags are left as they are.
|
||||
let flags = DlssFeatureFlags::LowResolutionMotionVectors
|
||||
| DlssFeatureFlags::InvertedDepth
|
||||
| DlssFeatureFlags::HighDynamicRange
|
||||
|
||||
@@ -86,6 +86,10 @@ pub(super) struct HdFrame {
|
||||
pub(super) taa: [f32; 4],
|
||||
/// x: the history's weight; y: the sharpening (0 without TAA); zw: the jitter in world pixels.
|
||||
pub(super) taa_params: [f32; 4],
|
||||
/// xy: the previous frame's jitter in world pixels, same orientation as `taa_params.zw`;
|
||||
/// zw: unused. The motion buffer carries both frames' jitter; `fs_taau` removes the
|
||||
/// difference to read its history on the stable output grid.
|
||||
pub(super) prev_jitter: [f32; 4],
|
||||
/// The (jittered) world-to-clip matrix the world was drawn with (rays in the water pass).
|
||||
pub(super) view_proj: [[f32; 4]; 4],
|
||||
/// x: the water effect runs this frame; y: seconds for the waves (wraps at 600); zw: the
|
||||
@@ -145,8 +149,12 @@ pub struct HdScene {
|
||||
pub prev_view_proj: Mat4,
|
||||
/// The same frame's matrix as it was drawn, jitter included. History kept on the jittered
|
||||
/// pixel grid (`fs_taa`, scale 1) is looked up with this; `fs_taau` resolves the history on the
|
||||
/// unjittered output grid and uses `prev_view_proj`.
|
||||
/// unjittered output grid and uses `prev_view_proj`. The G-buffer's motion buffer is built
|
||||
/// from this matrix, so it carries the jitter difference of the two frames.
|
||||
pub prev_view_proj_jittered: Mat4,
|
||||
/// Last frame's jitter in world-target pixels, oriented like `jitter_px`: the previous
|
||||
/// position in the motion buffer carries it, and the stable-history upscaler subtracts it.
|
||||
pub prev_jitter_px: [f32; 2],
|
||||
pub camera_delta: glam::Vec3,
|
||||
/// This frame is anti-aliased over time (the projection is jittered).
|
||||
pub taa: bool,
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
//! |---|---|---|---|
|
||||
//! | 1 | `sky` | frame | sky texture 128x72 (linear Rec. 709 radiance) |
|
||||
//! | 2 | `shadow_pass` x2 (caller draws) | - | shadow array (normal Z, 1 = far) |
|
||||
//! | 3 | `gbuffer_pass` (caller draws) | - | albedo (a = emission), normal, light levels, current→previous motion (render pixels), depth |
|
||||
//! | 3 | `gbuffer_pass` (caller draws) | - | albedo (a = emission), normal, light levels, current→previous motion (jittered render pixels), depth |
|
||||
//! | 3a | `water_pass` (caller draws) | - | water colour (a = block light), normal (a = sky light), water depth |
|
||||
//! | 3b | `ao` | G-buffer depth, normal | AO half size (x occlusion, y distance) |
|
||||
//! | 3c | `volumes` | frame, sky, world depth, shadows, noise | clouds (rgb, a = transmittance), cloud shadow map, fog (rgb, a = transmittance) + ray length |
|
||||
@@ -51,6 +51,15 @@
|
||||
//! on the CPU and only differences reach the GPU). Where a world coordinate is needed for a
|
||||
//! pattern (waves, cloud noise, wind) it is passed modulo a period (256, 65536) so it stays exact
|
||||
//! in `f32`. The world projection carries the TAA jitter; `HdScene::prev_view_proj*` says which.
|
||||
//! - **Motion.** The G-buffer's motion buffer is current→previous in *jittered* render pixels:
|
||||
//! both positions are projected with their frame's drawn matrix (`Globals.prev_view_proj` is
|
||||
//! the previous jittered one), so even a still surface writes the two frames' jitter difference.
|
||||
//! Each temporal consumer decodes it for its own history grid: `fs_taa` (1:1, history on the
|
||||
//! jittered grid) uses it as written; `fs_taau` (history on the stable output grid) adds the
|
||||
//! current jitter and subtracts the previous one (`HdFrame.prev_jitter`), leaving a still
|
||||
//! surface on the same output pixel on every phase. The DLSS backend receives the buffer
|
||||
//! unchanged with the current jitter alongside; NGX's input contract is checked on that path
|
||||
//! separately (#137), not inferred here.
|
||||
//! - **Time.** `frame counter` (`HdFrame.params.w`, modulo 64, only for noise rotation); *water time*
|
||||
//! (`water.y`, wall-clock seconds since HD started modulo 600); *game time* (`clouds.w`, seconds
|
||||
//! from `HdScene::seconds` modulo 300000, drives cloud wind). They are separate on purpose:
|
||||
@@ -722,6 +731,7 @@ impl Hd {
|
||||
scene.jitter_px[0],
|
||||
scene.jitter_px[1],
|
||||
],
|
||||
prev_jitter: [scene.prev_jitter_px[0], scene.prev_jitter_px[1], 0.0, 0.0],
|
||||
inverse_view_proj: scene.view_proj.inverse().to_cols_array_2d(),
|
||||
resolution: [
|
||||
self.size[0] as f32,
|
||||
|
||||
@@ -13,6 +13,7 @@ struct HdFrame {
|
||||
prev_view_proj: mat4x4<f32>,
|
||||
taa: vec4<f32>,
|
||||
taa_params: vec4<f32>,
|
||||
prev_jitter: vec4<f32>,
|
||||
view_proj: mat4x4<f32>,
|
||||
water: vec4<f32>,
|
||||
sky_color: vec4<f32>,
|
||||
|
||||
@@ -5,11 +5,15 @@
|
||||
//! - Reads: the colour source (`HdSource::Lit`/`Fx`, the lit world with water, or the mod's post
|
||||
//! output; display space, world size), the *world* depth (reversed-Z, the pass's own depth from the
|
||||
//! world pass, not the G-buffer's), the history (output size, `Rgba16Float`), and the G-buffer's
|
||||
//! motion/depth. Matching opaque pixels use explicit current-to-previous render-pixel motion;
|
||||
//! other pixels keep camera/depth reprojection. `HdFrame`:
|
||||
//! motion/depth. The motion buffer is current→previous in *jittered* render pixels (a still
|
||||
//! surface carries the two frames' jitter difference); matching opaque pixels decode it for
|
||||
//! their history grid — `fs_taa` as written (its history is on the jittered grid), `fs_taau`
|
||||
//! minus the jitter difference (its history is on the stable output grid) — and other pixels
|
||||
//! keep camera/depth reprojection. `HdFrame`:
|
||||
//! `prev_view_proj` (last frame's matrix; **with** jitter for `fs_taa`, **without** for `fs_taau`,
|
||||
//! chosen in `Hd::write`), `taa` (xyz the camera's move since, w the *native* history usable),
|
||||
//! `taa_params` (x history weight, y sharpening, zw jitter in world pixels).
|
||||
//! `taa_params` (x history weight, y sharpening, zw jitter in world pixels), `prev_jitter`
|
||||
//! (xy the previous frame's jitter in world pixels, for `fs_taau`'s decode).
|
||||
//! - Writes `target` (the resolved frame, output size) and the next history together (two
|
||||
//! targets); history alpha holds the camera distance for disocclusion. The histories ping-pong
|
||||
//! (`flip`); a teleport > 64 blocks, `resize` or TAA off starts them over.
|
||||
@@ -502,4 +506,871 @@ mod tests {
|
||||
assert!(!h.native_usable());
|
||||
assert!(h.dlss_reset());
|
||||
}
|
||||
|
||||
// #143: the motion buffer's coordinate contract, checked numerically on every jitter phase.
|
||||
// The helpers mirror the shaders' math: `motion_pixels` (terrain.wgsl / entity.wgsl) writes
|
||||
// current→previous in jittered render pixels; `taa_lookup` is fs_taa's decode (history on the
|
||||
// jittered grid), `taau_lookup` fs_taau's (history on the stable output grid).
|
||||
|
||||
use glam::{Vec3, Vec4};
|
||||
|
||||
/// The screen uv a matrix draws a camera-relative point at (the shaders' clip-to-uv).
|
||||
fn uv_of(m: Mat4, p: Vec3) -> [f32; 2] {
|
||||
let c = m * p.extend(1.0);
|
||||
[c.x / c.w * 0.5 + 0.5, 0.5 - c.y / c.w * 0.5]
|
||||
}
|
||||
|
||||
/// gfx.rs's jitter in render pixels, screen orientation (x right, y down).
|
||||
fn jitter_px(frame: u32, size: [u32; 2], count: u32) -> [f32; 2] {
|
||||
let j = jitter(frame, size, count);
|
||||
[j[0] * size[0] as f32 * 0.5, -j[1] * size[1] as f32 * 0.5]
|
||||
}
|
||||
|
||||
fn drawn(unjittered: Mat4, frame: u32, size: [u32; 2], count: u32) -> Mat4 {
|
||||
let j = jitter(frame, size, count);
|
||||
Mat4::from_translation(Vec3::new(j[0], j[1], 0.0)) * unjittered
|
||||
}
|
||||
|
||||
/// terrain.wgsl / entity.wgsl `motion_pixels`: current→previous in jittered render pixels.
|
||||
fn motion_pixels(
|
||||
current: Mat4,
|
||||
previous: Mat4,
|
||||
size: [u32; 2],
|
||||
pos: Vec3,
|
||||
prev_pos: Vec3,
|
||||
) -> [f32; 2] {
|
||||
let c = current * pos.extend(1.0);
|
||||
let p = previous * prev_pos.extend(1.0);
|
||||
if c.w <= 0.0 || p.w <= 0.0 {
|
||||
return [0.0; 2];
|
||||
}
|
||||
[
|
||||
(p.x / p.w - c.x / c.w) * 0.5 * size[0] as f32,
|
||||
(c.y / c.w - p.y / p.w) * 0.5 * size[1] as f32,
|
||||
]
|
||||
}
|
||||
|
||||
/// fs_taa's decode: the history lives on the jittered grid, the buffer is used as written.
|
||||
fn taa_lookup(in_uv: [f32; 2], motion: [f32; 2], size: [u32; 2]) -> [f32; 2] {
|
||||
[
|
||||
in_uv[0] + motion[0] / size[0] as f32,
|
||||
in_uv[1] + motion[1] / size[1] as f32,
|
||||
]
|
||||
}
|
||||
|
||||
/// fs_taau's decode: the history lives on the stable output grid, so the two frames' jitter
|
||||
/// difference is removed from the buffer.
|
||||
fn taau_lookup(
|
||||
in_uv: [f32; 2],
|
||||
motion: [f32; 2],
|
||||
low: [u32; 2],
|
||||
cur: [f32; 2],
|
||||
prev: [f32; 2],
|
||||
) -> [f32; 2] {
|
||||
[
|
||||
in_uv[0] + (motion[0] + cur[0] - prev[0]) / low[0] as f32,
|
||||
in_uv[1] + (motion[1] + cur[1] - prev[1]) / low[1] as f32,
|
||||
]
|
||||
}
|
||||
|
||||
/// The larger axis' distance between two uvs, in pixels of `size`.
|
||||
fn px_err(a: [f32; 2], b: [f32; 2], size: [u32; 2]) -> f32 {
|
||||
((a[0] - b[0]) * size[0] as f32)
|
||||
.abs()
|
||||
.max(((a[1] - b[1]) * size[1] as f32).abs())
|
||||
}
|
||||
|
||||
fn probe_points() -> [Vec3; 4] {
|
||||
[
|
||||
Vec3::new(0.0, 0.0, -20.0),
|
||||
Vec3::new(3.0, 2.0, -10.0),
|
||||
Vec3::new(-7.0, -4.0, -60.0),
|
||||
Vec3::new(0.5, 0.25, -5.0),
|
||||
]
|
||||
}
|
||||
|
||||
fn projection() -> Mat4 {
|
||||
Mat4::perspective_rh(1.0, 16.0 / 9.0, 0.05, 1000.0)
|
||||
}
|
||||
|
||||
/// A still camera and world: the stable history must be read at the same output pixel on
|
||||
/// every jitter phase, and the motion path must agree with the depth/camera fallback.
|
||||
#[test]
|
||||
fn taau_static_surface_reads_the_same_pixel_on_every_phase() {
|
||||
let unjittered = projection();
|
||||
for (low, out) in [
|
||||
([1280u32, 720], [1920u32, 1080]),
|
||||
([960, 540], [1920, 1080]),
|
||||
([1280, 720], [2560, 1440]),
|
||||
] {
|
||||
let count = jitter_count(out[0] as f32 / low[0] as f32);
|
||||
let mut legacy_worst = 0.0f32;
|
||||
for frame in 1..=count * 2 {
|
||||
let cur = drawn(unjittered, frame, low, count);
|
||||
let prev = drawn(unjittered, frame - 1, low, count);
|
||||
let jc = jitter_px(frame, low, count);
|
||||
let jp = jitter_px(frame - 1, low, count);
|
||||
for p in probe_points() {
|
||||
let motion = motion_pixels(cur, prev, low, p, p);
|
||||
let in_uv = uv_of(unjittered, p);
|
||||
let uv = taau_lookup(in_uv, motion, low, jc, jp);
|
||||
assert!(
|
||||
px_err(uv, in_uv, out) < 0.01,
|
||||
"{low:?}->{out:?} frame {frame} point {p:?}: lookup {uv:?} moved off {in_uv:?}"
|
||||
);
|
||||
// The depth/camera fallback (previous unjittered matrix) lands on the same pixel.
|
||||
let fallback = uv_of(unjittered, p);
|
||||
assert!(px_err(uv, fallback, out) < 0.01);
|
||||
// The old decode (the buffer as written) shifts by exactly the jitter
|
||||
// difference: the fixture reproduces the bug it guards against.
|
||||
let legacy = taa_lookup(in_uv, motion, low);
|
||||
let shift = [
|
||||
(jp[0] - jc[0]) * out[0] as f32 / low[0] as f32,
|
||||
(jp[1] - jc[1]) * out[1] as f32 / low[1] as f32,
|
||||
];
|
||||
assert!(
|
||||
(px_err(legacy, in_uv, out) - shift[0].abs().max(shift[1].abs())).abs()
|
||||
< 0.01
|
||||
);
|
||||
legacy_worst = legacy_worst.max(px_err(legacy, in_uv, out));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
legacy_worst > 0.3,
|
||||
"{low:?}->{out:?}: the fixture must show the old decode's shift"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 1:1 TAA keeps its history on the jittered grid: the buffer's jitter difference is the
|
||||
/// correction the lookup needs, on every phase — it must not be decoded away.
|
||||
#[test]
|
||||
fn taa_one_to_one_keeps_the_jitter_correction_on_every_phase() {
|
||||
let size = [1920u32, 1080];
|
||||
let count = jitter_count(1.0);
|
||||
let unjittered = projection();
|
||||
for frame in 1..=count * 2 {
|
||||
let cur = drawn(unjittered, frame, size, count);
|
||||
let prev = drawn(unjittered, frame - 1, size, count);
|
||||
let jp = jitter_px(frame - 1, size, count);
|
||||
for p in probe_points() {
|
||||
let motion = motion_pixels(cur, prev, size, p, p);
|
||||
let in_uv = uv_of(cur, p);
|
||||
let uv = taa_lookup(in_uv, motion, size);
|
||||
// The pixel the previous frame drew the point at: what its history holds there.
|
||||
let wrote = uv_of(prev, p);
|
||||
assert!(
|
||||
px_err(uv, wrote, size) < 0.01,
|
||||
"frame {frame} point {p:?}: lookup {uv:?} missed the drawn pixel {wrote:?}"
|
||||
);
|
||||
// Without the correction (an unjittered previous matrix) it would miss by the
|
||||
// previous frame's jitter.
|
||||
let stable = uv_of(unjittered, p);
|
||||
let miss = px_err(stable, wrote, size);
|
||||
assert!((miss - jp[0].abs().max(jp[1].abs())).abs() < 0.01);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A moving camera over a still world: the motion path and the depth/camera fallback agree
|
||||
/// on the same continuous surface, in both modes, on every phase.
|
||||
#[test]
|
||||
fn moving_camera_both_reprojection_paths_agree_on_every_phase() {
|
||||
let unjittered = projection();
|
||||
let step = Vec3::new(0.35, -0.2, 0.15);
|
||||
for (low, out) in [
|
||||
([1920u32, 1080], [1920u32, 1080]),
|
||||
([1280, 720], [1920, 1080]),
|
||||
([960, 540], [1920, 1080]),
|
||||
] {
|
||||
let count = jitter_count(out[0] as f32 / low[0] as f32);
|
||||
for frame in 1..=count * 2 {
|
||||
let cur = drawn(unjittered, frame, low, count);
|
||||
let prev = drawn(unjittered, frame - 1, low, count);
|
||||
let jc = jitter_px(frame, low, count);
|
||||
let jp = jitter_px(frame - 1, low, count);
|
||||
for p in probe_points() {
|
||||
// A world-static point's previous camera-relative position.
|
||||
let prev_pos = p + step;
|
||||
let motion = motion_pixels(cur, prev, low, p, prev_pos);
|
||||
// fs_taau: the stable grid, the fallback's previous unjittered matrix.
|
||||
let uv = taau_lookup(uv_of(unjittered, p), motion, low, jc, jp);
|
||||
let fallback = uv_of(unjittered, prev_pos);
|
||||
assert!(
|
||||
px_err(uv, fallback, out) < 0.02,
|
||||
"{low:?}->{out:?} frame {frame} point {p:?}: motion {uv:?} vs fallback {fallback:?}"
|
||||
);
|
||||
// fs_taa: the jittered grid, the fallback's previous jittered matrix.
|
||||
let uv = taa_lookup(uv_of(cur, p), motion, low);
|
||||
let fallback = uv_of(prev, prev_pos);
|
||||
assert!(
|
||||
px_err(uv, fallback, out) < 0.02,
|
||||
"{low:?}->{out:?} frame {frame} point {p:?}: motion {uv:?} vs fallback {fallback:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A moving model with a known world shift: its motion (the previous drawn transform, not
|
||||
/// the camera fallback) lands on its previous position in both history grids, every phase.
|
||||
#[test]
|
||||
fn moving_model_motion_lands_on_its_previous_drawn_position() {
|
||||
let unjittered = projection();
|
||||
let shift = Vec3::new(0.5, 0.1, -0.25);
|
||||
for (low, out) in [
|
||||
([1280u32, 720], [1920u32, 1080]),
|
||||
([1920, 1080], [1920, 1080]),
|
||||
] {
|
||||
let count = jitter_count(out[0] as f32 / low[0] as f32);
|
||||
for frame in 1..=count * 2 {
|
||||
let cur = drawn(unjittered, frame, low, count);
|
||||
let prev = drawn(unjittered, frame - 1, low, count);
|
||||
let jc = jitter_px(frame, low, count);
|
||||
let jp = jitter_px(frame - 1, low, count);
|
||||
for p in probe_points() {
|
||||
let prev_pos = p + shift;
|
||||
let motion = motion_pixels(cur, prev, low, p, prev_pos);
|
||||
let uv = taau_lookup(uv_of(unjittered, p), motion, low, jc, jp);
|
||||
let expected = uv_of(unjittered, prev_pos);
|
||||
assert!(
|
||||
px_err(uv, expected, out) < 0.02,
|
||||
"{low:?}->{out:?} frame {frame} point {p:?}: TAAU lookup {uv:?} vs {expected:?}"
|
||||
);
|
||||
let uv = taa_lookup(uv_of(cur, p), motion, low);
|
||||
let expected = uv_of(prev, prev_pos);
|
||||
assert!(
|
||||
px_err(uv, expected, out) < 0.02,
|
||||
"{low:?}->{out:?} frame {frame} point {p:?}: TAA lookup {uv:?} vs {expected:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The issue's worked example: the first two Halton(2,3) phases at 1280x720 -> 1920x1080.
|
||||
/// A still point's motion is (+1/4, +1/3) render pixels; the old decode shifted the history
|
||||
/// lookup by (+0.375, +0.5) output pixels, the corrected one by nothing.
|
||||
#[test]
|
||||
fn issue_143_first_halton_pair_shifts_by_the_jitter_difference() {
|
||||
let low = [1280u32, 720];
|
||||
let out = [1920u32, 1080];
|
||||
let count = jitter_count(out[0] as f32 / low[0] as f32);
|
||||
let jp = jitter_px(0, low, count);
|
||||
let jc = jitter_px(1, low, count);
|
||||
assert!(jp[0].abs() < 1e-6 && (jp[1] - 1.0 / 6.0).abs() < 1e-6);
|
||||
assert!((jc[0] + 0.25).abs() < 1e-6 && (jc[1] + 1.0 / 6.0).abs() < 1e-6);
|
||||
let unjittered = projection();
|
||||
let p = Vec3::new(2.0, -1.0, -30.0);
|
||||
let motion = motion_pixels(
|
||||
drawn(unjittered, 1, low, count),
|
||||
drawn(unjittered, 0, low, count),
|
||||
low,
|
||||
p,
|
||||
p,
|
||||
);
|
||||
assert!((motion[0] - 0.25).abs() < 1e-5 && (motion[1] - 1.0 / 3.0).abs() < 1e-5);
|
||||
let in_uv = uv_of(unjittered, p);
|
||||
let legacy = taa_lookup(in_uv, motion, low);
|
||||
assert!(((legacy[0] - in_uv[0]) * out[0] as f32 - 0.375).abs() < 1e-4);
|
||||
assert!(((legacy[1] - in_uv[1]) * out[1] as f32 - 0.5).abs() < 1e-4);
|
||||
let fixed = taau_lookup(in_uv, motion, low, jc, jp);
|
||||
assert!(px_err(fixed, in_uv, out) < 1e-3);
|
||||
}
|
||||
|
||||
/// fs_taau rebuilds each pixel's unjittered point from the jittered depth (the inverse
|
||||
/// jittered matrix at ndc + jitter): the point, and so the history's distance, must not
|
||||
/// depend on the phase.
|
||||
#[test]
|
||||
fn taau_unshifts_the_jittered_depth_point_on_every_phase() {
|
||||
let low = [1280u32, 720];
|
||||
let count = jitter_count(1.5);
|
||||
let unjittered = projection();
|
||||
for frame in 0..count * 2 {
|
||||
let cur = drawn(unjittered, frame, low, count);
|
||||
let jc = jitter_px(frame, low, count);
|
||||
let inv = cur.inverse();
|
||||
for p in probe_points() {
|
||||
let c = cur * p.extend(1.0);
|
||||
let d = c.z / c.w;
|
||||
// The output pixel the point's stable position lies at (fs_taau's in.uv).
|
||||
let uv = uv_of(unjittered, p);
|
||||
let ndc = Vec4::new(
|
||||
uv[0] * 2.0 - 1.0 + jc[0] * 2.0 / low[0] as f32,
|
||||
1.0 - uv[1] * 2.0 - jc[1] * 2.0 / low[1] as f32,
|
||||
d,
|
||||
1.0,
|
||||
);
|
||||
let h = inv * ndc;
|
||||
let q = h.truncate() / h.w;
|
||||
// f32 depth quantisation grows with distance²; the jitter itself must cancel.
|
||||
assert!(
|
||||
(q - p).length() < p.length() * 2e-4 + 1e-4,
|
||||
"frame {frame} point {p:?}: rebuilt {q:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #143 A/B smoke on the real `fs_taau`: a still, finely patterned surface at a fractional
|
||||
/// render scale (1280x720 -> 1920x1080) must resolve to the same stable output pixel on every
|
||||
/// jitter phase. A is the old decode (the buffer as written), B the corrected one; a third
|
||||
/// run forces the depth/camera fallback, which must agree with B, and a fourth runs the
|
||||
/// spatial filter alone: the production lanczos gather has its own sub-pixel error on fine
|
||||
/// detail, so B is judged against that floor, not against zero. Needs a GPU adapter:
|
||||
/// `cargo test -p horizon-client --lib gfx::hd::taa::tests::taau_gpu -- --ignored`.
|
||||
#[test]
|
||||
#[ignore = "requires a Vulkan/Metal/DX12 adapter"]
|
||||
fn taau_gpu_smoke_still_surface_ab() {
|
||||
use crate::gfx::hd::{assemble, frame::HdFrame};
|
||||
use bytemuck::Zeroable;
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
|
||||
let Ok(adapter) =
|
||||
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
|
||||
else {
|
||||
eprintln!("no GPU adapter; skipping the TAAU smoke");
|
||||
return;
|
||||
};
|
||||
eprintln!("TAAU smoke adapter: {:?}", adapter.get_info());
|
||||
let (device, queue) =
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap();
|
||||
|
||||
let low = [1280u32, 720];
|
||||
let out = [1920u32, 1080];
|
||||
let count = jitter_count(out[0] as f32 / low[0] as f32);
|
||||
let frames = count * 2;
|
||||
let unjittered = projection();
|
||||
// A plane at z = -20 filling the view; with no camera rotation its points are affine in
|
||||
// ndc, so the scene fills cheaply on the CPU.
|
||||
let a = 20.0 * (0.5f32).tan() * 16.0 / 9.0;
|
||||
let b = 20.0 * (0.5f32).tan();
|
||||
let pattern = |x: f32, y: f32| {
|
||||
0.5 + 0.25 * (std::f32::consts::TAU * 8.0 * x / 40.0).sin()
|
||||
+ 0.25 * (std::f32::consts::TAU * 8.0 * y / 22.0).sin()
|
||||
};
|
||||
let c = unjittered * Vec3::new(0.0, 0.0, -20.0).extend(1.0);
|
||||
let plane_depth = c.z / c.w;
|
||||
|
||||
fn f16(x: f32) -> u16 {
|
||||
let bits = x.to_bits();
|
||||
let sign = ((bits >> 16) & 0x8000) as u16;
|
||||
let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
|
||||
let mant = bits & 0x7fffff;
|
||||
if exp <= 0 {
|
||||
return sign;
|
||||
}
|
||||
if exp >= 31 {
|
||||
return sign | 0x7c00;
|
||||
}
|
||||
let m = mant + 0x1000;
|
||||
if m & 0x800000 != 0 {
|
||||
sign | (((exp + 1) as u16) << 10)
|
||||
} else {
|
||||
sign | ((exp as u16) << 10) | ((m >> 13) as u16)
|
||||
}
|
||||
}
|
||||
fn from_f16(h: u16) -> f32 {
|
||||
let sign = ((h & 0x8000) as u32) << 16;
|
||||
let exp = ((h >> 10) & 0x1f) as i32;
|
||||
let mant = (h & 0x3ff) as u32;
|
||||
let bits = match exp {
|
||||
0 if mant == 0 => sign,
|
||||
0 => {
|
||||
let (mut e, mut m) = (-1, mant);
|
||||
while m & 0x400 == 0 {
|
||||
m <<= 1;
|
||||
e -= 1;
|
||||
}
|
||||
sign | (((114 + e) as u32) << 23) | ((m & 0x3ff) << 13)
|
||||
}
|
||||
31 => sign | 0x7f800000 | (mant << 13),
|
||||
_ => sign | (((exp - 15 + 127) as u32) << 23) | (mant << 13),
|
||||
};
|
||||
f32::from_bits(bits)
|
||||
}
|
||||
|
||||
let tex = |label: &str, size: [u32; 2], 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: &[],
|
||||
})
|
||||
};
|
||||
let source = tex(
|
||||
"TAAU smoke source",
|
||||
low,
|
||||
HDR,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let depth = tex(
|
||||
"TAAU smoke depth",
|
||||
low,
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
);
|
||||
let gbuffer_depth = tex(
|
||||
"TAAU smoke gbuffer depth",
|
||||
low,
|
||||
wgpu::TextureFormat::Depth32Float,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
);
|
||||
let motion = tex(
|
||||
"TAAU smoke motion",
|
||||
low,
|
||||
wgpu::TextureFormat::Rg16Float,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
);
|
||||
let target = tex(
|
||||
"TAAU smoke target",
|
||||
out,
|
||||
HDR,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
);
|
||||
// Own histories (the pass's own lack COPY_DST for the initial fill).
|
||||
let hist_tex = [0, 1].map(|i| {
|
||||
tex(
|
||||
&format!("TAAU smoke history {i}"),
|
||||
out,
|
||||
HDR,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::COPY_DST,
|
||||
)
|
||||
});
|
||||
let hist_views = [&hist_tex[0], &hist_tex[1]].map(|t| t.create_view(&Default::default()));
|
||||
let source_view = source.create_view(&Default::default());
|
||||
let depth_view = depth.create_view(&Default::default());
|
||||
let gbuffer_view = gbuffer_depth.create_view(&Default::default());
|
||||
let motion_view = motion.create_view(&Default::default());
|
||||
let target_view = target.create_view(&Default::default());
|
||||
// Depth textures take no buffer copies: fill them with a constant frag_depth pass.
|
||||
let depth_fill_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("TAAU smoke depth fill"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
r#"
|
||||
@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
|
||||
let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
|
||||
return vec4<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, 0.0, 1.0);
|
||||
}
|
||||
override DEPTH_VALUE: f32 = 1.0;
|
||||
@fragment fn fs() -> @builtin(frag_depth) f32 {
|
||||
return DEPTH_VALUE;
|
||||
}
|
||||
"#
|
||||
.into(),
|
||||
),
|
||||
});
|
||||
let depth_fill_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("TAAU smoke depth fill"),
|
||||
bind_group_layouts: &[],
|
||||
..Default::default()
|
||||
});
|
||||
let depth_fill_pipeline = |value: f32| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("TAAU smoke depth fill"),
|
||||
layout: Some(&depth_fill_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &depth_fill_module,
|
||||
entry_point: Some("vs"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &depth_fill_module,
|
||||
entry_point: Some("fs"),
|
||||
compilation_options: wgpu::PipelineCompilationOptions {
|
||||
constants: &[("DEPTH_VALUE", value as f64)],
|
||||
..Default::default()
|
||||
},
|
||||
targets: &[],
|
||||
}),
|
||||
primitive: Default::default(),
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::Always),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let depth_plane = depth_fill_pipeline(plane_depth);
|
||||
let depth_zero = depth_fill_pipeline(0.0);
|
||||
let fill_depth = |view: &wgpu::TextureView, pipeline: &wgpu::RenderPipeline| {
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("TAAU smoke depth fill"),
|
||||
color_attachments: &[],
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(0.0),
|
||||
store: wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
queue.submit([encoder.finish()]);
|
||||
};
|
||||
fill_depth(&depth_view, &depth_plane);
|
||||
|
||||
// The pass's layout and production fs_taau pipeline (its own targets go unused).
|
||||
let taa = Taa::new(&device);
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
// A: the old decode, compiled from the same shader with the correction taken back out.
|
||||
let fixed_line = "uv = in.uv + (motion.xy + jit - frame.prev_jitter.xy) / low;";
|
||||
let legacy_src = TAA.replace(fixed_line, "uv = in.uv + motion.xy / low;");
|
||||
assert_ne!(legacy_src, TAA, "the A/B control must patch the decode");
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("TAAU smoke"),
|
||||
bind_group_layouts: &[Some(&taa.layout)],
|
||||
..Default::default()
|
||||
});
|
||||
let color_target = Some(wgpu::ColorTargetState {
|
||||
format: HDR,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
});
|
||||
let variant_pipeline = |src: &str, label: &str| {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(label),
|
||||
source: wgpu::ShaderSource::Wgsl(assemble(src).into()),
|
||||
});
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(label),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &module,
|
||||
entry_point: Some("vs_full"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[],
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs_taau"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[color_target.clone(), color_target.clone()],
|
||||
}),
|
||||
primitive: Default::default(),
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let legacy_pipeline = variant_pipeline(&legacy_src, "TAAU smoke legacy");
|
||||
// The spatial filter alone (no history): the production lanczos gather has its own
|
||||
// sub-pixel error on fine detail, which the temporal path must not add to.
|
||||
let recon_src = TAA.replace(
|
||||
"resolved = mix(current, past, clamp(keep, 0.0, 0.98));",
|
||||
"resolved = current;",
|
||||
);
|
||||
assert_ne!(recon_src, TAA);
|
||||
let recon_pipeline = variant_pipeline(&recon_src, "TAAU smoke recon");
|
||||
let frame_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("TAAU smoke frame"),
|
||||
contents: bytemuck::bytes_of(&HdFrame::zeroed()),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
let readback = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("TAAU smoke readback"),
|
||||
size: (out[0] * out[1] * 8) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
// The stable reference: the pattern at each output pixel's unjittered point.
|
||||
let mut reference = vec![[0.0f32; 3]; (out[0] * out[1]) as usize];
|
||||
for y in 0..out[1] {
|
||||
for x in 0..out[0] {
|
||||
let u = (x as f32 + 0.5) / out[0] as f32;
|
||||
let v = (y as f32 + 0.5) / out[1] as f32;
|
||||
let px = (u * 2.0 - 1.0) * a;
|
||||
let py = (1.0 - v * 2.0) * b;
|
||||
let c = pattern(px, py);
|
||||
reference[(y * out[0] + x) as usize] = [c, c, c];
|
||||
}
|
||||
}
|
||||
let history_init = {
|
||||
let mut data = vec![0u16; (out[0] * out[1] * 4) as usize];
|
||||
for y in 0..out[1] {
|
||||
for x in 0..out[0] {
|
||||
let u = (x as f32 + 0.5) / out[0] as f32;
|
||||
let v = (y as f32 + 0.5) / out[1] as f32;
|
||||
let px = (u * 2.0 - 1.0) * a;
|
||||
let py = (1.0 - v * 2.0) * b;
|
||||
let c = pattern(px, py);
|
||||
let dist = (px * px + py * py + 400.0).sqrt();
|
||||
let i = ((y * out[0] + x) * 4) as usize;
|
||||
data[i..i + 4].copy_from_slice(&[f16(c), f16(c), f16(c), f16(dist)]);
|
||||
}
|
||||
}
|
||||
data
|
||||
};
|
||||
|
||||
// One run: `legacy` picks the decode, `fallback` zeroes the G-buffer depth so every
|
||||
// pixel takes the depth/camera path. Returns (max error vs the reference, max spread
|
||||
// across phases), over the second jitter cycle and away from the border.
|
||||
let run = |variant: usize, fallback: bool| -> (f32, f32) {
|
||||
let pipeline = match variant {
|
||||
1 => &legacy_pipeline,
|
||||
2 => &recon_pipeline,
|
||||
_ => &taa.taau_pipeline,
|
||||
};
|
||||
fill_depth(
|
||||
&gbuffer_view,
|
||||
if fallback { &depth_zero } else { &depth_plane },
|
||||
);
|
||||
for h in &hist_tex {
|
||||
queue.write_texture(
|
||||
h.as_image_copy(),
|
||||
bytemuck::cast_slice(&history_init),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(out[0] * 8),
|
||||
rows_per_image: Some(out[1]),
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width: out[0],
|
||||
height: out[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut flip = 0usize;
|
||||
let mut first: Vec<[f32; 3]> = Vec::new();
|
||||
let (mut err, mut spread) = (0.0f32, 0.0f32);
|
||||
let mut scratch = vec![[0.0f32; 3]; (out[0] * out[1]) as usize];
|
||||
for frame in 0..frames {
|
||||
let j = jitter(frame, low, count);
|
||||
let jc = jitter_px(frame, low, count);
|
||||
let jp = jitter_px(frame.wrapping_sub(1), low, count);
|
||||
// The drawn (jittered) scene: the pixel at ndc shows the world point whose
|
||||
// unjittered ndc is ndc - j. Separable sine tables per row and column.
|
||||
let sx: Vec<f32> = (0..low[0])
|
||||
.map(|x| {
|
||||
let ndc = (x as f32 + 0.5) / low[0] as f32 * 2.0 - 1.0 - j[0];
|
||||
0.25 * (std::f32::consts::TAU * 8.0 * ndc * a / 40.0).sin()
|
||||
})
|
||||
.collect();
|
||||
let sy: Vec<f32> = (0..low[1])
|
||||
.map(|y| {
|
||||
let ndc = 1.0 - (y as f32 + 0.5) / low[1] as f32 * 2.0 - j[1];
|
||||
0.25 * (std::f32::consts::TAU * 8.0 * ndc * b / 22.0).sin()
|
||||
})
|
||||
.collect();
|
||||
let mut data = vec![0u16; (low[0] * low[1] * 4) as usize];
|
||||
for y in 0..low[1] {
|
||||
for x in 0..low[0] {
|
||||
let c = 0.5 + sx[x as usize] + sy[y as usize];
|
||||
let i = ((y * low[0] + x) * 4) as usize;
|
||||
data[i..i + 4].copy_from_slice(&[f16(c), f16(c), f16(c), f16(1.0)]);
|
||||
}
|
||||
}
|
||||
queue.write_texture(
|
||||
source.as_image_copy(),
|
||||
bytemuck::cast_slice(&data),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(low[0] * 8),
|
||||
rows_per_image: Some(low[1]),
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width: low[0],
|
||||
height: low[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
// A still surface's motion is exactly the two frames' jitter difference.
|
||||
let m = [f16(jp[0] - jc[0]), f16(jp[1] - jc[1])];
|
||||
let data = vec![m; (low[0] * low[1]) as usize];
|
||||
queue.write_texture(
|
||||
motion.as_image_copy(),
|
||||
bytemuck::cast_slice(&data),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(low[0] * 4),
|
||||
rows_per_image: Some(low[1]),
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width: low[0],
|
||||
height: low[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
let cur = drawn(unjittered, frame, low, count);
|
||||
let mut f = HdFrame::zeroed();
|
||||
f.inverse_view_proj = cur.inverse().to_cols_array_2d();
|
||||
f.view_proj = cur.to_cols_array_2d();
|
||||
f.prev_view_proj = unjittered.to_cols_array_2d();
|
||||
f.taa = [0.0, 0.0, 0.0, if frame > 0 { 1.0 } else { 0.0 }];
|
||||
// Weight 1: the resolved pixel is the history lookup itself, so a shifted
|
||||
// lookup shows up directly instead of hiding under the fresh sample.
|
||||
f.taa_params = [1.0, 0.12, jc[0], jc[1]];
|
||||
f.prev_jitter = [jp[0], jp[1], 0.0, 0.0];
|
||||
f.resolution = [
|
||||
low[0] as f32,
|
||||
low[1] as f32,
|
||||
1.0 / low[0] as f32,
|
||||
1.0 / low[1] as f32,
|
||||
];
|
||||
queue.write_buffer(&frame_buf, 0, bytemuck::bytes_of(&f));
|
||||
let (read, write) = (flip, 1 - flip);
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("TAAU smoke"),
|
||||
layout: &taa.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: frame_buf.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&source_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::TextureView(&depth_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 3,
|
||||
resource: wgpu::BindingResource::TextureView(&hist_views[read]),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: wgpu::BindingResource::TextureView(&motion_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 6,
|
||||
resource: wgpu::BindingResource::TextureView(&gbuffer_view),
|
||||
},
|
||||
],
|
||||
});
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
{
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("TAAU smoke"),
|
||||
color_attachments: &[&target_view, &hist_views[write]].map(|view| {
|
||||
Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &group, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
encoder.copy_texture_to_buffer(
|
||||
target.as_image_copy(),
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &readback,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(out[0] * 8),
|
||||
rows_per_image: Some(out[1]),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width: out[0],
|
||||
height: out[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
queue.submit([encoder.finish()]);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
readback.map_async(wgpu::MapMode::Read, .., move |r| tx.send(r).unwrap());
|
||||
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
|
||||
rx.recv().unwrap().unwrap();
|
||||
{
|
||||
let mapped = readback.get_mapped_range(..).unwrap();
|
||||
let pixels: &[[u16; 4]] = bytemuck::cast_slice(&mapped);
|
||||
for y in 2..out[1] - 2 {
|
||||
for x in 2..out[0] - 2 {
|
||||
let i = (y * out[0] + x) as usize;
|
||||
let c = from_f16(pixels[i][0]);
|
||||
scratch[i] = [c, c, c];
|
||||
}
|
||||
}
|
||||
}
|
||||
readback.unmap();
|
||||
flip = write;
|
||||
if frame >= count {
|
||||
if frame == count {
|
||||
first = scratch.clone();
|
||||
}
|
||||
for y in 2..out[1] - 2 {
|
||||
for x in 2..out[0] - 2 {
|
||||
let i = (y * out[0] + x) as usize;
|
||||
err = err.max((scratch[i][0] - reference[i][0]).abs());
|
||||
spread = spread.max((scratch[i][0] - first[i][0]).abs());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(err, spread)
|
||||
};
|
||||
|
||||
let (legacy_err, legacy_spread) = run(1, false);
|
||||
let (fixed_err, fixed_spread) = run(0, false);
|
||||
let (fallback_err, fallback_spread) = run(0, true);
|
||||
let (recon_err, recon_spread) = run(2, false);
|
||||
eprintln!(
|
||||
"TAAU smoke: legacy err {legacy_err:.5} spread {legacy_spread:.5}; \
|
||||
fixed err {fixed_err:.5} spread {fixed_spread:.5}; \
|
||||
fallback err {fallback_err:.5} spread {fallback_spread:.5}; \
|
||||
recon err {recon_err:.5} spread {recon_spread:.5}"
|
||||
);
|
||||
// The corrected decode adds nothing on top of the production spatial filter, and the
|
||||
// history steadies the picture across phases (the filter alone flickers with the jitter).
|
||||
assert!(
|
||||
fixed_err <= recon_err * 1.05 + 1e-4,
|
||||
"fixed decode err {fixed_err} above the filter's own {recon_err}"
|
||||
);
|
||||
assert!(fixed_spread < recon_spread);
|
||||
assert!(fixed_spread < 4e-3, "fixed decode spread {fixed_spread}");
|
||||
// The motion path and the depth/camera fallback agree on the continuous surface.
|
||||
assert!((fixed_err - fallback_err).abs() < 1e-5);
|
||||
assert!((fixed_spread - fallback_spread).abs() < 1e-5);
|
||||
// A reproduces the bug: the jitter difference drags the history lookup off the pixel.
|
||||
assert!(legacy_err > 1e-2, "legacy decode err {legacy_err}");
|
||||
assert!(
|
||||
legacy_err > 2.5 * fixed_err,
|
||||
"the A/B must separate: legacy {legacy_err} vs fixed {fixed_err}"
|
||||
);
|
||||
assert!(legacy_spread > 2.0 * fixed_spread);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,10 @@ struct TaaOut {
|
||||
@group(0) @binding(5) var motion_tex: texture_2d<f32>;
|
||||
@group(0) @binding(6) var gbuffer_depth: texture_depth_2d;
|
||||
|
||||
// Opaque G-buffer geometry has an explicit current-to-previous vector. World-only or translucent
|
||||
// pixels keep the depth/camera fallback until their own motion/reactive contract is defined.
|
||||
// Opaque G-buffer geometry has an explicit current-to-previous vector, in jittered render pixels
|
||||
// (both frames' jitter included, so a still surface carries their difference). Each caller decodes
|
||||
// it for its own history grid. World-only or translucent pixels keep the depth/camera fallback
|
||||
// until their own motion/reactive contract is defined.
|
||||
fn history_motion(px: vec2<i32>, world_depth: f32) -> vec3<f32> {
|
||||
let surface = textureLoad(gbuffer_depth, px, 0);
|
||||
if surface > 0.0 && abs(surface - world_depth) <= 0.000001 {
|
||||
@@ -116,6 +118,8 @@ fn fs_taa(in: FullOut) -> TaaOut {
|
||||
}
|
||||
let motion = history_motion(px, d);
|
||||
if motion.z > 0.5 {
|
||||
// This history lives on the jittered pixel grid, the same one the buffer was written
|
||||
// in: its jitter difference is exactly the correction the lookup needs, as written.
|
||||
uv = in.uv + motion.xy / vec2<f32>(size);
|
||||
}
|
||||
if DEBUG_MOTION {
|
||||
@@ -224,7 +228,10 @@ fn fs_taau(in: FullOut) -> TaaOut {
|
||||
}
|
||||
let motion = history_motion(nearest, d);
|
||||
if motion.z > 0.5 {
|
||||
uv = in.uv + motion.xy / low;
|
||||
// The buffer is current-to-previous in jittered render pixels, but this history lives
|
||||
// on the stable output grid: undo the two frames' jitter difference, so a still
|
||||
// surface reads the same output pixel on every jitter phase.
|
||||
uv = in.uv + (motion.xy + jit - frame.prev_jitter.xy) / low;
|
||||
}
|
||||
if DEBUG_MOTION {
|
||||
var out: TaaOut;
|
||||
|
||||
@@ -237,6 +237,9 @@ struct GBufferOut {
|
||||
@location(2) light: vec4<f32>,
|
||||
@location(3) motion: vec2<f32>,
|
||||
}
|
||||
// The motion buffer's contract: current-to-previous in jittered render pixels (both matrices as
|
||||
// drawn, so a still surface writes the two frames' jitter difference). The temporal passes decode
|
||||
// it for their history grid (gfx/hd/taa.wgsl); DLSS receives it unchanged.
|
||||
fn motion_pixels(pos: vec3<f32>, previous: vec4<f32>) -> vec2<f32> {
|
||||
let current = globals.view_proj * vec4(pos, 1.0);
|
||||
if current.w <= 0.0 || previous.w <= 0.0 { return vec2<f32>(0.0); }
|
||||
|
||||
Reference in New Issue
Block a user