Repository navigation
Conversation
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. CodeRabbit Verify
|
|
I'm taking this one for review. |
With antialiasing on, every subsample of a texel cast the full ray count of ambient occlusion, bent normal and thickness, so 8x8 cast 64 times the configured rays per texel and a default 8K bake took over an hour on the GPU (storytold#196). A texel's covered subsamples now take interleaved shares of one stratified pattern of max(rays, subsamples) directions, rotated by the texel's seed: a texel casts the configured rays however finely it is sampled, and its directions stay as well spread as a 1x1 bake's. Query carries the share; the CPU tracer and the GPU shader walk it with a stride. A share holds only a band of the pattern's elevations (its rays share their low index bits, and elevation comes from the reversed bits), so a bent normal normalized per share and then averaged leaned up to 11.6 degrees off. A subsample of a split texel returns the unnormalized sum of its open directions instead, and the texel normalizes the sum of its subsamples' once: its bent normal is the one its whole pattern gives. A share whose rays all fall below the surface reports NaN and the texel skips it, as a texel skips its rejected rays. Single-ray transfers still run once per subsample, and a 1x1 bake is bit-identical to before.
a5f3e18 to
cbac42a
Compare
|
Review notes (prepared with Claude Code) PR #274Verdict: merge after rework. The ray split is sound. One bug needs a fix, and the maintainers need to decide one behaviour question. What I checked
Changes requested
Question for the maintainersThe documented behaviour is "2x2 on a 2K map renders at 4K". With this PR antialiasing still smooths edges and keeps the mean, but it no longer reduces ray noise: texel-to-texel AO spread stays 0.0044 at every level, where main falls to 0.00056 at 8x8. That is a reasonable trade for speed, but it changes what the setting does, so it should be an explicit decision. Minor
Patch 1: a split texel with no accepted ray keeps the unantialiased valueThe changes described above, as a patch you can apply ( Show the patchFrom f242e621daae879415e22390ea118919546f1368 Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 07:08:01 -0500
Subject: [PATCH 1/2] fix(274): a split texel with no accepted ray keeps the
unantialiased value
When every ray subset of an antialiased texel fell below the surface, the
texel got the map's display neutral (raw thickness 1.0) where a 1x1 bake
gives the maximum ray distance, an outlier for min/max normalization.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
crates/bake/src/lib.rs | 19 +++++--
crates/bake/tests/antialiasing_fallback.rs | 61 ++++++++++++++++++++++
2 files changed, 77 insertions(+), 3 deletions(-)
create mode 100644 crates/bake/tests/antialiasing_fallback.rs
diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs
index b8afbbe..1c5bc6b 100644
--- a/crates/bake/src/lib.rs
+++ b/crates/bake/src/lib.rs
@@ -370,22 +370,27 @@ fn bake_rows(
let (occlusion_results, separate_bent_results, thickness) =
(next(context.ao.is_some()), next(separate_bent_pass.is_some()), next(context.thickness.is_some()));
let bent_results = if separate_bent_pass.is_some() { &separate_bent_results } else { &occlusion_results };
+ // What a thickness query with no accepted ray reports (Hemisphere::evaluate)
+ let thickness_dmax = context.thickness.map_or(1.0, |pass| pass.dmax);
rows.par_iter_mut().zip(&samples_by_row).zip(&row_offsets).for_each(|((row, samples), &first)| {
let mut sample_values = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut row_sample_index = 0;
for x in 0..width {
let texel_samples = samples.get(row_sample_index..).unwrap_or_default().iter().take_while(|sample| sample.x == x).count();
- let bent = texel_bent_normal(bent_results, first + row_sample_index..first + row_sample_index + texel_samples);
+ let texel = first + row_sample_index..first + row_sample_index + texel_samples;
+ let bent = texel_bent_normal(bent_results, texel.clone());
+ // A split texel none of whose rays was accepted reports what one query with no accepted ray does
+ let (ao_unset, thickness_unset) = (no_accepted_ray(&occlusion_results, texel.clone()), no_accepted_ray(&thickness, texel));
// Per map: a subsample without a finite value (a ray subset with no accepted ray) is skipped
let mut accumulated = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut counts = [0u32; BakedMap::ALL.len()];
while let Some(sample) = samples.get(row_sample_index).filter(|sample| sample.x == x) {
let sample_index = first + row_sample_index;
let traced = map::Traced {
- ao: occlusion_results.get(sample_index).map_or(1.0, |value| value[0]),
+ ao: occlusion_results.get(sample_index).map_or(1.0, |value| if ao_unset { 1.0 } else { value[0] }),
bent,
- thickness: thickness.get(sample_index).map_or(1.0, |value| value[0]),
+ thickness: thickness.get(sample_index).map_or(1.0, |value| if thickness_unset { thickness_dmax } else { value[0] }),
curvature: curvature.get(sample_index).copied().unwrap_or(0.5),
};
context.evaluate(maps, &sample.surface, sample.bary, transfer(sample_index), &traced, &mut sample_values);
@@ -411,6 +416,14 @@ fn bake_rows(
Ok(())
}
+/// Whether the texel whose subsamples have these hemisphere results split its rays and none of them
+/// was accepted (every subset reported NaN). Such a texel takes the value a single query with no
+/// accepted ray gives (unoccluded, or the maximum ray distance), as it would without antialiasing,
+/// rather than the map's display neutral. A texel traced as one query never reports NaN.
+fn no_accepted_ray(results: &[[f32; 4]], texel: std::ops::Range<usize>) -> bool {
+ results.get(texel).is_some_and(|values| values.len() > 1 && values.iter().all(|value| value[0].is_nan()))
+}
+
/// The bent normal of the texel whose subsamples have these hemisphere results. A texel traced as one
/// query has its own; subsamples that split a texel's rays hold unnormalized sums of open directions
/// (NaN for a subset with no accepted ray), normalized here once for the texel. None (each subsample
diff --git a/crates/bake/tests/antialiasing_fallback.rs b/crates/bake/tests/antialiasing_fallback.rs
new file mode 100644
index 0000000..5d44512
--- /dev/null
+++ b/crates/bake/tests/antialiasing_fallback.rs
@@ -0,0 +1,61 @@
+//! Antialiased texels whose rays all fall below the surface (#274 review).
+#![allow(clippy::unwrap_used)]
+
+use texturecraft_bake::{BakeOutput, BakeRequest, Progress, bake};
+use texturecraft_core::{BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, RaySettings, ThicknessNormalization};
+use texturecraft_geom::glam::{Vec2, Vec3};
+use texturecraft_geom::{Bvh, Mesh};
+
+/// A flat square in y = 0 whose shading normals are all `n`.
+fn plane(n: Vec3) -> Mesh {
+ Mesh::from_parts(
+ vec![Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, 1.0)],
+ Some(vec![n; 4]),
+ vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)],
+ vec![0, 2, 1, 0, 3, 2],
+ "Plane",
+ )
+ .unwrap()
+}
+
+/// Bakes `mesh` on the CPU tracer.
+fn run(mesh: &Mesh, s: &BakeSettings) -> BakeOutput {
+ let bvh = Bvh::new(mesh);
+ let request =
+ BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) };
+ bake(&request, &Progress::new()).unwrap()
+}
+
+/// The mean of a map's first component over all texels (the plane covers every texel).
+fn mean(out: &BakeOutput, map: BakedMap) -> f32 {
+ let values: Vec<f32> = out.maps[&map].iter().step_by(map.components()).copied().collect();
+ values.iter().sum::<f32>() / values.len() as f32
+}
+
+/// A texel whose every ray falls below the surface gets the same raw thickness and occlusion with
+/// antialiasing as without it (the maximum ray distance, and unoccluded), not the map's display
+/// neutral: a raw thickness of 1 would be an outlier for min/max normalization.
+#[test]
+fn antialiasing_gives_a_texel_with_no_accepted_ray_the_unantialiased_value() {
+ // Shading normals lying in the face and a zero spread: every ray grazes the face and is rejected
+ let m = plane(Vec3::X);
+ let mut base = BakeSettings::default();
+ base.common.resolution = BakeResolution::R16;
+ base.common.dilation = 0;
+ base.common.apply_diffusion = false;
+ base.maps.select([BakedMap::Thickness, BakedMap::AmbientOcclusion]);
+ base.maps.thickness.parameters.normalization = ThicknessNormalization::None;
+ for r in [&mut base.maps.thickness.parameters.rays, &mut base.maps.ao.parameters.rays] {
+ *r = RaySettings { rays: 4, max_distance: 0.1, spread: 0.0, ..*r };
+ }
+ let plain = run(&m, &base);
+ for antialiasing in [BakeAntialiasing::Subsampling2x2, BakeAntialiasing::Subsampling8x8] {
+ let mut s = base.clone();
+ s.common.antialiasing = antialiasing;
+ let smooth = run(&m, &s);
+ for map in [BakedMap::Thickness, BakedMap::AmbientOcclusion] {
+ let (plain, smooth) = (mean(&plain, map), mean(&smooth, map));
+ assert!((plain - smooth).abs() < 1e-6, "{antialiasing:?} {map:?}: {plain} without antialiasing, {smooth} with it");
+ }
+ }
+}
--
2.55.0.windows.5Patch 2: size hemisphere dispatches from the fewest covered subsamples (optional)The changes described above, as a patch you can apply ( Show the patchFrom 714da5506ef95bc973b521d082415fc6c1708aec Mon Sep 17 00:00:00 2001
From: SteamSmith <341182916+SteamSmith@users.noreply.github.com>
Date: Tue, 10 Nov 2026 07:08:02 -0500
Subject: [PATCH 2/2] fix(274): size hemisphere dispatches for the largest ray
share
Lanes are sized for a full texel's share, but an edge texel with few
covered subsamples casts more rays per query, so a dispatch sized by the
smallest share could cast several times RAYS_PER_DISPATCH rays in an
uncommon layout. Size dispatches from the fewest covered subsamples.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
crates/render/src/gpu_bake.rs | 37 ++++++++++++++++++++++++++++++-----
1 file changed, 32 insertions(+), 5 deletions(-)
diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs
index db292c0..357d821 100644
--- a/crates/render/src/gpu_bake.rs
+++ b/crates/render/src/gpu_bake.rs
@@ -301,6 +301,16 @@ impl GpuScene<'_> {
}
}
+/// Threads per query and queries per dispatch of a hemisphere pass of `rays` rays per texel, for
+/// queries that split their texel's rays into between `fewest` and `most` subsets. A query's rays
+/// spread over `lanes` threads of a workgroup (a power of two), sized for the usual full texel's
+/// share; a dispatch holds as many queries as keep it under RAYS_PER_DISPATCH even if they all cast
+/// the largest share (an edge texel with few covered subsamples casts more rays per query).
+fn hemisphere_sizes(rays: u32, (fewest, most): (u32, u32)) -> (u32, usize) {
+ let lanes = rays.div_ceil(most.max(1)).clamp(1, WORKGROUP).next_power_of_two();
+ (lanes, RAYS_PER_DISPATCH / rays.div_ceil(fewest.max(1)).max(1) as usize)
+}
+
/// A row of `v` (as bits) and `w`.
fn row(v: Vec3, w: u32) -> [u32; 4] {
[v.x.to_bits(), v.y.to_bits(), v.z.to_bits(), w]
@@ -329,14 +339,15 @@ impl RayScene for GpuScene<'_> {
})
.collect::<Result<Vec<_>, BakeError>>()?
.concat();
- // Antialiased texels split their rays between subsamples: size the lanes for a full texel's share.
+ // Antialiased texels split their rays between subsamples: size the lanes for a full texel's share,
+ // and the dispatches for the largest share (an edge texel's few subsamples cast more rays each),
+ // so that no dispatch casts more than RAYS_PER_DISPATCH rays.
let subsets = queries.par_iter().map(|q| q.subsets).max().unwrap_or(1).max(1);
+ let fewest_subsets = queries.par_iter().map(|q| q.subsets).min().unwrap_or(1).max(1);
let passes: Vec<Pass> = passes
.iter()
.map(|h| {
- // A query's rays spread over `lanes` threads of a workgroup (a power of two).
- let rays = h.rays.div_ceil(subsets);
- let lanes = rays.clamp(1, WORKGROUP).next_power_of_two();
+ let (lanes, per_dispatch) = hemisphere_sizes(h.rays, (fewest_subsets, subsets));
let flags =
[(h.uniform, UNIFORM), (h.ground_height.is_some(), 8), (h.same_key, SAME_KEY)].iter().filter(|(on, _)| *on).fold(0, |f, (_, b)| f | b);
let params = Params {
@@ -362,7 +373,7 @@ impl RayScene for GpuScene<'_> {
lanes,
..Params::default()
};
- Pass { params, per_dispatch: RAYS_PER_DISPATCH / rays.max(1) as usize, per_group: (WORKGROUP / lanes) as usize }
+ Pass { params, per_dispatch, per_group: (WORKGROUP / lanes) as usize }
})
.collect();
let gpu = self.gpu;
@@ -386,6 +397,22 @@ mod tests {
use super::*;
+ /// However a batch mixes fully and partly covered antialiased texels, no hemisphere dispatch casts
+ /// more than RAYS_PER_DISPATCH rays (the driver-watchdog bound), and unsplit queries are sized as
+ /// before rays were split.
+ #[test]
+ fn hemisphere_dispatches_stay_under_the_ray_budget() {
+ for rays in [1, 7, 64, 1000, 4096] {
+ for (fewest, most) in [(1, 1), (1, 4), (1, 64), (3, 16), (64, 64)] {
+ let (lanes, per_dispatch) = hemisphere_sizes(rays, (fewest, most));
+ assert!(lanes.is_power_of_two() && lanes <= WORKGROUP, "{rays} rays, {fewest}..{most} subsets: {lanes} lanes");
+ let worst = per_dispatch * rays.div_ceil(fewest) as usize;
+ assert!(worst <= RAYS_PER_DISPATCH, "{rays} rays, {fewest}..{most} subsets: up to {worst} rays per dispatch");
+ }
+ assert_eq!(hemisphere_sizes(rays, (1, 1)), (rays.clamp(1, WORKGROUP).next_power_of_two(), RAYS_PER_DISPATCH / rays as usize));
+ }
+ }
+
/// The GPU baker, or None (test skipped) without a hardware adapter.
fn gpu() -> Option<GpuBaker> {
let g = GpuBaker::new();
--
2.55.0.windows.5🤖 Generated with Claude Code |
When every ray share of an antialiased texel fell below the surface, the texel got the map's display neutral (raw thickness 1.0) where a 1x1 bake gives the maximum ray distance, an outlier under min/max normalization. Such a texel now reports what one query with no accepted ray does: unoccluded, and as thick as the maximum ray distance.
Lanes are sized for a full texel's share of the rays, and so were the queries per dispatch; but an edge texel with few covered subsamples casts more rays per query, so in an unusual UV layout a dispatch could cast several times RAYS_PER_DISPATCH rays. Dispatches are now sized from the fewest subsets in the batch, so none exceeds the budget. Lanes, and so the results, are unchanged.
The ray-counting test works from the query fields, and the bake-level comparison averages shares, so neither pins down which rays each share of a texel casts. Compare every query's GPU result with the CPU tracer's, for shares of several sizes mixed with whole texels in one batch, including shares that lose every ray.
|
Thanks @SteamSmith. I checked each point and agree with all of them. Pushed 74e1ddb, 0d41478 and dced3e4, and updated the description.
The maintainer question: the description now has a "What antialiasing does now" section. It says plainly that antialiasing no longer reduces ray noise and that this changes what the setting does. It also states the share-mean bias you measured (about −0.005 at 4×4) and that the leaning-normal test can't see it. I ran the bake and render tests (131 passed), the engine bake tests (31), clippy, fmt and |
# Conflicts: # crates/bake/src/lib.rs
Fixes the antialiasing cost in #196. Antialiasing defaults to off, and with it off this PR changes nothing.
Cause
With antialiasing on, every subsample of a texel became a full bake sample, and every ray map (ambient occlusion, bent normal, thickness) cast its whole ray count per subsample. At 8×8 a texel cast 64 × its configured rays: 4096 AO rays at the default 64. A default 8K bake that takes about 68 s with AA off takes about 70 min with 8×8 on an M3 Pro GPU (extrapolated from the measured 47–58× at 2K), and hours on the CPU fallback. The configured ray count was really "rays per subsample".
Fix
A texel's rays are now split between its covered subsamples instead of repeated for each.
max(rays, subsamples)directions (the sameHemisphere::directionpattern as before), rotated by the texel's seed. Its covered subsamples take interleaved shares of it: ofkcovered subsamples, numberscasts rayss, s + k, s + 2k, …. A fully covered texel casts exactly the configured number of rays. Its directions are the same well-stratified set a 1×1 bake would use, only spread over the subsample positions. Edge texels split the same budget over fewer subsamples, so they don't get noisier.Querygainssubsetandsubsets. The CPU tracer and the GPU shader both walk the share with a stride. The GPU packs the two values into the query's unused fourth row, so the buffer layout andParamsdon't change. Lanes per query are sized for one share, not for the whole pattern. Dispatches are sized so that even a batch of the largest shares stays under the per-dispatch ray budget.Measured
Apple M3 Pro. The scene is
hilofrom the #196 profile: a 4,096-triangle low poly baked from a 4.2M-triangle high poly at 2048². Default maps: AO and thickness at 64 rays each, plus normal, ID and the other transfers. Times are medians of 3 runs, in seconds. CPU 8×8 before is a single run (28 min).hilo, run alternately with the build without it, took 33.98 s against 34.24 s (medians of 3, on a busier machine than the table above).Verified
New tests in
crates/bake/src/tests.rs:antialiasing_splits_each_texels_rays_between_its_subsamplescounts rays through the publicTracertrait. At 2×2/4×4/8×8 a texel casts exactlymax(rays, subsamples). Before the fix: 4× to 64× that.antialiasing_keeps_the_mean_and_cost_of_traced_maps_and_still_smooths_themuses a floor through a turned cube, so occlusion and thickness both have hard slanted edges. At 4×4, AO and thickness keep the 1×1 mean against a 4× resolution box-filtered reference (bias ≤ 2e-4), cast the same rays as 1×1 (before the fix: 16×), and cut the edge-texel error about 10–15× (AO 0.109 → 0.007, thickness 0.075 → 0.007).antialiasing_skips_ray_subsets_that_fall_entirely_below_the_surfacefails if empty shares count as unoccluded.without_antialiasing_a_texel_is_one_query_casting_every_raychecks that 1×1 is one query per texel, with no split.antialiasing_keeps_bent_normals_unbiasedbakes a quad beside a wall at 2×2, 4×4 and 8×8 and compares the mean bent normal of four bands with the 1×1 bake's. They are within 0.1° (limit 0.5°). With each share normalized on its own they were 0.7–10.8° off.The analytic reference scenes (Bake: analytic reference scenes for the mesh-map baker #279, run here on top of this branch) all pass on the CPU and the GPU tracer. In
occlusion_beside_a_wall(256 rays, eight bands of floor from the far edge to the wall's base, tolerance 1.4–2.5°), the bent normal's largest error per band, uniform / cosine rays:mainThe table is the CPU tracer. The suite checks 1×1 and 2×2; I ran 4×4 and 8×8 by hand. The GPU tracer gives the same errors to within 0.02°. AO was within tolerance in every case.
1×1 output is bit-identical to
main. I hashed the full data of all ten maps on two scenes (hilowith a high poly,ballwithout) at 2048², on both the CPU and GPU tracers, and all 40 hashes match.gpu_bake_matches_the_cpu(2×2 AA, 16–24 rays) passes, so the GPU and CPU agree on the split.Review follow-ups:
antialiasing_gives_a_texel_with_no_accepted_ray_the_unantialiased_valuefails without the fallback (thickness 1.0 instead of 0.2).hemisphere_dispatches_stay_under_the_ray_budgetfails with the old dispatch sizing.gpu_hemisphere_queries_match_the_cpu_share_by_sharecompares every GPU query with the CPU one for shares of 1, 3, 4, 16 and 64. A shader that ignores the stride or the share offset fails it.cargo +1.96.0 xtask cipassed before the review changes. Since then I've run the bake, render and engine bake tests, clippy, fmt andcargo xtask wasm.What antialiasing does now
Antialiasing still smooths edges and keeps the mean, but it no longer reduces ray noise. A texel casts the configured rays however finely it is sampled, so texel-to-texel AO noise stays at the 1×1 level instead of falling with the subsample count. This changes what the setting does ("2×2 on a 2K map renders at 4K" is no longer true for ray maps), so it needs a maintainer's decision. A user who wants less noise can raise the ray count, which now costs what it says.
Where a leaning shading normal makes shares accept different numbers of rays, the equal-weight mean of share means is slightly biased: about −0.005 AO and thickness at 4×4, against −0.0002 before. The leaning-normal test runs at 8×8 with 64 rays, one ray per share, so it doesn't cover this.
Not changed
jofkrays, sharestakes rayj·k + (s + j) mod k), so that every share spans every elevation band. On its own it cut the wall-scene bent-normal error from up to 11.6° to 1.9°, still far above main's 0.04°, because each share's bent normal was still normalized on its own. Combined with the single normalization it made no measurable difference to the reference scenes or the leaning-normal test, and it made the edge error in the AA test worse (AO 0.0072 → 0.0114, thickness 0.0069 → 0.0156). It would also add a modulo per ray to the shader loop.