Skip to content

Average baked maps when they are read below the bake resolution - #276

Draft
simonhull wants to merge 2 commits into
storytold:mainfrom
simonhull:fix/filtered-baked-map-downsample
Draft

simonhull wants to merge 2 commits into
storytold:mainfrom
simonhull:fix/filtered-baked-map-downsample

Conversation

@simonhull

@simonhull simonhull commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Draft for discussion. Nobody asked for this, so I've opened it as a draft for you to evaluate, not as a request to merge. If it's useful, I'm happy to rework it, split it up or follow it through; if you'd rather handle this yourselves, or it overlaps something you've started, feel free to close it.

Fixes the display side of #195.

Updated: ported onto main's per-UV-tile bake layout, with the review's requests: renormalised directions, a byte-bounded cache and per-tile levels.

Cause

The bake is fine: 8×8 AA is an exact box filter in the baked data. The readers throw it away. Every reader of a baked map at a lower resolution than the bake used BakedMaps::sample, which takes one texel per output texel (x·W/size, nearest):

  • Mesh-map view: mesh_map_rgba fills the aux texture, capped at 2048 (aux_size), so an 8K bake is shown as 1 texel in 16. Thin AO creases come out dotted and stair-stepped, with AA on or off.
  • Viewport AO (display.rs, Orm) and the baked normal under the shown normal: they are read at the document resolution.
  • Mesh-map generators (AO, Dirt, Curvature, Edge Wear, Thin Areas) and baked lighting in the compositor: also read at the document resolution.
  • Export of baked maps and AO mixing: same sampler, same resolution.
  • UV tiles painted below their block's resolution: bakes are read per tile through BlockScales::bake_uv, so a tile at a quarter of its block's resolution reads one baked texel in four along each axis, even when the set matches the bake.

Fix

  • texel::area_downsample: a box filter over dense float images. Each output texel averages the source texels it covers, weighted by overlap. It handles non-integer ratios and rectangular images, and each axis is filtered on its own. It is linear in source texels, rows run in parallel with rayon, and hostile sizes return None. It lives in texel (L0), the lowest crate every reader can reach; texel now depends on rayon, as geom already does.
  • BakedMaps::view(read, working, &BlockScales, maps) -> BakedView: there is one level per distinct tile scale. Each holds as many texels per block as the reader samples there, and it is picked per texel with BlockScales::at. A set without tiles or overrides gets a single level at the reader's size. Blocks at or above the bake's resolution read through main's sample_working, unchanged. ID maps are never averaged, because their colours are labels. Averaged normals, world normals and bent normals are renormalised to unit length. The averaged levels are cached by source data identity: a Weak to the map's Arc, with least-recently-used eviction past 1 GiB. BakedMaps::maps now documents that baked data is replaced, never mutated in place, which the cache relies on. One view per composite block, upload pass or export costs a lock and a lookup. The averaging runs outside the lock, so rayon work-stealing can't deadlock on it. The cache is a process-wide static, not a field on BakedMaps, because a new field would break the struct literals other crates use. I'm happy to move it if you'd rather have it owned by the session.
  • Readers: the compositor (Texel holds a view for AO, curvature and thickness, made once per pass before its parallel loop), tile_bytes (now takes a BakedView from display_view, so the GPU display reads exactly what the CPU compositor reads), mesh_map_rgba, and export (Sampler gets a view of the maps the planned files read).

The averaging is linear in source texels. A quick single-run release measurement on an M3 Pro (machine under other load) gave: 8192² → 2048² in 14 ms for a scalar map and 27 ms for a 3-component map; 8192² → 4096² in 20 ms.

Verified

  • Helper: exact box averages for 2× and 8× (a 1-texel line → 1/8), overlap weights for 3→2 and 5→3, rectangular images and single-axis shrink, a 1×1 output equal to the mean, identity at the same size, and refusal of hostile sizes.
  • Every reader, with an 8× bake that has a 1-texel crease every 8 columns: the result is the average (0.875), not the aliased pick:
    • views_average_larger_bakes (store)
    • baked_ao_is_averaged_down_to_the_set (Orm display)
    • generators_average_a_larger_bake (AO generator: the result matches a same-size bake of the average, and differs from the nearest pick)
    • a_larger_bake_is_averaged_not_point_sampled (mesh-map view)
    • a_larger_bake_exports_averaged (export)
  • Unchanged reads: at the same size, every reader still shows each baked texel as it is, and reads at a larger size are bit-identical to BakedMaps::sample.
  • Tests fail without the fix: with view forced to skip averaging (exactly the old nearest reads), all five reader tests fail, and so does the single-axis-shrink check. The ID guard passes either way, as it should.
  • ID maps: never averaged (id_maps_are_never_averaged).
  • Cache: shared by clones (undo snapshots), separate for new data, and a map whose length doesn't match its size falls back to nearest (levels_are_cached_by_their_data). Least-recently-used eviction within the byte budget: use refreshes an entry, an oversized level is kept alone, and dropped bakes are purged (the_level_cache_keeps_the_most_recently_used_within_its_byte_budget).
  • UV tiles: creases inside a tile at a lower scale are averaged to that tile's resolution, and tiles at or above the bake read nearest. Tests: each_tile_block_is_averaged_to_its_own_resolution, tile_blocks_at_or_above_the_bake_read_nearest, baked_ao_in_a_smaller_uv_tile_is_averaged_down_to_it (main reads white there, this reads 0.75) and each_uv_tile_is_averaged_at_the_resolution_the_view_shows_it.
  • Directions: averaged_directions_stay_unit.
  • Tests fail without the fix: skipping every level fails 10 tests across compose, export and render. A single scale fails the three UV-tile tests. Dropping the renormalisation fails the direction test.
  • Ran: cargo nextest run --release on texel, compose, formats, render and engine (529 passed). Also clippy on the workspace with -D warnings, fmt, cargo xtask layers and cargo xtask wasm. I haven't re-run cargo +1.96.0 xtask ci since the port.

Behaviour change

Documents whose resolution is below their bake resolution now composite, display and export generator masks, baked AO and baked normals from the averaged map instead of the nearest texel. Thin features keep their proportional weight instead of appearing or vanishing depending on where the grid falls. Documents at or above their bake resolution are unchanged.

Not changed

  • The bake itself, and ID maps: ID maps still use nearest reads everywhere, ColorSelection included.
  • Upsampling (a document larger than its bake) stays nearest.
  • Export size override: the existing resize step (box filter for integer factors, bilinear otherwise) is untouched.
  • No warm-up: the first averaged view after a bake runs on the frame that needs it (about 100 ms for 8K to 4K AO and normal, per the review).
  • Not checked visually: no viewport screenshot of a real 8K bake. Verification is the unit tests above.

@coderabbitai

coderabbitai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Share

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@SteamSmith

Copy link
Copy Markdown
Collaborator

I'm taking this one for review.

@SteamSmith

Copy link
Copy Markdown
Collaborator

Review notes (prepared with Claude Code)

PR #276

Verdict: hold for rework, then merge. The idea and the filter are right, but the branch no longer applies to main, and a straight port still has three gaps.

What I checked

  • The bug is real on main: a thin AO crease baked at 8K and read in a 2K set (viewport AO, mesh-map view, generators, export) either disappears or fills whole texels depending on where the grid falls. A probe in the display tests shows a line every other column vanishing at half resolution (reads 255, correct 128).
  • The overlap-weighted box filter is correct: exact integer overlaps, f64 accumulation, per axis, no wrap, ID maps excluded, checked sizes, no lock held while averaging. Cost: 8192 to 2048 is 17 ms for a scalar map and 39 ms for a 3-component map; 8192 to 4096 is 30 and 70 ms, once per bake and size.
  • In a synthetic check (an 8K image of thin lines used as the bake, read in a smaller set) main shows isolated dots and the change shows continuous lines. The spec does not say how bakes are resampled, so this extends the documented behaviour rather than departing from it.
  • A port onto current main (bakes are now read per UV tile through BlockScales::bake_uv) builds and passes the ui-egui, render, texel, compose, formats and engine bake suites and cargo xtask wasm.

Changes requested

  1. Rebase onto main's new baked-map layout (6 files conflict). The PR as written does not compile against it.
  2. Renormalise averaged directions. Normal, world-normal and bent-normal levels come out shorter than unit length where texels tilt apart (two texels at +-37 degrees average to 0.8). The display and the final normal export renormalise anyway, but the raw "Mesh maps" export and the mesh-map view write them short. Test: averaged_directions_stay_unit (in my port).
  3. Bound the level cache by bytes, not just count. One 8K to 4K normal level is 192 MiB and undo snapshots keep old bakes (and their levels) alive. A 1 GiB budget (the live set for an 8K bake read at 4K is about 400 MiB) with least-recently-used eviction fixes it. Relatedly, a flat 32-entry limit thrashes with about 8 or more texture sets all recompositing.
  4. UV tiles painted below their block's resolution still alias. A crease every 8 bake columns in a quarter-resolution tile reads as all 1.0 where 0.875 is correct. BlockScales::at and bake_uv are public, so one level per distinct tile scale, picked with scales.at(x, y), should fix this in compose without touching core (I have not implemented it). The UDIM test keeps tile 1002 white, so it cannot catch this; it needs creases in the scaled tile.

Smaller notes

I have a working port onto current main (item 1) with items 2 and 3 done, and it merges cleanly; item 4 is not done. I can share it if that helps, or you may prefer to do it so the change stays yours.


🤖 Generated with Claude Code

Every reader of a baked map took one texel per output texel (nearest).
The mesh-map view caps its texture at 2048, so an 8K bake was shown as
1 texel in 16 and thin AO creases came out dotted and stair-stepped.
Viewport AO, the baked normal, mesh-map generators and export read the
same way whenever the document resolution is below the bake's (storytold#195),
and so does a UV tile painted below its block's resolution.

Add texel::area_downsample, a box filter weighted by overlap that
handles non-integer ratios and each axis on its own, and
BakedMaps::view, which reads the listed maps through levels averaged
down to what the reader samples. Bakes are read per UV tile through
BlockScales::bake_uv, so there is one level per distinct tile scale,
each block holding as many texels as the reader samples there, picked
per texel with BlockScales::at; a set without tiles or overrides gets
a single level at the reader's size. Averaged normals, world normals
and bent normals are renormalised to unit length. ID maps are never
averaged.

Levels are cached by source data, so undo snapshots share them, with
least-recently-used eviction past 1 GiB. The compositor, the display
tiles (tile_bytes now takes a BakedView from display_view, so the GPU
display reads what the CPU compositor reads), the mesh-map view and
export all go through it. Reads at the same or a larger size are
unchanged.
@simonhull
simonhull force-pushed the fix/filtered-baked-map-downsample branch from 6a800ef to d237c30 Compare November 10, 2026 16:44
@simonhull

Copy link
Copy Markdown
Contributor Author

Thanks @SteamSmith, and for offering your port. I've pushed my own, d237c30, which is one commit on current main and replaces the old one. The description is updated.

  1. Rebase onto the per-tile layout: done. BakedMaps::view(read, working, &BlockScales, maps) reads through bake_uv, and blocks at or above the bake's resolution use main's sample_working unchanged.
  2. Renormalise averaged directions: done for Normal, WorldNormal and BentNormal. All three are packed as v · 0.5 + 0.5, so each texel is decoded, normalised and re-packed; a vector that averages to almost nothing is left alone. Test: averaged_directions_stay_unit.
  3. Byte-bounded cache: done. The 32-entry limit is replaced by least-recently-used eviction past 1 GiB. Using an entry refreshes it, the newest level is always kept, and an oversized level is kept alone. Test: the_level_cache_keeps_the_most_recently_used_within_its_byte_budget.
  4. UV tiles below their block's resolution: done as you suggested, with one level per distinct tile scale, picked with scales.at(x, y), in compose only. Each level is sized so a block gets as many texels as the reader samples there. The new tests put creases inside the scaled tile 1002. With the fix, baked_ao_in_a_smaller_uv_tile_is_averaged_down_to_it reads 0.75 where main reads white. Forcing a single scale fails the three UV-tile tests.

From the smaller notes:

  • Doc on BakedMaps::maps: added. Baked data must be replaced, never mutated in place.
  • chunks_exact: gone from every line I added. The remaining calls in resample.rs have sizes only known at runtime, and clippy doesn't flag those.
  • Generator test: it now uses a crease every other column. The generator's default ramp clips 0.875 to the same output as white, so the old pattern couldn't tell the fix apart.
  • Not done: warming the levels when a bake is applied, and the island-edge bleed with diffusion off. Both are noted in the description.

I ran cargo nextest run --release on texel, compose, formats, render and engine (529 passed), clippy on the workspace with -D warnings, cargo xtask layers and cargo xtask wasm. I'll merge with #278 when one of them lands.

@autocraft-bot autocraft-bot Bot added the bugfix Fixes something that is broken: wrong result, crash, data loss label Nov 26, 2026
Main's display writes half-float normals, the compositor evaluates through
EvaluationInputs, and export owns more of the tiling. The averaged view
carries over to each:
- the Normal display reads the baked normal through the view (BakedView::has
  replaces the map lookup), keeping main's checks on invalid samples;
- every Texel::new, including main's new ones in anchor heights, filter
  regions, input colors and folder thumbnails, takes a view made once
  before its parallel loop, from the evaluation's plain inputs;
- the upload paths main added (selected display kinds, batched headless
  uploads, the automation perf test) pass a display view.
@autocraft-bot autocraft-bot Bot added the needs decision Needs a product or scope decision by a maintainer label Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix Fixes something that is broken: wrong result, crash, data loss needs decision Needs a product or scope decision by a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants