Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add an optional GPU a-trous wavelet filter (denoise: atrous) to the Cook native tracer (#895)

Nguyen Xuan Anf4185db1da6e
diff --git a/bench/cycles-parity/trace-native.mjs b/bench/cycles-parity/trace-native.mjs
index 20848e0d..3e42cdcc 100644
--- a/bench/cycles-parity/trace-native.mjs
+++ b/bench/cycles-parity/trace-native.mjs
@@ -9,6 +9,7 @@ import { buildTraceSceneWithManyLights } from './trace-scene-many-lights.mjs';
import * as renderNative from '../../packages/render-native/index.mjs';
import { writeFloat32Npy } from './npy.mjs';
import { reconstructTraceSceneSource } from './scene-bridge.mjs';
+import { denoiseRadiance } from '../../src/path-tracer-denoise.js';
const SUPPORTED_KERNELS = new Set(['legacy', 'cycles']);
const SUPPORTED_FILTERS = new Set(['box', 'gaussian', 'blackman-harris']);
@@ -78,6 +79,10 @@ function parseSamplerOption(argumentList) {
return sampler;
}
+function parseDenoiseOption(argumentList) {
+ return parseChoiceOption(argumentList, '--denoise', ['none', 'wavelet', 'atrous'], 'none');
+}
+
function parseLightSamplingOption(argumentList) {
const lightSampling = String(readFlagValue(argumentList, '--light-sampling', 'auto'));
if (!['auto', 'tree', 'uniform'].includes(lightSampling)) {
@@ -96,7 +101,7 @@ function parseLightSamplingOption(argumentList) {
function parseTraceArguments(argumentList) {
if (argumentList.length < 2 || argumentList[0].startsWith('--') || argumentList[1].startsWith('--')) {
- throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--kernel legacy|cycles] [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--sampler white|sobol-burley] [--light-sampling auto|tree|uniform] [--path-regeneration] [--env-compensation 0..1] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0]');
+ throw new RangeError('Usage: node bench/cycles-parity/trace-native.mjs <sceneJsonPath> <outputPrefix> [--kernel legacy|cycles] [--samples 256] [--bounces 8] [--seed 1] [--width 960] [--height 540] [--sampler white|sobol-burley] [--light-sampling auto|tree|uniform] [--path-regeneration] [--env-compensation 0..1] [--filter-type box|gaussian|blackman-harris] [--filter-width 1.0] [--clamp-direct 0] [--clamp-indirect 0] [--firefly-clamp 1e9] [--noise-threshold 0] [--denoise none|wavelet|atrous]');
}
return {
sceneJsonPath: resolve(argumentList[0]),
@@ -120,6 +125,7 @@ function parseTraceArguments(argumentList) {
filterGlossy: parseNumberOption(argumentList, '--filter-glossy', 1.0, 0),
fireflyClamp: parseNumberOption(argumentList, '--firefly-clamp', 1e9, 0),
noiseThreshold: parseNumberOption(argumentList, '--noise-threshold', 0, 0),
+ denoise: parseDenoiseOption(argumentList),
samplesPerDispatch: argumentList.includes('--samples-per-dispatch')
? parseIntegerOption(argumentList, '--samples-per-dispatch', 16, 1)
: undefined,
@@ -146,6 +152,40 @@ function extractLinearRgb(rgbaPixels, pixelCount) {
return linearRgb;
}
+function normalizeNormals(normal) {
+ for (let offset = 0; offset < normal.length; offset += 3) {
+ const length = Math.hypot(normal[offset], normal[offset + 1], normal[offset + 2]);
+ if (length > 1e-6) {
+ normal[offset] /= length;
+ normal[offset + 1] /= length;
+ normal[offset + 2] /= length;
+ }
+ }
+}
+
+/**
+ * Runs the existing wavelet filter (src/path-tracer-denoise.js) on the traced guides. Pixels where it returns a value that
+ * is not finite (background pixels with zero normal and depth, issue 969) keep their unfiltered colour; the count is reported.
+ */
+function applyWavelet(traced, linearRgb, width, height) {
+ const features = { color: linearRgb, albedo: traced.albedo, normal: traced.normal, depth: traced.depth, variance: traced.variance };
+ normalizeNormals(features.normal);
+ const started = performance.now();
+ const filtered = denoiseRadiance({ width, height, ...features });
+ const seconds = (performance.now() - started) / 1000;
+ const result = new Float32Array(linearRgb);
+ let replacedPixels = 0;
+ for (let pixel = 0; pixel < width * height; pixel++) {
+ const offset = pixel * 3;
+ if (Number.isFinite(filtered[offset]) && Number.isFinite(filtered[offset + 1]) && Number.isFinite(filtered[offset + 2])) {
+ result.set(filtered.subarray(offset, offset + 3), offset);
+ } else {
+ replacedPixels++;
+ }
+ }
+ return { image: result, seconds, replacedPixels };
+}
+
async function runCli() {
setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
const options = parseTraceArguments(process.argv.slice(2));
@@ -181,11 +221,16 @@ async function runCli() {
clampDirect: options.clampDirect,
clampIndirect: options.clampIndirect,
filterGlossy: options.filterGlossy,
+ denoise: options.denoise === 'atrous' ? 'atrous' : 'none',
});
const totalTraceSeconds = (performance.now() - totalStarted) / 1000;
const postTraceRssMegabytes = process.memoryUsage().rss / (1024 * 1024);
const pixelCount = options.width * options.height;
- const linearRgb = extractLinearRgb(traced.rgba, pixelCount);
+ const unfilteredRgb = extractLinearRgb(traced.rgba, pixelCount);
+ // A filtered image is a biased, smoothed estimate, never a converged one.
+ const wavelet = options.denoise === 'wavelet' ? applyWavelet(traced, unfilteredRgb, options.width, options.height) : null;
+ const atrousRgb = options.denoise === 'atrous' ? extractLinearRgb(traced.denoisedRgba, pixelCount) : null;
+ const linearRgb = wavelet ? wavelet.image : (atrousRgb ?? unfilteredRgb);
const npyPath = `${options.outputPrefix}.npy`;
await writeFloat32Npy(npyPath, linearRgb, [options.height, options.width, 3]);
const setupSeconds = sceneBuildSeconds + traced.setupSeconds + traced.compileSeconds + traced.uploadSeconds + traced.accelerationBuildSeconds;
@@ -211,6 +256,11 @@ async function runCli() {
clampIndirect: options.clampIndirect,
fireflyClamp: options.fireflyClamp,
noiseThreshold: options.noiseThreshold,
+ denoise: options.denoise,
+ denoiseSeconds: wavelet ? Number(wavelet.seconds.toFixed(6)) : Number((traced.denoiseSeconds ?? 0).toFixed(6)),
+ denoiseGpuSeconds: Number((traced.denoiseGpuSeconds ?? 0).toFixed(6)),
+ denoiseCompileSeconds: Number((traced.denoiseCompileSeconds ?? 0).toFixed(6)),
+ denoiseNonFinitePixelsReplaced: wavelet ? wavelet.replacedPixels : 0,
triangleCount: nativeInput.triangleCount,
adapter: traced.adapter,
backend: traced.backend,
diff --git a/packages/render-native/index.mjs b/packages/render-native/index.mjs
index ad7ad6f3..8b212e9d 100644
--- a/packages/render-native/index.mjs
+++ b/packages/render-native/index.mjs
@@ -74,10 +74,13 @@ export function traceNative(input, options = {}) {
validatePackOptions(options, 'traceNative', true);
const { sampler, lightSampling } = resolveSamplingOptions(options, 'traceNative');
validatePathRegenerationOption(options.pathRegeneration, 'traceNative');
- const { width, height, samples, maxSeconds, kernel, samplesPerDispatch, bootstrapKernel } = options;
+ const { width, height, samples, maxSeconds, kernel, samplesPerDispatch, bootstrapKernel, denoise } = options;
const selectedKernel = resolveNativeKernel(kernel);
const addon = loadAddon();
if (selectedKernel === 'legacy') {
+ if (denoise === 'atrous') {
+ throw new TypeError('traceNative: `denoise: "atrous"` filters the Cycles kernel result; pass kernel "cycles", or call denoiseAtrous with the traced guide buffers.');
+ }
if (input?.schemaVersion === FORMAT_V2_VERSION) {
throw new TypeError(
'Cannot pass a FORMAT-v2 scene input to kernel "legacy": pass kernel "cycles" or build a v1 input with buildNativeInput.'
@@ -115,9 +118,28 @@ export function traceNative(input, options = {}) {
samplesPerDispatch,
maxSeconds,
bootstrapKernel,
+ denoise,
});
}
+/**
+ * Filters a traced image with the edge-avoiding a-trous wavelet filter on the GPU (Dammertz 2010 with SVGF's variance
+ * guidance, spatial only). `rgba` holds four floats per pixel; `albedo`, `normal` (any length, zero where nothing was
+ * hit), `depth` and `variance` are the guide buffers `traceNative` returns. The result is smoothed and biased: it is not
+ * a converged image. Returns `{ rgba, compileSeconds, uploadSeconds, gpuSeconds, readbackSeconds }`.
+ */
+export function denoiseAtrous({ width, height, rgba, albedo, normal, depth, variance }) {
+ const pixelCount = width * height;
+ validateImagePixelCount(width, height, 'denoiseAtrous');
+ const planes = { rgba: [rgba, 4], albedo: [albedo, 3], normal: [normal, 3], depth: [depth, 1], variance: [variance, 1] };
+ for (const [name, [plane, floatsPerPixel]] of Object.entries(planes)) {
+ if (!(plane instanceof Float32Array) || plane.length !== pixelCount * floatsPerPixel) {
+ throw new TypeError(`denoiseAtrous: \`${name}\` must be a Float32Array of ${pixelCount * floatsPerPixel} floats for a ${width}x${height} image.`);
+ }
+ }
+ return loadAddon().denoiseAtrous({ width, height, rgba, albedo, normal, depth, variance });
+}
+
function hasFilterOptions(options) {
return options.filterType !== undefined || options.pixelFilter !== undefined || options.filterWidth !== undefined;
}
diff --git a/packages/render-native/pack-input-v2.mjs b/packages/render-native/pack-input-v2.mjs
index d284cb4f..44c60bd0 100644
--- a/packages/render-native/pack-input-v2.mjs
+++ b/packages/render-native/pack-input-v2.mjs
@@ -1572,6 +1572,15 @@ export function validateSamplerOption(sampler, callerName) {
}
}
+/** Throws unless `denoise` is undefined, "none" or "atrous". */
+export function validateDenoiseOption(denoise, callerName) {
+ if (denoise !== undefined && denoise !== 'none' && denoise !== 'atrous') {
+ throw new RangeError(
+ `${callerName}: \`denoise\` must be "none" (default) or "atrous", got ${JSON.stringify(denoise)}.`
+ );
+ }
+}
+
/** Throws unless `lightSampling` is undefined, "auto", "tree" or "uniform". */
export function validateLightSamplingOption(lightSampling, callerName) {
if (lightSampling !== undefined && !VALID_LIGHT_SAMPLING.includes(lightSampling)) {
@@ -1653,6 +1662,7 @@ export function validatePackOptions(options, callerName, requireDimensionsAndSam
validateMaxSeconds(options.maxSeconds, callerName);
resolveSamplingOptions(options, callerName);
resolveEnvCompensationFraction(options.envCompensation, callerName);
+ validateDenoiseOption(options.denoise, callerName);
validateFilterOptions(options, callerName);
if (width !== undefined && height !== undefined) {
validateImagePixelCount(width, height, callerName);
diff --git a/packages/render-native/src/denoise_atrous.wgsl b/packages/render-native/src/denoise_atrous.wgsl
new file mode 100644
index 00000000..3a39359e
--- /dev/null
+++ b/packages/render-native/src/denoise_atrous.wgsl
@@ -0,0 +1,191 @@
+// An edge-avoiding a-trous wavelet filter on the GPU, after Dammertz et al. 2010 (edge-avoiding a-trous wavelet transform)
+// with the variance guided luminance weight of Schied et al. 2017 (SVGF), spatial part only. It is the WGSL form of
+// src/path-tracer-denoise.js and keeps its constants. The result is a biased, smoothed estimate, not a converged image.
+//
+// Entry points, dispatched in this order: prepare, atrous five times (steps 1, 2, 4, 8, 16), finish.
+
+struct Parameters {
+ width: u32,
+ height: u32,
+ pass_step: u32,
+ read_from_b: u32,
+}
+
+@group(0) @binding(0) var<uniform> parameters: Parameters;
+// The traced colour in, the filtered colour out (linear RGBA, alpha 1).
+@group(0) @binding(1) var<storage, read_write> color: array<vec4<f32>>;
+@group(0) @binding(2) var<storage, read_write> albedo: array<f32>;
+// Three floats per pixel; `prepare` turns each into a unit vector, or zero where the first ray escaped.
+@group(0) @binding(3) var<storage, read_write> normal: array<f32>;
+@group(0) @binding(4) var<storage, read_write> depth: array<f32>;
+@group(0) @binding(5) var<storage, read_write> variance: array<f32>;
+// Demodulated light in xyz and its noise variance in w; the passes ping-pong between the two.
+@group(0) @binding(6) var<storage, read_write> light_a: array<vec4<f32>>;
+@group(0) @binding(7) var<storage, read_write> light_b: array<vec4<f32>>;
+
+const ALBEDO_FLOOR: f32 = 0.02;
+const NORMAL_POWER: f32 = 64.0;
+const LUMINANCE_SIGMA: f32 = 3.0;
+const LUMINANCE_WEIGHTS: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
+
+fn luminance_of(value: vec3<f32>) -> f32 {
+ return dot(value, LUMINANCE_WEIGHTS);
+}
+
+fn albedo_at(pixel: u32) -> vec3<f32> {
+ return vec3<f32>(albedo[pixel * 3u], albedo[pixel * 3u + 1u], albedo[pixel * 3u + 2u]);
+}
+
+fn normal_at(pixel: u32) -> vec3<f32> {
+ return vec3<f32>(normal[pixel * 3u], normal[pixel * 3u + 1u], normal[pixel * 3u + 2u]);
+}
+
+fn kernel_weight(offset: i32) -> f32 {
+ let magnitude = abs(offset);
+ if (magnitude == 0) {
+ return 0.375;
+ }
+ if (magnitude == 1) {
+ return 0.25;
+ }
+ return 0.0625;
+}
+
+fn load_light(read_from_b: bool, pixel: u32) -> vec4<f32> {
+ if (read_from_b) {
+ return light_b[pixel];
+ }
+ return light_a[pixel];
+}
+
+fn store_light(write_to_b: bool, pixel: u32, value: vec4<f32>) {
+ if (write_to_b) {
+ light_b[pixel] = value;
+ } else {
+ light_a[pixel] = value;
+ }
+}
+
+// The variance of the light (albedo divided out) at one pixel, smoothed over the 3 by 3 neighbourhood.
+fn smoothed_noise(column: u32, row: u32) -> f32 {
+ let width = i32(parameters.width);
+ let height = i32(parameters.height);
+ var sum = 0.0;
+ var count = 0.0;
+ for (var row_offset = -1; row_offset <= 1; row_offset++) {
+ for (var column_offset = -1; column_offset <= 1; column_offset++) {
+ let neighbor_row = i32(row) + row_offset;
+ let neighbor_column = i32(column) + column_offset;
+ if (neighbor_row < 0 || neighbor_row >= height || neighbor_column < 0 || neighbor_column >= width) {
+ continue;
+ }
+ let neighbor = u32(neighbor_row * width + neighbor_column);
+ let brightness = max(luminance_of(albedo_at(neighbor)), ALBEDO_FLOOR);
+ sum += variance[neighbor] / (brightness * brightness);
+ count += 1.0;
+ }
+ }
+ return sum / count;
+}
+
+@compute @workgroup_size(8, 8, 1)
+fn prepare(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x >= parameters.width || id.y >= parameters.height) {
+ return;
+ }
+ let pixel = id.y * parameters.width + id.x;
+ let raw_normal = normal_at(pixel);
+ var unit_normal = vec3<f32>(0.0);
+ if (length(raw_normal) > 1e-6) {
+ unit_normal = normalize(raw_normal);
+ }
+ normal[pixel * 3u] = unit_normal.x;
+ normal[pixel * 3u + 1u] = unit_normal.y;
+ normal[pixel * 3u + 2u] = unit_normal.z;
+ let light = color[pixel].xyz / max(albedo_at(pixel), vec3<f32>(ALBEDO_FLOOR));
+ light_a[pixel] = vec4<f32>(light, smoothed_noise(id.x, id.y));
+}
+
+// Rays that escaped carry no normal: two such pixels agree fully, one such pixel agrees with nothing.
+fn normal_agreement(center_normal: vec3<f32>, neighbor_normal: vec3<f32>) -> f32 {
+ let center_present = dot(center_normal, center_normal) > 0.5;
+ let neighbor_present = dot(neighbor_normal, neighbor_normal) > 0.5;
+ if (!center_present && !neighbor_present) {
+ return 1.0;
+ }
+ if (center_present != neighbor_present) {
+ return 0.0;
+ }
+ let cosine = dot(center_normal, neighbor_normal);
+ if (cosine <= 0.0) {
+ return 0.0;
+ }
+ return pow(cosine, NORMAL_POWER);
+}
+
+fn clamped_depth(column: i32, row: i32) -> f32 {
+ let clamped_column = clamp(column, 0, i32(parameters.width) - 1);
+ let clamped_row = clamp(row, 0, i32(parameters.height) - 1);
+ return depth[u32(clamped_row) * parameters.width + u32(clamped_column)];
+}
+
+@compute @workgroup_size(8, 8, 1)
+fn atrous(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x >= parameters.width || id.y >= parameters.height) {
+ return;
+ }
+ let width = i32(parameters.width);
+ let height = i32(parameters.height);
+ let column = i32(id.x);
+ let row = i32(id.y);
+ let pass_step = i32(parameters.pass_step);
+ let read_from_b = parameters.read_from_b == 1u;
+ let center = id.y * parameters.width + id.x;
+ let center_light = load_light(read_from_b, center);
+ let center_luminance = luminance_of(center_light.xyz);
+ let center_normal = normal_at(center);
+ let center_depth = depth[center];
+ let gradient_x = (clamped_depth(column + 1, row) - clamped_depth(column - 1, row)) * 0.5;
+ let gradient_y = (clamped_depth(column, row + 1) - clamped_depth(column, row - 1)) * 0.5;
+ let luminance_scale = LUMINANCE_SIGMA * sqrt(max(center_light.w, 0.0)) + 1e-4;
+ var weight_sum = 0.0;
+ var variance_sum = 0.0;
+ var light_sum = vec3<f32>(0.0);
+ for (var kernel_row = -2; kernel_row <= 2; kernel_row++) {
+ let neighbor_row = row + kernel_row * pass_step;
+ if (neighbor_row < 0 || neighbor_row >= height) {
+ continue;
+ }
+ for (var kernel_column = -2; kernel_column <= 2; kernel_column++) {
+ let neighbor_column = column + kernel_column * pass_step;
+ if (neighbor_column < 0 || neighbor_column >= width) {
+ continue;
+ }
+ let neighbor = u32(neighbor_row * width + neighbor_column);
+ let neighbor_light = load_light(read_from_b, neighbor);
+ let depth_tolerance = abs(gradient_x * f32(kernel_column * pass_step))
+ + abs(gradient_y * f32(kernel_row * pass_step))
+ + 1e-3 * abs(center_depth) + 1e-5;
+ let depth_weight = exp(-abs(center_depth - depth[neighbor]) / depth_tolerance);
+ let luminance_weight = exp(-abs(center_luminance - luminance_of(neighbor_light.xyz)) / luminance_scale);
+ let weight = kernel_weight(kernel_row) * kernel_weight(kernel_column)
+ * normal_agreement(center_normal, normal_at(neighbor)) * depth_weight * luminance_weight;
+ weight_sum += weight;
+ variance_sum += weight * weight * neighbor_light.w;
+ light_sum += weight * neighbor_light.xyz;
+ }
+ }
+ let filtered = vec4<f32>(light_sum / weight_sum, variance_sum / (weight_sum * weight_sum));
+ store_light(!read_from_b, center, filtered);
+}
+
+// The five passes end in light_b; the albedo goes back on.
+@compute @workgroup_size(8, 8, 1)
+fn finish(@builtin(global_invocation_id) id: vec3<u32>) {
+ if (id.x >= parameters.width || id.y >= parameters.height) {
+ return;
+ }
+ let pixel = id.y * parameters.width + id.x;
+ let restored = light_b[pixel].xyz * max(albedo_at(pixel), vec3<f32>(ALBEDO_FLOOR));
+ color[pixel] = vec4<f32>(restored, 1.0);
+}
diff --git a/packages/render-native/src/host/denoise.rs b/packages/render-native/src/host/denoise.rs
new file mode 100644
index 00000000..13608320
--- /dev/null
+++ b/packages/render-native/src/host/denoise.rs
@@ -0,0 +1,193 @@
+use std::time::Instant;
+
+use napi::Result;
+use wgpu::util::DeviceExt;
+
+use crate::host::device::{failure, layout_entry, storage_entry};
+use crate::host::film::{image_workgroups, read_accumulation};
+use crate::host::session::compile_compute_pipeline;
+
+const SHADER_SOURCE: &str = include_str!("../denoise_atrous.wgsl");
+/// The distance between the taps of each pass; the five passes cover a 61 pixel radius.
+const PASS_STEPS: [u32; 5] = [1, 2, 4, 8, 16];
+const MAXIMUM_BUFFER_BYTES: u64 = 1 << 30;
+
+/// The guide planes of one traced image, row by row from the top (the layout `ResolvedImage` has).
+pub(crate) struct DenoiseInput<'a> {
+ pub(crate) width: u32,
+ pub(crate) height: u32,
+ pub(crate) rgba: &'a [f32],
+ pub(crate) albedo: &'a [f32],
+ pub(crate) normal: &'a [f32],
+ pub(crate) depth: &'a [f32],
+ pub(crate) variance: &'a [f32],
+}
+
+pub(crate) struct DenoiseOutput {
+ pub(crate) rgba: Vec<f32>,
+ pub(crate) compile_seconds: f64,
+ pub(crate) upload_seconds: f64,
+ /// From the submit of the seven dispatches until the device reports them done.
+ pub(crate) gpu_seconds: f64,
+ pub(crate) readback_seconds: f64,
+}
+
+fn denoise_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
+ let mut entries = vec![layout_entry(
+ 0,
+ wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ )];
+ entries.extend((1..=7).map(|binding| storage_entry(binding, false)));
+ device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("a-trous filter"),
+ entries: &entries,
+ })
+}
+
+fn float_buffer(device: &wgpu::Device, label: &str, values: &[f32], extra_usage: wgpu::BufferUsages) -> wgpu::Buffer {
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some(label),
+ contents: bytemuck::cast_slice(values),
+ usage: wgpu::BufferUsages::STORAGE | extra_usage,
+ })
+}
+
+fn empty_light_buffer(device: &wgpu::Device, label: &str, pixel_count: u64) -> wgpu::Buffer {
+ device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some(label),
+ size: pixel_count * 16,
+ usage: wgpu::BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ })
+}
+
+fn parameter_buffer(device: &wgpu::Device, width: u32, height: u32, pass_step: u32, read_from_b: u32) -> wgpu::Buffer {
+ let words = [width, height, pass_step, read_from_b];
+ device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("a-trous parameters"),
+ contents: bytemuck::cast_slice(&words),
+ usage: wgpu::BufferUsages::UNIFORM,
+ })
+}
+
+fn validate_input(input: &DenoiseInput) -> Result<()> {
+ let pixel_count = input.width as usize * input.height as usize;
+ if input.width == 0 || input.height == 0 {
+ return Err(failure("The a-trous filter needs a width and a height of at least 1."));
+ }
+ if pixel_count as u64 * 16 > MAXIMUM_BUFFER_BYTES {
+ return Err(failure("The image is too large for the a-trous filter's buffers."));
+ }
+ let planes = [
+ ("rgba", input.rgba.len(), pixel_count * 4),
+ ("albedo", input.albedo.len(), pixel_count * 3),
+ ("normal", input.normal.len(), pixel_count * 3),
+ ("depth", input.depth.len(), pixel_count),
+ ("variance", input.variance.len(), pixel_count),
+ ];
+ for (name, actual, expected) in planes {
+ if actual != expected {
+ return Err(failure(format!(
+ "The a-trous filter expects {expected} floats in `{name}` for a {}x{} image, got {actual}.",
+ input.width, input.height
+ )));
+ }
+ }
+ Ok(())
+}
+
+/// Filters the traced colour with the a-trous wavelet filter and returns linear RGBA with alpha 1.
+pub(crate) fn atrous_denoise(device: &wgpu::Device, queue: &wgpu::Queue, input: &DenoiseInput) -> Result<DenoiseOutput> {
+ validate_input(input)?;
+ let pixel_count = input.width as u64 * input.height as u64;
+
+ let compile_started = Instant::now();
+ let layout = denoise_layout(device);
+ let prepare_pipeline = compile_compute_pipeline(device, SHADER_SOURCE.to_string(), "prepare", &layout)?;
+ let atrous_pipeline = compile_compute_pipeline(device, SHADER_SOURCE.to_string(), "atrous", &layout)?;
+ let finish_pipeline = compile_compute_pipeline(device, SHADER_SOURCE.to_string(), "finish", &layout)?;
+ let compile_seconds = compile_started.elapsed().as_secs_f64();
+
+ let upload_started = Instant::now();
+ let color = float_buffer(device, "a-trous color", input.rgba, wgpu::BufferUsages::COPY_SRC);
+ let albedo = float_buffer(device, "a-trous albedo", input.albedo, wgpu::BufferUsages::empty());
+ let normal = float_buffer(device, "a-trous normal", input.normal, wgpu::BufferUsages::empty());
+ let depth = float_buffer(device, "a-trous depth", input.depth, wgpu::BufferUsages::empty());
+ let variance = float_buffer(device, "a-trous variance", input.variance, wgpu::BufferUsages::empty());
+ let light_a = empty_light_buffer(device, "a-trous light a", pixel_count);
+ let light_b = empty_light_buffer(device, "a-trous light b", pixel_count);
+ let bind_groups: Vec<wgpu::BindGroup> = PASS_STEPS
+ .iter()
+ .enumerate()
+ .map(|(pass_index, pass_step)| {
+ let parameters = parameter_buffer(device, input.width, input.height, *pass_step, (pass_index % 2) as u32);
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("a-trous pass"),
+ layout: &layout,
+ entries: &[
+ wgpu::BindGroupEntry { binding: 0, resource: parameters.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 1, resource: color.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 2, resource: albedo.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 3, resource: normal.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 4, resource: depth.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 5, resource: variance.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 6, resource: light_a.as_entire_binding() },
+ wgpu::BindGroupEntry { binding: 7, resource: light_b.as_entire_binding() },
+ ],
+ })
+ })
+ .collect();
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ let upload_seconds = upload_started.elapsed().as_secs_f64();
+
+ let groups = image_workgroups(input.width, input.height);
+ let gpu_started = Instant::now();
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("a-trous filter"),
+ });
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: None,
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&prepare_pipeline);
+ pass.set_bind_group(0, &bind_groups[0], &[]);
+ pass.dispatch_workgroups(groups.0, groups.1, 1);
+ }
+ for bind_group in &bind_groups {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: None,
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&atrous_pipeline);
+ pass.set_bind_group(0, bind_group, &[]);
+ pass.dispatch_workgroups(groups.0, groups.1, 1);
+ }
+ {
+ let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
+ label: None,
+ timestamp_writes: None,
+ });
+ pass.set_pipeline(&finish_pipeline);
+ pass.set_bind_group(0, &bind_groups[0], &[]);
+ pass.dispatch_workgroups(groups.0, groups.1, 1);
+ }
+ queue.submit(Some(encoder.finish()));
+ let _ = device.poll(wgpu::PollType::wait_indefinitely());
+ let gpu_seconds = gpu_started.elapsed().as_secs_f64();
+
+ let readback_started = Instant::now();
+ let rgba = read_accumulation(device, queue, &color, pixel_count * 16)?;
+ let readback_seconds = readback_started.elapsed().as_secs_f64();
+ Ok(DenoiseOutput {
+ rgba,
+ compile_seconds,
+ upload_seconds,
+ gpu_seconds,
+ readback_seconds,
+ })
+}
diff --git a/packages/render-native/src/host/mod.rs b/packages/render-native/src/host/mod.rs
index 9d597bfd..6e4bc72d 100644
--- a/packages/render-native/src/host/mod.rs
+++ b/packages/render-native/src/host/mod.rs
@@ -1,4 +1,5 @@
pub(crate) mod accel;
+pub(crate) mod denoise;
pub(crate) mod dispatch;
pub(crate) mod device;
pub(crate) mod film;
diff --git a/packages/render-native/src/host/session.rs b/packages/render-native/src/host/session.rs
index aab00315..51d6b754 100644
--- a/packages/render-native/src/host/session.rs
+++ b/packages/render-native/src/host/session.rs
@@ -108,7 +108,7 @@ fn lock_device_cache() -> MutexGuard<'static, Option<CachedDevice>> {
/// Returns cloned device/queue/metadata from the cache, opening once per process.
/// When the device was lost the cache is dropped and a fresh device is opened.
-fn get_cached_device() -> Result<(wgpu::Device, wgpu::Queue, String, String, String)> {
+pub(crate) fn get_cached_device() -> Result<(wgpu::Device, wgpu::Queue, String, String, String)> {
let mut guard = lock_device_cache();
let was_lost = guard.as_ref().is_some_and(|cached| cached.device_lost.load(Ordering::SeqCst));
if was_lost {
@@ -342,7 +342,7 @@ fn create_cycles_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayo
})
}
-fn compile_compute_pipeline(
+pub(crate) fn compile_compute_pipeline(
device: &wgpu::Device,
shader_source: String,
entry_point: &str,
diff --git a/packages/render-native/src/lib.rs b/packages/render-native/src/lib.rs
index 11699ff8..204f0522 100644
--- a/packages/render-native/src/lib.rs
+++ b/packages/render-native/src/lib.rs
@@ -8,6 +8,7 @@ use napi::bindgen_prelude::{Float32Array, Uint32Array, Uint8Array};
use napi::Result;
use napi_derive::napi;
+use crate::host::denoise::{atrous_denoise, DenoiseInput};
use crate::host::device::failure;
use crate::host::film::{
image_accumulation_bytes, image_workgroups, pad_texel_vectors, resolve_image, resolve_texels,
@@ -83,6 +84,30 @@ pub struct NativeCyclesTraceOptions {
pub samples_per_dispatch: Option<u32>,
pub max_seconds: Option<f64>,
pub bootstrap_kernel: Option<bool>,
+ /// `"none"` (default) or `"atrous"`: also filter the image with the edge-avoiding a-trous wavelet filter.
+ pub denoise: Option<String>,
+}
+
+#[napi(object)]
+pub struct DenoiseAtrousOptions {
+ pub width: u32,
+ pub height: u32,
+ /// Linear RGBA, four floats per pixel.
+ pub rgba: Float32Array,
+ pub albedo: Float32Array,
+ /// Three floats per pixel; the filter normalises them.
+ pub normal: Float32Array,
+ pub depth: Float32Array,
+ pub variance: Float32Array,
+}
+
+#[napi(object)]
+pub struct DenoiseAtrousResult {
+ pub rgba: Float32Array,
+ pub compile_seconds: f64,
+ pub upload_seconds: f64,
+ pub gpu_seconds: f64,
+ pub readback_seconds: f64,
}
#[napi(object)]
@@ -133,6 +158,13 @@ pub struct NativeTexelResult {
pub struct NativeTraceResult {
/// Linear RGBA, averaged over the samples, row by row from the top.
pub rgba: Float32Array,
+ /// The `rgba` image after the a-trous filter (biased: smoothed, not converged); present only when `denoise` was `"atrous"`.
+ pub denoised_rgba: Option<Float32Array>,
+ /// What the filter took in seconds, excluding its one-time pipeline compile: upload, the seven dispatches, readback.
+ pub denoise_seconds: Option<f64>,
+ /// Only the seven dispatches, from submit until the device finished them.
+ pub denoise_gpu_seconds: Option<f64>,
+ pub denoise_compile_seconds: Option<f64>,
/// First-hit albedo and normal (three floats per pixel, averaged over the samples; normalise the normal), the first-hit
/// depth and the variance of each pixel's mean luminance: the features the wavelet and OIDN denoisers read.
pub albedo: Float32Array,
@@ -156,6 +188,16 @@ pub struct NativeTraceResult {
pub traced_seconds: f64,
}
+fn parse_denoise_option(requested: Option<&str>) -> Result<bool> {
+ match requested {
+ None | Some("none") => Ok(false),
+ Some("atrous") => Ok(true),
+ Some(other) => Err(failure(format!(
+ "Invalid denoise option {other:?}: pass \"none\" (default) or \"atrous\"."
+ ))),
+ }
+}
+
fn select_kernel_source(requested_kernel: Option<&str>) -> Result<(String, bool)> {
let kernel_name = match requested_kernel {
Some(name) => name,
@@ -196,6 +238,10 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
let resolved = resolve_image(&sums, pixel_count);
Ok(NativeTraceResult {
rgba: Float32Array::new(resolved.rgba),
+ denoised_rgba: None,
+ denoise_seconds: None,
+ denoise_gpu_seconds: None,
+ denoise_compile_seconds: None,
albedo: Float32Array::new(resolved.albedo),
normal: Float32Array::new(resolved.normal),
depth: Float32Array::new(resolved.depth),
@@ -217,6 +263,7 @@ pub fn trace_scene(input: NativeTraceInput, options: NativeTraceOptions) -> Resu
/// Traces a packed `FORMAT-v2` scene on the GPU using the assembled Cycles-parity WGSL kernel.
#[napi]
pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceOptions) -> Result<NativeTraceResult> {
+ let use_atrous_filter = parse_denoise_option(options.denoise.as_deref())?;
let source = cycles::assemble_cycles_kernel_entry("main", options.bootstrap_kernel.unwrap_or(false))?;
let pixel_count = options.width as u64 * options.height as u64;
let accumulation_bytes = image_accumulation_bytes(options.width, options.height);
@@ -248,8 +295,32 @@ pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceO
)?;
let (sums, traced_seconds, samples_per_dispatch) = (trace.sums, trace.traced_seconds, trace.largest_batch);
let resolved = resolve_image(&sums, pixel_count);
+ let filtered = if use_atrous_filter {
+ Some(atrous_denoise(
+ &prepared.device,
+ &prepared.queue,
+ &DenoiseInput {
+ width: options.width,
+ height: options.height,
+ rgba: &resolved.rgba,
+ albedo: &resolved.albedo,
+ normal: &resolved.normal,
+ depth: &resolved.depth,
+ variance: &resolved.variance,
+ },
+ )?)
+ } else {
+ None
+ };
+ let denoise_seconds = filtered.as_ref().map(|output| output.upload_seconds + output.gpu_seconds + output.readback_seconds);
+ let denoise_gpu_seconds = filtered.as_ref().map(|output| output.gpu_seconds);
+ let denoise_compile_seconds = filtered.as_ref().map(|output| output.compile_seconds);
Ok(NativeTraceResult {
rgba: Float32Array::new(resolved.rgba),
+ denoised_rgba: filtered.map(|output| Float32Array::new(output.rgba)),
+ denoise_seconds,
+ denoise_gpu_seconds,
+ denoise_compile_seconds,
albedo: Float32Array::new(resolved.albedo),
normal: Float32Array::new(resolved.normal),
depth: Float32Array::new(resolved.depth),
@@ -268,6 +339,32 @@ pub fn trace_scene_cycles(input: NativeTraceInputV2, options: NativeCyclesTraceO
})
}
+/// Filters a traced image with the edge-avoiding a-trous wavelet filter on the GPU (spatial only; the result is biased).
+#[napi]
+pub fn denoise_atrous(options: DenoiseAtrousOptions) -> Result<DenoiseAtrousResult> {
+ let (device, queue, _adapter, _backend, _features) = get_cached_device()?;
+ let output = atrous_denoise(
+ &device,
+ &queue,
+ &DenoiseInput {
+ width: options.width,
+ height: options.height,
+ rgba: &options.rgba,
+ albedo: &options.albedo,
+ normal: &options.normal,
+ depth: &options.depth,
+ variance: &options.variance,
+ },
+ )?;
+ Ok(DenoiseAtrousResult {
+ rgba: Float32Array::new(output.rgba),
+ compile_seconds: output.compile_seconds,
+ upload_seconds: output.upload_seconds,
+ gpu_seconds: output.gpu_seconds,
+ readback_seconds: output.readback_seconds,
+ })
+}
+
/// Dispatches `"test_lobe_samples"` on the assembled Cycles WGSL shader and returns all 4 raw `film_accumulation` planes.
#[napi]
pub fn probe_cycles_lobe(options: ProbeCyclesLobeOptions) -> Result<Float32Array> {
diff --git a/tests/native-denoise.test.js b/tests/native-denoise.test.js
new file mode 100644
index 00000000..aff0f6e5
--- /dev/null
+++ b/tests/native-denoise.test.js
@@ -0,0 +1,151 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { denoiseAtrous, findNativeAddon } from '../packages/render-native/index.mjs';
+import { validatePackOptions } from '../packages/render-native/pack-input-v2.mjs';
+import { denoiseRadiance } from '../src/path-tracer-denoise.js';
+
+const hasAddon = findNativeAddon() !== null;
+const skipWithoutAddon = hasAddon ? false : 'the native addon is not built';
+const WIDTH = 48;
+const HEIGHT = 40;
+const EDGE_COLUMN = 24;
+
+function seededRandom(seed) {
+ let state = seed >>> 0;
+ return () => {
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
+ return state / 4294967296;
+ };
+}
+
+/** A two-material image with a vertical edge, noisy light and the guide buffers a trace would give. */
+function buildImage() {
+ const random = seededRandom(7);
+ const pixelCount = WIDTH * HEIGHT;
+ const rgba = new Float32Array(pixelCount * 4);
+ const albedo = new Float32Array(pixelCount * 3);
+ const normal = new Float32Array(pixelCount * 3);
+ const depth = new Float32Array(pixelCount);
+ const variance = new Float32Array(pixelCount);
+ for (let row = 0; row < HEIGHT; row++) {
+ for (let column = 0; column < WIDTH; column++) {
+ const pixel = row * WIDTH + column;
+ const rightSide = column >= EDGE_COLUMN;
+ const surfaceAlbedo = rightSide ? [0.2, 0.6, 0.3] : [0.7, 0.5, 0.4];
+ const surfaceLight = rightSide ? 1.5 : 1.0;
+ const noise = 0.5 + random();
+ for (let channel = 0; channel < 3; channel++) {
+ albedo[pixel * 3 + channel] = surfaceAlbedo[channel];
+ rgba[pixel * 4 + channel] = surfaceAlbedo[channel] * surfaceLight * noise;
+ }
+ rgba[pixel * 4 + 3] = 1;
+ const surfaceNormal = rightSide ? [0, 0.6, 0.8] : [0, 0, 2];
+ normal.set(surfaceNormal, pixel * 3);
+ depth[pixel] = rightSide ? 3 + 0.01 * column : 5 + 0.02 * row;
+ variance[pixel] = 0.05 * surfaceLight * surfaceLight;
+ }
+ }
+ return { rgba, albedo, normal, depth, variance };
+}
+
+function withoutAlpha(rgba) {
+ const color = new Float32Array((rgba.length / 4) * 3);
+ for (let pixel = 0; pixel < rgba.length / 4; pixel++) {
+ color.set(rgba.subarray(pixel * 4, pixel * 4 + 3), pixel * 3);
+ }
+ return color;
+}
+
+function unitNormals(normal) {
+ const unit = new Float32Array(normal);
+ for (let pixel = 0; pixel < unit.length / 3; pixel++) {
+ const length = Math.hypot(unit[pixel * 3], unit[pixel * 3 + 1], unit[pixel * 3 + 2]);
+ for (let channel = 0; channel < 3; channel++) {
+ unit[pixel * 3 + channel] /= length;
+ }
+ }
+ return unit;
+}
+
+function noiseAround(values, columns, rows, channel) {
+ let sum = 0;
+ let squareSum = 0;
+ let count = 0;
+ for (const row of rows) {
+ for (const column of columns) {
+ const value = values[(row * WIDTH + column) * 4 + channel];
+ sum += value;
+ squareSum += value * value;
+ count++;
+ }
+ }
+ const mean = sum / count;
+ return { mean, deviation: Math.sqrt(Math.max(squareSum / count - mean * mean, 0)) };
+}
+
+function range(from, to) {
+ return Array.from({ length: to - from }, (_, index) => from + index);
+}
+
+test('the denoise option accepts none and atrous and names the choices otherwise', () => {
+ assert.doesNotThrow(() => validatePackOptions({ denoise: 'none' }, 'test'));
+ assert.doesNotThrow(() => validatePackOptions({ denoise: 'atrous' }, 'test'));
+ assert.doesNotThrow(() => validatePackOptions({}, 'test'));
+ assert.throws(() => validatePackOptions({ denoise: 'oidn' }, 'test'), /"none" \(default\) or "atrous"/);
+});
+
+test('denoiseAtrous rejects a plane of the wrong length', { skip: skipWithoutAddon }, () => {
+ const image = buildImage();
+ assert.throws(
+ () => denoiseAtrous({ width: WIDTH, height: HEIGHT, ...image, depth: new Float32Array(3) }),
+ /`depth` must be a Float32Array of 1920 floats/,
+ );
+});
+
+test('the GPU filter matches the CPU wavelet filter it was written from', { skip: skipWithoutAddon }, () => {
+ const image = buildImage();
+ const gpu = denoiseAtrous({ width: WIDTH, height: HEIGHT, ...image });
+ const cpu = denoiseRadiance({
+ width: WIDTH,
+ height: HEIGHT,
+ color: withoutAlpha(image.rgba),
+ albedo: image.albedo,
+ normal: unitNormals(image.normal),
+ depth: image.depth,
+ variance: image.variance,
+ });
+ let largestRelativeDifference = 0;
+ for (let pixel = 0; pixel < WIDTH * HEIGHT; pixel++) {
+ assert.equal(gpu.rgba[pixel * 4 + 3], 1);
+ for (let channel = 0; channel < 3; channel++) {
+ const expected = cpu[pixel * 3 + channel];
+ const actual = gpu.rgba[pixel * 4 + channel];
+ largestRelativeDifference = Math.max(largestRelativeDifference, Math.abs(actual - expected) / Math.max(Math.abs(expected), 0.05));
+ }
+ }
+ assert.ok(largestRelativeDifference < 2e-3, `largest relative difference ${largestRelativeDifference}`);
+});
+
+test('the filter smooths the noise inside a surface and keeps the edge between two surfaces', { skip: skipWithoutAddon }, () => {
+ const image = buildImage();
+ const gpu = denoiseAtrous({ width: WIDTH, height: HEIGHT, ...image });
+ const innerRows = range(10, 30);
+ const leftColumns = range(4, 18);
+ const before = noiseAround(image.rgba, leftColumns, innerRows, 0);
+ const after = noiseAround(gpu.rgba, leftColumns, innerRows, 0);
+ assert.ok(after.deviation < before.deviation * 0.5, `deviation ${before.deviation} -> ${after.deviation}`);
+ const leftMean = noiseAround(gpu.rgba, range(20, 24), innerRows, 0).mean;
+ const rightMean = noiseAround(gpu.rgba, range(24, 28), innerRows, 0).mean;
+ assert.ok(rightMean < leftMean * 0.7 || rightMean > leftMean * 1.3, `edge lost: ${leftMean} against ${rightMean}`);
+ assert.ok(gpu.gpuSeconds > 0 && gpu.uploadSeconds >= 0 && gpu.readbackSeconds >= 0);
+});
+
+test('pixels that hit nothing (zero normal and depth) stay finite', { skip: skipWithoutAddon }, () => {
+ const image = buildImage();
+ for (let pixel = 0; pixel < WIDTH * HEIGHT; pixel += 7) {
+ image.normal.fill(0, pixel * 3, pixel * 3 + 3);
+ image.depth[pixel] = 0;
+ }
+ const gpu = denoiseAtrous({ width: WIDTH, height: HEIGHT, ...image });
+ assert.ok(gpu.rgba.every(Number.isFinite));
+});