mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-27 14:27:34 +00:00
craft-pbr: keep halving, resampling and SH tables inside Limits
- try_half computes each output pixel's covered source span on the fly instead of building per-axis weight tables, so halving allocates only the output buffer that Limits already counts. Results are unchanged. - try_half and try_resampled check the source against the limits as well as the result. - try_sh9 checks its column table (48 bytes per column) against Limits::max_bytes before reserving it. - The TextureCraft migration step says that the import, each try_half and try_resampled need Limits raised past the default 2048 side. - The test helper max_rel_diff treats a NaN or infinite value as infinitely far, so a non-finite result can no longer compare equal.
This commit is contained in:
@@ -45,7 +45,8 @@ file or network I/O and has no `unsafe` code.
|
||||
`width × width / 2`.
|
||||
- **Limits.** `Limits` caps the side (2048), the pixels of one image (2^22), the bytes one call
|
||||
holds at once (256 MiB, counting the source copies, the pyramid, every level and the sample
|
||||
table of `try_prefilter`; a single level is only a copy of the source), the levels (8), the samples per pixel (1024) and the sample
|
||||
table of `try_prefilter`, and the column table of `try_sh9`, 48 bytes per column; a single
|
||||
level is only a copy of the source), the levels (8), the samples per pixel (1024) and the sample
|
||||
evaluations of one `try_prefilter` call (2^28). Every `try_` function checks its source against
|
||||
them and returns a `PbrError` before allocating over them, and a buffer is never larger than
|
||||
`isize::MAX` bytes even with raised limits. Pixel buffers are reserved fallibly
|
||||
@@ -83,7 +84,12 @@ prefiltered levels match theirs for sources with even sides. Changes from those
|
||||
- **TextureCraft.** Replace `texturecraft_render::ibl` with `craft_pbr`. Pass
|
||||
`PrefilterOptions` with `firefly_cap: Some(64.0)` to keep today's output. `EnvImage::from_rgba`
|
||||
becomes `EnvImage::try_from_rgba` followed by the app's import sizing: `try_half` while a side is
|
||||
over 2048, then `try_resampled` up to at least 128 × 64.
|
||||
over 2048, then `try_resampled` up to at least 128 × 64. The default `Limits` refuse a source
|
||||
with a side over 2048 (a 4096 × 2048 source gives `PbrError::BadSize`), so the import passes
|
||||
`Limits` with `max_side`, `max_pixels` and `max_bytes` raised to the largest source the app
|
||||
accepts, and passes the same limits to each `try_half` and to `try_resampled`. The
|
||||
`texturecraft_import` helper in `tests/it/moved.rs` uses `max_side` 2^16, `max_pixels` 2^26 and
|
||||
`max_bytes` 1 GiB.
|
||||
- **MaterialCraft.** Replace `materialcraft_render::ibl` with `craft_pbr`, with the same
|
||||
`firefly_cap`. `by_id` stays in the app and maps view ids to `Environment::from_name`.
|
||||
`hammersley` returns `None` when `i` is not below `n`.
|
||||
|
||||
@@ -151,8 +151,9 @@ impl EnvImage {
|
||||
|
||||
/// Box-downsamples by 2 to `max(width / 2, 1) × max(height / 2, 1)`. Each output pixel
|
||||
/// averages the source area it covers, so the last column or row of an odd side is kept in
|
||||
/// the average.
|
||||
/// the average. Returns an error when the source or the result is over `limits`.
|
||||
pub fn try_half(&self, limits: &Limits) -> Result<EnvImage, PbrError> {
|
||||
limits.check(self.width, self.height)?;
|
||||
let (w, h) = half_size(self.width, self.height);
|
||||
let len = limits.check(w, h)?;
|
||||
let mut data = try_pixels(len)?;
|
||||
@@ -165,13 +166,12 @@ impl EnvImage {
|
||||
}
|
||||
});
|
||||
} else {
|
||||
let (wx, wy) = (box_weights(self.width, w), box_weights(self.height, h));
|
||||
for_each_row(&mut data, w as usize, |y, row| {
|
||||
let ys = wy.get(y).map_or(&[][..], Vec::as_slice);
|
||||
let ys = box_span(self.height, h, y);
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let mut acc = V3::ZERO;
|
||||
for &(sy, fy) in ys {
|
||||
for &(sx, fx) in wx.get(x).map_or(&[][..], Vec::as_slice) {
|
||||
for (sy, fy) in ys.clone() {
|
||||
for (sx, fx) in box_span(self.width, w, x) {
|
||||
acc += self.get(sx as i64, sy as i64) * (fx * fy);
|
||||
}
|
||||
}
|
||||
@@ -182,8 +182,10 @@ impl EnvImage {
|
||||
Ok(EnvImage { width: w, height: h, data })
|
||||
}
|
||||
|
||||
/// Resamples to `width × height` by bilinear lookup at each output pixel's direction.
|
||||
/// Resamples to `width × height` by bilinear lookup at each output pixel's direction. Returns
|
||||
/// an error when the source or the result is over `limits`.
|
||||
pub fn try_resampled(&self, width: u32, height: u32, limits: &Limits) -> Result<EnvImage, PbrError> {
|
||||
limits.check(self.width, self.height)?;
|
||||
let len = limits.check(width, height)?;
|
||||
let mut data = try_pixels(len)?;
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
@@ -201,23 +203,18 @@ pub(crate) fn half_size(w: u32, h: u32) -> (u32, u32) {
|
||||
((w / 2).max(1), (h / 2).max(1))
|
||||
}
|
||||
|
||||
/// For each of `dst` output pixels along one axis, the source pixels it covers and the share of
|
||||
/// its width each covers. The shares of one output pixel add up to 1.
|
||||
fn box_weights(src: u32, dst: u32) -> Vec<Vec<(usize, f32)>> {
|
||||
/// The source pixels that output pixel `i` covers along one axis when `src` pixels become `dst`,
|
||||
/// each with the share of the output pixel's width it covers. The shares add up to 1. Nothing is
|
||||
/// allocated.
|
||||
fn box_span(src: u32, dst: u32, i: usize) -> impl Iterator<Item = (usize, f32)> + Clone {
|
||||
let scale = f64::from(src) / f64::from(dst);
|
||||
(0..dst)
|
||||
.map(|i| {
|
||||
let (lo, hi) = (f64::from(i) * scale, f64::from(i + 1) * scale);
|
||||
let first = lo.floor() as usize;
|
||||
let last = (hi.ceil() as usize).min(src as usize);
|
||||
(first..last)
|
||||
.filter_map(|s| {
|
||||
let cover = (hi.min(s as f64 + 1.0) - lo.max(s as f64)) / scale;
|
||||
(cover > 0.0).then_some((s, cover as f32))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
let (lo, hi) = (i as f64 * scale, (i as f64 + 1.0) * scale);
|
||||
let first = lo.floor() as usize;
|
||||
let last = (hi.ceil() as usize).min(src as usize);
|
||||
(first..last).filter_map(move |s| {
|
||||
let cover = (hi.min(s as f64 + 1.0) - lo.max(s as f64)) / scale;
|
||||
(cover > 0.0).then_some((s, cover as f32))
|
||||
})
|
||||
}
|
||||
|
||||
/// A soft rectangular light: azimuth and elevation of its center and its half sizes, in degrees.
|
||||
|
||||
@@ -92,7 +92,8 @@ pub struct Limits {
|
||||
/// Most pixels (width × height) of one image. Default 2^22, which is 2048 × 2048.
|
||||
pub max_pixels: u64,
|
||||
/// Most bytes of pixel data one call holds at once: for [`try_prefilter`] the source copies,
|
||||
/// the pyramid, every output level and the sample table together. Default 256 MiB.
|
||||
/// the pyramid, every output level and the sample table together, and for [`try_sh9`] its
|
||||
/// table of column integrals (48 bytes per column). Default 256 MiB.
|
||||
pub max_bytes: u64,
|
||||
/// Most levels [`try_prefilter`] makes. Default 8.
|
||||
pub max_levels: u32,
|
||||
|
||||
@@ -10,9 +10,12 @@ use crate::{Limits, PbrError};
|
||||
/// convolved with the cosine lobe and divided by `π`: `Σ c_k Y_k(n)` times the albedo is the
|
||||
/// diffuse radiance a surface with normal `n` reflects. Every pixel of the source is projected,
|
||||
/// with each basis function integrated over the area of the pixel. Returns an error when the
|
||||
/// source is over `limits`.
|
||||
/// source is over `limits` or its table of column integrals, one per column, is over
|
||||
/// [`Limits::max_bytes`].
|
||||
pub fn try_sh9(env: &EnvImage, limits: &Limits) -> Result<[[f32; 3]; 9], PbrError> {
|
||||
limits.check(env.width(), env.height())?;
|
||||
let (w, h) = (env.width(), env.height());
|
||||
limits.check(w, h)?;
|
||||
limits.check_total_bytes(u64::from(w).checked_mul(size_of::<Column>() as u64), w, h)?;
|
||||
project(env)
|
||||
}
|
||||
|
||||
|
||||
@@ -84,6 +84,15 @@ fn prefiltering_over_the_byte_or_work_budget_is_refused() {
|
||||
assert_eq!(try_prefilter(&tiny, &opts(|o| o.levels = u32::MAX), &unbounded), Err(PbrError::TooMuchWork { needed, limit: 1 << 28 }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sh9_over_the_byte_budget_for_its_column_table_is_refused() {
|
||||
// A 2048 × 1 source is 24 KiB; its column table holds six `f64` per column, 96 KiB.
|
||||
let env = env_from(2048, 1, |_, _| [1.0; 3]);
|
||||
let table = 2048 * 48;
|
||||
assert_eq!(try_sh9(&env, &limits(|l| l.max_bytes = table - 1)), Err(PbrError::TooLarge(2048, 1)));
|
||||
assert!(try_sh9(&env, &limits(|l| l.max_bytes = table)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_infinite_and_negative_radiance_is_refused() {
|
||||
let limits = Limits::default();
|
||||
@@ -154,6 +163,11 @@ fn sources_over_the_size_limits_are_refused() {
|
||||
assert_eq!(try_sh9(&env, &few), Err(PbrError::TooLarge(16, 8)));
|
||||
let narrow = limits(|l| l.max_side = 8);
|
||||
assert_eq!(try_prefilter(&env, &PrefilterOptions::default(), &narrow), Err(PbrError::BadSize(16, 8)));
|
||||
// Halving and resampling check the source too, not only the smaller result.
|
||||
assert_eq!(env.try_half(&few), Err(PbrError::TooLarge(16, 8)));
|
||||
assert_eq!(env.try_resampled(4, 2, &few), Err(PbrError::TooLarge(16, 8)));
|
||||
assert_eq!(env.try_half(&narrow), Err(PbrError::BadSize(16, 8)));
|
||||
assert_eq!(env.try_resampled(8, 4, &narrow), Err(PbrError::BadSize(16, 8)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -31,12 +31,27 @@ pub fn limits(f: impl FnOnce(&mut Limits)) -> Limits {
|
||||
}
|
||||
|
||||
/// The largest difference between two pixel lists, relative to `max(1, |a|, |b|)` per value.
|
||||
/// Lists of different lengths differ by infinity.
|
||||
/// Lists of different lengths, and a NaN or infinite value on either side, differ by infinity.
|
||||
pub fn max_rel_diff(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 {
|
||||
if a.len() != b.len() {
|
||||
return f32::INFINITY;
|
||||
}
|
||||
a.iter().zip(b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| (x - y).abs() / 1f32.max(x.abs()).max(y.abs()))).fold(0.0, f32::max)
|
||||
let rel = |x: f32, y: f32| {
|
||||
if x.is_finite() && y.is_finite() { (x - y).abs() / 1f32.max(x.abs()).max(y.abs()) } else { f32::INFINITY }
|
||||
};
|
||||
a.iter().zip(b).flat_map(|(p, q)| p.iter().zip(q).map(|(x, y)| rel(*x, *y))).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_rel_diff_counts_non_finite_values_as_infinitely_far() {
|
||||
for bad in [f32::INFINITY, f32::NEG_INFINITY, f32::NAN] {
|
||||
assert_eq!(max_rel_diff(&[[bad; 3]], &[[0.0; 3]]), f32::INFINITY, "{bad} against 0");
|
||||
assert_eq!(max_rel_diff(&[[0.0; 3]], &[[bad; 3]]), f32::INFINITY, "0 against {bad}");
|
||||
assert_eq!(max_rel_diff(&[[1.0, 1.0, 1.0]], &[[1.0, bad, 1.0]]), f32::INFINITY, "one channel {bad}");
|
||||
}
|
||||
assert_eq!(max_rel_diff(&[[f32::INFINITY; 3]], &[[f32::INFINITY; 3]]), f32::INFINITY);
|
||||
assert_eq!(max_rel_diff(&[[2.0, 0.5, 0.0]], &[[2.0, 0.5, 0.0]]), 0.0);
|
||||
assert!((max_rel_diff(&[[4.0, 0.0, 0.0]], &[[3.0, 0.0, 0.0]]) - 0.25).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// An environment of linear pixels made by `f(x, y)`, with default limits.
|
||||
|
||||
@@ -165,3 +165,33 @@ fn halving_an_odd_side_keeps_the_last_column_and_row() {
|
||||
assert!((mean(&half) - mean(&env)).abs() < 1e-5, "{w}x{h}: mean {} for {}", mean(&half), mean(&env));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halving_averages_the_source_area_each_pixel_covers() {
|
||||
let limits = Limits::default();
|
||||
let value = |x: u32, y: u32| f64::from((x * 7 + y * 13) % 11) + 0.5;
|
||||
// The share of source pixel `s` inside output pixel `i` when `src` pixels become `dst`.
|
||||
let cover = |src: u32, dst: u32, i: u32, s: u32| {
|
||||
let scale = f64::from(src) / f64::from(dst);
|
||||
let (lo, hi) = (f64::from(i) * scale, f64::from(i + 1) * scale);
|
||||
(hi.min(f64::from(s) + 1.0) - lo.max(f64::from(s))).max(0.0) / scale
|
||||
};
|
||||
for (w, h) in [(1u32, 1u32), (3, 1), (1, 3), (5, 3), (3, 5), (7, 4), (4, 7), (9, 9), (2047, 1)] {
|
||||
let env = env_from(w, h, |x, y| [value(x, y) as f32; 3]);
|
||||
let half = env.try_half(&limits).unwrap();
|
||||
let (hw, hh) = (half.width(), half.height());
|
||||
assert_eq!((hw, hh), ((w / 2).max(1), (h / 2).max(1)));
|
||||
for oy in 0..hh {
|
||||
for ox in 0..hw {
|
||||
let mut want = 0.0;
|
||||
for sy in 0..h {
|
||||
for sx in 0..w {
|
||||
want += value(sx, sy) * cover(w, hw, ox, sx) * cover(h, hh, oy, sy);
|
||||
}
|
||||
}
|
||||
let got = f64::from(half.pixels()[(oy * hw + ox) as usize][0]);
|
||||
assert!((got - want).abs() < 1e-4 * want.max(1.0), "{w}x{h} at ({ox}, {oy}): {got} for {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user