Merge remote-tracking branch 'origin/pr/94' into review/pr-94

This commit is contained in:
Rafael Mendes committed 2026-11-05 15:51:22 -03:00
commit 7abc44eb0d
3 files changed
+213 -65

No files matched your search

+13 -22
View File
@@ -326,33 +326,24 @@ fn distance(ctx: &Ctx) -> CookResult {
let mask = ctx.gray_or(0, 0.0);
let maxd = (ctx.f("distance").max(0.0) * ctx.w as f32 / 256.0).max(1e-3);
let data = mask.data.clone();
let d2 = ops::distance_sq(ctx.w, ctx.h, |i| data.get(i).copied().unwrap_or(0.0) > 0.5, ctx.tile);
let inside = |i| data.get(i).copied().unwrap_or(0.0) > 0.5;
let Some(src) = ctx.sized(1) else {
let d2 = ops::distance_sq(ctx.w, ctx.h, inside, ctx.tile);
return Ok(vec![ops::gray_from(ctx.w, ctx.h, d2.iter().map(|d| (1.0 - d.sqrt() / maxd).clamp(0.0, 1.0)).collect())]);
};
// Spread the source's colors: each pixel takes the color of the nearest mask pixel, found by
// walking down the distance field's gradient.
let dist: Vec<f32> = d2.iter().map(|d| d.sqrt()).collect();
// Propagate the exact nearest mask pixel. Gradient walks can stall at stationary points or
// stop before reaching the mask, leaving background-colored gaps inside the distance range.
let (d2, sites) = ops::distance_sq_with_sites(ctx.w, ctx.h, inside, ctx.tile);
let combine = ctx.b("combine");
let (w, h) = (ctx.w as i64, ctx.h as i64);
let field = ops::gray_from(ctx.w, ctx.h, dist);
Ok(vec![Image::generate(ctx.w, ctx.h, src.kind, |x, y| {
let (mut px, mut py) = (x as f32, y as f32);
for _ in 0..64 {
let d = field.get_gray(px.round() as i64, py.round() as i64, ctx.tile);
if d < 0.5 {
break;
}
let (gx, gy) = ops::slope(&field, px.round() as i64, py.round() as i64, ctx.tile);
let g = (gx * gx + gy * gy).sqrt().max(1e-4);
px -= gx / g * d.min(8.0);
py -= gy / g * d.min(8.0);
if !ctx.tile && (px < 0.0 || py < 0.0 || px >= w as f32 || py >= h as f32) {
break;
}
}
let mut c = src.get(px.round() as i64, py.round() as i64, ctx.tile);
let d = field.get_gray(x as i64, y as i64, ctx.tile);
let i = y as usize * ctx.w as usize + x as usize;
let site = sites.get(i).copied().unwrap_or(usize::MAX);
let mut c = if site == usize::MAX {
[0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }]
} else {
src.get((site % ctx.w as usize) as i64, (site / ctx.w as usize) as i64, false)
};
let d = d2.get(i).copied().unwrap_or(f32::INFINITY).sqrt();
if d > maxd {
c = [0.0, 0.0, 0.0, if src.is_gray() { 1.0 } else { 0.0 }];
} else if combine {
+134 -43
View File
@@ -122,62 +122,108 @@ fn box_1d(src: &Image, r: i64, horizontal: bool, tile: bool) -> Image {
/// Squared Euclidean distance (pixels) from every pixel to the nearest pixel where `inside` is
/// true (Felzenszwalb–Huttenlocher, exact, linear time). With `tile`, distances wrap.
pub fn distance_sq(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> Vec<f32> {
distance_transform::<false>(w, h, inside, tile).0
}
/// The same exact distance transform, also retaining the nearest mask pixel's row-major index.
/// Empty masks have no nearest pixel: their indices are `usize::MAX`.
pub fn distance_sq_with_sites(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> (Vec<f32>, Vec<usize>) {
distance_transform::<true>(w, h, inside, tile)
}
const DISTANCE_INF: f32 = 1e20;
fn edt_1d<const SITES: bool>(f: &[f32]) -> (Vec<f32>, Vec<usize>) {
let n = f.len();
if n == 0 {
return (Vec::new(), Vec::new());
}
let f: Vec<f64> = f.iter().map(|v| *v as f64).collect();
let mut d = vec![0.0f32; n];
// Distance-only callers do not allocate or propagate site indices.
let mut sites = if SITES { vec![usize::MAX; n] } else { Vec::new() };
let mut v = vec![0usize; n];
let mut z = vec![0.0f64; n + 1];
let mut k = 0usize;
z[0] = -(DISTANCE_INF as f64);
z[1] = DISTANCE_INF as f64;
let cross = |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64);
for q in 1..n {
let mut s = cross(q, v[k]);
while k > 0 && s <= z[k] {
k -= 1;
s = cross(q, v[k]);
}
k += 1;
v[k] = q;
z[k] = s;
z[k + 1] = DISTANCE_INF as f64;
}
k = 0;
for (q, dq) in d.iter_mut().enumerate() {
while k + 1 < n && z[k + 1] < q as f64 {
k += 1;
}
let p = v[k];
*dq = ((q as f64 - p as f64).powi(2) + f[p]) as f32;
if SITES && f[p] < DISTANCE_INF as f64 {
sites[q] = p;
}
}
(d, sites)
}
fn distance_transform<const SITES: bool>(w: u32, h: u32, inside: impl Fn(usize) -> bool + Sync, tile: bool) -> (Vec<f32>, Vec<usize>) {
let (w, h) = (w as usize, h as usize);
const INF: f32 = 1e20;
if w == 0 || h == 0 {
return (Vec::new(), Vec::new());
}
// Tiling: run on a 3x tiled line so distances cross the edges.
let rep = if tile { 3 } else { 1 };
let edt_1d = |f: &[f32]| -> Vec<f32> {
let n = f.len();
let f: Vec<f64> = f.iter().map(|v| *v as f64).collect();
let mut d = vec![0.0f32; n];
let mut v = vec![0usize; n];
let mut z = vec![0.0f64; n + 1];
let mut k = 0usize;
z[0] = -(INF as f64);
z[1] = INF as f64;
let cross = |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64);
for q in 1..n {
let mut s = cross(q, v[k]);
while k > 0 && s <= z[k] {
k -= 1;
s = cross(q, v[k]);
}
k += 1;
v[k] = q;
z[k] = s;
z[k + 1] = INF as f64;
}
k = 0;
for (q, dq) in d.iter_mut().enumerate() {
while k + 1 < n && z[k + 1] < q as f64 {
k += 1;
}
let p = v[k];
*dq = ((q as f64 - p as f64).powi(2) + f[p]) as f32;
}
d
};
// Columns.
let cols: Vec<Vec<f32>> = (0..w)
// Columns. Site indices are vertical coordinates at this stage.
let cols: Vec<_> = (0..w)
.into_par_iter()
.map(|x| {
let f: Vec<f32> = (0..h * rep).map(|y| if inside((y % h) * w + x) { 0.0 } else { INF }).collect();
let d = edt_1d(&f);
let f: Vec<f32> = (0..h * rep).map(|y| if inside((y % h) * w + x) { 0.0 } else { DISTANCE_INF }).collect();
let (d, sites) = edt_1d::<SITES>(&f);
let off = if tile { h } else { 0 };
d[off..off + h].to_vec()
(d[off..off + h].to_vec(), if SITES { sites[off..off + h].to_vec() } else { Vec::new() })
})
.collect();
// Rows.
let rows: Vec<Vec<f32>> = (0..h)
// Rows. Carry the chosen column's vertical site through the horizontal transform.
let rows: Vec<_> = (0..h)
.into_par_iter()
.map(|y| {
let f: Vec<f32> = (0..w * rep).map(|x| cols[x % w][y]).collect();
let d = edt_1d(&f);
let f: Vec<f32> = (0..w * rep).map(|x| cols[x % w].0[y]).collect();
let (d, sites) = edt_1d::<SITES>(&f);
let off = if tile { w } else { 0 };
d[off..off + w].to_vec()
let sites = if SITES {
sites[off..off + w]
.iter()
.map(|&x| {
if x == usize::MAX {
usize::MAX
} else {
let x = x % w;
let sy = cols[x].1[y];
if sy == usize::MAX { usize::MAX } else { (sy % h) * w + x }
}
})
.collect()
} else {
Vec::new()
};
(d[off..off + w].to_vec(), sites)
})
.collect();
rows.concat()
drop(cols);
let mut distances = Vec::with_capacity(w * h);
let mut sites = if SITES { Vec::with_capacity(w * h) } else { Vec::new() };
for (row, row_sites) in rows {
distances.extend(row);
sites.extend(row_sites);
}
(distances, sites)
}
/// Slope (dx, dy) of a gray image by central differences, in value units per pixel.
@@ -353,6 +399,51 @@ mod tests {
assert_eq!(t[8], 1.0);
}
#[test]
fn edt_sites_match_brute_force() {
// Exhaust all small masks, including ties and empty/full masks. Larger rectangles use
// deterministic pseudo-random masks; the oracle measures every site independently.
for (w, h) in [(1usize, 1usize), (1, 7), (7, 1), (2, 3), (3, 3), (5, 7), (8, 6)] {
let cases = if w * h <= 9 { 1usize << (w * h) } else { 128 };
for case in 0..cases {
let mut state = case as u32 + 1;
let mask: Vec<bool> = (0..w * h)
.map(|i| {
if w * h <= 9 {
case & (1 << i) != 0
} else {
state = state.wrapping_mul(1664525).wrapping_add(1013904223);
state.is_multiple_of(7)
}
})
.collect();
for tile in [false, true] {
let (d, sites) = distance_sq_with_sites(w as u32, h as u32, |i| mask[i], tile);
assert_eq!(d, distance_sq(w as u32, h as u32, |i| mask[i], tile));
for i in 0..w * h {
let distance = |site: usize| {
let dx = (i % w).abs_diff(site % w);
let dy = (i / w).abs_diff(site / w);
let (dx, dy) = if tile { (dx.min(w - dx), dy.min(h - dy)) } else { (dx, dy) };
(dx * dx + dy * dy) as f32
};
let expected = (0..mask.len()).filter(|&site| mask[site]).map(distance).reduce(f32::min);
if let Some(expected) = expected {
assert_eq!(d[i], expected, "{w}x{h}, mask {case}, tile {tile}, pixel {i}");
assert!(sites[i] < mask.len() && mask[sites[i]]);
assert_eq!(distance(sites[i]), expected);
} else {
assert_eq!(sites[i], usize::MAX);
assert!(d[i] >= DISTANCE_INF);
}
}
}
}
}
assert!(distance_sq_with_sites(0, 3, |_| true, true).0.is_empty());
assert!(distance_sq_with_sites(3, 0, |_| true, false).1.is_empty());
}
#[test]
fn hsl_round_trip() {
let c = [0.8, 0.3, 0.1, 1.0];
+66
View File
@@ -0,0 +1,66 @@
use std::collections::BTreeMap;
use materialcraft_core::Value;
use materialcraft_image::{Image, Kind};
use materialcraft_nodes::{Ctx, find, resolve_params};
fn cook(mask: Image, source: Option<Image>, tile: bool, combine: bool, distance: f32) -> Image {
let def = find("distance").unwrap();
let params = resolve_params(def, &BTreeMap::from([("distance".into(), Value::Float(distance)), ("combine".into(), Value::Bool(combine))]));
let (w, h) = (mask.w, mask.h);
let inputs = [Some(mask), source];
let vars = BTreeMap::new();
let resource = |_: &str| None;
let ctx = Ctx { w, h, seed: 0, tile, inputs: &inputs, params: &params, resource: &resource, vars: &vars };
(def.cook)(&ctx).unwrap().remove(0)
}
#[test]
fn tiled_distance_spreads_source_across_stationary_gradient() {
let mask = Image::gray(32, 32, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 });
let output = cook(mask.clone(), Some(mask), true, false, 256.0);
// This is within range of the only mask pixel, but the symmetric distance field has zero
// slope here. A gradient walk stopped on the black source background instead of the seed.
assert_eq!(output.get_gray(16, 16, false), 1.0);
assert!(output.data.iter().all(|&v| v == 1.0));
}
#[test]
fn distance_spreads_source_beyond_the_old_walk_limit() {
let mask = Image::gray(1024, 1, |x, _| if x == 0 { 1.0 } else { 0.0 });
let output = cook(mask.clone(), Some(mask), false, false, 256.0);
assert_eq!(output.get_gray(1023, 0, false), 1.0);
}
#[test]
fn distance_preserves_source_alpha_range_and_combine() {
for tile in [false, true] {
let mask = Image::gray(9, 3, |x, y| if x == 0 && y == 1 { 1.0 } else { 0.0 });
let source = Image::generate(9, 3, Kind::Color, |x, y| if x == 0 && y == 1 { [0.8, 0.4, 0.2, 0.6] } else { [0.1, 0.1, 0.1, 1.0] });
for combine in [false, true] {
let output = cook(mask.clone(), Some(source.clone()), tile, combine, 512.0 / 9.0); // two pixels
assert_eq!(output.get(0, 1, false), [0.8, 0.4, 0.2, 0.6]);
let expected = if combine { [0.4, 0.2, 0.1, 0.6] } else { [0.8, 0.4, 0.2, 0.6] };
assert_eq!(output.get(1, 1, false), expected);
assert_eq!(output.get(4, 1, false), [0.0; 4]);
assert_eq!(output.get(8, 1, false), if tile { expected } else { [0.0; 4] });
}
}
}
#[test]
fn distance_handles_empty_full_masks_and_no_source() {
for tile in [false, true] {
let empty = Image::filled(7, 5, Kind::Gray, [0.0; 4]);
let full = Image::filled(7, 5, Kind::Gray, [1.0; 4]);
let source = Image::generate(7, 5, Kind::Color, |x, y| [x as f32 / 7.0, y as f32 / 5.0, 0.4, 0.7]);
assert!(cook(empty.clone(), Some(source.clone()), tile, false, 256.0).data.iter().all(|&v| v == 0.0));
assert_eq!(cook(full, Some(source), tile, true, 256.0).get(3, 2, false), [3.0 / 7.0, 2.0 / 5.0, 0.4, 0.7]);
assert!(cook(empty, None, tile, true, 256.0).data.iter().all(|&v| v == 0.0));
let mask = Image::gray(7, 5, |x, y| if x == 0 && y == 0 { 1.0 } else { 0.0 });
let ramp = cook(mask, None, tile, false, 512.0 / 7.0);
assert_eq!(ramp.get_gray(0, 0, false), 1.0);
assert_eq!(ramp.get_gray(1, 0, false), 0.5);
assert_eq!(ramp.get_gray(3, 0, false), 0.0);
}
}