PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fix radial blur sampling density (#515) (#658)
Alex Gorevskief8610adebaf
diff --git a/crates/algo/src/blur.rs b/crates/algo/src/blur.rsindex 2ca3bcc88..adb8984be 100644--- a/crates/algo/src/blur.rs+++ b/crates/algo/src/blur.rs@@ -5,7 +5,7 @@ use photocraft_raster::Interrupt;use crate::image::{Edge, Image, premultiply, unpremultiply};use crate::photo_util::{par_map, par_rows};-use crate::{Ctx, FilterParams, RadialMethod};+use crate::{Ctx, FilterParams, RadialMethod, RadialQuality};/// Normalized Gaussian kernel with standard deviation `sigma` (radius 3σ).pub(crate) fn gaussian_kernel(sigma: f32) -> Vec<f32> {@@ -310,13 +310,17 @@ pub(crate) fn boxed(src: &Image, out: Rect, ctx: &Ctx, radius: f32) -> Vec<f32>}}-fn average_samples(src: &Image, out: Rect, ctx: &Ctx, mut offsets: impl FnMut(f32, f32, &mut Vec<(f32, f32)>)) -> Vec<f32> {+fn average_samples(src: &Image, out: Rect, ctx: &Ctx, offsets: impl Fn(f32, f32, &mut Vec<(f32, f32)>) + Sync) -> Vec<f32> {let n = src.ch;- let mut res = Vec::with_capacity(out.width() as usize * out.height() as usize * n);- let mut pts = Vec::new();- let mut tmp = vec![0.0f32; n];- let mut acc = vec![0.0f32; n];- for y in out.y0..out.y1 {+ let (ow, oh) = (out.width() as usize, out.height() as usize);+ let mut res = vec![0.0; ow * oh * n];+ if ow == 0 || oh == 0 || n == 0 {+ return res;+ }+ let process_row = |y: i32, row: &mut [f32]| {+ let mut pts = Vec::new();+ let mut tmp = vec![0.0f32; n];+ let mut acc = vec![0.0f32; n];for x in out.x0..out.x1 {let (cx, cy) = (x as f32 + 0.5, y as f32 + 0.5);pts.clear();@@ -333,17 +337,26 @@ fn average_samples(src: &Image, out: Rect, ctx: &Ctx, mut offsets: impl FnMut(f3}}let k = 1.0 / pts.len().max(1) as f32;- for a in acc.iter_mut() {- *a *= k;+ for (dst, value) in row[(x - out.x0) as usize * n..][..n].iter_mut().zip(&acc) {+ *dst = *value * k;}if ctx.alpha {- let a = acc[n - 1];- for v in acc.iter_mut().take(n - 1) {- *v = if a > 1e-7 { *v / a } else { 0.0 };+ let alpha = acc[n - 1] * k;+ let dst = &mut row[(x - out.x0) as usize * n..][..n];+ for value in dst.iter_mut().take(n - 1) {+ *value = if alpha > 1e-7 { *value / alpha } else { 0.0 };}}- res.extend_from_slice(&acc);}+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ res.par_chunks_mut(ow * n).enumerate().for_each(|(row, data)| process_row(out.y0 + row as i32, data));+ }+ #[cfg(target_arch = "wasm32")]+ {+ res.chunks_mut(ow * n).enumerate().for_each(|(row, data)| process_row(out.y0 + row as i32, data));}res}@@ -427,7 +440,20 @@ pub(crate) fn motion(src: &Image, out: Rect, ctx: &Ctx, angle: f32, distance: f3res}-pub(crate) fn radial(src: &Image, out: Rect, ctx: &Ctx, amount: f32, method: RadialMethod, center: (f32, f32)) -> Vec<f32> {+fn radial_intervals(path_length: f32, quality: RadialQuality) -> usize {+ let max = match quality {+ RadialQuality::Draft => 64,+ RadialQuality::Good => 256,+ RadialQuality::Best => 4096,+ };++ if path_length.is_nan() {+ return 1;+ }+ path_length.ceil().clamp(1.0, max as f32) as usize+}++pub(crate) fn radial(src: &Image, out: Rect, ctx: &Ctx, amount: f32, method: RadialMethod, quality: RadialQuality, center: (f32, f32)) -> Vec<f32> {let b = ctx.bounds;let (cx, cy) = (b.x0 as f32 + b.width() as f32 * center.0, b.y0 as f32 + b.height() as f32 * center.1);let amount = amount.clamp(0.0, 100.0);@@ -438,7 +464,7 @@ pub(crate) fn radial(src: &Image, out: Rect, ctx: &Ctx, amount: f32, method: RadRadialMethod::Spin => {// Arc of `amount` degrees centred on the pixel.let arc = amount.to_radians();- let n = ((arc * r).ceil() as i32).clamp(1, 64);+ let n = radial_intervals(arc * r, quality);for i in 0..=n {let t = (i as f32 / n as f32 - 0.5) * arc;let (s, c) = t.sin_cos();@@ -448,7 +474,7 @@ pub(crate) fn radial(src: &Image, out: Rect, ctx: &Ctx, amount: f32, method: RadRadialMethod::Zoom => {// Samples along the ray, up to amount/2 % closer to the centre.let span = amount / 200.0;- let n = ((span * r).ceil() as i32).clamp(1, 64);+ let n = radial_intervals(span * r, quality);for i in 0..=n {let k = 1.0 - span * i as f32 / n as f32;pts.push((cx + dx * k, cy + dy * k));@@ -587,6 +613,53 @@ mod tests {use photocraft_color::{ColorMode, PixelFormat, SampleType};use photocraft_raster::Surface;+ #[test]+ fn radial_blur_samples_large_arcs_beyond_64_intervals() {+ let bounds = Rect::new(0, 0, 1000, 1000);+ let out = Rect::new(999, 500, 1000, 501);+ let ctx = Ctx { bounds, mode: photocraft_color::ColorMode::Grayscale, alpha: false };+ let mut img = Image::new(bounds, 1);+ let (cx, cy) = (500.0f32, 500.0f32);+ let (x, y) = (999.5f32, 500.5f32);+ let (dx, dy) = (x - cx, y - cy);+ let arc = 100.0f32.to_radians();+ let count = radial_intervals(arc * dx.hypot(dy), RadialQuality::Good);+ assert_eq!(count, 256);+ assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Draft), 64);+ assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Good), 256);+ assert_eq!(radial_intervals(f32::INFINITY, RadialQuality::Best), 4096);+ assert_eq!(radial_intervals(f32::NAN, RadialQuality::Best), 1);++ // Put a small bright patch halfway between two samples from the former 64-interval+ // limit. Dense sampling should pick it up; the coarse path misses it entirely.+ let sparse_midpoint = (31.5 / 64.0 - 0.5) * arc;+ let (s, c) = sparse_midpoint.sin_cos();+ let px = (cx + dx * c - dy * s - 0.5).round() as i32;+ let py = (cy + dx * s + dy * c - 0.5).round() as i32;+ for yy in py - 1..=py + 1 {+ for xx in px - 1..=px + 1 {+ let index = (yy - bounds.y0) as usize * bounds.width() as usize + (xx - bounds.x0) as usize;+ img.data[index] = 1.0;+ }+ }++ let sample_path = |x: f32, y: f32, pts: &mut Vec<(f32, f32)>, intervals: usize| {+ let (dx, dy) = (x - cx, y - cy);+ for i in 0..=intervals {+ let t = (i as f32 / intervals as f32 - 0.5) * arc;+ let (s, c) = t.sin_cos();+ pts.push((cx + dx * c - dy * s, cy + dx * s + dy * c));+ }+ };+ let actual = radial(&img, out, &ctx, 100.0, RadialMethod::Spin, RadialQuality::Good, (0.5, 0.5))[0];+ let expected = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 8192))[0];+ let coarse = average_samples(&img, out, &ctx, |x, y, pts| sample_path(x, y, pts, 64))[0];++ assert!(actual > 0.001, "dense radial samples should resolve the bright patch, got {actual}");+ assert!((actual - expected).abs() < 0.0015, "radial result {actual} differs from dense reference {expected}");+ assert!(coarse < expected * 0.1, "former 64-interval sampling unexpectedly resolved the patch: {coarse} vs {expected}");+ }+#[test]fn box_gaussian_matches_exact_kernel() {// A hard vertical edge (premultiplied RGBA-ish, 2 channels) blurred with σ = 12.diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex ec20883d6..9eba8cfa3 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -105,6 +105,19 @@ pub enum RadialMethod {Zoom,}+/// Sampling quality for radial blur. Higher quality improves large-radius detail at greater cost.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "camelCase")]+pub enum RadialQuality {+ /// Up to 64 intervals per pixel for a faster, coarser result.+ Draft,+ /// Up to 256 intervals per pixel; the default.+ #[default]+ Good,+ /// Up to 4096 intervals per pixel.+ Best,+}+/// Noise distribution.#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]#[serde(rename_all = "camelCase")]@@ -195,6 +208,8 @@ pub enum FilterParams {RadialBlur {amount: f32,method: RadialMethod,+ #[serde(default)]+ quality: RadialQuality,center_x: f32,center_y: f32,},@@ -686,7 +701,9 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<fFilterParams::GaussianBlur { radius } => blur::gaussian(src, out, ctx, *radius),FilterParams::BoxBlur { radius } => blur::boxed(src, out, ctx, *radius),FilterParams::MotionBlur { angle, distance } => blur::motion(src, out, ctx, *angle, *distance),- FilterParams::RadialBlur { amount, method, center_x, center_y } => blur::radial(src, out, ctx, *amount, *method, (*center_x, *center_y)),+ FilterParams::RadialBlur { amount, method, quality, center_x, center_y } => {+ blur::radial(src, out, ctx, *amount, *method, *quality, (*center_x, *center_y))+ }FilterParams::SurfaceBlur { radius, threshold } => blur::surface(src, out, ctx, *radius, *threshold),FilterParams::UnsharpMask { amount, radius, threshold } => sharpen::unsharp(src, out, ctx, *amount, *radius, *threshold),FilterParams::SmartSharpen { amount, radius, reduce_noise } => sharpen::smart(src, out, ctx, *amount, *radius, *reduce_noise),diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rsindex 2b053a54d..763cc0bce 100644--- a/crates/algo/src/tests.rs+++ b/crates/algo/src/tests.rs@@ -38,8 +38,8 @@ fn all_filters() -> Vec<FilterParams> {FilterParams::BoxBlur { radius: 2.0 },FilterParams::BoxBlur { radius: 6.0 },FilterParams::MotionBlur { angle: 30.0, distance: 7.0 },- FilterParams::RadialBlur { amount: 20.0, method: RadialMethod::Spin, center_x: 0.5, center_y: 0.5 },- FilterParams::RadialBlur { amount: 30.0, method: RadialMethod::Zoom, center_x: 0.3, center_y: 0.6 },+ FilterParams::RadialBlur { amount: 20.0, method: RadialMethod::Spin, quality: RadialQuality::Good, center_x: 0.5, center_y: 0.5 },+ FilterParams::RadialBlur { amount: 30.0, method: RadialMethod::Zoom, quality: RadialQuality::Good, center_x: 0.3, center_y: 0.6 },FilterParams::SurfaceBlur { radius: 3.0, threshold: 20.0 },FilterParams::UnsharpMask { amount: 150.0, radius: 1.5, threshold: 2.0 },FilterParams::SmartSharpen { amount: 100.0, radius: 1.0, reduce_noise: 20.0 },@@ -77,6 +77,19 @@ fn all_filters() -> Vec<FilterParams> {]}+#[test]+fn radial_blur_quality_defaults_for_older_serialized_parameters() {+ let params = serde_json::json!({+ "filter": "radialBlur",+ "amount": 20.0,+ "method": "spin",+ "centerX": 0.5,+ "centerY": 0.5+ });+ let decoded: FilterParams = serde_json::from_value(params).unwrap();+ assert_eq!(decoded, FilterParams::RadialBlur { amount: 20.0, method: RadialMethod::Spin, quality: RadialQuality::Good, center_x: 0.5, center_y: 0.5 });+}+#[test]fn every_filter_is_tile_independent() {let s = pattern(SampleType::U8, R);diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rsindex 1f1aa3104..e24b67c9d 100644--- a/crates/engine/src/filters.rs+++ b/crates/engine/src/filters.rs@@ -4,7 +4,9 @@//! smart object, recording a smart filter), respects the selection, and is//! undoable. `filter.lastFilter` re-runs the most recent filter command.-use photocraft_algo::{self as algo, Distribution, FilterParams, PolarMode, Preserve, RadialMethod, RippleSize, SpherizeMode, UndefinedAreas, WaveType};+use photocraft_algo::{+ self as algo, Distribution, FilterParams, PolarMode, Preserve, RadialMethod, RadialQuality, RippleSize, SpherizeMode, UndefinedAreas, WaveType,+};use photocraft_doc::{LayerContent, SmartFilter};use serde_json::{Value, json};@@ -65,6 +67,12 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {"filter.blur.radialBlur" => FilterParams::RadialBlur {amount: f(p, "amount", 10.0).clamp(1.0, 100.0),method: if s(p, "method", "spin") == "zoom" { RadialMethod::Zoom } else { RadialMethod::Spin },+ quality: match s(p, "quality", "good") {+ "draft" => RadialQuality::Draft,+ "best" => RadialQuality::Best,+ "good" => RadialQuality::Good,+ _ => RadialQuality::Good,+ },center_x: f(p, "centerX", 0.5),center_y: f(p, "centerY", 0.5),},@@ -315,7 +323,7 @@ pub fn specs() -> Vec<CommandSpec> {"filter.blur.radialBlur","Radial Blur…",["Filter", "Blur"],- r##"{"amount":1..100=10,"method":"spin|zoom","centerX":0..1=0.5,"centerY":0..1=0.5}"##+ r##"{"amount":1..100=10,"method":"spin|zoom","quality":"draft|good|best"="good","centerX":0..1=0.5,"centerY":0..1=0.5}"##),filter_cmd!("filter.blur.surfaceBlur", "Surface Blur…", ["Filter", "Blur"], r##"{"radius":1..100=5,"threshold":2..255=15}"##),filter_cmd!(@@ -585,6 +593,10 @@ mod tests {#[test]fn params_map_to_algorithm_units() {assert_eq!(params_for("filter.blur.gaussianBlur", &json!({"radius": 4.5})), Some(FilterParams::GaussianBlur { radius: 4.5 }));+ assert_eq!(+ params_for("filter.blur.radialBlur", &json!({"quality": "best"})),+ Some(FilterParams::RadialBlur { amount: 10.0, method: RadialMethod::Spin, quality: RadialQuality::Best, center_x: 0.5, center_y: 0.5 })+ );assert_eq!(params_for("filter.noise.addNoise", &json!({"amount": 10, "distribution": "gaussian", "monochromatic": true})),Some(FilterParams::AddNoise { amount: 10.0, distribution: Distribution::Gaussian, monochromatic: true, seed: 0 })diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex bc38c1798..900327306 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2726,3 +2726,5 @@ cameraRaw Color 색상Lines +/− 줄 +/−@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{binAdded} / −{binDeleted} binary assets, {first} – {last} @{login}: PR {prs}개, 커밋 {commits}개, 줄 +{added} / −{deleted} (Δ {delta}), 바이너리 +{binAdded} / −{binDeleted}, {first} – {last}Apply At Canvas Bounds 캔버스 경계에 효과 적용+ Good 좋음+ Best 최적