mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge remote-tracking branch 'origin/main' into feat/batch-recursion-naming
# Conflicts: # docs/gaps.md
This commit is contained in:
commit
720a1e4b9c
89 files changed
+6219
-295
No files matched your search
@@ -0,0 +1,990 @@
|
||||
//! Depth from focus for Edit › Auto-Blend Layers › Stack Images: a dense, sub-layer depth map
|
||||
//! from the aligned stack, the index of the layer each pixel is sharpest in.
|
||||
//!
|
||||
//! The pipeline is the non-learned "focus volume" recipe, written from the papers:
|
||||
//!
|
||||
//! 1. **Focus measure** per layer on luminance at full resolution: the *ring difference filter*
|
||||
//! of Jeon, Surh, Im & Kweon, *Ring Difference Filter for Fast and Noise Robust Depth From
|
||||
//! Focus*, IEEE TIP 29 (2019), the magnitude of the difference between the mean of a small
|
||||
//! disk and the mean of the ring around it, a band-pass whose support averages sensor noise
|
||||
//! away while staying local. Block-averaged to a working grid (half resolution).
|
||||
//! 2. **Cost aggregation**: each slice of the focus volume is filtered with the *guided filter*
|
||||
//! (He, Sun & Tang, PAMI 2013) using the all-in-focus luminance as guide, edge-aware
|
||||
//! aggregation as in fast cost-volume filtering (Hosni et al., PAMI 2013).
|
||||
//! 3. **Peak search** per pixel over the layer axis, one slice at a time: the global peak and its
|
||||
//! two neighbours for the *Gaussian interpolation* of Nayar & Nakagawa, *Shape from Focus*,
|
||||
//! PAMI 1994 (sub-layer depth), the second-best local maximum for a peak-ratio confidence,
|
||||
//! the profile mean for a prominence term and the profile minimum for a noise gate.
|
||||
//! 4. **Regularisation**: the sub-layer depth is smoothed and holes filled by an edge-aware
|
||||
//! weighted least squares energy (Farbman, Fattal, Lischinski & Szeliski, SIGGRAPH 2008)
|
||||
//! whose data term is the confidence, solved by conjugate gradients preconditioned by a
|
||||
//! multigrid V-cycle from the separable sweeps of the *fast global smoother* (Min, Choi, Lu,
|
||||
//! Ham, Sohn & Do, IEEE TIP 2014) as the start, with one Huber reweighting so isolated
|
||||
//! outliers stop pulling.
|
||||
//! 5. **Upsampling** to full resolution with the guided filter's linear coefficients.
|
||||
//!
|
||||
//! Everything is deterministic; the slices are folded one at a time, so memory is one working
|
||||
//! grid per layer plus a few planes.
|
||||
|
||||
use crate::photo_util::{par_map, par_rows, par_rows2};
|
||||
|
||||
/// Depth-from-focus settings.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DepthParams {
|
||||
/// The working grid is `1 / 2^scale` of full resolution (1 = half).
|
||||
pub scale: usize,
|
||||
/// Ring difference filter radii: the disk `r ≤ r_in`, the ring `r_in < r ≤ r_out`.
|
||||
pub r_in: usize,
|
||||
pub r_out: usize,
|
||||
/// Guided-filter aggregation radius (working-grid pixels) and regulariser.
|
||||
pub agg_radius: usize,
|
||||
pub agg_eps: f32,
|
||||
/// Smoothness weight and guide-edge sensitivity (luminance units) of the regularisation.
|
||||
pub lambda: f32,
|
||||
pub sigma_c: f32,
|
||||
/// Noise gate: full confidence needs a peak ≥ `(1 + gate) ×` the noise floor (the median
|
||||
/// over pixels of the profile minimum). 0 = off.
|
||||
pub gate: f32,
|
||||
/// Robust data term: after the first solve the data weights are scaled by the Huber factor
|
||||
/// `min(1, robust / |d − u|)` (in layers) and the system is solved once more. 0 = off.
|
||||
pub robust: f32,
|
||||
}
|
||||
|
||||
impl Default for DepthParams {
|
||||
fn default() -> Self {
|
||||
DepthParams { scale: 1, r_in: 1, r_out: 3, agg_radius: 3, agg_eps: 1e-4, lambda: 3.0, sigma_c: 0.04, gate: 1.0, robust: 1.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of [`depth_from_focus`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct DepthMap {
|
||||
/// Full-resolution fractional layer index per pixel, in `0 ..= n − 1`.
|
||||
pub depth: Vec<f32>,
|
||||
/// Full-resolution confidence in `0 ..= 1`.
|
||||
pub conf: Vec<f32>,
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
}
|
||||
|
||||
/// Mean over `k × k` blocks (partial blocks at the far edges use their own count).
|
||||
pub fn block_mean(src: &[f32], w: usize, h: usize, k: usize) -> (Vec<f32>, usize, usize) {
|
||||
let k = k.max(1);
|
||||
let (dw, dh) = (w.div_ceil(k), h.div_ceil(k));
|
||||
if k == 1 {
|
||||
return (src.to_vec(), dw, dh);
|
||||
}
|
||||
let mut out = vec![0.0f32; dw * dh];
|
||||
par_rows(&mut out, dw, 1, |oy, row| {
|
||||
let (y0, y1) = (oy * k, (oy * k + k).min(h));
|
||||
for y in y0..y1 {
|
||||
let s = &src[y * w..y * w + w];
|
||||
for (ox, o) in row.iter_mut().enumerate() {
|
||||
*o += s[ox * k..(ox * k + k).min(w)].iter().sum::<f32>();
|
||||
}
|
||||
}
|
||||
for (ox, o) in row.iter_mut().enumerate() {
|
||||
*o /= ((y1 - y0) * ((ox * k + k).min(w) - ox * k)) as f32;
|
||||
}
|
||||
});
|
||||
(out, dw, dh)
|
||||
}
|
||||
|
||||
/// Bilinear resampling of a working-grid plane (block size `k`, samples at block centres) to
|
||||
/// `w × h`.
|
||||
pub fn upsample_bilinear(g: &[f32], dw: usize, dh: usize, w: usize, h: usize, k: usize) -> Vec<f32> {
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
if dw == 0 || dh == 0 {
|
||||
return out;
|
||||
}
|
||||
let inv = 1.0 / k.max(1) as f32;
|
||||
par_rows(&mut out, w, 1, |y, row| {
|
||||
let fy = ((y as f32 + 0.5) * inv - 0.5).clamp(0.0, (dh - 1) as f32);
|
||||
let y0 = fy as usize;
|
||||
let y1 = (y0 + 1).min(dh - 1);
|
||||
let ty = fy - y0 as f32;
|
||||
let (r0, r1) = (&g[y0 * dw..y0 * dw + dw], &g[y1 * dw..y1 * dw + dw]);
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let fx = ((x as f32 + 0.5) * inv - 0.5).clamp(0.0, (dw - 1) as f32);
|
||||
let x0 = fx as usize;
|
||||
let x1 = (x0 + 1).min(dw - 1);
|
||||
let tx = fx - x0 as f32;
|
||||
let top = r0[x0] + (r0[x1] - r0[x0]) * tx;
|
||||
let bot = r1[x0] + (r1[x1] - r1[x0]) * tx;
|
||||
*o = top + (bot - top) * ty;
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Box means over a `(2r + 1)²` window clamped to the plane (partial windows at the borders use
|
||||
/// their own count): a horizontal moving sum per row in parallel, then a vertical moving sum
|
||||
/// carried down the rows as one accumulator row.
|
||||
struct BoxFilter {
|
||||
w: usize,
|
||||
h: usize,
|
||||
r: usize,
|
||||
inv_count: Vec<f32>,
|
||||
}
|
||||
|
||||
impl BoxFilter {
|
||||
fn new(w: usize, h: usize, r: usize) -> BoxFilter {
|
||||
let cnt = |n: usize, i: usize| ((i + r + 1).min(n) - i.saturating_sub(r)) as f32;
|
||||
let mut inv_count = vec![0.0f32; w * h];
|
||||
par_rows(&mut inv_count, w, 1, |y, row| {
|
||||
let cy = cnt(h, y);
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = 1.0 / (cy * cnt(w, x));
|
||||
}
|
||||
});
|
||||
BoxFilter { w, h, r, inv_count }
|
||||
}
|
||||
|
||||
fn mean(&self, src: &[f32]) -> Vec<f32> {
|
||||
let (w, h, r) = (self.w, self.h, self.r);
|
||||
let mut tmp = vec![0.0f32; w * h];
|
||||
par_rows(&mut tmp, w, 1, |y, row| {
|
||||
let s = &src[y * w..y * w + w];
|
||||
let mut acc: f64 = s[..(r + 1).min(w)].iter().map(|v| f64::from(*v)).sum();
|
||||
for x in 0..w {
|
||||
row[x] = acc as f32;
|
||||
if x + r + 1 < w {
|
||||
acc += f64::from(s[x + r + 1]);
|
||||
}
|
||||
if x >= r {
|
||||
acc -= f64::from(s[x - r]);
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
let mut acc = vec![0.0f64; w];
|
||||
for y in 0..(r + 1).min(h) {
|
||||
for (a, v) in acc.iter_mut().zip(&tmp[y * w..y * w + w]) {
|
||||
*a += f64::from(*v);
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for ((o, a), c) in out[y * w..y * w + w].iter_mut().zip(&acc).zip(&self.inv_count[y * w..y * w + w]) {
|
||||
*o = *a as f32 * c;
|
||||
}
|
||||
if y + r + 1 < h {
|
||||
for (a, v) in acc.iter_mut().zip(&tmp[(y + r + 1) * w..(y + r + 2) * w]) {
|
||||
*a += f64::from(*v);
|
||||
}
|
||||
}
|
||||
if y >= r {
|
||||
for (a, v) in acc.iter_mut().zip(&tmp[(y - r) * w..(y - r + 1) * w]) {
|
||||
*a -= f64::from(*v);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Guided filter (He, Sun & Tang 2013) with a fixed grayscale guide: made once per guide and
|
||||
/// radius, it keeps the guide's statistics so a slice costs only the arithmetic.
|
||||
struct GuidedFilter {
|
||||
guide: Vec<f32>,
|
||||
mean_i: Vec<f32>,
|
||||
var_i: Vec<f32>,
|
||||
bf: BoxFilter,
|
||||
eps: f32,
|
||||
}
|
||||
|
||||
impl GuidedFilter {
|
||||
fn new(guide: Vec<f32>, w: usize, h: usize, r: usize, eps: f32) -> GuidedFilter {
|
||||
let bf = BoxFilter::new(w, h, r);
|
||||
let mean_i = bf.mean(&guide);
|
||||
let ii: Vec<f32> = guide.iter().map(|v| v * v).collect();
|
||||
let var_i: Vec<f32> = bf.mean(&ii).iter().zip(&mean_i).map(|(v, m)| (v - m * m).max(0.0)).collect();
|
||||
GuidedFilter { guide, mean_i, var_i, bf, eps }
|
||||
}
|
||||
|
||||
/// The box-averaged linear coefficients `(ā, b̄)` such that `q ≈ ā·I + b̄`.
|
||||
fn coeffs(&self, p: &[f32]) -> (Vec<f32>, Vec<f32>) {
|
||||
let mean_p = self.bf.mean(p);
|
||||
let ip: Vec<f32> = self.guide.iter().zip(p).map(|(i, p)| i * p).collect();
|
||||
let corr_ip = self.bf.mean(&ip);
|
||||
let (mut a, mut b) = (vec![0.0f32; p.len()], vec![0.0f32; p.len()]);
|
||||
for k in 0..p.len() {
|
||||
let cov = corr_ip[k] - self.mean_i[k] * mean_p[k];
|
||||
a[k] = cov / (self.var_i[k] + self.eps);
|
||||
b[k] = mean_p[k] - a[k] * self.mean_i[k];
|
||||
}
|
||||
(self.bf.mean(&a), self.bf.mean(&b))
|
||||
}
|
||||
|
||||
fn filter(&self, p: &[f32]) -> Vec<f32> {
|
||||
let (a, b) = self.coeffs(p);
|
||||
(0..p.len()).map(|k| a[k] * self.guide[k] + b[k]).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ring difference filter taps `(dy, dx, weight)`: `+1/|disk|` for `r ≤ r_in`, `−1/|ring|` for
|
||||
/// `r_in < r ≤ r_out`.
|
||||
fn rdf_taps(r_in: usize, r_out: usize) -> Vec<(i64, i64, f32)> {
|
||||
let (ri2, ro2) = ((r_in * r_in) as i64, (r_out * r_out) as i64);
|
||||
let (mut disk, mut ring) = (Vec::new(), Vec::new());
|
||||
let r = r_out as i64;
|
||||
for dy in -r..=r {
|
||||
for dx in -r..=r {
|
||||
let d2 = dx * dx + dy * dy;
|
||||
if d2 <= ri2 {
|
||||
disk.push((dy, dx));
|
||||
} else if d2 <= ro2 {
|
||||
ring.push((dy, dx));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (wd, wr) = (1.0 / disk.len().max(1) as f32, -1.0 / ring.len().max(1) as f32);
|
||||
disk.into_iter().map(|(y, x)| (y, x, wd)).chain(ring.into_iter().map(|(y, x)| (y, x, wr))).collect()
|
||||
}
|
||||
|
||||
/// Per-pixel focus measure of a luminance plane: the magnitude of the ring difference filter,
|
||||
/// clamped borders.
|
||||
pub fn focus_measure(y: &[f32], w: usize, h: usize, r_in: usize, r_out: usize) -> Vec<f32> {
|
||||
let taps = rdf_taps(r_in, r_out.max(r_in + 1));
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
if w == 0 || h == 0 {
|
||||
return out;
|
||||
}
|
||||
par_rows(&mut out, w, 1, |yy, row| {
|
||||
for &(dy, dx, wt) in &taps {
|
||||
let sy = (yy as i64 + dy).clamp(0, h as i64 - 1) as usize;
|
||||
let s = &y[sy * w..sy * w + w];
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o += wt * s[(x as i64 + dx).clamp(0, w as i64 - 1) as usize];
|
||||
}
|
||||
}
|
||||
row.iter_mut().for_each(|v| *v = v.abs());
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Per-pixel state of the focus profile, updated one slice at a time.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Px {
|
||||
/// Best local maximum (value, left neighbour, right neighbour; −1 = none) and its index.
|
||||
c1: f32,
|
||||
l1: f32,
|
||||
r1: f32,
|
||||
i1: u32,
|
||||
/// Second-best local maximum (−1 = none).
|
||||
c2: f32,
|
||||
/// The last two slice values.
|
||||
prev: f32,
|
||||
prev2: f32,
|
||||
sum: f32,
|
||||
cmin: f32,
|
||||
}
|
||||
|
||||
impl Px {
|
||||
fn register(&mut self, val: f32, idx: u32, l: f32, r: f32) {
|
||||
if val > self.c1 {
|
||||
if self.c1 >= 0.0 {
|
||||
self.c2 = self.c1;
|
||||
}
|
||||
(self.c1, self.i1, self.l1, self.r1) = (val, idx, l, r);
|
||||
} else if val > self.c2 {
|
||||
self.c2 = val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The streaming peak search over the layer axis.
|
||||
struct PeakTracker {
|
||||
px: Vec<Px>,
|
||||
m: usize,
|
||||
}
|
||||
|
||||
impl PeakTracker {
|
||||
fn new(n: usize) -> PeakTracker {
|
||||
PeakTracker { px: vec![Px { c1: -1.0, l1: -1.0, r1: -1.0, i1: 0, c2: -1.0, prev: 0.0, prev2: 0.0, sum: 0.0, cmin: f32::INFINITY }; n], m: 0 }
|
||||
}
|
||||
|
||||
/// Fold the next slice (aggregated focus values ≥ 0).
|
||||
fn push(&mut self, c: &[f32]) {
|
||||
let m = self.m;
|
||||
for (p, &v) in self.px.iter_mut().zip(c) {
|
||||
if m >= 1 && (m == 1 || p.prev >= p.prev2) && p.prev > v {
|
||||
let l = if m >= 2 { p.prev2 } else { -1.0 };
|
||||
p.register(p.prev, (m - 1) as u32, l, v);
|
||||
}
|
||||
p.sum += v;
|
||||
p.cmin = p.cmin.min(v);
|
||||
(p.prev2, p.prev) = (p.prev, v);
|
||||
}
|
||||
self.m += 1;
|
||||
}
|
||||
|
||||
/// Close the profiles: the sub-layer depth and the raw confidence per pixel.
|
||||
fn finish(mut self, gate: f32) -> (Vec<f32>, Vec<f32>) {
|
||||
let n = self.m;
|
||||
if n == 0 {
|
||||
return (vec![0.0; self.px.len()], vec![0.0; self.px.len()]);
|
||||
}
|
||||
for p in self.px.iter_mut() {
|
||||
if n == 1 || p.prev >= p.prev2 {
|
||||
let l = if n >= 2 { p.prev2 } else { -1.0 };
|
||||
p.register(p.prev, (n - 1) as u32, l, -1.0);
|
||||
}
|
||||
}
|
||||
// The noise floor: the median of the per-pixel profile minimum (subsampled).
|
||||
let mut mins: Vec<f32> = self.px.iter().step_by(7).map(|p| if p.cmin.is_finite() { p.cmin } else { 0.0 }).collect();
|
||||
let floor = if mins.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
let mid = mins.len() / 2;
|
||||
*mins.select_nth_unstable_by(mid, |a, b| a.total_cmp(b)).1
|
||||
};
|
||||
let inv_n = 1.0 / n as f32;
|
||||
let out: Vec<(f32, f32)> = par_map(self.px.len(), |i| {
|
||||
let p = &self.px[i];
|
||||
let (c1, l, r) = (p.c1, p.l1, p.r1);
|
||||
let mut delta = 0.0f32;
|
||||
if l >= 0.0 && r >= 0.0 && c1 > 0.0 {
|
||||
// Gaussian interpolation (Nayar & Nakagawa 1994): a parabola in the log domain.
|
||||
let (ll, lc, lr) = (l.max(1e-12).ln(), c1.ln(), r.max(1e-12).ln());
|
||||
let den = ll - 2.0 * lc + lr;
|
||||
if den < 0.0 {
|
||||
delta = (0.5 * (ll - lr) / den).clamp(-0.5, 0.5);
|
||||
}
|
||||
}
|
||||
let conf = if c1 > 0.0 {
|
||||
let prom = (1.0 - p.sum * inv_n / c1).clamp(0.0, 1.0);
|
||||
// A rival local maximum of similar height means an ambiguous profile.
|
||||
let pkr = if p.c2 >= 0.0 { (1.0 - p.c2 / c1).clamp(0.0, 1.0) } else { 1.0 };
|
||||
let g = if gate > 0.0 && floor > 0.0 { ((c1 - floor) / (gate * floor)).clamp(0.0, 1.0) } else { 1.0 };
|
||||
prom * pkr * g
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
(p.i1 as f32 + delta, conf)
|
||||
});
|
||||
out.into_iter().unzip()
|
||||
}
|
||||
}
|
||||
|
||||
/// Scale the confidence so its 90th percentile maps to 1: `lambda` then means the same on every
|
||||
/// stack.
|
||||
fn normalize_conf(conf: &mut [f32]) {
|
||||
let mut sample: Vec<f32> = conf.iter().step_by(7).copied().collect();
|
||||
if sample.is_empty() {
|
||||
return;
|
||||
}
|
||||
let k = (sample.len() * 9 / 10).min(sample.len() - 1);
|
||||
let p90 = *sample.select_nth_unstable_by(k, |a, b| a.total_cmp(b)).1;
|
||||
if p90 > 1e-6 {
|
||||
conf.iter_mut().for_each(|c| *c = (*c / p90).min(1.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// 3×3 median, clamped borders.
|
||||
fn median3(src: &[f32], w: usize, h: usize) -> Vec<f32> {
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
par_rows(&mut out, w, 1, |y, row| {
|
||||
let ys = [y.saturating_sub(1), y, (y + 1).min(h - 1)];
|
||||
let mut v = [0.0f32; 9];
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let xs = [x.saturating_sub(1), x, (x + 1).min(w - 1)];
|
||||
for (k, (yy, xx)) in ys.iter().flat_map(|yy| xs.iter().map(move |xx| (*yy, *xx))).enumerate() {
|
||||
v[k] = src[yy * w + xx];
|
||||
}
|
||||
v.sort_unstable_by(|a, b| a.total_cmp(b));
|
||||
*o = v[4];
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Edge weights between horizontal and vertical neighbours: `exp(−|ΔI| / σ)`; `ax[i]` sits
|
||||
/// between `(x, y)` and `(x + 1, y)`, `ay[i]` between `(x, y)` and `(x, y + 1)`.
|
||||
fn edge_weights(guide: &[f32], w: usize, h: usize, sigma: f32) -> (Vec<f32>, Vec<f32>) {
|
||||
let inv = -1.0 / sigma.max(1e-6);
|
||||
let (mut ax, mut ay) = (vec![0.0f32; w * h], vec![0.0f32; w * h]);
|
||||
par_rows2(&mut ax, &mut ay, w, |y, rx, ry| {
|
||||
let g = &guide[y * w..y * w + w];
|
||||
for x in 0..w.saturating_sub(1) {
|
||||
rx[x] = ((g[x] - g[x + 1]).abs() * inv).exp();
|
||||
}
|
||||
if y + 1 < h {
|
||||
let g1 = &guide[(y + 1) * w..(y + 2) * w];
|
||||
for x in 0..w {
|
||||
ry[x] = ((g[x] - g1[x]).abs() * inv).exp();
|
||||
}
|
||||
}
|
||||
});
|
||||
(ax, ay)
|
||||
}
|
||||
|
||||
/// One 1-D weighted-least-squares line `(wd_i + λ(a_{i−1} + a_i)) u_i − λ a_{i−1} u_{i−1} −
|
||||
/// λ a_i u_{i+1} = wd_i f_i` by the Thomas algorithm; `a[i]` is the weight between `i` and
|
||||
/// `i + 1`; `scratch` holds the sweep's two coefficient lines.
|
||||
fn solve_line(u: &mut [f32], f: &[f32], wd: &[f32], a: &[f32], lam: f32, scratch: &mut [f32]) {
|
||||
let n = u.len();
|
||||
if n == 0 || scratch.len() < 2 * n {
|
||||
return;
|
||||
}
|
||||
let (cp, dp) = scratch.split_at_mut(n);
|
||||
let mut prev_a = 0.0f32;
|
||||
for i in 0..n {
|
||||
let ai = if i + 1 < n { a[i] } else { 0.0 };
|
||||
let diag = wd[i] + lam * (prev_a + ai);
|
||||
let lower = -lam * prev_a;
|
||||
let upper = -lam * ai;
|
||||
let (c0, d0) = if i > 0 { (cp[i - 1], dp[i - 1]) } else { (0.0, 0.0) };
|
||||
let m = diag - lower * c0;
|
||||
let m = if m.abs() < 1e-12 { 1e-12 } else { m };
|
||||
cp[i] = upper / m;
|
||||
dp[i] = (wd[i] * f[i] - lower * d0) / m;
|
||||
prev_a = ai;
|
||||
}
|
||||
u[n - 1] = dp[n - 1];
|
||||
for i in (0..n - 1).rev() {
|
||||
u[i] = dp[i] - cp[i] * u[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/// The row sweeps of the fast global smoother, in parallel over rows.
|
||||
fn solve_rows(u: &mut [f32], f: &[f32], wd: &[f32], ax: &[f32], w: usize, lam: f32) {
|
||||
par_rows(u, w, 1, |y, row| {
|
||||
let o = y * w;
|
||||
let mut scratch = vec![0.0f32; 2 * w];
|
||||
solve_line(row, &f[o..o + w], &wd[o..o + w], &ax[o..o + w], lam, &mut scratch);
|
||||
});
|
||||
}
|
||||
|
||||
/// The column sweeps: the planes are transposed, swept as rows, and transposed back.
|
||||
fn solve_cols(u: &mut [f32], f: &[f32], wd: &[f32], ay: &[f32], w: usize, h: usize, lam: f32) {
|
||||
let t = |p: &[f32]| -> Vec<f32> {
|
||||
let mut o = vec![0.0f32; w * h];
|
||||
par_rows(&mut o, h, 1, |x, col| {
|
||||
for (y, v) in col.iter_mut().enumerate() {
|
||||
*v = p[y * w + x];
|
||||
}
|
||||
});
|
||||
o
|
||||
};
|
||||
let (ft, wdt, ayt) = (t(f), t(wd), t(ay));
|
||||
let mut ut = vec![0.0f32; w * h];
|
||||
solve_rows(&mut ut, &ft, &wdt, &ayt, h, lam);
|
||||
par_rows(u, w, 1, |y, row| {
|
||||
for (x, v) in row.iter_mut().enumerate() {
|
||||
*v = ut[x * h + y];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The fast global smoother's three separable passes with the `λ_t` schedule of Min et al.
|
||||
/// 2014, the first pass carrying the data weights so holes are filled by interpolation, the
|
||||
/// later ones the previous output: the initial guess of [`wls_solve`].
|
||||
fn sweeps(d: &[f32], wd: &[f32], ex: &[f32], ey: &[f32], w: usize, h: usize, lambda: f32) -> Vec<f32> {
|
||||
const T: i32 = 3;
|
||||
let ones = vec![1.0f32; w * h];
|
||||
let mut u = vec![0.0f32; w * h];
|
||||
let mut f = d.to_vec();
|
||||
for t in 1..=T {
|
||||
let lam_t = 1.5 * lambda * 4f32.powi(T - t) / (4f32.powi(T) - 1.0);
|
||||
let wt: &[f32] = if t == 1 { wd } else { &ones };
|
||||
solve_rows(&mut u, &f, wt, ex, w, lam_t);
|
||||
f.copy_from_slice(&u);
|
||||
solve_cols(&mut u, &f, &ones, ey, w, h, lam_t);
|
||||
f.copy_from_slice(&u);
|
||||
}
|
||||
u
|
||||
}
|
||||
|
||||
/// The WLS operator `A = W + Σ λ a_pq` on one grid of the multigrid hierarchy, with the planes
|
||||
/// a V-cycle needs there.
|
||||
struct MgLevel {
|
||||
w: usize,
|
||||
h: usize,
|
||||
/// Data weight per cell; on the coarse grids the sum over the block.
|
||||
wd: Vec<f32>,
|
||||
/// `λ·a` between `(x, y)` and `(x + 1, y)`, and between `(x, y)` and `(x, y + 1)`; on the
|
||||
/// coarse grids the sum of the fine edges the block boundary cuts.
|
||||
ax: Vec<f32>,
|
||||
ay: Vec<f32>,
|
||||
/// `1 / diag(A)`.
|
||||
dinv: Vec<f32>,
|
||||
x: Vec<f32>,
|
||||
b: Vec<f32>,
|
||||
r: Vec<f32>,
|
||||
}
|
||||
|
||||
/// Damped-Jacobi weight (4/5 is the smoothing optimum of the 5-point stencil).
|
||||
const MG_OMEGA: f32 = 0.8;
|
||||
/// Smoothing sweeps before and after the coarse correction, and on the coarsest grid (where
|
||||
/// they are the solve).
|
||||
const MG_PRE: usize = 1;
|
||||
const MG_POST: usize = 1;
|
||||
const MG_COARSE: usize = 32;
|
||||
/// Coarsen until the grid is this small on its longer side.
|
||||
const MG_MIN: usize = 16;
|
||||
|
||||
impl MgLevel {
|
||||
fn new(w: usize, h: usize) -> MgLevel {
|
||||
let n = w * h;
|
||||
MgLevel { w, h, wd: vec![0.0; n], ax: vec![0.0; n], ay: vec![0.0; n], dinv: vec![0.0; n], x: vec![0.0; n], b: vec![0.0; n], r: vec![0.0; n] }
|
||||
}
|
||||
|
||||
/// `out_i = f(i, (A x)_i)` over the grid.
|
||||
fn apply<F: Fn(usize, f32) -> f32 + Sync + Send>(&self, x: &[f32], out: &mut [f32], f: F) {
|
||||
let (w, h) = (self.w, self.h);
|
||||
let (wd, ax, ay) = (&self.wd, &self.ax, &self.ay);
|
||||
par_rows(out, w, 1, |y, row| {
|
||||
let o = y * w;
|
||||
for (i, r) in row.iter_mut().enumerate() {
|
||||
let k = o + i;
|
||||
let xk = x[k];
|
||||
let mut v = wd[k] * xk;
|
||||
if i > 0 {
|
||||
v += ax[k - 1] * (xk - x[k - 1]);
|
||||
}
|
||||
if i + 1 < w {
|
||||
v += ax[k] * (xk - x[k + 1]);
|
||||
}
|
||||
if y > 0 {
|
||||
v += ay[k - w] * (xk - x[k - w]);
|
||||
}
|
||||
if y + 1 < h {
|
||||
v += ay[k] * (xk - x[k + w]);
|
||||
}
|
||||
*r = f(k, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn set_dinv(&mut self) {
|
||||
let (w, h) = (self.w, self.h);
|
||||
let (wd, ax, ay) = (&self.wd, &self.ax, &self.ay);
|
||||
par_rows(&mut self.dinv, w, 1, |y, row| {
|
||||
for (i, r) in row.iter_mut().enumerate() {
|
||||
let k = y * w + i;
|
||||
let mut v = wd[k];
|
||||
if i > 0 {
|
||||
v += ax[k - 1];
|
||||
}
|
||||
if i + 1 < w {
|
||||
v += ax[k];
|
||||
}
|
||||
if y > 0 {
|
||||
v += ay[k - w];
|
||||
}
|
||||
if y + 1 < h {
|
||||
v += ay[k];
|
||||
}
|
||||
*r = 1.0 / v.max(1e-12);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One damped-Jacobi sweep on `x` for `b`: `x += ω D⁻¹ (b − A x)`.
|
||||
fn jacobi(&mut self, zero_start: bool) {
|
||||
if zero_start {
|
||||
for ((x, b), d) in self.x.iter_mut().zip(&self.b).zip(&self.dinv) {
|
||||
*x = MG_OMEGA * d * b;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut r = std::mem::take(&mut self.r);
|
||||
{
|
||||
let (x, b, dinv) = (&self.x, &self.b, &self.dinv);
|
||||
self.apply(x, &mut r, |k, ax| x[k] + MG_OMEGA * dinv[k] * (b[k] - ax));
|
||||
}
|
||||
self.r = std::mem::replace(&mut self.x, r);
|
||||
}
|
||||
|
||||
/// The 2×2 aggregation of this grid: the Galerkin operator of a piecewise-constant
|
||||
/// prolongation (data weights summed over the block, the fine edges cut by a block boundary
|
||||
/// summed into the coarse edge).
|
||||
fn coarsen(&self) -> MgLevel {
|
||||
let (w, h) = (self.w, self.h);
|
||||
let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
|
||||
let mut c = MgLevel::new(cw, ch);
|
||||
self.coarsen_wd_into(&mut c);
|
||||
let (ax, ay) = (&self.ax, &self.ay);
|
||||
par_rows(&mut c.ax, cw, 1, |yy, row| {
|
||||
for y in 2 * yy..(2 * yy + 2).min(h) {
|
||||
for (xx, o) in row.iter_mut().enumerate() {
|
||||
if xx + 1 < cw {
|
||||
*o += ax[y * w + 2 * xx + 1];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
par_rows(&mut c.ay, cw, 1, |yy, row| {
|
||||
if yy + 1 < ch {
|
||||
let y = 2 * yy + 1;
|
||||
for (xx, o) in row.iter_mut().enumerate() {
|
||||
*o = ay[y * w..y * w + w][2 * xx..(2 * xx + 2).min(w)].iter().sum::<f32>();
|
||||
}
|
||||
}
|
||||
});
|
||||
c
|
||||
}
|
||||
|
||||
/// The data weights of the coarse grid `c` from this grid's (after a reweighting; the edges
|
||||
/// do not change).
|
||||
fn coarsen_wd_into(&self, c: &mut MgLevel) {
|
||||
let (w, h, cw) = (self.w, self.h, c.w);
|
||||
let wd = &self.wd;
|
||||
par_rows(&mut c.wd, cw, 1, |yy, row| {
|
||||
row.fill(0.0);
|
||||
for y in 2 * yy..(2 * yy + 2).min(h) {
|
||||
for (xx, o) in row.iter_mut().enumerate() {
|
||||
*o += wd[y * w..y * w + w][2 * xx..(2 * xx + 2).min(w)].iter().sum::<f32>();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// `x += P x_c`: the coarse correction injected (piecewise constant).
|
||||
fn prolong_add(x: &mut [f32], w: usize, xc: &[f32], cw: usize) {
|
||||
par_rows(x, w, 1, |y, row| {
|
||||
let c = &xc[(y / 2) * cw..(y / 2) * cw + cw];
|
||||
for (i, o) in row.iter_mut().enumerate() {
|
||||
*o += c[i / 2];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `b_c = Pᵀ r`: the residual summed over each block.
|
||||
fn restrict(r: &[f32], w: usize, h: usize, bc: &mut [f32], cw: usize) {
|
||||
par_rows(bc, cw, 1, |yy, row| {
|
||||
row.fill(0.0);
|
||||
for y in 2 * yy..(2 * yy + 2).min(h) {
|
||||
let s = &r[y * w..y * w + w];
|
||||
for (xx, o) in row.iter_mut().enumerate() {
|
||||
*o += s[2 * xx..(2 * xx + 2).min(w)].iter().sum::<f32>();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One V-cycle from `levels[0]` (whose `b` is set) into its `x`.
|
||||
fn vcycle(levels: &mut [MgLevel]) {
|
||||
let Some((top, rest)) = levels.split_first_mut() else { return };
|
||||
let Some(next) = rest.first_mut() else {
|
||||
for k in 0..MG_COARSE {
|
||||
top.jacobi(k == 0);
|
||||
}
|
||||
return;
|
||||
};
|
||||
for k in 0..MG_PRE {
|
||||
top.jacobi(k == 0);
|
||||
}
|
||||
{
|
||||
let mut r = std::mem::take(&mut top.r);
|
||||
let (x, b) = (&top.x, &top.b);
|
||||
top.apply(x, &mut r, |k, ax| b[k] - ax);
|
||||
top.r = r;
|
||||
}
|
||||
restrict(&top.r, top.w, top.h, &mut next.b, next.w);
|
||||
vcycle(rest);
|
||||
let Some(next) = rest.first() else { return };
|
||||
prolong_add(&mut top.x, top.w, &next.x, next.w);
|
||||
for _ in 0..MG_POST {
|
||||
top.jacobi(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Edge-aware WLS: `argmin_u Σ w_p (u_p − d_p)² + λ Σ a_pq (u_p − u_q)²`, the 2-D system
|
||||
/// `(W + λL) u = W d` solved by conjugate gradients from the separable sweeps' guess,
|
||||
/// preconditioned by one multigrid V-cycle (2×2 aggregation, damped Jacobi), so the low modes
|
||||
/// converge where the confidence is low over a large area (a flat wall). The solver keeps its
|
||||
/// hierarchy between solves, so a reweighting costs no rebuild.
|
||||
struct WlsSolver {
|
||||
w: usize,
|
||||
h: usize,
|
||||
lambda: f32,
|
||||
/// Edge weights `exp(−|ΔI| / σ)` (without λ), for the separable sweeps.
|
||||
ex: Vec<f32>,
|
||||
ey: Vec<f32>,
|
||||
levels: Vec<MgLevel>,
|
||||
}
|
||||
|
||||
impl WlsSolver {
|
||||
fn new(guide: &[f32], w: usize, h: usize, lambda: f32, sigma_c: f32) -> WlsSolver {
|
||||
let (ex, ey) = edge_weights(guide, w, h, sigma_c);
|
||||
let mut top = MgLevel::new(w, h);
|
||||
for (a, e) in top.ax.iter_mut().zip(&ex) {
|
||||
*a = lambda * e;
|
||||
}
|
||||
for (a, e) in top.ay.iter_mut().zip(&ey) {
|
||||
*a = lambda * e;
|
||||
}
|
||||
let mut levels = vec![top];
|
||||
while levels.last().is_some_and(|l| l.w.max(l.h) > MG_MIN) {
|
||||
let Some(last) = levels.last() else { break };
|
||||
let c = last.coarsen();
|
||||
levels.push(c);
|
||||
}
|
||||
WlsSolver { w, h, lambda, ex, ey, levels }
|
||||
}
|
||||
|
||||
/// The data weights: the confidence (plus a floor so the system is definite where nothing
|
||||
/// is known), aggregated down the hierarchy.
|
||||
fn set_weights(&mut self, conf: &[f32]) {
|
||||
const EPS_DATA: f32 = 1e-4;
|
||||
if let Some(top) = self.levels.first_mut() {
|
||||
for (w, c) in top.wd.iter_mut().zip(conf) {
|
||||
*w = c.max(0.0) + EPS_DATA;
|
||||
}
|
||||
}
|
||||
for l in 0..self.levels.len() {
|
||||
if l > 0 {
|
||||
let (fine, coarse) = self.levels.split_at_mut(l);
|
||||
if let (Some(f), Some(c)) = (fine.last(), coarse.first_mut()) {
|
||||
f.coarsen_wd_into(c);
|
||||
}
|
||||
}
|
||||
self.levels[l].set_dinv();
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve for the data `d`: the solution and its final relative residual.
|
||||
fn solve(&mut self, d: &[f32], max_iters: usize) -> (Vec<f32>, f32) {
|
||||
let (w, h, lambda) = (self.w, self.h, self.lambda);
|
||||
let n = w * h;
|
||||
let Some(top) = self.levels.first() else { return (vec![0.0; n], 0.0) };
|
||||
let mut u = sweeps(d, &top.wd, &self.ex, &self.ey, w, h, lambda);
|
||||
if w == 1 || h == 1 || n == 0 {
|
||||
return (u, 0.0);
|
||||
}
|
||||
let dot = |a: &[f32], b: &[f32]| -> f64 { a.iter().zip(b).map(|(x, y)| f64::from(*x) * f64::from(*y)).sum() };
|
||||
let b: Vec<f32> = top.wd.iter().zip(d).map(|(w, d)| w * d).collect();
|
||||
let bnorm = dot(&b, &b).sqrt().max(1e-30);
|
||||
let mut r = vec![0.0f32; n];
|
||||
top.apply(&u, &mut r, |k, au| b[k] - au);
|
||||
let precond = |levels: &mut [MgLevel], r: &[f32], z: &mut [f32]| {
|
||||
if let Some(top) = levels.first_mut() {
|
||||
top.b.copy_from_slice(r);
|
||||
}
|
||||
vcycle(levels);
|
||||
if let Some(top) = levels.first() {
|
||||
z.copy_from_slice(&top.x);
|
||||
}
|
||||
};
|
||||
let mut z = vec![0.0f32; n];
|
||||
precond(&mut self.levels, &r, &mut z);
|
||||
let mut p = z.clone();
|
||||
let mut ap = vec![0.0f32; n];
|
||||
let mut rz = dot(&r, &z);
|
||||
let mut rel = (dot(&r, &r).sqrt() / bnorm) as f32;
|
||||
for _ in 0..max_iters {
|
||||
if rel < 1e-5 {
|
||||
break;
|
||||
}
|
||||
let Some(top) = self.levels.first() else { break };
|
||||
top.apply(&p, &mut ap, |_, v| v);
|
||||
let pap = dot(&p, &ap);
|
||||
if pap <= 0.0 {
|
||||
break;
|
||||
}
|
||||
let alpha = (rz / pap) as f32;
|
||||
for (u, p) in u.iter_mut().zip(&p) {
|
||||
*u += alpha * p;
|
||||
}
|
||||
for (r, ap) in r.iter_mut().zip(&ap) {
|
||||
*r -= alpha * ap;
|
||||
}
|
||||
rel = (dot(&r, &r).sqrt() / bnorm) as f32;
|
||||
if rel < 1e-5 {
|
||||
break;
|
||||
}
|
||||
precond(&mut self.levels, &r, &mut z);
|
||||
let rz_new = dot(&r, &z);
|
||||
let beta = (rz_new / rz) as f32;
|
||||
rz = rz_new;
|
||||
for (p, z) in p.iter_mut().zip(&z) {
|
||||
*p = z + beta * *p;
|
||||
}
|
||||
}
|
||||
(u, rel)
|
||||
}
|
||||
}
|
||||
|
||||
/// Conjugate-gradient iteration cap of the regularisation.
|
||||
const CG_ITERS: usize = 200;
|
||||
|
||||
/// Depth from focus over the `n` layers' luminance planes `luma` (`w × h`, aligned), guided by
|
||||
/// the all-in-focus luminance `guide` of the same size. Without layers, or when `guide` or a
|
||||
/// plane is not `w × h` long, the map is empty: depth 0 and confidence 0 everywhere.
|
||||
pub fn depth_from_focus(luma: &[&[f32]], guide: &[f32], w: usize, h: usize, p: &DepthParams) -> DepthMap {
|
||||
let n = luma.len();
|
||||
let empty = n == 0 || w == 0 || h == 0 || guide.len() != w * h || luma.iter().any(|l| l.len() != w * h);
|
||||
if empty {
|
||||
return DepthMap { depth: vec![0.0; w * h], conf: vec![0.0; w * h], w, h };
|
||||
}
|
||||
let k = 1usize << p.scale.min(8);
|
||||
let (g, dw, dh) = block_mean(guide, w, h, k);
|
||||
let gf = GuidedFilter::new(g.clone(), dw, dh, p.agg_radius, p.agg_eps);
|
||||
let mut tracker = PeakTracker::new(dw * dh);
|
||||
for l in luma {
|
||||
let slice = block_mean(&focus_measure(l, w, h, p.r_in, p.r_out), w, h, k).0;
|
||||
if p.agg_radius > 0 {
|
||||
// The guided filter can undershoot; the profile statistics assume ≥ 0.
|
||||
let agg: Vec<f32> = gf.filter(&slice).into_iter().map(|v| v.max(0.0)).collect();
|
||||
tracker.push(&agg);
|
||||
} else {
|
||||
tracker.push(&slice);
|
||||
}
|
||||
}
|
||||
let (depth_w, mut conf) = tracker.finish(p.gate);
|
||||
let depth_w = median3(&depth_w, dw, dh);
|
||||
normalize_conf(&mut conf);
|
||||
let depth_w = if p.lambda > 0.0 {
|
||||
let mut solver = WlsSolver::new(&g, dw, dh, p.lambda, p.sigma_c);
|
||||
solver.set_weights(&conf);
|
||||
let (u, _) = solver.solve(&depth_w, CG_ITERS);
|
||||
if p.robust > 0.0 {
|
||||
// One reweighted step with a Huber loss on the data residual.
|
||||
let wd2: Vec<f32> = conf.iter().zip(&depth_w).zip(&u).map(|((c, d), u)| c * (p.robust / (d - u).abs().max(1e-6)).min(1.0)).collect();
|
||||
solver.set_weights(&wd2);
|
||||
solver.solve(&depth_w, CG_ITERS).0
|
||||
} else {
|
||||
u
|
||||
}
|
||||
} else {
|
||||
depth_w
|
||||
};
|
||||
let max_d = (n - 1) as f32;
|
||||
let up = GuidedFilter::new(g, dw, dh, 2, 1e-2);
|
||||
let depth: Vec<f32> = if k == 1 {
|
||||
up.filter(&depth_w)
|
||||
} else {
|
||||
let (a, b) = up.coeffs(&depth_w);
|
||||
let a = upsample_bilinear(&a, dw, dh, w, h, k);
|
||||
let b = upsample_bilinear(&b, dw, dh, w, h, k);
|
||||
(0..w * h).map(|i| a[i] * guide[i] + b[i]).collect()
|
||||
};
|
||||
let depth = depth.into_iter().map(|v| v.clamp(0.0, max_d)).collect();
|
||||
let conf = if k == 1 { conf } else { upsample_bilinear(&conf, dw, dh, w, h, k) };
|
||||
DepthMap { depth, conf, w, h }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lcg(seed: &mut u64) -> f32 {
|
||||
*seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
((*seed >> 33) % 10000) as f32 / 10000.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_filter_matches_the_naive_window() {
|
||||
let (w, h, r) = (23, 17, 3);
|
||||
let mut s = 5u64;
|
||||
let src: Vec<f32> = (0..w * h).map(|_| lcg(&mut s)).collect();
|
||||
let m = BoxFilter::new(w, h, r).mean(&src);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let (mut acc, mut cnt) = (0.0, 0.0);
|
||||
for yy in y.saturating_sub(r)..(y + r + 1).min(h) {
|
||||
for xx in x.saturating_sub(r)..(x + r + 1).min(w) {
|
||||
acc += src[yy * w + xx];
|
||||
cnt += 1.0;
|
||||
}
|
||||
}
|
||||
assert!((m[y * w + x] - acc / cnt).abs() < 1e-4, "({x},{y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guided_filter_with_a_flat_guide_is_a_double_box_mean() {
|
||||
let (w, h) = (40, 30);
|
||||
let mut s = 9u64;
|
||||
let p: Vec<f32> = (0..w * h).map(|_| lcg(&mut s)).collect();
|
||||
let q = GuidedFilter::new(vec![0.5; w * h], w, h, 2, 1e-3).filter(&p);
|
||||
let bf = BoxFilter::new(w, h, 2);
|
||||
let m = bf.mean(&bf.mean(&p));
|
||||
assert!(q.iter().zip(&m).all(|(a, b)| (a - b).abs() < 1e-4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ring_difference_is_zero_mean_and_sees_texture() {
|
||||
let taps = rdf_taps(1, 3);
|
||||
assert!(taps.iter().map(|t| t.2).sum::<f32>().abs() < 1e-6);
|
||||
let (w, h) = (32, 32);
|
||||
assert!(focus_measure(&vec![0.4; w * h], w, h, 1, 3).iter().all(|v| v.abs() < 1e-6));
|
||||
let check: Vec<f32> = (0..w * h).map(|i| if ((i % w) / 2 + (i / w) / 2).is_multiple_of(2) { 0.2 } else { 0.8 }).collect();
|
||||
assert!(focus_measure(&check, w, h, 1, 3).iter().cloned().fold(0.0, f32::max) > 0.1);
|
||||
let (m, dw, dh) = block_mean(&check, w, h, 2);
|
||||
assert_eq!((dw, dh, m.len()), (16, 16, 256));
|
||||
assert!(m.iter().all(|v| (v - 0.2).abs() < 1e-6 || (v - 0.8).abs() < 1e-6));
|
||||
let up = upsample_bilinear(&m, dw, dh, w, h, 2);
|
||||
assert_eq!(up.len(), w * h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peak_search_interpolates_between_layers() {
|
||||
// A profile peaking between layers 2 and 3 (log-parabola), one flat profile.
|
||||
let mut t = PeakTracker::new(2);
|
||||
for m in 0..6 {
|
||||
let v = (-((m as f32 - 2.4).powi(2)) / 2.0).exp();
|
||||
t.push(&[v, 0.1]);
|
||||
}
|
||||
let (d, c) = t.finish(0.0);
|
||||
assert!((d[0] - 2.4).abs() < 0.05, "{d:?}");
|
||||
assert!(c[0] > 0.5 && c[1] < 1e-6, "{c:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoothing_fills_holes_and_respects_edges() {
|
||||
let (w, h) = (40, 20);
|
||||
// A guide with a hard edge at x = 20; data known only at two pixels, one per side.
|
||||
let guide: Vec<f32> = (0..w * h).map(|i| if i % w < 20 { 0.0 } else { 1.0 }).collect();
|
||||
let mut d = vec![0.0f32; w * h];
|
||||
let mut wd = vec![1e-4f32; w * h];
|
||||
(d[10 * w + 5], wd[10 * w + 5]) = (1.0, 1.0);
|
||||
(d[10 * w + 35], wd[10 * w + 35]) = (5.0, 1.0);
|
||||
let mut solver = WlsSolver::new(&guide, w, h, 3.0, 0.04);
|
||||
solver.set_weights(&wd);
|
||||
let (u, rel) = solver.solve(&d, CG_ITERS);
|
||||
assert!(rel < 1e-4, "residual {rel}");
|
||||
// Each side follows its own sample (the data floor on the unknown pixels pulls a little
|
||||
// toward zero), and the edge keeps them apart.
|
||||
assert!((u[3 * w + 15] - 1.0).abs() < 0.15, "left side follows its sample: {}", u[3 * w + 15]);
|
||||
assert!((u[15 * w + 25] - 5.0).abs() < 0.6, "right side follows its sample: {}", u[15 * w + 25]);
|
||||
assert!(u[10 * w + 19] < 1.5 && u[10 * w + 20] > 4.0, "the edge holds: {} | {}", u[10 * w + 19], u[10 * w + 20]);
|
||||
// The sweeps alone leave the holes near zero; the solve fills them.
|
||||
let guess = sweeps(&d, &wd, &solver.ex, &solver.ey, w, h, 3.0);
|
||||
assert!(guess[3 * w + 15] < 0.5);
|
||||
assert_eq!(median3(&[0.5; 9], 3, 3)[4], 0.5);
|
||||
}
|
||||
|
||||
/// Three layers: the left third sharp in layer 0, the middle in 1, the right in 2. The depth
|
||||
/// map says so, sub-layer in between, with high confidence on the texture.
|
||||
#[test]
|
||||
fn depth_from_focus_finds_the_sharp_layer() {
|
||||
let (w, h) = (96, 48);
|
||||
let texture = |x: usize, y: usize| if ((x / 2) + (y / 2)).is_multiple_of(2) { 0.2 } else { 0.8 };
|
||||
let flat = 0.5;
|
||||
let layers: Vec<Vec<f32>> = (0..3).map(|k| (0..w * h).map(|i| if (i % w) / 32 == k { texture(i % w, i / w) } else { flat }).collect()).collect();
|
||||
let guide: Vec<f32> = (0..w * h).map(|i| texture(i % w, i / w)).collect();
|
||||
let refs: Vec<&[f32]> = layers.iter().map(Vec::as_slice).collect();
|
||||
let dm = depth_from_focus(&refs, &guide, w, h, &DepthParams::default());
|
||||
assert_eq!((dm.w, dm.h, dm.depth.len()), (w, h, w * h));
|
||||
for (x, want) in [(8, 0.0), (48, 1.0), (88, 2.0)] {
|
||||
let d = dm.depth[24 * w + x];
|
||||
assert!((d - want).abs() < 0.35, "x {x}: depth {d}, want {want}");
|
||||
assert!(dm.conf[24 * w + x] > 0.3, "x {x}: conf {}", dm.conf[24 * w + x]);
|
||||
}
|
||||
assert!(dm.depth.iter().all(|v| (0.0..=2.0).contains(v)));
|
||||
// Degenerate inputs are fine.
|
||||
assert_eq!(depth_from_focus(&[], &guide, w, h, &DepthParams::default()).depth, vec![0.0; w * h]);
|
||||
// A guide or a plane of the wrong length is no input: the empty map, never a panic.
|
||||
let empty = DepthMap { depth: vec![0.0; w * h], conf: vec![0.0; w * h], w, h };
|
||||
assert_eq!(depth_from_focus(&refs, &guide[1..], w, h, &DepthParams::default()), empty);
|
||||
let short = &refs[0][..w * h - 1];
|
||||
assert_eq!(depth_from_focus(&[refs[0], short], &guide, w, h, &DepthParams::default()), empty);
|
||||
assert_eq!(depth_from_focus(&refs, &guide, w + 1, h, &DepthParams::default()).w, w + 1);
|
||||
let one = depth_from_focus(&refs[..1], &guide, w, h, &DepthParams::default());
|
||||
assert!(one.depth.iter().all(|v| *v == 0.0));
|
||||
}
|
||||
}
|
||||
+42
-11
@@ -26,6 +26,7 @@ pub mod camera_raw;
|
||||
pub mod color_to_alpha;
|
||||
pub mod content_aware;
|
||||
mod denoise;
|
||||
pub mod dff;
|
||||
pub mod direct;
|
||||
mod distort;
|
||||
mod distort2;
|
||||
@@ -552,7 +553,8 @@ impl FilterParams {
|
||||
let g = |sigma: f32| Halo::Radius((sigma.max(0.0) * 3.0).ceil() as i32 + 1);
|
||||
match self {
|
||||
FilterParams::GaussianBlur { radius } | FilterParams::HighPass { radius } => g(*radius),
|
||||
FilterParams::UnsharpMask { radius, .. } | FilterParams::SmartSharpen { radius, .. } => g(*radius),
|
||||
FilterParams::UnsharpMask { radius, .. } => Halo::Radius(sharpen::exact::halo(*radius)),
|
||||
FilterParams::SmartSharpen { radius, .. } => g(*radius),
|
||||
FilterParams::BoxBlur { radius }
|
||||
| FilterParams::SurfaceBlur { radius, .. }
|
||||
| FilterParams::Median { radius }
|
||||
@@ -937,7 +939,8 @@ pub fn apply_in(surface: &Surface, params: &FilterParams, area: Rect, bounds: Re
|
||||
}
|
||||
|
||||
/// [`apply_in`] that can be cancelled (checked before each tile) and reports progress per tile
|
||||
/// group. `None` when `ctl` was cancelled; the input surface is never modified.
|
||||
/// group. `None` when cancelled, or when a checked filter rejects geometry/allocation;
|
||||
/// the input surface is never modified.
|
||||
pub fn apply_in_with(
|
||||
surface: &Surface,
|
||||
params: &FilterParams,
|
||||
@@ -969,13 +972,13 @@ pub fn apply_tiled(
|
||||
tile: i32,
|
||||
extent: Option<Rect>,
|
||||
) -> Surface {
|
||||
// Preserve the input if a checked Shape Blur allocation cannot be completed.
|
||||
// Preserve the input if a checked filter allocation cannot be completed.
|
||||
apply_tiled_with(surface, params, area, bounds, selection, tile, extent, &photocraft_raster::Interrupt::NONE).unwrap_or_else(|| surface.clone())
|
||||
}
|
||||
|
||||
/// [`apply_tiled`] with cancellation (checked before each tile, so a cancel takes effect within
|
||||
/// one tile's work) and progress (after each group of tiles). `None` when cancelled,
|
||||
/// or when Shape Blur cannot allocate a tile.
|
||||
/// or when a checked filter rejects geometry or cannot allocate a tile.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn apply_tiled_with(
|
||||
surface: &Surface,
|
||||
@@ -1000,15 +1003,27 @@ fn apply_tiled_with_impl(
|
||||
tile: i32,
|
||||
extent: Option<Rect>,
|
||||
ctl: &photocraft_raster::Interrupt,
|
||||
prepare_radial: bool,
|
||||
prepare_fast_paths: bool,
|
||||
) -> Option<Surface> {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
if let FilterParams::UnsharpMask { amount, radius, threshold } = *params
|
||||
&& (!sharpen::exact::valid_params(amount, radius, threshold)
|
||||
|| !sharpen::exact::valid_area(area)
|
||||
|| !sharpen::exact::valid_area(bounds)
|
||||
|| extent.is_some_and(|e| !sharpen::exact::valid_area(e)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut out = surface.clone();
|
||||
if area.is_empty() {
|
||||
return Some(out);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if prepare_fast_paths && let Some(result) = sharpen::fft::apply(surface, params, area, selection, extent, ctl) {
|
||||
return result;
|
||||
}
|
||||
if let Some(boxes) = blur::box_widths(params) {
|
||||
return apply_box_blur(out, surface, area, extent, selection, &boxes, ctl);
|
||||
}
|
||||
@@ -1016,15 +1031,15 @@ fn apply_tiled_with_impl(
|
||||
return result;
|
||||
}
|
||||
// The public tile override must not create a zero-step loop or an
|
||||
// unbounded Shape Blur scratch buffer. Standard automatic tiles are unchanged.
|
||||
let tile = if matches!(params, FilterParams::ShapeBlur { .. }) { tile.clamp(1, 2048) } else { tile };
|
||||
// unbounded scratch buffer for these checked filters. Automatic tiles are unchanged.
|
||||
let tile = if matches!(params, FilterParams::ShapeBlur { .. } | FilterParams::UnsharpMask { .. }) { tile.clamp(1, 2048) } else { tile };
|
||||
let fmt = surface.format();
|
||||
let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };
|
||||
// Prepare the immutable sample transforms once for all output tiles. If the
|
||||
// optional table allocation fails, use the existing sampler; only a real
|
||||
// cancellation returns None. Source reads keep their upstream semantics.
|
||||
let radial = match params {
|
||||
FilterParams::RadialBlur { amount, method, quality, center_x, center_y } if prepare_radial => {
|
||||
FilterParams::RadialBlur { amount, method, quality, center_x, center_y } if prepare_fast_paths => {
|
||||
blur::radial::Plan::for_area(bounds, *amount, *method, *quality, (*center_x, *center_y), area, ctl)
|
||||
}
|
||||
_ => None,
|
||||
@@ -1033,6 +1048,17 @@ fn apply_tiled_with_impl(
|
||||
return None;
|
||||
}
|
||||
let halo = params.halo_for(bounds);
|
||||
if matches!(params, FilterParams::UnsharpMask { .. }) {
|
||||
let Halo::Radius(reach) = halo else { return None };
|
||||
let (w, h) = (area.width().min(tile as u32) as usize, area.height().min(tile as u32) as usize);
|
||||
let read_samples = w.checked_add(2 * reach as usize)?.checked_mul(h.checked_add(2 * reach as usize)?)?.checked_mul(fmt.channels())?;
|
||||
let tile_count = u64::from(area.width()).div_ceil(tile as u64).checked_mul(u64::from(area.height()).div_ceil(tile as u64))?;
|
||||
// Reject hostile source-window sizes before Image::read allocates them.
|
||||
// Ordinary filter parameters and automatic tiles fit these bounds.
|
||||
if read_samples > 512 * 1024 * 1024 || read_samples.checked_mul(std::mem::size_of::<f32>())? > isize::MAX as usize || tile_count > 1_048_576 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let shared = (halo == Halo::Bounds).then(|| Image::read(surface, bounds.union(&area)));
|
||||
// Shape rasterization depends only on params, not on a tile's pixels.
|
||||
let shape = match params {
|
||||
@@ -1090,7 +1116,10 @@ fn apply_tiled_with_impl(
|
||||
None if ctl.cancelled() => None,
|
||||
None => Some(kernel(params, src, *t, &ctx)),
|
||||
},
|
||||
(None, None) => Some(kernel(params, src, *t, &ctx)),
|
||||
(None, None) => match *params {
|
||||
FilterParams::UnsharpMask { amount, radius, threshold } => sharpen::exact::run(src, *t, &ctx, amount, radius, threshold, ctl),
|
||||
_ => Some(kernel(params, src, *t, &ctx)),
|
||||
},
|
||||
}) else {
|
||||
return (*t, Vec::new());
|
||||
};
|
||||
@@ -1123,9 +1152,11 @@ fn apply_tiled_with_impl(
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
// Shape Blur can reject malformed geometry or an allocation failure.
|
||||
// Checked filters can reject malformed geometry or an allocation failure.
|
||||
// Do not hand an incomplete tile to Surface::write_region.
|
||||
if shape.is_some() && results.iter().any(|(t, data)| data.len() != t.width() as usize * t.height() as usize * fmt.channels()) {
|
||||
if (shape.is_some() || matches!(params, FilterParams::UnsharpMask { .. }))
|
||||
&& results.iter().any(|(t, data)| data.len() != t.width() as usize * t.height() as usize * fmt.channels())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for (t, data) in results {
|
||||
|
||||
@@ -6,6 +6,17 @@ use crate::Ctx;
|
||||
use crate::blur::{conv_sep, gaussian_kernel};
|
||||
use crate::image::Image;
|
||||
|
||||
pub(crate) mod exact;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) mod fft;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod fft_bench;
|
||||
|
||||
fn with_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, mut f: impl FnMut(f32, f32) -> f32) -> Vec<f32> {
|
||||
let k = gaussian_kernel(radius);
|
||||
let blurred = conv_sep(src, out, &k, &k, ctx.alpha);
|
||||
@@ -24,12 +35,7 @@ fn with_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, mut f: impl FnMut(f
|
||||
}
|
||||
|
||||
pub(crate) fn unsharp(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, threshold: f32) -> Vec<f32> {
|
||||
let k = amount / 100.0;
|
||||
let t = threshold / 255.0;
|
||||
with_blur(src, out, ctx, radius, |o, b| {
|
||||
let d = o - b;
|
||||
if d.abs() + 1e-6 >= t { o + k * d } else { o }
|
||||
})
|
||||
exact::run(src, out, ctx, amount, radius, threshold, &photocraft_raster::Interrupt::NONE).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn smart(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, reduce_noise: f32) -> Vec<f32> {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Exact separable convolution for Unsharp Mask: stream one source row and reuse
|
||||
//! the blurred output for the final arithmetic. Each sample retains its tap order.
|
||||
use crate::image::premultiply;
|
||||
use crate::{Ctx, Image};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Interrupt;
|
||||
|
||||
const MAX_SAMPLES: usize = 128 * 1024 * 1024;
|
||||
// The filter dialog caps radius at 1000. Preserve Details resampling can ask
|
||||
// for more; permit that while the unchanged kernel's i32 square is safe.
|
||||
const MAX_RADIUS: f32 = 15_446.0;
|
||||
|
||||
pub(crate) fn valid_params(amount: f32, radius: f32, threshold: f32) -> bool {
|
||||
amount.is_finite() && threshold.is_finite() && radius.is_finite() && (0.0..=MAX_RADIUS).contains(&radius)
|
||||
}
|
||||
|
||||
pub(crate) fn halo(radius: f32) -> i32 {
|
||||
if radius.is_finite() && (0.0..=MAX_RADIUS).contains(&radius) { (radius * 3.0).ceil() as i32 + 1 } else { 0 }
|
||||
}
|
||||
|
||||
pub(crate) fn valid_area(r: Rect) -> bool {
|
||||
r.x0 <= r.x1
|
||||
&& r.y0 <= r.y1
|
||||
&& r.width() <= 300_000
|
||||
&& r.height() <= 300_000
|
||||
&& [r.x0, r.x1, r.y0, r.y1].iter().all(|v| (-1_000_000..=1_000_000).contains(v))
|
||||
}
|
||||
|
||||
fn zeros(len: usize) -> Option<Vec<f32>> {
|
||||
if len > MAX_SAMPLES {
|
||||
return None;
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(len).ok()?;
|
||||
data.resize(len, 0.0);
|
||||
Some(data)
|
||||
}
|
||||
|
||||
/// Checked contiguous row copy, with the same zero extension as Image::get.
|
||||
fn read_row(src: &Image, x0: i32, x1: i32, y: i32, dst: &mut [f32]) -> Option<()> {
|
||||
dst.fill(0.0);
|
||||
if y < src.rect.y0 || y >= src.rect.y1 {
|
||||
return Some(());
|
||||
}
|
||||
let (lo, hi) = (x0.max(src.rect.x0), x1.min(src.rect.x1));
|
||||
if lo >= hi {
|
||||
return Some(());
|
||||
}
|
||||
let n = src.ch;
|
||||
let count = usize::try_from(i64::from(hi) - i64::from(lo)).ok()?.checked_mul(n)?;
|
||||
let offset = usize::try_from(i64::from(lo) - i64::from(x0)).ok()?.checked_mul(n)?;
|
||||
let row = usize::try_from(i64::from(y) - i64::from(src.rect.y0)).ok()?;
|
||||
let col = usize::try_from(i64::from(lo) - i64::from(src.rect.x0)).ok()?;
|
||||
let start = row.checked_mul(src.rect.width() as usize)?.checked_add(col)?.checked_mul(n)?;
|
||||
dst.get_mut(offset..offset.checked_add(count)?)?.copy_from_slice(src.data.get(start..start.checked_add(count)?)?);
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn run(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, threshold: f32, ctl: &Interrupt) -> Option<Vec<f32>> {
|
||||
if ctl.cancelled() || !valid_params(amount, radius, threshold) || !valid_area(out) || !valid_area(src.rect) {
|
||||
return None;
|
||||
}
|
||||
let n = src.ch;
|
||||
if n == 0 || n > crate::fxutil::MAXC {
|
||||
return None;
|
||||
}
|
||||
if src.data.len() != (src.rect.width() as usize).checked_mul(src.rect.height() as usize)?.checked_mul(n)? {
|
||||
return None;
|
||||
}
|
||||
if out.is_empty() {
|
||||
return Some(Vec::new());
|
||||
}
|
||||
let kernel = super::gaussian_kernel(radius);
|
||||
let r = kernel.len() / 2;
|
||||
let (ow, oh) = (out.width() as usize, out.height() as usize);
|
||||
let row_len = ow.checked_mul(n)?;
|
||||
let th = oh.checked_add(2 * r)?;
|
||||
let ww = ow.checked_add(2 * r)?;
|
||||
let (x0, x1, y0) = (out.x0.checked_sub(r as i32)?, out.x1.checked_add(r as i32)?, out.y0.checked_sub(r as i32)?);
|
||||
let mut row = zeros(ww.checked_mul(n)?)?;
|
||||
let mut tmp = zeros(row_len.checked_mul(th)?)?;
|
||||
let mut result = zeros(row_len.checked_mul(oh)?)?;
|
||||
for (y, dst) in tmp.chunks_exact_mut(row_len).enumerate() {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
read_row(src, x0, x1, y0.checked_add(y as i32)?, &mut row)?;
|
||||
premultiply(&mut row, n, ctx.alpha);
|
||||
// Tap-major traversal exposes contiguous independent samples to LLVM. No
|
||||
// reduction, tap merging, symmetry or fused multiply-add changes the sums.
|
||||
for (i, weight) in kernel.iter().enumerate() {
|
||||
let start = i.checked_mul(n)?;
|
||||
let samples = row.get(start..start.checked_add(row_len)?)?;
|
||||
for (d, s) in dst.iter_mut().zip(samples) {
|
||||
*d += s * weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (amount, threshold) = (amount / 100.0, threshold / 255.0);
|
||||
let cc = n - usize::from(ctx.alpha);
|
||||
for (y, dst) in result.chunks_exact_mut(row_len).enumerate() {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
for (i, weight) in kernel.iter().enumerate() {
|
||||
let start = y.checked_add(i)?.checked_mul(row_len)?;
|
||||
let samples = tmp.get(start..start.checked_add(row_len)?)?;
|
||||
for (d, s) in dst.iter_mut().zip(samples) {
|
||||
*d += s * weight;
|
||||
}
|
||||
}
|
||||
let originals = row.get_mut(..row_len)?;
|
||||
read_row(src, out.x0, out.x1, out.y0.checked_add(y as i32)?, originals)?;
|
||||
for (blurred, original) in dst.chunks_exact_mut(n).zip(originals.chunks_exact(n)) {
|
||||
if ctx.alpha && *original.last()? <= 0.0 {
|
||||
blurred.copy_from_slice(original);
|
||||
continue;
|
||||
}
|
||||
let a = if ctx.alpha { *blurred.last()? } else { 1.0 };
|
||||
for (b, o) in blurred.iter_mut().zip(original).take(cc) {
|
||||
// Keep the original unpremultiply cut-off and division, followed by
|
||||
// the threshold epsilon and inclusive comparison, at every depth.
|
||||
let b_value = if ctx.alpha { if a > 1e-7 { *b / a } else { 0.0 } } else { *b };
|
||||
let d = o - b_value;
|
||||
*b = if d.abs() + 1e-6 >= threshold { o + amount * d } else { *o };
|
||||
}
|
||||
if ctx.alpha {
|
||||
*blurred.last_mut()? = *original.last()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
//! Wide exact-kernel Gaussian convolution using FFTs. Summation order changes:
|
||||
//! positive thresholds and unstable samples retain the sequential f32 fallback.
|
||||
use crate::{FilterParams, Image};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
use rayon::prelude::*;
|
||||
use rustfft::{Fft, FftPlanner, num_complex::Complex};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
const MAX_BYTES: usize = 1 << 30;
|
||||
const MAX_SIDE: usize = 32_768;
|
||||
const STRIPE: usize = 32;
|
||||
type Number = Complex<f64>;
|
||||
|
||||
fn buffer<T: Clone>(len: usize, value: T) -> Option<Vec<T>> {
|
||||
if len.checked_mul(std::mem::size_of::<T>())? > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
data.try_reserve_exact(len).ok()?;
|
||||
data.resize(len, value);
|
||||
Some(data)
|
||||
}
|
||||
|
||||
struct Plan {
|
||||
size: usize,
|
||||
forward: Arc<dyn Fft<f64>>,
|
||||
inverse: Arc<dyn Fft<f64>>,
|
||||
spectrum: Vec<Number>,
|
||||
scratch: usize,
|
||||
}
|
||||
impl Plan {
|
||||
fn new(needed: usize, kernel: &[f32], planner: &mut FftPlanner<f64>) -> Option<Self> {
|
||||
let size = needed.checked_next_power_of_two()?;
|
||||
if size > MAX_SIDE || kernel.len() > size {
|
||||
return None;
|
||||
}
|
||||
let forward = planner.plan_fft_forward(size);
|
||||
let inverse = planner.plan_fft_inverse(size);
|
||||
let scratch = forward.get_inplace_scratch_len().max(inverse.get_inplace_scratch_len());
|
||||
let mut spectrum = buffer(size, Number::default())?;
|
||||
for (dst, &weight) in spectrum.iter_mut().zip(kernel) {
|
||||
dst.re = f64::from(weight) / size as f64;
|
||||
}
|
||||
forward.process_with_scratch(&mut spectrum, &mut buffer(scratch, Number::default())?);
|
||||
Some(Self { size, forward, inverse, spectrum, scratch })
|
||||
}
|
||||
fn work(&self) -> Option<(Vec<Number>, Vec<Number>)> {
|
||||
Some((buffer(self.size, Number::default())?, buffer(self.scratch, Number::default())?))
|
||||
}
|
||||
fn convolve(&self, data: &mut [Number], scratch: &mut [Number]) -> Option<()> {
|
||||
if data.len() != self.size || scratch.len() < self.scratch {
|
||||
return None;
|
||||
}
|
||||
self.forward.process_with_scratch(data, scratch);
|
||||
for (d, k) in data.iter_mut().zip(&self.spectrum) {
|
||||
*d *= k;
|
||||
}
|
||||
self.inverse.process_with_scratch(data, scratch);
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
// Bound the complete temporary working set, including all concurrently live
|
||||
// column gathers, originals, FFT scratch and result stripes. Document tiles are
|
||||
// excluded, just as in the existing tile scheduler's scratch budget.
|
||||
fn group_size(resident: usize, worker: usize, count: usize, workers: usize) -> Option<usize> {
|
||||
let group = MAX_BYTES.checked_sub(resident)?.checked_div(worker.max(1))?.min(workers).min(count);
|
||||
(group > 0).then_some(group)
|
||||
}
|
||||
|
||||
/// `None` declines the optimization, `Some(None)` propagates cancellation.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn apply(
|
||||
surface: &Surface,
|
||||
params: &FilterParams,
|
||||
area: Rect,
|
||||
selection: Option<&Surface>,
|
||||
extent: Option<Rect>,
|
||||
ctl: &Interrupt,
|
||||
) -> Option<Option<Surface>> {
|
||||
let FilterParams::UnsharpMask { amount, radius, threshold } = *params else { return None };
|
||||
// At a positive threshold, even a tiny sum-order difference can switch the
|
||||
// entire sharpen contribution. Zero/negative thresholds always keep it.
|
||||
if !(64.0..=1000.0).contains(&radius)
|
||||
|| threshold > 0.0
|
||||
|| amount == 0.0
|
||||
|| !super::exact::valid_params(amount, radius, threshold)
|
||||
|| !super::exact::valid_area(area)
|
||||
|| area.is_empty()
|
||||
|| u64::from(area.width()) * u64::from(area.height()) < 65_536
|
||||
|| !(1..=crate::fxutil::MAXC).contains(&surface.channels())
|
||||
|| selection.is_some_and(|s| s.channels() == 0)
|
||||
|| extent.is_some_and(|e| !super::exact::valid_area(e) || area.intersect(&e) != area)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return Some(None);
|
||||
}
|
||||
match run(surface, area, amount, radius, selection, extent, ctl) {
|
||||
Some(out) => Some(Some(out)),
|
||||
None if ctl.cancelled() => Some(None),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run(surface: &Surface, area: Rect, amount: f32, radius: f32, selection: Option<&Surface>, extent: Option<Rect>, ctl: &Interrupt) -> Option<Surface> {
|
||||
let (w, h, n) = (area.width() as usize, area.height() as usize, surface.channels());
|
||||
let alpha = surface.format().alpha;
|
||||
let kernel = super::gaussian_kernel(radius);
|
||||
let r = kernel.len() / 2;
|
||||
let reach = i32::try_from(r).ok()?;
|
||||
let (x0, x1) = (area.x0.checked_sub(reach)?, area.x1.checked_add(reach)?);
|
||||
let (y0, y1) = (area.y0.checked_sub(reach)?, area.y1.checked_add(reach)?);
|
||||
let (read_x0, read_x1, read_y0, read_y1) = match extent {
|
||||
Some(e) => (x0.max(e.x0), x1.min(e.x1), y0.max(e.y0), y1.min(e.y1)),
|
||||
None => (x0, x1, y0, y1),
|
||||
};
|
||||
let rows = usize::try_from(i64::from(read_y1) - i64::from(read_y0)).ok()?;
|
||||
let read_width = usize::try_from(i64::from(read_x1) - i64::from(read_x0)).ok()?;
|
||||
let row_len = w.checked_mul(n)?;
|
||||
let samples = row_len.checked_mul(rows)?;
|
||||
let resident = samples.checked_mul(4)?;
|
||||
let mut planner = FftPlanner::<f64>::new();
|
||||
let horizontal = Plan::new(w.checked_add(2 * r)?, &kernel, &mut planner)?;
|
||||
let vertical = Plan::new(h.checked_add(2 * r)?, &kernel, &mut planner)?;
|
||||
// A conservative allowance includes FFT plans/twiddles in addition to spectra.
|
||||
let plans = horizontal.size.checked_add(vertical.size)?.checked_mul(256)?;
|
||||
let resident = resident.checked_add(plans)?;
|
||||
let workers = rayon::current_num_threads().max(1);
|
||||
let horizontal_worker = read_width.checked_mul(n)?.checked_mul(4)?.checked_add(horizontal.size.checked_add(horizontal.scratch)?.checked_mul(16)?)?;
|
||||
let vertical_worker = STRIPE
|
||||
.checked_mul(rows)?
|
||||
.checked_mul(n)?
|
||||
.checked_mul(4)?
|
||||
.checked_add(STRIPE.checked_mul(h)?.checked_mul(n)?.checked_mul(12)?)?
|
||||
.checked_add(vertical.size.checked_add(vertical.scratch)?.checked_mul(16)?)?;
|
||||
let group = group_size(resident, horizontal_worker.max(vertical_worker), w.div_ceil(STRIPE), workers)?;
|
||||
let mut tmp = buffer(samples, 0.0f32)?;
|
||||
let finished = AtomicUsize::new(0);
|
||||
// Read each needed real row once. Outside a repeated extent, horizontal
|
||||
// results are repeated lazily by the vertical gather, not transformed again.
|
||||
for band in tmp.chunks_mut(row_len.checked_mul(group)?) {
|
||||
let first = finished.load(Ordering::Relaxed);
|
||||
let ok: Option<Vec<()>> = band
|
||||
.par_chunks_exact_mut(row_len)
|
||||
.enumerate()
|
||||
.map(|(offset, dst)| {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
let y = read_y0.checked_add(i32::try_from(first.checked_add(offset)?).ok()?)?;
|
||||
let mut row = buffer(read_width.checked_mul(n)?, 0.0f32)?;
|
||||
// Reservation above covers resize, so the reusable raster read cannot allocate.
|
||||
surface.read_region_into(Rect::new(read_x0, y, read_x1, y.checked_add(1)?), &mut row);
|
||||
let mut scales = [0.0f64; crate::fxutil::MAXC];
|
||||
for px in row.chunks_exact_mut(n) {
|
||||
if px.iter().any(|v| !v.is_finite() || v.abs() > 1e6) || (alpha && !px.last().is_some_and(|a| (0.0..=1.0).contains(a))) {
|
||||
return None;
|
||||
}
|
||||
let a = if alpha { *px.last()? } else { 1.0 };
|
||||
for (c, v) in px.iter_mut().enumerate() {
|
||||
if alpha && c + 1 < n {
|
||||
*v *= a;
|
||||
}
|
||||
let scale = scales.get_mut(c)?;
|
||||
*scale = scale.max(f64::from(v.abs()));
|
||||
}
|
||||
}
|
||||
let (mut data, mut scratch) = horizontal.work()?;
|
||||
for channel in (0..n).step_by(2) {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
data.fill(Number::default());
|
||||
for (i, d) in data.iter_mut().take(w + 2 * r).enumerate() {
|
||||
let sx = x0.checked_add(i32::try_from(i).ok()?)?.clamp(read_x0, read_x1.checked_sub(1)?);
|
||||
let start = usize::try_from(sx - read_x0).ok()?.checked_mul(n)?;
|
||||
let px = row.get(start..start.checked_add(n)?)?;
|
||||
let sample = |c: usize| -> f64 {
|
||||
match (px.get(c), scales.get(c)) {
|
||||
(Some(v), Some(s)) if *s > 0.0 => f64::from(*v) / s,
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
*d = Number::new(sample(channel), sample(channel + 1));
|
||||
}
|
||||
horizontal.convolve(&mut data, &mut scratch)?;
|
||||
for (px, d) in dst.chunks_exact_mut(n).zip(data.get(2 * r..2 * r + w)?) {
|
||||
*px.get_mut(channel)? = (d.re * scales.get(channel)?) as f32;
|
||||
if let Some(v) = px.get_mut(channel + 1) {
|
||||
*v = (d.im * scales.get(channel + 1)?) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
finished.fetch_add(1, Ordering::Relaxed);
|
||||
Some(())
|
||||
})
|
||||
.collect();
|
||||
ok?;
|
||||
ctl.progress(0.5 * finished.load(Ordering::Relaxed) as f32 / rows as f32);
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut out = surface.clone();
|
||||
let count = w.div_ceil(STRIPE);
|
||||
for first in (0..count).step_by(group) {
|
||||
let end = first.checked_add(group)?.min(count);
|
||||
let results: Option<Vec<_>> = (first..end)
|
||||
.into_par_iter()
|
||||
.map(|index| {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
let x = index.checked_mul(STRIPE)?;
|
||||
let width = STRIPE.min(w.checked_sub(x)?);
|
||||
let mut columns = buffer(width.checked_mul(rows)?.checked_mul(n)?, 0.0f32)?;
|
||||
for (y, row) in tmp.chunks_exact(row_len).enumerate() {
|
||||
if y % 64 == 0 && ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
for (c, px) in row.get(x * n..(x + width) * n)?.chunks_exact(n).enumerate() {
|
||||
let start = (c * rows + y) * n;
|
||||
columns.get_mut(start..start + n)?.copy_from_slice(px);
|
||||
}
|
||||
}
|
||||
let rect = Rect::new(area.x0.checked_add(x as i32)?, area.y0, area.x0.checked_add((x + width) as i32)?, area.y1);
|
||||
let len = width.checked_mul(h)?.checked_mul(n)?;
|
||||
let mut result = buffer(len, 0.0f32)?;
|
||||
let mut original = buffer(len, 0.0f32)?;
|
||||
surface.read_region_into(rect, &mut original);
|
||||
let (mut data, mut scratch) = vertical.work()?;
|
||||
for (c, samples) in columns.chunks_exact(rows * n).enumerate() {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
let mut scales = [0.0f64; crate::fxutil::MAXC];
|
||||
for px in samples.chunks_exact(n) {
|
||||
for (s, v) in scales.iter_mut().zip(px) {
|
||||
*s = s.max(f64::from(v.abs()));
|
||||
}
|
||||
}
|
||||
for channel in (0..n).step_by(2) {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
data.fill(Number::default());
|
||||
for (i, d) in data.iter_mut().take(h + 2 * r).enumerate() {
|
||||
let sy = y0.checked_add(i as i32)?.clamp(read_y0, read_y1.checked_sub(1)?);
|
||||
let start = usize::try_from(sy - read_y0).ok()?.checked_mul(n)?;
|
||||
let px = samples.get(start..start + n)?;
|
||||
let sample = |c: usize| -> f64 {
|
||||
match (px.get(c), scales.get(c)) {
|
||||
(Some(v), Some(s)) if *s > 0.0 => f64::from(*v) / s,
|
||||
_ => 0.0,
|
||||
}
|
||||
};
|
||||
*d = Number::new(sample(channel), sample(channel + 1));
|
||||
}
|
||||
vertical.convolve(&mut data, &mut scratch)?;
|
||||
for (y, d) in data.get(2 * r..2 * r + h)?.iter().enumerate() {
|
||||
let start = (y * width + c) * n;
|
||||
*result.get_mut(start + channel)? = (d.re * scales.get(channel)?) as f32;
|
||||
if let Some(v) = result.get_mut(start + channel + 1).filter(|_| channel + 1 < n) {
|
||||
*v = (d.im * scales.get(channel + 1)?) as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (px, o) in result.chunks_exact_mut(n).zip(original.chunks_exact(n)) {
|
||||
if alpha && *o.last()? <= 0.0 {
|
||||
px.copy_from_slice(o);
|
||||
continue;
|
||||
}
|
||||
let a = if alpha { *px.last()? } else { 1.0 };
|
||||
// Near the original unpremultiply cutoff, cancellation/FFT noise
|
||||
// or f32 sum order can expose colour. Decline the whole fast path.
|
||||
let uncertainty = 4.0 * kernel.len() as f32 * f32::EPSILON;
|
||||
if alpha && a <= 1e-7 + uncertainty {
|
||||
return None;
|
||||
}
|
||||
for (v, o) in px.iter_mut().zip(o).take(n - usize::from(alpha)) {
|
||||
let b = if alpha { *v / a } else { *v };
|
||||
*v = o + amount / 100.0 * (o - b);
|
||||
if !v.is_finite() {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
if alpha {
|
||||
*px.last_mut()? = *o.last()?;
|
||||
}
|
||||
}
|
||||
if let Some(sel) = selection {
|
||||
crate::mix_selection(&mut result, rect, sel, &Image { rect, ch: n, data: original }, alpha);
|
||||
}
|
||||
Some((rect, result))
|
||||
})
|
||||
.collect();
|
||||
for (rect, data) in results? {
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
out.try_write_region(rect, &data).ok()?;
|
||||
}
|
||||
ctl.progress(0.5 + 0.48 * end as f32 / count as f32);
|
||||
}
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
out.prune();
|
||||
if ctl.cancelled() {
|
||||
return None;
|
||||
}
|
||||
ctl.progress(1.0);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,146 @@
|
||||
use super::*;
|
||||
use crate::sharpen::tests::{reference, source};
|
||||
use crate::{Ctx, image::Image};
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
|
||||
fn compare(old: &Surface, new: &Surface, area: Rect) {
|
||||
let tolerance = match old.format().sample {
|
||||
SampleType::U8 => 1.0 / 255.0 + 1e-7,
|
||||
SampleType::U16 => 2.0 / 65535.0 + 1e-7,
|
||||
SampleType::F32 => 3e-5,
|
||||
};
|
||||
for (a, b) in old.read_region(area).iter().zip(new.read_region(area)) {
|
||||
let limit = if old.format().sample == SampleType::F32 { tolerance * (1.0 + a.abs()) } else { tolerance };
|
||||
assert!((a - b).abs() <= limit, "{a} != {b}, tolerance {limit}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fft_preserves_gaussian_quality_at_every_depth_and_model() {
|
||||
let area = Rect::new(-3, 2, 10, 13);
|
||||
for mode in [
|
||||
ColorMode::Bitmap,
|
||||
ColorMode::Grayscale,
|
||||
ColorMode::Duotone,
|
||||
ColorMode::Indexed,
|
||||
ColorMode::Rgb,
|
||||
ColorMode::Cmyk,
|
||||
ColorMode::Lab,
|
||||
ColorMode::Multichannel,
|
||||
] {
|
||||
for depth in SampleType::ALL {
|
||||
for alpha in [false, true] {
|
||||
let s = source(area, PixelFormat::new(mode, depth, alpha));
|
||||
let ctx = Ctx { bounds: area, mode, alpha };
|
||||
for radius in [3.25, 64.0] {
|
||||
let src = Image::read_clamped(&s, area.inflate((radius * 3.0_f32).ceil() as i32 + 1), area);
|
||||
let pixels = reference::unsharp(&src, area, &ctx, 500.0, radius, 0.0);
|
||||
let mut expected = s.clone();
|
||||
expected.write_region(area, &pixels);
|
||||
let actual = run(&s, area, 500.0, radius, None, Some(area), &Interrupt::NONE).unwrap();
|
||||
compare(&expected, &actual, area);
|
||||
if alpha {
|
||||
for (a, b) in s.read_region(area).chunks_exact(s.channels()).zip(actual.read_region(area).chunks_exact(s.channels())) {
|
||||
assert_eq!(a.last(), b.last());
|
||||
if a.last() == Some(&0.0) {
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fft_keeps_partial_regions_selections_and_edge_policies() {
|
||||
let extent = Rect::new(-7, -9, 35, 39);
|
||||
let area = Rect::new(-3, 2, 19, 23);
|
||||
let mut sel = Surface::new(PixelFormat::GRAY8);
|
||||
sel.fill_rect(area, &[0.4]);
|
||||
for depth in SampleType::ALL {
|
||||
let s = source(extent, PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
let p = FilterParams::UnsharpMask { amount: 150.0, radius: 64.0, threshold: 0.0 };
|
||||
for edge in [None, Some(extent)] {
|
||||
let expected = crate::sharpen::tests::apply_reference(&s, &p, area, extent, Some(&sel), edge, 256);
|
||||
let actual = run(&s, area, 150.0, 64.0, Some(&sel), edge, &Interrupt::NONE).unwrap();
|
||||
compare(&expected, &actual, extent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fft_falls_back_for_thresholds_and_unstable_samples() {
|
||||
let area = Rect::new(0, 0, 256, 256);
|
||||
let mut s = source(area, PixelFormat::RGBA32F);
|
||||
let p = FilterParams::UnsharpMask { amount: 150.0, radius: 64.0, threshold: 8.0 };
|
||||
assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
|
||||
let p = FilterParams::UnsharpMask { amount: 150.0, radius: 64.0, threshold: 0.0 };
|
||||
s.fill_rect(Rect::new(0, 0, 1, 1), &[f32::NAN, 0.5, 0.5, 1.0]);
|
||||
assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
|
||||
s.fill_rect(area, &[0.5, 0.5, 0.5, 1e-8]);
|
||||
assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
|
||||
s.fill_rect(area, &[0.5, 0.5, 0.5, -0.1]);
|
||||
assert!(apply(&s, &p, area, None, Some(area), &Interrupt::NONE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fft_cancellation_discards_partial_work_and_bounds_scratch() {
|
||||
let area = Rect::new(0, 0, 256, 256);
|
||||
let s = source(area, PixelFormat::RGBA8);
|
||||
let original = s.to_interleaved(area);
|
||||
let p = FilterParams::UnsharpMask { amount: 150.0, radius: 300.0, threshold: 0.0 };
|
||||
let flag = std::sync::atomic::AtomicBool::new(false);
|
||||
let cancel = || flag.load(Ordering::Relaxed);
|
||||
let progress = |_| flag.store(true, Ordering::Relaxed);
|
||||
assert!(apply(&s, &p, area, None, Some(area), &Interrupt::new(&cancel, &progress)).unwrap().is_none());
|
||||
assert_eq!(s.to_interleaved(area), original);
|
||||
flag.store(false, Ordering::Relaxed);
|
||||
let after_writes = |value| {
|
||||
if value > 0.55 {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
};
|
||||
assert!(apply(&s, &p, area, None, Some(area), &Interrupt::new(&cancel, &after_writes)).unwrap().is_none());
|
||||
assert_eq!(s.to_interleaved(area), original);
|
||||
assert_eq!(group_size(MAX_BYTES, 1, 1, 1), None);
|
||||
assert_eq!(group_size(0, usize::MAX, 1, 1), None);
|
||||
assert!(Plan::new(usize::MAX, &[1.0], &mut FftPlanner::new()).is_none());
|
||||
assert!(buffer::<f32>(usize::MAX, 0.0).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_threshold_dispatch_retains_exact_pixel_decisions() {
|
||||
let area = Rect::new(-3, 2, 253, 258);
|
||||
for depth in SampleType::ALL {
|
||||
let s = source(area, PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
let p = FilterParams::UnsharpMask { amount: 500.0, radius: 64.0, threshold: 8.0 };
|
||||
let expected = crate::sharpen::tests::apply_reference(&s, &p, area, area, None, Some(area), 256);
|
||||
let actual = crate::apply_in(&s, &p, area, area, None, area);
|
||||
assert_eq!(expected.to_interleaved(area), actual.to_interleaved(area));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fft_handles_maximum_radius_and_hdr_alpha_channel_pairs() {
|
||||
let area = Rect::new(0, 0, 1, 1);
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));
|
||||
s.fill_rect(area, &[0.5]);
|
||||
let ctx = Ctx { bounds: area, mode: ColorMode::Grayscale, alpha: false };
|
||||
let src = Image::read_clamped(&s, area.inflate(3001), area);
|
||||
let pixels = reference::unsharp(&src, area, &ctx, 500.0, 1000.0, 0.0);
|
||||
let mut expected = s.clone();
|
||||
expected.write_region(area, &pixels);
|
||||
compare(&expected, &run(&s, area, 500.0, 1000.0, None, Some(area), &Interrupt::NONE).unwrap(), area);
|
||||
|
||||
let area = Rect::new(-2, 3, 11, 14);
|
||||
let mut s = Surface::new(PixelFormat::RGBA32F);
|
||||
s.fill_rect(area, &[1e6, -1e5, 1e-4, 0.02]);
|
||||
let ctx = Ctx { bounds: area, mode: ColorMode::Rgb, alpha: true };
|
||||
let src = Image::read_clamped(&s, area.inflate(193), area);
|
||||
let pixels = reference::unsharp(&src, area, &ctx, 500.0, 64.0, 0.0);
|
||||
let mut expected = s.clone();
|
||||
expected.write_region(area, &pixels);
|
||||
compare(&expected, &run(&s, area, 500.0, 64.0, None, Some(area), &Interrupt::NONE).unwrap(), area);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! Opt-in benchmark of the adaptive production path against the frozen original.
|
||||
use super::tests::{apply_reference, source};
|
||||
use crate::FilterParams;
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
use std::time::Instant;
|
||||
#[test]
|
||||
#[ignore = "adaptive large-radius full-operation quality and performance; run alone"]
|
||||
fn unsharp_fft_performance() {
|
||||
let number = |name: &str, default| std::env::var(name).ok().and_then(|v| v.parse::<i32>().ok()).unwrap_or(default);
|
||||
let (w, h) = (number("PHOTOCRAFT_UNSHARP_WIDTH", 1920), number("PHOTOCRAFT_UNSHARP_HEIGHT", 1080));
|
||||
let reps = number("PHOTOCRAFT_UNSHARP_REPS", 3);
|
||||
assert!((1..=8192).contains(&w) && (1..=8192).contains(&h) && (1..=5).contains(&reps));
|
||||
let depth = match number("PHOTOCRAFT_UNSHARP_DEPTH", 8) {
|
||||
8 => SampleType::U8,
|
||||
16 => SampleType::U16,
|
||||
32 => SampleType::F32,
|
||||
_ => panic!("depth"),
|
||||
};
|
||||
let area = Rect::new(0, 0, w, h);
|
||||
let surface = source(area, PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
let cases = std::env::var("PHOTOCRAFT_UNSHARP_CASES").unwrap_or_else(|_| "100:150:0,300:150:0,500:150:8".into());
|
||||
for case in cases.split(',') {
|
||||
let v: Vec<f32> = case.split(':').map(|v| v.parse().unwrap()).collect();
|
||||
let (radius, amount, threshold) = (v[0], v[1], v[2]);
|
||||
let params = FilterParams::UnsharpMask { amount, radius, threshold };
|
||||
let baseline = || apply_reference(&surface, ¶ms, area, area, None, Some(area), crate::auto_tile(¶ms, area));
|
||||
let candidate = || crate::apply_in(&surface, ¶ms, area, area, None, area);
|
||||
for _ in 0..2 {
|
||||
std::hint::black_box(baseline());
|
||||
std::hint::black_box(candidate());
|
||||
}
|
||||
let mut before = Vec::new();
|
||||
let mut after = Vec::new();
|
||||
let mut max_error = 0.0f32;
|
||||
let mut changed = 0usize;
|
||||
let mut sum_error = 0.0f64;
|
||||
for rep in 0..reps {
|
||||
let timed = |f: &dyn Fn() -> Surface| {
|
||||
let t = Instant::now();
|
||||
let output = f();
|
||||
(output, t.elapsed().as_secs_f64() * 1000.0)
|
||||
};
|
||||
let ((old, a), (new, b)) = if rep % 2 == 0 {
|
||||
(timed(&baseline), timed(&candidate))
|
||||
} else {
|
||||
let b = timed(&candidate);
|
||||
(timed(&baseline), b)
|
||||
};
|
||||
before.push(a);
|
||||
after.push(b);
|
||||
for (a, b) in old.read_region(area).iter().zip(new.read_region(area)) {
|
||||
let e = (a - b).abs();
|
||||
let limit = match depth {
|
||||
SampleType::U8 => 1.0 / 255.0 + 1e-7,
|
||||
SampleType::U16 => 3.0 / 65535.0 + 1e-7,
|
||||
SampleType::F32 => 3e-5 * (1.0 + a.abs()),
|
||||
};
|
||||
assert!(e <= limit, "quality regression: {a} != {b} at radius {radius}, threshold {threshold}");
|
||||
max_error = max_error.max(e);
|
||||
if rep == 0 {
|
||||
sum_error += f64::from(e);
|
||||
changed += usize::from(a.to_bits() != b.to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
let median = |v: &[f64]| {
|
||||
let mut v = v.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"experiment":"adaptive FFT same Gaussian, changed summation","width":w,"height":h,"depth":number("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"before_ms":before,"after_ms":after,"before_median_ms":median(&before),"after_median_ms":median(&after),"speedup":median(&before)/median(&after),"max_error":max_error,"mean_error":sum_error/(w as f64*h as f64*4.0),"changed_samples":changed})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "4K wide-radius cancellation latency; run alone in release"]
|
||||
fn unsharp_fft_cancel_latency() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
let area = Rect::new(0, 0, 3840, 2160);
|
||||
let surface = source(area, PixelFormat::RGBA8);
|
||||
let input = surface.to_interleaved(area);
|
||||
let p = FilterParams::UnsharpMask { amount: 150.0, radius: 1000.0, threshold: 0.0 };
|
||||
let mut latencies = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let flag = AtomicBool::new(false);
|
||||
let cancel_at = AtomicU64::new(0);
|
||||
let started = Instant::now();
|
||||
std::thread::scope(|scope| {
|
||||
let timer = scope.spawn(|| {
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
cancel_at.store(started.elapsed().as_micros() as u64, Ordering::Relaxed);
|
||||
flag.store(true, Ordering::Release);
|
||||
});
|
||||
let cancel = || flag.load(Ordering::Acquire);
|
||||
let result = crate::apply_in_with(&surface, &p, area, area, None, area, &photocraft_raster::Interrupt::cancel_only(&cancel));
|
||||
let elapsed = started.elapsed().as_micros() as u64;
|
||||
timer.join().unwrap();
|
||||
assert!(result.is_none());
|
||||
latencies.push(elapsed.saturating_sub(cancel_at.load(Ordering::Relaxed)) as f64 / 1000.0);
|
||||
});
|
||||
assert_eq!(surface.to_interleaved(area), input);
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"width":3840,"height":2160,"radius":1000,"cancel_after_ms":10,"cancel_return_latencies_ms":latencies,"scope":"native full-resolution algo dispatch, excludes GUI scheduling/proxy creation"})
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Frozen exact Unsharp Mask from a28d7866, independent of production helpers.
|
||||
use crate::Ctx;
|
||||
use crate::image::{Image, premultiply, unpremultiply};
|
||||
use photocraft_geom::Rect;
|
||||
pub(crate) fn gaussian_kernel(sigma: f32) -> Vec<f32> {
|
||||
if sigma < 0.05 {
|
||||
return vec![1.0];
|
||||
}
|
||||
let r = (sigma * 3.0).ceil() as i32;
|
||||
let k: Vec<f32> = (-r..=r).map(|i| (-(i * i) as f32 / (2.0 * sigma * sigma)).exp()).collect();
|
||||
let s: f32 = k.iter().sum();
|
||||
k.into_iter().map(|v| v / s).collect()
|
||||
}
|
||||
|
||||
/// Separable convolution of `src` (premultiplied internally) for `out`.
|
||||
/// `src` must cover `out` grown by the kernel radii.
|
||||
pub(crate) fn conv_sep(src: &Image, out: Rect, kx: &[f32], ky: &[f32], alpha: bool) -> Vec<f32> {
|
||||
let n = src.ch;
|
||||
let (rx, ry) = ((kx.len() / 2) as i32, (ky.len() / 2) as i32);
|
||||
let (ow, oh) = (out.width() as usize, out.height() as usize);
|
||||
let th = oh + 2 * ry as usize;
|
||||
// Premultiplied copy of the needed source window.
|
||||
let win = Rect::new(out.x0 - rx, out.y0 - ry, out.x1 + rx, out.y1 + ry);
|
||||
let ww = win.width() as usize;
|
||||
let mut p = vec![0.0f32; ww * win.height() as usize * n];
|
||||
for y in win.y0..win.y1 {
|
||||
for x in win.x0..win.x1 {
|
||||
let o = ((y - win.y0) as usize * ww + (x - win.x0) as usize) * n;
|
||||
for c in 0..n {
|
||||
p[o + c] = src.get(x, y, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
premultiply(&mut p, n, alpha);
|
||||
// Horizontal pass: (ow × th).
|
||||
let mut tmp = vec![0.0f32; ow * th * n];
|
||||
for ty in 0..th {
|
||||
let row = &p[ty * ww * n..(ty + 1) * ww * n];
|
||||
let dst = &mut tmp[ty * ow * n..(ty + 1) * ow * n];
|
||||
match n {
|
||||
1 => conv_row::<1>(row, dst, kx),
|
||||
2 => conv_row::<2>(row, dst, kx),
|
||||
3 => conv_row::<3>(row, dst, kx),
|
||||
4 => conv_row::<4>(row, dst, kx),
|
||||
5 => conv_row::<5>(row, dst, kx),
|
||||
_ => {
|
||||
for ox in 0..ow {
|
||||
let d = &mut dst[ox * n..(ox + 1) * n];
|
||||
for (i, kv) in kx.iter().enumerate() {
|
||||
let s = &row[(ox + i) * n..(ox + i + 1) * n];
|
||||
for c in 0..n {
|
||||
d[c] += s[c] * kv;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Vertical pass.
|
||||
let mut res = vec![0.0f32; ow * oh * n];
|
||||
for oy in 0..oh {
|
||||
let d = &mut res[oy * ow * n..(oy + 1) * ow * n];
|
||||
for (i, kv) in ky.iter().enumerate() {
|
||||
let s = &tmp[(oy + i) * ow * n..(oy + i + 1) * ow * n];
|
||||
for (dv, sv) in d.iter_mut().zip(s) {
|
||||
*dv += sv * kv;
|
||||
}
|
||||
}
|
||||
}
|
||||
unpremultiply(&mut res, n, alpha);
|
||||
res
|
||||
}
|
||||
|
||||
// Fixed channel counts let LLVM keep one pixel's accumulators in registers and vectorize
|
||||
// channels. The tap order is unchanged; unusual multichannel images keep the generic path.
|
||||
fn conv_row<const N: usize>(src: &[f32], dst: &mut [f32], kernel: &[f32]) {
|
||||
let pixels = src.as_chunks::<N>().0;
|
||||
for (x, out) in dst.as_chunks_mut::<N>().0.iter_mut().enumerate() {
|
||||
let mut acc = [0.0f32; N];
|
||||
for (pixel, weight) in pixels.get(x..).unwrap_or(&[]).iter().zip(kernel) {
|
||||
for c in 0..N {
|
||||
acc[c] += pixel[c] * weight;
|
||||
}
|
||||
}
|
||||
*out = acc;
|
||||
}
|
||||
}
|
||||
|
||||
fn with_blur(src: &Image, out: Rect, ctx: &Ctx, radius: f32, mut f: impl FnMut(f32, f32) -> f32) -> Vec<f32> {
|
||||
let k = gaussian_kernel(radius);
|
||||
let blurred = conv_sep(src, out, &k, &k, ctx.alpha);
|
||||
let mut res = src.crop(out);
|
||||
let n = src.ch;
|
||||
let cc = if ctx.alpha { n - 1 } else { n };
|
||||
for (px, bl) in res.chunks_exact_mut(n).zip(blurred.chunks_exact(n)) {
|
||||
if ctx.alpha && px[n - 1] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
for c in 0..cc {
|
||||
px[c] = f(px[c], bl[c]);
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
pub(crate) fn unsharp(src: &Image, out: Rect, ctx: &Ctx, amount: f32, radius: f32, threshold: f32) -> Vec<f32> {
|
||||
let k = amount / 100.0;
|
||||
let t = threshold / 255.0;
|
||||
with_blur(src, out, ctx, radius, |o, b| {
|
||||
let d = o - b;
|
||||
if d.abs() + 1e-6 >= t { o + k * d } else { o }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
use super::*;
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_raster::{Interrupt, Surface};
|
||||
use std::time::Instant;
|
||||
|
||||
#[path = "reference.rs"]
|
||||
pub(super) mod reference;
|
||||
|
||||
pub(super) fn source(rect: Rect, fmt: PixelFormat) -> Surface {
|
||||
let mut s = Surface::new(fmt);
|
||||
for y in rect.y0..rect.y1 {
|
||||
let data: Vec<f32> = (rect.x0..rect.x1)
|
||||
.flat_map(|x| {
|
||||
(0..fmt.channels()).map(move |c| {
|
||||
if fmt.alpha && c + 1 == fmt.channels() {
|
||||
if (x + y).rem_euclid(17) == 0 { 0.0 } else { ((x ^ y).rem_euclid(255) + 1) as f32 / 255.0 }
|
||||
} else {
|
||||
let value = ((x * (7 + c as i32) + y * 13).rem_euclid(257)) as f32 / 256.0;
|
||||
if fmt.sample == SampleType::F32 { 3.0 * value - 0.5 } else { value }
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
s.write_region(Rect::new(rect.x0, y, rect.x1, y + 1), &data);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
// Preserve the surrounding tiled workload as well as the old convolution: halo reads,
|
||||
// automatic tiles, grouping, selection mixing, writes and pruning are timed in both paths.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn apply_reference(
|
||||
s: &Surface,
|
||||
p: &crate::FilterParams,
|
||||
area: Rect,
|
||||
bounds: Rect,
|
||||
sel: Option<&Surface>,
|
||||
extent: Option<Rect>,
|
||||
tile: i32,
|
||||
) -> Surface {
|
||||
let crate::FilterParams::UnsharpMask { amount, radius, threshold } = *p else { panic!("unsharp params") };
|
||||
let crate::Halo::Radius(halo) = p.halo_for(bounds) else { panic!("radius halo") };
|
||||
let fmt = s.format();
|
||||
let ctx = Ctx { bounds, mode: fmt.mode, alpha: fmt.alpha };
|
||||
let tiles: Vec<_> = (area.y0..area.y1)
|
||||
.step_by(tile as usize)
|
||||
.flat_map(|y| (area.x0..area.x1).step_by(tile as usize).map(move |x| Rect::new(x, y, (x + tile).min(area.x1), (y + tile).min(area.y1))))
|
||||
.collect();
|
||||
let group = (crate::RESULT_BUDGET / ((tile as usize).pow(2) * fmt.channels() * 4)).max(workers()).max(1);
|
||||
let finished = std::sync::atomic::AtomicUsize::new(0);
|
||||
let ctl = Interrupt::NONE;
|
||||
let run = |t: &Rect| {
|
||||
let src = match extent {
|
||||
Some(e) => Image::read_clamped(s, t.inflate(halo), e),
|
||||
None => Image::read(s, t.inflate(halo)),
|
||||
};
|
||||
let mut data = reference::unsharp(&src, *t, &ctx, amount, radius, threshold);
|
||||
if let Some(sel) = sel {
|
||||
crate::mix_selection(&mut data, *t, sel, &src, fmt.alpha);
|
||||
}
|
||||
let done = finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
ctl.progress(0.98 * done as f32 / tiles.len().max(1) as f32);
|
||||
(*t, data)
|
||||
};
|
||||
let mut out = s.clone();
|
||||
for chunk in tiles.chunks(group) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let results: Vec<_> = {
|
||||
use rayon::prelude::*;
|
||||
chunk.par_iter().map(run).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let results: Vec<_> = chunk.iter().map(run).collect();
|
||||
for (t, data) in results {
|
||||
out.write_region(t, &data);
|
||||
}
|
||||
}
|
||||
out.prune();
|
||||
out
|
||||
}
|
||||
|
||||
fn workers() -> usize {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
rayon::current_num_threads()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_reference_matches_current_kernel() {
|
||||
let out = Rect::new(-3, 2, 16, 15);
|
||||
let src = Image { rect: out.inflate(13), ch: 4, data: (0..(out.width() + 26) * (out.height() + 26) * 4).map(|i| (i % 127) as f32 / 126.0).collect() };
|
||||
let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha: true };
|
||||
for radius in [0.1, 0.6, 1.5, 4.0] {
|
||||
assert_eq!(unsharp(&src, out, &ctx, 150.0, radius, 8.0), reference::unsharp(&src, out, &ctx, 150.0, radius, 8.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn same_bits(a: &[f32], b: &[f32]) {
|
||||
assert_eq!(a.len(), b.len());
|
||||
for (i, (&a, &b)) in a.iter().zip(b).enumerate() {
|
||||
assert!(a.to_bits() == b.to_bits() || a.is_nan() && b.is_nan(), "sample {i}: {a:?} ({:x}) != {b:?} ({:x})", a.to_bits(), b.to_bits());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_kernel_across_models_depths_edges_and_thresholds() {
|
||||
let modes = [
|
||||
ColorMode::Bitmap,
|
||||
ColorMode::Grayscale,
|
||||
ColorMode::Duotone,
|
||||
ColorMode::Indexed,
|
||||
ColorMode::Rgb,
|
||||
ColorMode::Cmyk,
|
||||
ColorMode::Lab,
|
||||
ColorMode::Multichannel,
|
||||
];
|
||||
for mode in modes {
|
||||
for depth in SampleType::ALL {
|
||||
for alpha in [false, true] {
|
||||
let fmt = PixelFormat::new(mode, depth, alpha);
|
||||
let area = Rect::new(-3, 2, 8, 7);
|
||||
let mut surface = source(area, fmt);
|
||||
if depth == SampleType::F32 {
|
||||
// HDR, negative, signed zero, subnormal and nonfinite samples; colour is
|
||||
// never clamped by this filter. Transparent hidden colour must survive.
|
||||
let px: Vec<f32> = (0..fmt.channels()).map(|c| if alpha && c + 1 == fmt.channels() { 0.0 } else { -4.0 }).collect();
|
||||
surface.fill_rect(Rect::new(0, 3, 1, 4), &px);
|
||||
for (x, value) in [3.5, -0.0, f32::MIN_POSITIVE, f32::INFINITY, f32::NAN].into_iter().enumerate() {
|
||||
let mut px = vec![value; fmt.channels()];
|
||||
if alpha {
|
||||
*px.last_mut().unwrap() = if x == 2 { 1e-8 } else { 1.0 };
|
||||
}
|
||||
surface.fill_rect(Rect::new(x as i32, 5, x as i32 + 1, 6), &px);
|
||||
}
|
||||
}
|
||||
let ctx = Ctx { bounds: area, mode, alpha };
|
||||
for radius in [0.0, 0.049, 0.1, 0.6, 1.5, 4.0, 17.25] {
|
||||
let src = Image::read_clamped(&surface, area.inflate((radius * 3.0_f32).ceil() as i32 + 1), area);
|
||||
for (amount, threshold) in [(0.0, 0.0), (50.0, 0.0), (500.0, 8.0), (300.0, 255.0)] {
|
||||
same_bits(&unsharp(&src, area, &ctx, amount, radius, threshold), &reference::unsharp(&src, area, &ctx, amount, radius, threshold));
|
||||
}
|
||||
// An incomplete halo has zero extension, even with alpha.
|
||||
let src = Image::read(&surface, area);
|
||||
let out = Rect::new(-5, 1, 10, 8);
|
||||
same_bits(&unsharp(&src, out, &ctx, 150.0, radius, 8.0), &reference::unsharp(&src, out, &ctx, 150.0, radius, 8.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_threshold_boundary_and_degenerate_images() {
|
||||
for (w, h, n) in [(1, 1, 1), (1, 7, 2), (9, 1, 3), (7, 5, 4), (2, 3, 5), (5, 2, 7)] {
|
||||
let out = Rect::new(-2, 3, w - 2, h + 3);
|
||||
let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha: n % 2 == 0 };
|
||||
let src = Image { rect: out, ch: n, data: (0..w * h * n as i32).map(|i| if i % 7 == 0 { -0.0 } else { (i % 17) as f32 / 16.0 }).collect() };
|
||||
for radius in [0.0, 0.1, 0.75, 8.5, 64.0] {
|
||||
let k = reference::gaussian_kernel(radius);
|
||||
let blurred = reference::conv_sep(&src, out, &k, &k, ctx.alpha);
|
||||
for (&o, &b) in src.data.iter().zip(&blurred).take(8) {
|
||||
let boundary = ((o - b).abs() + 1e-6) * 255.0;
|
||||
for threshold in [boundary, f32::from_bits(boundary.to_bits().saturating_sub(1)), f32::from_bits(boundary.to_bits() + 1)] {
|
||||
same_bits(&unsharp(&src, out, &ctx, 500.0, radius, threshold), &reference::unsharp(&src, out, &ctx, 500.0, radius, threshold));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let empty = Image { rect: Rect::EMPTY, ch: 4, data: Vec::new() };
|
||||
let ctx = Ctx { bounds: Rect::EMPTY, mode: ColorMode::Rgb, alpha: true };
|
||||
assert!(unsharp(&empty, Rect::EMPTY, &ctx, 100.0, 1.0, 0.0).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_tiled_selected_outputs_and_cancellation() {
|
||||
let bounds = Rect::new(-13, -7, 281, 271);
|
||||
let area = Rect::new(-3, 5, 273, 265);
|
||||
let mut sel = Surface::new(PixelFormat::GRAY8);
|
||||
sel.fill_rect(area, &[0.4]);
|
||||
sel.fill_rect(Rect::new(250, 250, 270, 265), &[1.0]);
|
||||
for depth in SampleType::ALL {
|
||||
let surface = source(bounds, PixelFormat::new(ColorMode::Rgb, depth, true));
|
||||
for radius in [0.6, 3.0, 10.0] {
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 150.0, radius, threshold: 8.0 };
|
||||
for extent in [None, Some(bounds)] {
|
||||
let expected = apply_reference(&surface, &p, area, bounds, Some(&sel), extent, 256);
|
||||
for tile in [63, 256, 512] {
|
||||
let actual = crate::apply_tiled(&surface, &p, area, bounds, Some(&sel), tile, extent);
|
||||
assert_eq!(expected.to_interleaved(bounds), actual.to_interleaved(bounds));
|
||||
}
|
||||
}
|
||||
let cancelled = std::sync::atomic::AtomicBool::new(false);
|
||||
let cancel = || cancelled.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let progress = |_| cancelled.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
let ctl = Interrupt::new(&cancel, &progress);
|
||||
let input = surface.to_interleaved(bounds);
|
||||
assert!(crate::apply_in_with(&surface, &p, area, bounds, Some(&sel), bounds, &ctl).is_none());
|
||||
assert_eq!(surface.to_interleaved(bounds), input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserve_details_resampling_keeps_the_same_sharpening() {
|
||||
use crate::resample::{Resample, resize_surface};
|
||||
let src = Rect::new(-3, 2, 19, 17);
|
||||
let (sx, sy) = (2.0, 1.5);
|
||||
let dst = crate::resample::scaled_rect(src, sx, sy);
|
||||
for depth in SampleType::ALL {
|
||||
for mode in [ColorMode::Grayscale, ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
let s = source(src, PixelFormat::new(mode, depth, true));
|
||||
let resized = resize_surface(&s, sx, sy, Resample::Lanczos);
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
|
||||
let area = crate::output_area(&p, resized.content_bounds(), dst, None);
|
||||
let expected = apply_reference(&resized, &p, area, dst, None, None, crate::auto_tile(&p, dst));
|
||||
let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails);
|
||||
assert_eq!(actual.to_interleaved(area), expected.to_interleaved(area));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_fields_and_sharp_edges_keep_exact_halos() {
|
||||
let out = Rect::new(0, 0, 17, 9);
|
||||
for alpha in [false, true] {
|
||||
let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha };
|
||||
for radius in [0.1, 0.6, 3.25, 64.0] {
|
||||
let rect = out.inflate((radius * 3.0_f32).ceil() as i32 + 1);
|
||||
for edge in [false, true] {
|
||||
let n = 3 + usize::from(alpha);
|
||||
let data = (rect.y0..rect.y1)
|
||||
.flat_map(|_| {
|
||||
(rect.x0..rect.x1).flat_map(|x| {
|
||||
(0..n).map(move |c| {
|
||||
if alpha && c + 1 == n {
|
||||
0.7
|
||||
} else if edge && x >= 8 {
|
||||
0.75
|
||||
} else {
|
||||
0.25
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let src = Image { rect, ch: n, data };
|
||||
same_bits(&unsharp(&src, out, &ctx, 300.0, radius, 0.0), &reference::unsharp(&src, out, &ctx, 300.0, radius, 0.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_inputs_and_allocations_stop_gracefully() {
|
||||
let rect = Rect::new(0, 0, 2, 2);
|
||||
let src = Image { rect, ch: 1, data: vec![0.5; 4] };
|
||||
let ctx = Ctx { bounds: rect, mode: ColorMode::Grayscale, alpha: false };
|
||||
for (amount, radius, threshold) in [(f32::NAN, 1.0, 0.0), (100.0, f32::INFINITY, 0.0), (100.0, -1.0, 0.0), (100.0, f32::MAX, 0.0), (100.0, 1.0, f32::NAN)] {
|
||||
assert!(exact::run(&src, rect, &ctx, amount, radius, threshold, &Interrupt::NONE).is_none());
|
||||
let s = source(rect, PixelFormat::GRAY8);
|
||||
let p = crate::FilterParams::UnsharpMask { amount, radius, threshold };
|
||||
assert!(crate::apply_in_with(&s, &p, rect, rect, None, rect, &Interrupt::NONE).is_none());
|
||||
assert_eq!(crate::apply_in(&s, &p, rect, rect, None, rect), s);
|
||||
}
|
||||
for bad in [Image { ch: 0, ..src.clone() }, Image { data: vec![0.0], ..src.clone() }, Image { rect: Rect::new(5, 0, 0, 2), ..src.clone() }] {
|
||||
assert!(exact::run(&bad, rect, &ctx, 100.0, 1.0, 0.0, &Interrupt::NONE).is_none());
|
||||
}
|
||||
for rect in [Rect::new(i32::MIN, 0, i32::MAX, 2), Rect::new(0, 0, 300_000, 300_000), Rect::new(2, 0, 0, 2)] {
|
||||
assert!(exact::run(&src, rect, &ctx, 100.0, 1.0, 0.0, &Interrupt::NONE).is_none());
|
||||
}
|
||||
let s = source(Rect::new(0, 0, 2, 2), PixelFormat::GRAY8);
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 100.0, radius: 1.0, threshold: 0.0 };
|
||||
for tile in [i32::MIN, 0, i32::MAX] {
|
||||
let r = s.content_bounds();
|
||||
assert_eq!(crate::apply_tiled(&s, &p, r, r, None, tile, Some(r)), crate::apply_in(&s, &p, r, r, None, r));
|
||||
}
|
||||
// Allocation/geometry guard prevents a huge halo read before allocating it.
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 100.0, radius: 15_446.0, threshold: 0.0 };
|
||||
assert!(crate::apply_in_with(&s, &p, s.content_bounds(), s.content_bounds(), None, s.content_bounds(), &Interrupt::NONE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_supported_radius_matches_the_frozen_kernel() {
|
||||
let out = Rect::new(0, 0, 1, 1);
|
||||
let src = Image { rect: out, ch: 1, data: vec![0.75] };
|
||||
let ctx = Ctx { bounds: out, mode: ColorMode::Grayscale, alpha: false };
|
||||
same_bits(&unsharp(&src, out, &ctx, 500.0, 1000.0, 8.0), &reference::unsharp(&src, out, &ctx, 500.0, 1000.0, 8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_stops_inside_a_tile_before_publishing() {
|
||||
let rect = Rect::new(0, 0, 16, 16);
|
||||
let s = source(rect, PixelFormat::RGBA8);
|
||||
let src = Image::read(&s, rect);
|
||||
let ctx = Ctx { bounds: rect, mode: ColorMode::Rgb, alpha: true };
|
||||
let checks = std::sync::atomic::AtomicUsize::new(0);
|
||||
let cancel = || checks.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 10;
|
||||
assert!(exact::run(&src, rect, &ctx, 150.0, 30.0, 8.0, &Interrupt::cancel_only(&cancel)).is_none());
|
||||
assert_eq!(src, Image::read(&s, rect));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release full-operation baseline/candidate comparison; run alone"]
|
||||
fn unsharp_performance() {
|
||||
let number = |name: &str, default: i32| std::env::var(name).ok().and_then(|s| s.parse::<i32>().ok()).unwrap_or(default);
|
||||
let (w, h, reps) = (number("PHOTOCRAFT_UNSHARP_WIDTH", 1500), number("PHOTOCRAFT_UNSHARP_HEIGHT", 1000), number("PHOTOCRAFT_UNSHARP_REPS", 5));
|
||||
assert!((1..=8192).contains(&w) && (1..=8192).contains(&h) && (1..=15).contains(&reps));
|
||||
let depth = match number("PHOTOCRAFT_UNSHARP_DEPTH", 8) {
|
||||
8 => SampleType::U8,
|
||||
16 => SampleType::U16,
|
||||
32 => SampleType::F32,
|
||||
_ => panic!("depth"),
|
||||
};
|
||||
let area = Rect::new(0, 0, w, h);
|
||||
let channels = number("PHOTOCRAFT_UNSHARP_CHANNELS", 4);
|
||||
let (mode, alpha) = match channels {
|
||||
1 => (ColorMode::Grayscale, false),
|
||||
2 => (ColorMode::Grayscale, true),
|
||||
3 => (ColorMode::Rgb, false),
|
||||
4 => (ColorMode::Rgb, true),
|
||||
5 => (ColorMode::Cmyk, true),
|
||||
_ => panic!("channels 1..5"),
|
||||
};
|
||||
let surface = source(area, PixelFormat::new(mode, depth, alpha));
|
||||
let measure = std::env::var("PHOTOCRAFT_UNSHARP_MODE").unwrap_or_else(|_| "paired".into());
|
||||
assert!(matches!(measure.as_str(), "paired" | "reference" | "candidate"));
|
||||
let cases = std::env::var("PHOTOCRAFT_UNSHARP_CASES").unwrap_or_else(|_| "0.6:150:0,3:150:8,10:300:16,30:150:0".into());
|
||||
for case in cases.split(',') {
|
||||
let values: Vec<f32> = case.split(':').map(|v| v.parse().unwrap()).collect();
|
||||
let (radius, amount, threshold) = (values[0], values[1], values[2]);
|
||||
let p = crate::FilterParams::UnsharpMask { amount, radius, threshold };
|
||||
let tile = crate::auto_tile(&p, area);
|
||||
let before = || apply_reference(&surface, &p, area, area, None, Some(area), tile);
|
||||
// Isolate the streamed exact path from the new adaptive FFT dispatcher.
|
||||
let after = || crate::apply_tiled_with_impl(&surface, &p, area, area, None, tile, Some(area), &Interrupt::NONE, false).unwrap();
|
||||
if measure != "paired" {
|
||||
let f = if measure == "reference" { &before as &dyn Fn() -> Surface } else { &after as &dyn Fn() -> Surface };
|
||||
let mut times = Vec::new();
|
||||
for rep in 0..reps + 2 {
|
||||
let start = Instant::now();
|
||||
let output = f();
|
||||
let ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
std::hint::black_box(output);
|
||||
if rep >= 2 {
|
||||
times.push(ms);
|
||||
}
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"mode":measure,"width":w,"height":h,"channels":channels,"depth":number("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"workers":workers(),"runs_ms":times})
|
||||
);
|
||||
continue;
|
||||
}
|
||||
for _ in 0..2 {
|
||||
std::hint::black_box(before());
|
||||
std::hint::black_box(after());
|
||||
}
|
||||
let (mut a, mut b) = (Vec::new(), Vec::new());
|
||||
for rep in 0..reps {
|
||||
let timed = |f: &dyn Fn() -> Surface| {
|
||||
let start = Instant::now();
|
||||
let s = f();
|
||||
(s, start.elapsed().as_secs_f64() * 1000.0)
|
||||
};
|
||||
let ((old, old_ms), (new, new_ms)) = if rep % 2 == 0 {
|
||||
(timed(&before), timed(&after))
|
||||
} else {
|
||||
let b = timed(&after);
|
||||
(timed(&before), b)
|
||||
};
|
||||
assert_eq!(old.to_interleaved(area), new.to_interleaved(area));
|
||||
a.push(old_ms);
|
||||
b.push(new_ms);
|
||||
}
|
||||
let median = |v: &[f64]| {
|
||||
let mut v = v.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"width":w,"height":h,"channels":channels,"depth":number("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"workers":workers(),"before_ms":a,"after_ms":b,"before_median_ms":median(&a),"after_median_ms":median(&b),"speedup":median(&a)/median(&b),"max_error":0})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "unchanged-filter stage profile; run alone in release"]
|
||||
fn unsharp_baseline_profile() {
|
||||
let out = Rect::new(0, 0, 256, 256);
|
||||
for radius in [0.6, 3.0, 10.0, 30.0] {
|
||||
let reach = (radius * 3.0_f32).ceil() as i32 + 1;
|
||||
let s = source(out.inflate(reach), PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
|
||||
let src = Image::read(&s, out.inflate(reach));
|
||||
let ctx = Ctx { bounds: out, mode: ColorMode::Rgb, alpha: true };
|
||||
let k = reference::gaussian_kernel(radius);
|
||||
let mut times = [0.0; 4];
|
||||
for _ in 0..20 {
|
||||
let start = Instant::now();
|
||||
std::hint::black_box(reference::gaussian_kernel(radius));
|
||||
times[0] += start.elapsed().as_secs_f64();
|
||||
let start = Instant::now();
|
||||
let bl = reference::conv_sep(&src, out, &k, &k, true);
|
||||
times[1] += start.elapsed().as_secs_f64();
|
||||
let start = Instant::now();
|
||||
let mut res = src.crop(out);
|
||||
for (px, b) in res.as_chunks_mut::<4>().0.iter_mut().zip(bl.as_chunks::<4>().0) {
|
||||
if px[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
for c in 0..3 {
|
||||
let d = px[c] - b[c];
|
||||
if d.abs() + 1e-6 >= 8.0 / 255.0 {
|
||||
px[c] += 1.5 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::hint::black_box(res);
|
||||
times[2] += start.elapsed().as_secs_f64();
|
||||
let start = Instant::now();
|
||||
std::hint::black_box(reference::unsharp(&src, out, &ctx, 150.0, radius, 8.0));
|
||||
times[3] += start.elapsed().as_secs_f64();
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"baseline_tile_radius":radius,"kernel_ms":times[0]*50.0,"convolution_ms":times[1]*50.0,"crop_blend_ms":times[2]*50.0,"total_kernel_ms":times[3]*50.0})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -227,6 +227,27 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
let npixels = w.checked_mul(h).ok_or_else(|| err("the data window is too large"))?;
|
||||
limits.check_bytes(w as u32, h as u32, (header.channels.list.len().max(1) as u64) * 4)?;
|
||||
|
||||
// The display window is the full stage the renderer composed onto (a render pass's data
|
||||
// window is often its crop). Open on the stage when it plausibly holds the data region:
|
||||
// sane size for the limits, and the data region inside it. Otherwise fall back to the
|
||||
// data window alone, as before.
|
||||
let display = header.shared_attributes.display_window;
|
||||
let display_size = (display.size.0.max(1) as u32, display.size.1.max(1) as u32);
|
||||
let (stage, origin) = match display_size {
|
||||
(sw, sh)
|
||||
if sw <= 1 << 15
|
||||
&& sh <= 1 << 15
|
||||
&& limits.check_bytes(sw, sh, 4).is_ok()
|
||||
&& dw.position.0 >= display.position.0
|
||||
&& dw.position.1 >= display.position.1
|
||||
&& dw.position.0.saturating_add(w as i32) <= display.position.0.saturating_add(sw as i32)
|
||||
&& dw.position.1.saturating_add(h as i32) <= display.position.1.saturating_add(sh as i32) =>
|
||||
{
|
||||
(Some((sw, sh)), (dw.position.0 - display.position.0, dw.position.1 - display.position.1))
|
||||
}
|
||||
_ => (None, (0, 0)),
|
||||
};
|
||||
|
||||
let exr_types: Vec<ExrSample> = header.channels.list.iter().map(|c| c.sample_type).collect();
|
||||
let bytes_per_sample: usize = exr_types.iter().map(|t| sample_bytes(*t)).sum();
|
||||
let multipart = meta.requirements.has_multiple_layers;
|
||||
@@ -440,7 +461,7 @@ pub(crate) fn decode_deep(meta: &MetaData, bytes: &[u8], limits: &Limits) -> Res
|
||||
}
|
||||
}
|
||||
|
||||
Ok(DeepImage { width: w as u32, height: h as u32, channels, counts: deep_counts })
|
||||
Ok(DeepImage { width: w as u32, height: h as u32, stage, origin, channels, counts: deep_counts })
|
||||
}
|
||||
|
||||
/// Where the headers end and the offset tables begin. [`MetaData::read_from_buffered`]
|
||||
@@ -565,7 +586,28 @@ pub(crate) fn flatten(deep: &DeepImage) -> Result<Image, CodecError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut img = Image::from_f32(deep.width, deep.height, layout, &out)?;
|
||||
// Open on the full display-window stage when the file declares one: the renderer's data
|
||||
// window is its crop, and the composition lives on the whole stage. The composed region
|
||||
// pads to the stage at its offset, transparent elsewhere (limits validated the size).
|
||||
let mut img = match deep.stage {
|
||||
Some((sw, sh)) => {
|
||||
let mut padded = vec![0f32; sw as usize * sh as usize * nc];
|
||||
let row_len = deep.width as usize * nc;
|
||||
let dx = deep.origin.0.max(0) as usize;
|
||||
for row in 0..deep.height as usize {
|
||||
let src = row * row_len;
|
||||
let dst = (row + deep.origin.1.max(0) as usize) * sw as usize + dx;
|
||||
if let (Some(d), Some(r)) = (padded.get_mut(dst * nc..dst * nc + row_len), out.get(src..src + row_len)) {
|
||||
d.copy_from_slice(r);
|
||||
}
|
||||
}
|
||||
Image::from_f32(sw, sh, layout, &padded)?
|
||||
}
|
||||
None => Image::from_f32(deep.width, deep.height, layout, &out)?,
|
||||
};
|
||||
if let Some((sw, sh)) = deep.stage {
|
||||
img.warnings.push(DecodeWarning::DisplayWindowStage { stage: (sw, sh), origin: deep.origin });
|
||||
}
|
||||
img.warnings.push(DecodeWarning::DeepFlattened { format: F, max_samples_per_pixel: max_samples });
|
||||
Ok(img)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub(crate) mod pcx;
|
||||
pub(crate) mod png;
|
||||
pub(crate) mod pnm;
|
||||
pub(crate) mod tiff;
|
||||
pub(crate) mod tiff_exif;
|
||||
pub(crate) mod tiff_ifd;
|
||||
pub(crate) mod via_image;
|
||||
pub(crate) mod vp8;
|
||||
|
||||
@@ -35,6 +35,7 @@ use tiff::encoder::colortype::{self, ColorType as TiffColorType};
|
||||
use tiff::encoder::{Rational, TiffEncoder, TiffKind, TiffKindBig, TiffKindStandard, TiffValue};
|
||||
use tiff::tags::{PhotometricInterpretation, ResolutionUnit, SampleFormat, Tag, Type};
|
||||
|
||||
use super::tiff_exif::{self, ExifDirs};
|
||||
use super::tiff_ifd::{self as ifd, File, Ifd};
|
||||
use crate::Format;
|
||||
use crate::error::CodecError;
|
||||
@@ -297,6 +298,13 @@ fn metadata(f: &File<'_>, dir: &Ifd, icc: &mut Option<Vec<u8>>) -> Metadata {
|
||||
if dir.at == f.first_ifd { photoshop_tags(f.b) } else { (f.tag_bytes(dir, TAG_PHOTOSHOP), f.tag_bytes(dir, TAG_IMAGE_SOURCE_DATA)) };
|
||||
meta.photoshop_resources = resources.map(<[u8]>::to_vec);
|
||||
meta.photoshop_layers = layers.map(<[u8]>::to_vec);
|
||||
// EXIF: the Exif and GPS directories IFD0 points to, with IFD0's descriptive tags, as an
|
||||
// EXIF block (the other pages are reduced copies or layers of the same image).
|
||||
if dir.at == f.first_ifd
|
||||
&& let Some(e) = tiff_exif::read(f.b).filter(ExifDirs::has_directories)
|
||||
{
|
||||
meta.exif = Some(tiff_exif::block(&e));
|
||||
}
|
||||
meta
|
||||
}
|
||||
|
||||
@@ -1016,6 +1024,8 @@ custom_colortype!(CmykA32F, f32, PI::CMYK, &[32; 5], &[SampleFormat::IEEEFP; 5],
|
||||
|
||||
struct TagSet<'a> {
|
||||
icc: Option<&'a [u8]>,
|
||||
/// The EXIF block's directories and IFD0 tags, written as the TIFF's own.
|
||||
exif: Option<ExifDirs>,
|
||||
xmp: Option<&'a [u8]>,
|
||||
dpi: Option<(f32, f32)>,
|
||||
text: Vec<(Tag, &'a str)>,
|
||||
@@ -1032,6 +1042,16 @@ where
|
||||
[C::Inner]: TiffValue,
|
||||
K: TiffKind,
|
||||
{
|
||||
// The Exif and GPS directories go before the image, outside its chain; IFD0 points to them.
|
||||
let mut sub = |e: &ExifDirs, fields: &[tiff_exif::Field]| (!fields.is_empty()).then(|| tiff_exif::write_directory(enc, fields, e.le)).transpose();
|
||||
let exif_at = match &tags.exif {
|
||||
Some(e) => sub(e, &e.exif)?,
|
||||
None => None,
|
||||
};
|
||||
let gps_at = match &tags.exif {
|
||||
Some(e) => sub(e, &e.gps)?,
|
||||
None => None,
|
||||
};
|
||||
let mut im = enc.new_image::<C>(w, h)?;
|
||||
if let Some((x, y)) = tags.dpi {
|
||||
im.resolution_unit(ResolutionUnit::Inch);
|
||||
@@ -1052,6 +1072,17 @@ where
|
||||
for (tag, s) in &tags.text {
|
||||
d.write_tag(*tag, *s)?;
|
||||
}
|
||||
if let Some(e) = &tags.exif {
|
||||
// The EXIF block's descriptive IFD0 tags, unless the text metadata already wrote them.
|
||||
let ifd0: Vec<tiff_exif::Field> = e.ifd0.iter().filter(|f| !tags.text.iter().any(|(t, _)| t.to_u16() == f.tag)).cloned().collect();
|
||||
tiff_exif::write_fields(d, &ifd0, e.le)?;
|
||||
}
|
||||
if let Some(at) = exif_at {
|
||||
d.write_tag(Tag::Unknown(tiff_exif::TAG_EXIF_IFD), at)?;
|
||||
}
|
||||
if let Some(at) = gps_at {
|
||||
d.write_tag(Tag::Unknown(tiff_exif::TAG_GPS_IFD), at)?;
|
||||
}
|
||||
if let Some(r) = tags.photoshop_resources {
|
||||
d.write_tag(Tag::Unknown(TAG_PHOTOSHOP), r)?;
|
||||
}
|
||||
@@ -1099,7 +1130,8 @@ const CLASSIC_LIMIT: u64 = u32::MAX as u64;
|
||||
/// room for the directory and strip tables.
|
||||
fn estimated_size(img: &Image, tags: &TagSet<'_>) -> u64 {
|
||||
let payloads = [tags.icc, tags.xmp, tags.photoshop_resources, tags.photoshop_layers].iter().flatten().map(|p| p.len() as u64).sum::<u64>();
|
||||
let text = tags.text.iter().map(|(_, s)| s.len() as u64).sum::<u64>();
|
||||
let text = tags.text.iter().map(|(_, s)| s.len() as u64).sum::<u64>()
|
||||
+ tags.exif.iter().flat_map(|e| e.ifd0.iter().chain(&e.exif).chain(&e.gps)).map(|f| f.value.len() as u64 + 12).sum::<u64>();
|
||||
// Strip tables: one offset and one count per strip of about 1 MB.
|
||||
let tables = (img.data().len() as u64 / (1 << 20) + 1) * 16;
|
||||
(img.data().len() as u64).saturating_add(payloads).saturating_add(text).saturating_add(tables).saturating_add(1 << 20)
|
||||
@@ -1132,6 +1164,7 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
|
||||
let xmp = if opts.embed_metadata { img.meta.xmp.as_deref().map(|x| crate::resolution::export_xmp(x, img.meta.dpi)) } else { None };
|
||||
let tags = TagSet {
|
||||
icc: if opts.embed_icc { img.icc.as_deref() } else { None },
|
||||
exif: if opts.embed_metadata { img.meta.exif.as_deref().and_then(|e| tiff_exif::read(crate::orientation::tiff_body(e))) } else { None },
|
||||
xmp: xmp.as_deref().map(str::as_bytes),
|
||||
dpi: if opts.embed_metadata { img.meta.dpi.filter(|d| d.0 > 0.0 && d.1 > 0.0) } else { None },
|
||||
text,
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! EXIF in a TIFF file: the Exif (34665) and GPS (34853) directories that IFD0 points to, plus
|
||||
//! IFD0's descriptive tags (make, model, software, artist, …), the way cameras and Photoshop
|
||||
//! write them.
|
||||
//!
|
||||
//! An EXIF block (`Metadata::exif`) is itself a small TIFF stream, so both directions go through
|
||||
//! the same reader ([`super::tiff_ifd::File`]): reading a TIFF builds a block from the file's own
|
||||
//! directories, writing one copies the block's directories into the file. Values are copied as
|
||||
//! bytes (re-ordered when the byte orders differ), so tags PhotoCraft doesn't know survive.
|
||||
//! Classic TIFF only on the reading side: an EXIF block has 4-byte offsets.
|
||||
|
||||
use tiff::encoder::{DirectoryEncoder, TiffEncoder, TiffKind};
|
||||
use tiff::tags::{Tag, Type};
|
||||
use tiff::{Directory, TiffResult};
|
||||
|
||||
use super::tiff_ifd::{File, Ifd};
|
||||
|
||||
/// IFD0's pointer to the Exif directory.
|
||||
pub(crate) const TAG_EXIF_IFD: u16 = 34665;
|
||||
/// IFD0's pointer to the GPS directory.
|
||||
pub(crate) const TAG_GPS_IFD: u16 = 34853;
|
||||
/// The Exif directory's pointer to the Interoperability directory (not carried: it holds only
|
||||
/// the interoperability index, and a copied pointer would point nowhere).
|
||||
const TAG_INTEROP_IFD: u16 = 40965;
|
||||
/// IFD0 tags an EXIF block carries next to its directories: ImageDescription, Make, Model,
|
||||
/// Software, DateTime, Artist, Copyright. Structure, resolution and orientation belong to the
|
||||
/// image and are written from it.
|
||||
const IFD0_TAGS: [u16; 7] = [270, 271, 272, 305, 306, 315, 33432];
|
||||
/// At most this many entries are copied from one directory.
|
||||
const MAX_FIELDS: usize = 1024;
|
||||
|
||||
/// One entry with its value bytes in the byte order of the stream it came from.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Field {
|
||||
pub tag: u16,
|
||||
pub ty: u16,
|
||||
pub count: u32,
|
||||
pub value: Vec<u8>,
|
||||
}
|
||||
|
||||
/// The EXIF parts of a TIFF stream, in its byte order (`le`).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct ExifDirs {
|
||||
pub le: bool,
|
||||
pub ifd0: Vec<Field>,
|
||||
pub exif: Vec<Field>,
|
||||
pub gps: Vec<Field>,
|
||||
}
|
||||
|
||||
impl ExifDirs {
|
||||
/// Whether there is an Exif or GPS directory (IFD0's descriptive tags alone are not EXIF).
|
||||
pub fn has_directories(&self) -> bool {
|
||||
!self.exif.is_empty() || !self.gps.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(f: &File<'_>, ifd: &Ifd, keep: impl Fn(u16) -> bool) -> Vec<Field> {
|
||||
ifd.entries
|
||||
.iter()
|
||||
.filter(|e| keep(e.tag) && !matches!(e.tag, TAG_EXIF_IFD | TAG_GPS_IFD | TAG_INTEROP_IFD))
|
||||
.filter_map(|e| Some(Field { tag: e.tag, ty: e.ty, count: u32::try_from(e.count).ok()?, value: f.data(e)?.to_vec() }))
|
||||
.take(MAX_FIELDS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn sub(f: &File<'_>, ifd: &Ifd, tag: u16) -> Option<Ifd> {
|
||||
let at = f.tag_uint(ifd, tag)?;
|
||||
(at != ifd.at).then(|| f.ifd(at)).flatten()
|
||||
}
|
||||
|
||||
/// The EXIF parts of the classic TIFF stream `b` (a TIFF file, or an EXIF block without its
|
||||
/// `Exif\0\0` prefix): IFD0's descriptive tags and the Exif and GPS directories.
|
||||
pub(crate) fn read(b: &[u8]) -> Option<ExifDirs> {
|
||||
let f = File::parse(b)?;
|
||||
if f.big {
|
||||
return None;
|
||||
}
|
||||
let ifd0 = f.ifd(f.first_ifd)?;
|
||||
let dir = |tag: u16| sub(&f, &ifd0, tag).map(|d| fields(&f, &d, |_| true)).unwrap_or_default();
|
||||
Some(ExifDirs { le: f.le, ifd0: fields(&f, &ifd0, |t| IFD0_TAGS.contains(&t)), exif: dir(TAG_EXIF_IFD), gps: dir(TAG_GPS_IFD) })
|
||||
}
|
||||
|
||||
/// Bytes per element whose order a byte-order change reverses: a RATIONAL is two LONGs.
|
||||
fn element(ty: u16) -> usize {
|
||||
match ty {
|
||||
3 | 8 => 2,
|
||||
4 | 5 | 9 | 10 | 11 | 13 => 4,
|
||||
12 | 16 | 17 | 18 => 8,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` of type `ty` in byte order `to_le`, from `from_le`.
|
||||
pub(crate) fn reorder(ty: u16, value: &[u8], from_le: bool, to_le: bool) -> Vec<u8> {
|
||||
let n = element(ty);
|
||||
if from_le == to_le || n == 1 {
|
||||
return value.to_vec();
|
||||
}
|
||||
value.chunks(n).flat_map(|c| c.iter().rev().copied()).collect()
|
||||
}
|
||||
|
||||
/// An EXIF block: a classic TIFF stream in `dirs.le` order whose IFD0 holds `dirs.ifd0` and
|
||||
/// points to the Exif and GPS directories.
|
||||
pub(crate) fn block(dirs: &ExifDirs) -> Vec<u8> {
|
||||
let le = dirs.le;
|
||||
let u16b = |v: u16| if le { v.to_le_bytes() } else { v.to_be_bytes() };
|
||||
let u32b = |v: u32| if le { v.to_le_bytes() } else { v.to_be_bytes() };
|
||||
let mut ifd0: Vec<Field> = dirs.ifd0.clone();
|
||||
// Placeholders for the pointers; their offsets are known once the layout is.
|
||||
let pointer = |tag: u16| Field { tag, ty: 4, count: 1, value: vec![0; 4] };
|
||||
if !dirs.exif.is_empty() {
|
||||
ifd0.push(pointer(TAG_EXIF_IFD));
|
||||
}
|
||||
if !dirs.gps.is_empty() {
|
||||
ifd0.push(pointer(TAG_GPS_IFD));
|
||||
}
|
||||
// Layout: header, then each directory followed by its out-of-line values.
|
||||
let size = |fs: &[Field]| 2 + 12 * fs.len() + 4 + fs.iter().filter(|f| f.value.len() > 4).map(|f| f.value.len().next_multiple_of(2)).sum::<usize>();
|
||||
let at0 = 8;
|
||||
let at_exif = at0 + size(&ifd0);
|
||||
let at_gps = at_exif + if dirs.exif.is_empty() { 0 } else { size(&dirs.exif) };
|
||||
for f in &mut ifd0 {
|
||||
match f.tag {
|
||||
TAG_EXIF_IFD => f.value = u32b(at_exif as u32).to_vec(),
|
||||
TAG_GPS_IFD => f.value = u32b(at_gps as u32).to_vec(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(if le { b"II" } else { b"MM" });
|
||||
out.extend_from_slice(&u16b(42));
|
||||
out.extend_from_slice(&u32b(at0 as u32));
|
||||
let write_dir = |out: &mut Vec<u8>, fs: &[Field]| {
|
||||
let mut fs = fs.to_vec();
|
||||
fs.sort_by_key(|f| f.tag);
|
||||
let start = out.len();
|
||||
let mut extra = start + 2 + 12 * fs.len() + 4;
|
||||
let mut values = Vec::new();
|
||||
out.extend_from_slice(&u16b(fs.len() as u16));
|
||||
for f in &fs {
|
||||
out.extend_from_slice(&u16b(f.tag));
|
||||
out.extend_from_slice(&u16b(f.ty));
|
||||
out.extend_from_slice(&u32b(f.count));
|
||||
if f.value.len() <= 4 {
|
||||
let mut inline = f.value.clone();
|
||||
inline.resize(4, 0);
|
||||
out.extend_from_slice(&inline);
|
||||
} else {
|
||||
out.extend_from_slice(&u32b(extra as u32));
|
||||
values.extend_from_slice(&f.value);
|
||||
if f.value.len() % 2 == 1 {
|
||||
values.push(0);
|
||||
}
|
||||
extra += f.value.len().next_multiple_of(2);
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&u32b(0));
|
||||
out.extend_from_slice(&values);
|
||||
};
|
||||
write_dir(&mut out, &ifd0);
|
||||
if !dirs.exif.is_empty() {
|
||||
write_dir(&mut out, &dirs.exif);
|
||||
}
|
||||
if !dirs.gps.is_empty() {
|
||||
write_dir(&mut out, &dirs.gps);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Writes `fields` (in byte order `from_le`) into a directory of `enc` that is not part of the
|
||||
/// page chain, and returns its offset for the pointer tag.
|
||||
pub(crate) fn write_directory<W: std::io::Write + std::io::Seek, K: TiffKind>(
|
||||
enc: &mut TiffEncoder<W, K>,
|
||||
fields: &[Field],
|
||||
from_le: bool,
|
||||
) -> TiffResult<K::OffsetType> {
|
||||
let mut sub = enc.extra_directory()?;
|
||||
write_fields(&mut sub, fields, from_le)?;
|
||||
Ok(sub.finish_with_offsets()?.offset)
|
||||
}
|
||||
|
||||
/// Adds `fields` (in byte order `from_le`) to directory `d`, in the file's (native) byte order.
|
||||
pub(crate) fn write_fields<W: std::io::Write + std::io::Seek, K: TiffKind>(
|
||||
d: &mut DirectoryEncoder<'_, W, K>,
|
||||
fields: &[Field],
|
||||
from_le: bool,
|
||||
) -> TiffResult<()> {
|
||||
let mut dir = Directory::empty();
|
||||
for f in fields {
|
||||
let Some(ty) = Type::from_u16(f.ty) else { continue };
|
||||
let entry = d.write_entry_bytes(ty, &reorder(f.ty, &f.value, from_le, cfg!(target_endian = "little")))?;
|
||||
dir.extend([(Tag::from_u16_exhaustive(f.tag), entry)]);
|
||||
}
|
||||
d.extend_from(&dir);
|
||||
Ok(())
|
||||
}
|
||||
@@ -233,7 +233,7 @@ pub fn caps(format: Format) -> FormatCaps {
|
||||
FormatCaps { depths: &[S::U8, S::U16], layouts: RGB_GRAY, icc: true, exif: true, xmp: true, dpi: true, text: true, animation: true, ..base }
|
||||
}
|
||||
Format::Jpeg => FormatCaps { layouts: &[L::Gray, L::Rgb, L::Cmyk], alpha: false, icc: true, exif: true, xmp: true, dpi: true, lossy: true, ..base },
|
||||
Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, icc: true, xmp: true, dpi: true, text: true, ..base },
|
||||
Format::Tiff => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, icc: true, exif: true, xmp: true, dpi: true, text: true, ..base },
|
||||
Format::WebP => FormatCaps { icc: true, exif: true, xmp: true, animation: true, ..base },
|
||||
Format::Gif => FormatCaps { layouts: &[L::Rgba], animation: true, lossy: true, ..base },
|
||||
Format::Bmp => base,
|
||||
|
||||
@@ -150,6 +150,8 @@ pub enum DecodeWarning {
|
||||
MorePages { total: Option<u32> },
|
||||
/// Only one part of a multi-part file was decoded; `total` counts every part when known.
|
||||
MoreParts { total: Option<u32> },
|
||||
/// The image opened on the full `display_window` stage; the data region sits at `origin`.
|
||||
DisplayWindowStage { stage: (u32, u32), origin: (i32, i32) },
|
||||
/// The image data ends early (truncated or damaged file); the decoder filled in the rest
|
||||
/// (a baseline JPEG's missing rows come out grey).
|
||||
Truncated { format: Format },
|
||||
@@ -193,6 +195,9 @@ impl fmt::Display for DecodeWarning {
|
||||
DecodeWarning::MorePages { total: None } => write!(f, "only the first page of the file was imported"),
|
||||
DecodeWarning::MoreParts { total: Some(n) } => write!(f, "only one of {n} EXR parts was imported"),
|
||||
DecodeWarning::MoreParts { total: None } => write!(f, "only one EXR part of the file was imported"),
|
||||
DecodeWarning::DisplayWindowStage { stage, origin } => {
|
||||
write!(f, "opened on the full display window stage ({}x{}); the data sits at ({}, {})", stage.0, stage.1, origin.0, origin.1)
|
||||
}
|
||||
DecodeWarning::Truncated { format } => {
|
||||
write!(f, "{} data ends early (the file is truncated or damaged); part of the image is missing", format.name())
|
||||
}
|
||||
@@ -232,6 +237,13 @@ pub struct DeepChannel {
|
||||
pub struct DeepImage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// The full stage the image opens on: the EXR `display_window` size, when the file declares
|
||||
/// one the data region fits into and the limits allow. `None` when absent, absurd or not
|
||||
/// containing the data region — then the image opens on the data window alone, as before.
|
||||
pub stage: Option<(u32, u32)>,
|
||||
/// Where this image's (0, 0) sits on the stage: `data_window.position - display_window.position`.
|
||||
/// `(0, 0)` when [`Self::stage`] is `None`.
|
||||
pub origin: (i32, i32),
|
||||
/// The sample channels in file order.
|
||||
pub channels: Vec<DeepChannel>,
|
||||
/// Cumulative sample counts, `len == width as usize * height as usize + 1`: pixel `i`
|
||||
|
||||
@@ -254,6 +254,9 @@ fn gen_deep(
|
||||
out
|
||||
}
|
||||
|
||||
/// RGBA float channels in chlist (alphabetical) order, no Z (everything composites).
|
||||
const RGBA_NO_Z: [Chan; 4] = [Chan { name: "A", ty: 2 }, Chan { name: "B", ty: 2 }, Chan { name: "G", ty: 2 }, Chan { name: "R", ty: 2 }];
|
||||
|
||||
/// RGBA(Z) float channels in chlist (alphabetical) order.
|
||||
const RGBAZ: [Chan; 5] =
|
||||
[Chan { name: "A", ty: 2 }, Chan { name: "B", ty: 2 }, Chan { name: "G", ty: 2 }, Chan { name: "R", ty: 2 }, Chan { name: "Z", ty: 2 }];
|
||||
@@ -709,3 +712,131 @@ fn real_deep_files_decode() {
|
||||
assert!(img.warnings.iter().any(|w| matches!(w, photocraft_codecs::DecodeWarning::DeepFlattened { .. })), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `gen_deep` for a cropped render: the data window sits at `(dwx, dwy)` inside a larger
|
||||
/// display window of `sw × sh` (the stage the renderer composed onto). Scanline chunk Y
|
||||
/// coordinates are absolute display rows, so they carry the data-window offset.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gen_deep_cropped(
|
||||
w: usize,
|
||||
h: usize,
|
||||
dwx: i32,
|
||||
dwy: i32,
|
||||
sw: usize,
|
||||
sh: usize,
|
||||
channels: &[Chan],
|
||||
counts: &[u32],
|
||||
sample: &dyn Fn(usize, usize) -> Vec<f32>,
|
||||
) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(&0x0131_2f76u32.to_le_bytes());
|
||||
out.extend_from_slice(&(2u32 | 0x800).to_le_bytes());
|
||||
|
||||
let mut chlist = Vec::new();
|
||||
for c in channels {
|
||||
chlist.extend_from_slice(c.name.as_bytes());
|
||||
chlist.push(0);
|
||||
chlist.extend_from_slice(&c.ty.to_le_bytes());
|
||||
chlist.push(0);
|
||||
chlist.extend_from_slice(&[0u8; 3]);
|
||||
chlist.extend_from_slice(&1i32.to_le_bytes());
|
||||
chlist.extend_from_slice(&1i32.to_le_bytes());
|
||||
}
|
||||
chlist.push(0);
|
||||
attr(&mut out, "channels", "chlist", &chlist);
|
||||
attr(&mut out, "compression", "compression", &[0u8]);
|
||||
// box2i is inclusive: the windows end at position + size - 1.
|
||||
let dw: Vec<u8> = [dwx, dwy, dwx + w as i32 - 1, dwy + h as i32 - 1].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
attr(&mut out, "dataWindow", "box2i", &dw);
|
||||
let disp: Vec<u8> = [0i32, 0, sw as i32 - 1, sh as i32 - 1].iter().flat_map(|v| v.to_le_bytes()).collect();
|
||||
attr(&mut out, "displayWindow", "box2i", &disp);
|
||||
attr(&mut out, "lineOrder", "lineOrder", &[0]);
|
||||
attr(&mut out, "pixelAspectRatio", "float", &1f32.to_le_bytes());
|
||||
attr(&mut out, "screenWindowCenter", "v2f", &[0f32.to_le_bytes(), 0f32.to_le_bytes()].concat());
|
||||
attr(&mut out, "screenWindowWidth", "float", &1f32.to_le_bytes());
|
||||
attr(&mut out, "type", "string", b"deepscanline");
|
||||
attr(&mut out, "version", "int", &1i32.to_le_bytes());
|
||||
out.push(0);
|
||||
|
||||
// One scanline block per data row; the pixel indexing stays data-relative.
|
||||
let mut chunks: Vec<Vec<u8>> = Vec::new();
|
||||
for y in 0..h {
|
||||
let pixels: Vec<usize> = (y * w..y * w + w).collect();
|
||||
let mut c = Vec::new();
|
||||
c.extend_from_slice(&(dwy + y as i32).to_le_bytes());
|
||||
let mut table = Vec::with_capacity(pixels.len() * 4);
|
||||
let mut acc = 0u32;
|
||||
for &p in &pixels {
|
||||
acc += counts[p];
|
||||
table.extend_from_slice(&acc.to_le_bytes());
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
for (ci, _) in channels.iter().enumerate() {
|
||||
for &p in &pixels {
|
||||
for v in sample(p, ci) {
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
c.extend_from_slice(&(table.len() as u64).to_le_bytes());
|
||||
c.extend_from_slice(&(data.len() as u64).to_le_bytes());
|
||||
c.extend_from_slice(&(data.len() as u64).to_le_bytes());
|
||||
c.extend_from_slice(&table);
|
||||
c.extend_from_slice(&data);
|
||||
chunks.push(c);
|
||||
}
|
||||
let mut pos = out.len() + chunks.len() * 8;
|
||||
let mut table = Vec::new();
|
||||
for c in &chunks {
|
||||
table.extend_from_slice(&(pos as u64).to_le_bytes());
|
||||
pos += c.len();
|
||||
}
|
||||
out.extend_from_slice(&table);
|
||||
for c in chunks {
|
||||
out.extend_from_slice(&c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A cropped render opens on the full display-window stage: MY27-style renders carry a
|
||||
/// `display_window` of the full frame (e.g. 4000×3000) while the deep data window is the
|
||||
/// render pass's crop inside it. The image must open at stage size with the data at its
|
||||
/// crop offset, transparent elsewhere — not cropped to the data window.
|
||||
#[test]
|
||||
fn cropped_deep_data_opens_on_the_display_stage() {
|
||||
let (w, h, dwx, dwy, sw, sh) = (24usize, 16usize, 8i32, 6i32, 48usize, 32usize);
|
||||
let counts = vec![1u32; w * h];
|
||||
let sample = |p: usize, ci: usize| -> Vec<f32> {
|
||||
// chlist order (RGBA_NO_Z): A, B, G, R.
|
||||
let x = p % w;
|
||||
let y = p / w;
|
||||
match ci {
|
||||
0 => vec![1.0], // A
|
||||
1 => vec![0.5], // B
|
||||
2 => vec![y as f32 / h as f32], // G
|
||||
_ => vec![x as f32 / w as f32], // R
|
||||
}
|
||||
};
|
||||
let bytes = gen_deep_cropped(w, h, dwx, dwy, sw, sh, &RGBA_NO_Z, &counts, &sample);
|
||||
let img = decode(&bytes).expect("cropped deep EXR decodes");
|
||||
assert_eq!((img.width(), img.height()), (sw as u32, sh as u32), "opens on the display window stage");
|
||||
assert!(img.warnings.iter().any(|w| matches!(w, photocraft_codecs::DecodeWarning::DisplayWindowStage { origin, .. } if *origin == (dwx, dwy))));
|
||||
|
||||
// The data sits at its crop offset: the first data pixel's green channel carries its
|
||||
// data-row fraction, everything outside the data region stays transparent black.
|
||||
let s = img.to_f32_samples().expect("f32");
|
||||
let nc = s.len() / (sw * sh);
|
||||
let px = |x: usize, y: usize| -> Vec<f32> { s[y * sw * nc + x * nc..y * sw * nc + x * nc + nc].to_vec() };
|
||||
let first = px(dwx as usize, dwy as usize);
|
||||
assert!(
|
||||
(first[0] - 0.0).abs() < 1e-5 && (first[1] - 0.0).abs() < 1e-5 && (first[2] - 0.5).abs() < 1e-5 && (first[3] - 1.0).abs() < 1e-5,
|
||||
"first data pixel at the offset: {first:?}"
|
||||
);
|
||||
let last = px(dwx as usize + w - 1, dwy as usize + h - 1);
|
||||
assert!(
|
||||
(last[0] - (w - 1) as f32 / w as f32).abs() < 1e-5 && (last[1] - (h - 1) as f32 / h as f32).abs() < 1e-5,
|
||||
"last data pixel keeps its coordinates: {last:?}"
|
||||
);
|
||||
let outside = px(0, 0);
|
||||
assert_eq!(outside, vec![0.0, 0.0, 0.0, 0.0], "outside the data region: transparent");
|
||||
}
|
||||
@@ -34,7 +34,11 @@ fn check_format(format: Format) {
|
||||
} else {
|
||||
assert!(warnings.contains(&FidelityWarning::IccDropped), "{format:?}");
|
||||
}
|
||||
if c.exif {
|
||||
if c.exif && format == Format::Tiff {
|
||||
// TIFF writes the block's directories as its own and rebuilds a block from them on
|
||||
// reading (tests/tiff_exif.rs); IFD0's orientation here is the image's.
|
||||
assert!(!warnings.contains(&FidelityWarning::ExifDropped), "{format:?}");
|
||||
} else if c.exif {
|
||||
assert_eq!(back.meta.exif, img.meta.exif, "{format:?} exif");
|
||||
} else {
|
||||
assert!(warnings.contains(&FidelityWarning::ExifDropped), "{format:?}");
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! EXIF in TIFF: an EXIF block's Exif and GPS directories and IFD0's descriptive tags are
|
||||
//! written as the TIFF's own directories (IFD0 pointing to them, as cameras and Photoshop write
|
||||
//! them) and read back into a block.
|
||||
|
||||
use photocraft_codecs::*;
|
||||
|
||||
/// A classic TIFF stream builder for EXIF blocks: directories of (tag, type, count, value bytes).
|
||||
struct Block {
|
||||
le: bool,
|
||||
}
|
||||
|
||||
type Entry = (u16, u16, u32, Vec<u8>);
|
||||
|
||||
impl Block {
|
||||
fn u16(&self, v: u16) -> [u8; 2] {
|
||||
if self.le { v.to_le_bytes() } else { v.to_be_bytes() }
|
||||
}
|
||||
fn u32(&self, v: u32) -> [u8; 4] {
|
||||
if self.le { v.to_le_bytes() } else { v.to_be_bytes() }
|
||||
}
|
||||
fn rational(&self, n: u32, d: u32) -> Vec<u8> {
|
||||
[self.u32(n), self.u32(d)].concat()
|
||||
}
|
||||
/// IFD0 (with pointers to `exif` and `gps` appended) followed by the two directories.
|
||||
fn build(&self, mut ifd0: Vec<Entry>, exif: Vec<Entry>, gps: Vec<Entry>) -> Vec<u8> {
|
||||
let size = |d: &[Entry]| 2 + 12 * d.len() + 4 + d.iter().filter(|e| e.3.len() > 4).map(|e| e.3.len().next_multiple_of(2)).sum::<usize>();
|
||||
ifd0.push((34665, 4, 1, vec![0; 4]));
|
||||
ifd0.push((34853, 4, 1, vec![0; 4]));
|
||||
let at_exif = 8 + size(&ifd0);
|
||||
let at_gps = at_exif + size(&exif);
|
||||
let n = ifd0.len();
|
||||
ifd0[n - 2].3 = self.u32(at_exif as u32).to_vec();
|
||||
ifd0[n - 1].3 = self.u32(at_gps as u32).to_vec();
|
||||
let mut out = if self.le { b"II".to_vec() } else { b"MM".to_vec() };
|
||||
out.extend(self.u16(42));
|
||||
out.extend(self.u32(8));
|
||||
for d in [ifd0, exif, gps] {
|
||||
let start = out.len();
|
||||
let mut extra = start + 2 + 12 * d.len() + 4;
|
||||
let mut values = Vec::new();
|
||||
out.extend(self.u16(d.len() as u16));
|
||||
for (tag, ty, count, v) in &d {
|
||||
out.extend(self.u16(*tag));
|
||||
out.extend(self.u16(*ty));
|
||||
out.extend(self.u32(*count));
|
||||
if v.len() <= 4 {
|
||||
let mut inline = v.clone();
|
||||
inline.resize(4, 0);
|
||||
out.extend(inline);
|
||||
} else {
|
||||
out.extend(self.u32(extra as u32));
|
||||
values.extend(v);
|
||||
if v.len() % 2 == 1 {
|
||||
values.push(0);
|
||||
}
|
||||
extra += v.len().next_multiple_of(2);
|
||||
}
|
||||
}
|
||||
out.extend(self.u32(0));
|
||||
out.extend(values);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries (tag, type, count, value bytes in the block's order) of IFD0 and of the
|
||||
/// directories its tags `34665` and `34853` point to.
|
||||
fn dirs(b: &[u8]) -> (bool, Vec<Entry>, Vec<Entry>, Vec<Entry>) {
|
||||
let le = &b[..2] == b"II";
|
||||
let u16 = |at: usize| if le { u16::from_le_bytes([b[at], b[at + 1]]) } else { u16::from_be_bytes([b[at], b[at + 1]]) };
|
||||
let u32 = |at: usize| {
|
||||
let s = [b[at], b[at + 1], b[at + 2], b[at + 3]];
|
||||
if le { u32::from_le_bytes(s) } else { u32::from_be_bytes(s) }
|
||||
};
|
||||
let size = |ty: u16| match ty {
|
||||
3 | 8 => 2,
|
||||
4 | 9 | 11 | 13 => 4,
|
||||
5 | 10 | 12 => 8,
|
||||
_ => 1,
|
||||
};
|
||||
let read = |at: usize| -> Vec<Entry> {
|
||||
(0..usize::from(u16(at)))
|
||||
.map(|i| {
|
||||
let e = at + 2 + 12 * i;
|
||||
let (tag, ty, count) = (u16(e), u16(e + 2), u32(e + 4));
|
||||
let len = count as usize * size(ty);
|
||||
let at = if len <= 4 { e + 8 } else { u32(e + 8) as usize };
|
||||
(tag, ty, count, b[at..at + len].to_vec())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let ifd0 = read(u32(4) as usize);
|
||||
let sub = |tag: u16| ifd0.iter().find(|e| e.0 == tag).map(|e| read(u32_of(&e.3, le) as usize)).unwrap_or_default();
|
||||
let (exif, gps) = (sub(34665), sub(34853));
|
||||
(le, ifd0.into_iter().filter(|e| !matches!(e.0, 34665 | 34853)).collect(), exif, gps)
|
||||
}
|
||||
|
||||
fn u32_of(v: &[u8], le: bool) -> u32 {
|
||||
let s = [v[0], v[1], v[2], v[3]];
|
||||
if le { u32::from_le_bytes(s) } else { u32::from_be_bytes(s) }
|
||||
}
|
||||
|
||||
/// The entries of `d` with their values in little-endian order, sorted by tag.
|
||||
fn normalized(d: &[Entry], le: bool) -> Vec<(u16, u16, u32, Vec<u8>)> {
|
||||
let swap = |ty: u16, v: &[u8]| -> Vec<u8> {
|
||||
let n = match ty {
|
||||
3 | 8 => 2,
|
||||
4 | 5 | 9 | 10 | 11 | 13 => 4,
|
||||
12 => 8,
|
||||
_ => 1,
|
||||
};
|
||||
if le || n == 1 { v.to_vec() } else { v.chunks(n).flat_map(|c| c.iter().rev().copied()).collect() }
|
||||
};
|
||||
let mut v: Vec<_> = d.iter().map(|e| (e.0, e.1, e.2, swap(e.1, &e.3))).collect();
|
||||
v.sort_by_key(|e| e.0);
|
||||
v
|
||||
}
|
||||
|
||||
fn camera_block(le: bool) -> Vec<u8> {
|
||||
let b = Block { le };
|
||||
let ascii = |s: &str| [s.as_bytes(), b"\0"].concat();
|
||||
b.build(
|
||||
vec![(271, 2, 4, ascii("Cam")), (272, 2, 9, ascii("Model X1")), (315, 2, 16, ascii("A. Photographer")), (274, 3, 1, b.u16(1).to_vec())],
|
||||
vec![
|
||||
(33434, 5, 1, b.rational(1, 125)),
|
||||
(34855, 3, 1, b.u16(200).to_vec()),
|
||||
(36867, 2, 20, ascii("2026:10:13 09:30:00")),
|
||||
(37386, 5, 1, b.rational(50, 1)),
|
||||
(37500, 7, 6, b"maker!".to_vec()),
|
||||
],
|
||||
vec![(1, 2, 2, ascii("N")), (2, 5, 3, [b.rational(51, 1), b.rational(30, 1), b.rational(0, 1)].concat())],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exif_round_trips_through_a_tiff_in_either_byte_order() {
|
||||
for le in [true, false] {
|
||||
let block = camera_block(le);
|
||||
let mut img = Image::from_raw(4, 3, ChannelLayout::Rgb, SampleType::U8, vec![90; 36]).unwrap();
|
||||
img.meta.exif = Some(block.clone());
|
||||
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
|
||||
assert!(fidelity_warnings(&img, Format::Tiff).iter().all(|w| *w != FidelityWarning::ExifDropped));
|
||||
let back = decode(&tiff).unwrap().meta.exif.expect("EXIF read back");
|
||||
let (ble, b0, bexif, bgps) = dirs(&back);
|
||||
let (ole, o0, oexif, ogps) = dirs(&block);
|
||||
assert_eq!(normalized(&bexif, ble), normalized(&oexif, ole), "Exif directory (le {le})");
|
||||
assert_eq!(normalized(&bgps, ble), normalized(&ogps, ole), "GPS directory (le {le})");
|
||||
// IFD0's descriptive tags come along; its orientation is the image's own.
|
||||
let descriptive: Vec<_> = o0.into_iter().filter(|e| e.0 != 274).collect();
|
||||
assert_eq!(normalized(&b0, ble), normalized(&descriptive, ole), "IFD0 (le {le})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiff_without_exif_directories_reads_no_exif() {
|
||||
let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
|
||||
img.meta.text = vec![("Artist".into(), "A. Photographer".into())];
|
||||
let tiff = encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(decode(&tiff).unwrap().meta.exif, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_exif_is_written_without_embed_metadata() {
|
||||
let mut img = Image::from_raw(2, 2, ChannelLayout::Gray, SampleType::U8, vec![0; 4]).unwrap();
|
||||
img.meta.exif = Some(camera_block(true));
|
||||
let tiff = encode(&img, Format::Tiff, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
|
||||
assert_eq!(decode(&tiff).unwrap().meta.exif, None);
|
||||
}
|
||||
@@ -15,10 +15,10 @@
|
||||
//! of strokes blend onto the backdrop with their own modes, an upper stroke covering the
|
||||
//! lower ones. Drop shadows are knocked out only through see-through fill.
|
||||
//!
|
||||
//! Shapes come from the layer's alpha (after its mask). Strokes and spread / choke measure
|
||||
//! distances with a 5 × 5 chamfer metric seeded at sub-pixel edge offsets (as Photoshop does);
|
||||
//! precise glows and chiselled bevels use an exact Euclidean distance transform. Soft falloffs
|
||||
//! are two box blurs (a tent).
|
||||
//! Shapes come from the layer's alpha (after its mask). A stroke's outer edge, and precise glows /
|
||||
//! chiselled bevels, use an exact Euclidean transform: a 5 × 5 chamfer's level sets are polygons,
|
||||
//! which a wide stroke shows as flat facets (#3646). Inside stroke edges and spread / choke keep the
|
||||
//! cheaper chamfer. Soft falloffs are two box blurs (a tent).
|
||||
|
||||
use photocraft_color::blend::BlendMode;
|
||||
use photocraft_doc::Pattern;
|
||||
@@ -394,12 +394,30 @@ fn dist_outside(s: &Map) -> Vec<f32> {
|
||||
/// Distance metric for effect distance fields.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Metric {
|
||||
/// Exact Euclidean (precise glows, bevels).
|
||||
/// Exact Euclidean (effect edges).
|
||||
Euclidean,
|
||||
/// 5 × 5 chamfer (strokes, spread / choke; see [`chamfer_nearest`]).
|
||||
/// 5 × 5 chamfer (inside strokes, spread / choke; see [`chamfer_nearest`]).
|
||||
Chamfer,
|
||||
}
|
||||
|
||||
/// Outside width from which a stroke's outer edge uses the exact Euclidean transform instead of
|
||||
/// the fitted 5 × 5 chamfer.
|
||||
///
|
||||
/// The chamfer's level sets are octagons: measured against a point source, its distance exceeds
|
||||
/// the Euclidean radius by up to `0.027 · r` px — 0.48 px at r = 18 (the widest outside stroke any
|
||||
/// Photoshop oracle matches with the chamfer) and 1.6 px at r = 60, where a wide stroke's boundary
|
||||
/// visibly facets (#3646). Half a pixel of deviation is reached at r ≈ 19, so strokes narrower
|
||||
/// than 20 px keep the chamfer, whose sub-pixel edge seeding Photoshop matches at small offsets,
|
||||
/// and wider ones stay round.
|
||||
pub const STROKE_CHAMFER_MAX: f32 = 20.0;
|
||||
|
||||
/// Whether a stroke whose outside edge is `out_w` px wide uses the exact Euclidean transform (round)
|
||||
/// rather than the 5 × 5 chamfer's octagon ([`STROKE_CHAMFER_MAX`]). The CPU compositor and the GPU
|
||||
/// compositor's `program_with` both call this, so a stroke picks the same field in each.
|
||||
pub fn stroke_outside_exact(out_w: f32) -> bool {
|
||||
out_w >= STROKE_CHAMFER_MAX
|
||||
}
|
||||
|
||||
fn dist_outside_by(s: &Map, m: Metric) -> Vec<f32> {
|
||||
if m == Metric::Chamfer {
|
||||
// Seeds start at their sub-pixel edge offset (1 − coverage).
|
||||
@@ -1657,9 +1675,14 @@ pub struct FxMaps {
|
||||
per: Vec<Vec<Map>>,
|
||||
bevel_paint: Vec<BevelPaint>,
|
||||
din: Option<Vec<f32>>,
|
||||
/// Stroke outside distance below [`STROKE_CHAMFER_MAX`]: the fitted 5 × 5 chamfer.
|
||||
dout: Option<Vec<f32>>,
|
||||
/// Shape layers: distance outside the vector outline (from local coverage).
|
||||
/// Stroke outside distance at or above [`STROKE_CHAMFER_MAX`]: the exact Euclidean transform.
|
||||
dout_exact: Option<Vec<f32>>,
|
||||
/// Shape layers: chamfer distance outside the vector outline (from local coverage).
|
||||
vdout: Option<Vec<f32>>,
|
||||
/// Shape layers: exact Euclidean distance outside the vector outline (from local coverage).
|
||||
vdout_exact: Option<Vec<f32>>,
|
||||
/// `shape` joins the alpha with a filled shape's outline (`crate::effect_outline`).
|
||||
outline: bool,
|
||||
/// Frames of gradient strokes by outside width (bits): see [`stroke_frame`].
|
||||
@@ -1678,7 +1701,14 @@ impl FxMaps {
|
||||
pub fn bytes(&self) -> usize {
|
||||
let n = self.shape.v.len();
|
||||
let maps: usize = self.per.iter().map(Vec::len).sum();
|
||||
(1 + maps + usize::from(self.din.is_some()) + usize::from(self.dout.is_some()) + usize::from(self.vdout.is_some())) * n * 4
|
||||
(1 + maps
|
||||
+ usize::from(self.din.is_some())
|
||||
+ usize::from(self.dout.is_some())
|
||||
+ usize::from(self.dout_exact.is_some())
|
||||
+ usize::from(self.vdout.is_some())
|
||||
+ usize::from(self.vdout_exact.is_some()))
|
||||
* n
|
||||
* 4
|
||||
}
|
||||
|
||||
fn crop_vec(&self, v: &[f32], to: Rect, fill: f32) -> Vec<f32> {
|
||||
@@ -1765,10 +1795,34 @@ pub(crate) fn build_maps_prepared(
|
||||
.collect();
|
||||
let has_stroke = items.iter().any(|e| matches!(e, Effect::Stroke(_)));
|
||||
let vector_shape = matches!(layer.content, photocraft_doc::LayerContent::Shape(_));
|
||||
let (din, dout) = if has_stroke { (Some(dist_inside_by(&shape, Metric::Chamfer)), Some(dist_outside_by(&shape, Metric::Chamfer))) } else { (None, None) };
|
||||
// Without an outline (unfilled shapes), estimate the vector outline from local coverage.
|
||||
// A stroke's outer edge keeps the 5 × 5 chamfer while its outside width is under
|
||||
// `STROKE_CHAMFER_MAX` — Photoshop matches the chamfer's sub-pixel edge seeding at small
|
||||
// offsets — and uses the exact Euclidean transform at or above it, where the chamfer's octagon
|
||||
// facets a wide stroke (#3646). Inside stroke distances always keep the chamfer. Each outer
|
||||
// field is built only when a stroke of that width is present; the compositor picks per stroke,
|
||||
// so one layer may hold both a narrow and a wide stroke.
|
||||
let out_widths: Vec<f32> =
|
||||
items.iter().filter_map(|e| if let Effect::Stroke(st) = e { Some(stroke_widths(st).1) } else { None }).filter(|w| *w > 0.0).collect();
|
||||
let chamfer_out = out_widths.iter().any(|&w| !stroke_outside_exact(w));
|
||||
let exact_out = out_widths.iter().any(|&w| stroke_outside_exact(w));
|
||||
let (din, dout, dout_exact) = if has_stroke {
|
||||
(
|
||||
Some(dist_inside_by(&shape, Metric::Chamfer)),
|
||||
chamfer_out.then(|| dist_outside_by(&shape, Metric::Chamfer)),
|
||||
exact_out.then(|| dist_outside_by(&shape, Metric::Euclidean)),
|
||||
)
|
||||
} else {
|
||||
(None, None, None)
|
||||
};
|
||||
// Without an outline (unfilled shapes), estimate the vector outline from local coverage; it
|
||||
// picks the chamfer or the exact transform the same way.
|
||||
let outline = crate::effect_outline(layer).is_some();
|
||||
let vdout = (has_stroke && vector_shape && !outline).then(|| dist_outside_by(&local_coverage(&shape), Metric::Chamfer));
|
||||
let (vdout, vdout_exact) = if has_stroke && vector_shape && !outline {
|
||||
let lc = local_coverage(&shape);
|
||||
(chamfer_out.then(|| dist_outside_by(&lc, Metric::Chamfer)), exact_out.then(|| dist_outside_by(&lc, Metric::Euclidean)))
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
let mut frames: Vec<(u32, Rect)> = Vec::new();
|
||||
for e in &items {
|
||||
if let Effect::Stroke(st) = e
|
||||
@@ -1780,7 +1834,7 @@ pub(crate) fn build_maps_prepared(
|
||||
}
|
||||
}
|
||||
}
|
||||
FxMaps { rect, shape, per, bevel_paint, din, dout, vdout, outline, frames }
|
||||
FxMaps { rect, shape, per, bevel_paint, din, dout, dout_exact, vdout, vdout_exact, outline, frames }
|
||||
}
|
||||
|
||||
/// Far outside any shape (distance fill for cropped distance fields).
|
||||
@@ -1963,10 +2017,13 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
// Strokes. Inside parts are painted over the layer (bottom instance first); outside parts
|
||||
// are slid beneath it, so the first listed (top) instance is processed first.
|
||||
let strokes: Vec<&photocraft_doc::StrokeFx> = items.iter().filter_map(|e| if let Effect::Stroke(s) = e { Some(s) } else { None }).collect();
|
||||
let (din, dout) = match (&maps.din, &maps.dout) {
|
||||
(Some(a), Some(b)) if !strokes.is_empty() => (maps.crop_vec(a, big, 0.0), maps.crop_vec(b, big, FAR)),
|
||||
_ => (Vec::new(), Vec::new()),
|
||||
};
|
||||
let ready = !strokes.is_empty();
|
||||
let din = if ready { maps.din.as_ref().map(|a| maps.crop_vec(a, big, 0.0)).unwrap_or_default() } else { Vec::new() };
|
||||
// A stroke's outer edge picks the chamfer or the exact field by its width
|
||||
// ([`stroke_outside_exact`]); both are cropped here, and only the ones a stroke needs exist.
|
||||
let crop_out = |v: &Option<Vec<f32>>| v.as_ref().map(|b| maps.crop_vec(b, big, FAR));
|
||||
let (dout, dout_exact, vdout, vdout_exact) =
|
||||
if ready { (crop_out(&maps.dout), crop_out(&maps.dout_exact), crop_out(&maps.vdout), crop_out(&maps.vdout_exact)) } else { (None, None, None, None) };
|
||||
let widths = stroke_widths;
|
||||
// A gradient stroke aligned with the layer spans the stroke's own extent.
|
||||
let frame = |st: &photocraft_doc::StrokeFx| maps.stroke_frame(st).unwrap_or(sb);
|
||||
@@ -1994,7 +2051,9 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
for (p, a) in lay.px.iter_mut().zip(&shape.v) {
|
||||
p[3] *= a.min(1.0);
|
||||
}
|
||||
let vdout = maps.vdout.as_ref().filter(|_| vector_shape && !strokes.is_empty()).map(|v| maps.crop_vec(v, big, FAR));
|
||||
// Shape layers without a filled outline stroke their vector outline, estimated from local
|
||||
// coverage; every other layer strokes its shape. The width then picks the field.
|
||||
let vector_outline = vector_shape && !maps.outline;
|
||||
// Outside parts lie beneath the layer and blend onto the backdrop with their own mode. A
|
||||
// higher stroke covers the ones below it (Photoshop: a Multiply stroke listed above a wider
|
||||
// Normal stroke multiplies the backdrop, not the lower stroke). Each stroke's share is its
|
||||
@@ -2012,7 +2071,14 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
// Shape layers: Photoshop strokes the vector outline (estimated from local coverage
|
||||
// for unfilled shapes); the stroke never shows through the shape's pixels. Along a
|
||||
// filled shape's outline it covers the part of each edge pixel outside the path.
|
||||
let d = vdout.as_ref().unwrap_or(&dout);
|
||||
let exact = stroke_outside_exact(out_w);
|
||||
let d: &[f32] = if vector_outline {
|
||||
(if exact { vdout_exact.as_deref() } else { vdout.as_deref() }).unwrap_or_default()
|
||||
} else if exact {
|
||||
dout_exact.as_deref().unwrap_or_default()
|
||||
} else {
|
||||
dout.as_deref().unwrap_or_default()
|
||||
};
|
||||
let mut share = vec![0.0f32; w * h];
|
||||
for (i, sh) in share.iter_mut().enumerate() {
|
||||
let band = (out_w + 0.5 - d[i]).clamp(0.0, 1.0);
|
||||
@@ -2176,15 +2242,23 @@ pub enum FieldKind {
|
||||
BevelOutside,
|
||||
/// `bevel_dist_inside` of the shape: the inside distance of chiselled bevels.
|
||||
BevelInside,
|
||||
/// Chamfer distance outside the shape: outside strokes, and the spread of drop shadows and
|
||||
/// softer outer glows ([`dilate`]).
|
||||
/// Chamfer distance outside the shape: a narrow raster stroke's outer edge (see
|
||||
/// [`stroke_outside_exact`]), and the spread of drop shadows and softer outer glows
|
||||
/// ([`dilate`]); their metric is fitted to Photoshop (#224) and keeps the sub-pixel seeding.
|
||||
StrokeOutside,
|
||||
/// Chamfer distance outside `1 - alpha`: the choke of inner shadows and softer inner glows.
|
||||
ChokeInside,
|
||||
/// Stroke distance inside the shape.
|
||||
StrokeInside,
|
||||
/// Stroke distance outside a shape layer's outline (from its local coverage).
|
||||
/// Exact Euclidean distance outside the shape: a wide raster stroke's outer edge (see
|
||||
/// [`stroke_outside_exact`]). The chamfer's level sets are polygons (an ~8-fold octagon), so a
|
||||
/// wide stroke's outer boundary facets; the shadow / glow spread above keeps the chamfer (#3646).
|
||||
StrokeOutsideExact,
|
||||
/// Stroke distance outside a shape layer's outline (from its local coverage), exact Euclidean.
|
||||
StrokeOutsideVector,
|
||||
/// Chamfer distance outside a shape layer's outline (from its local coverage): a narrow vector
|
||||
/// stroke's outer edge, where the chamfer matches Photoshop (see [`STROKE_CHAMFER_MAX`]).
|
||||
StrokeOutsideVectorChamfer,
|
||||
}
|
||||
|
||||
/// The `kind` distance field of the shape `alpha` (row-major `w × h`). Values past `reach` pixels
|
||||
@@ -2199,7 +2273,9 @@ pub fn distance_field(kind: FieldKind, alpha: Vec<f32>, w: usize, h: usize, reac
|
||||
FieldKind::StrokeOutside => dist_outside_by(&s, Metric::Chamfer),
|
||||
FieldKind::ChokeInside => dist_outside_by(&s.map(|a| 1.0 - a), Metric::Chamfer),
|
||||
FieldKind::StrokeInside => dist_inside_by(&s, Metric::Chamfer),
|
||||
FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Chamfer),
|
||||
FieldKind::StrokeOutsideExact => dist_outside_by(&s, Metric::Euclidean),
|
||||
FieldKind::StrokeOutsideVector => dist_outside_by(&local_coverage(&s), Metric::Euclidean),
|
||||
FieldKind::StrokeOutsideVectorChamfer => dist_outside_by(&local_coverage(&s), Metric::Chamfer),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1315,17 +1315,61 @@ fn shapeless_effect_maps_cover_only_the_band_being_rendered() {
|
||||
// ---------- PSD-fidelity effect semantics (fitted on Photoshop composites) ----------
|
||||
|
||||
#[test]
|
||||
fn stroke_corners_follow_the_5x5_chamfer_metric() {
|
||||
// Square 10..30, outside stroke 3: pixel (9, 7) is offset (1, 3) from the corner pixel.
|
||||
// Photoshop measures √5 + 1 = 3.236 there (exact distance 3.162): coverage 3 + 1 − 3.236.
|
||||
fn stroke_edges_use_the_chamfer_when_narrow_and_the_exact_distance_when_wide() {
|
||||
// #3646: a narrow stroke's outer edge keeps the 5 × 5 chamfer, whose sub-pixel seeding
|
||||
// Photoshop matches at small offsets (see `stroke_outside_exact`); only a wide one — where the
|
||||
// chamfer's octagon facets (see `a_wide_outside_stroke_is_round_not_a_polygon`) — uses the
|
||||
// exact Euclidean transform.
|
||||
// Square 10..30, outside stroke 3: (9, 7) is offset (1, 3) from the corner pixel. Photoshop
|
||||
// measures √5 + 1 = 3.236 there, so coverage is 3 + 1 − 3.236 = 0.764 (the exact distance is
|
||||
// 3.162, coverage 0.838).
|
||||
let d = fx_doc(vec![stroke(3.0, StrokePosition::Outside)]);
|
||||
let a = 1.0 - px(&d, 9, 7)[0]; // blue stroke over white: red channel drops by coverage
|
||||
assert!((a - 0.764).abs() < 0.01, "{a}");
|
||||
// (2, 2) stays Euclidean (two diagonal steps).
|
||||
// (2, 2) is the same in both metrics (two diagonal steps).
|
||||
let a = 1.0 - px(&d, 8, 8)[0];
|
||||
assert!((a - 1.0).abs() < 0.01, "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stroke_metric_switches_at_the_fitted_threshold() {
|
||||
// The widest outside stroke any Photoshop oracle matches with the chamfer is 18 px
|
||||
// (ag-psd read-write/strokes): its octagon deviates 0.48 px from a circle there; 20 px keeps
|
||||
// it. Wider strokes (the 60 px #3646 case) are round.
|
||||
assert!(!crate::effects::stroke_outside_exact(18.0));
|
||||
assert!(crate::effects::stroke_outside_exact(crate::effects::STROKE_CHAMFER_MAX));
|
||||
assert!(crate::effects::stroke_outside_exact(60.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wide_outside_stroke_is_round_not_a_polygon() {
|
||||
// A point source dilated by 60 px must stay a circle. The 5 × 5 chamfer's octagonal level set
|
||||
// made the boundary swing ~2.5 px at this radius (~10 px at 245 px) — the "low-poly" #3646.
|
||||
let mut d = doc_white(170, 170);
|
||||
let mut l = solid_layer("dot", Rect::new(85, 85, 86, 86), [1.0, 0.0, 0.0, 1.0]);
|
||||
l.effects.items = vec![stroke(60.0, StrokePosition::Outside)];
|
||||
d.layers.push(l);
|
||||
let buf = render(&d, Rect::new(0, 0, 170, 170));
|
||||
let at = |x: i32, y: i32| buf.px[(y as usize) * 170 + x as usize];
|
||||
let (mut lo, mut hi) = (f64::MAX, 0.0f64);
|
||||
let stroke_at = |x: i32, y: i32| x >= 0 && y >= 0 && x < 170 && y < 170 && at(x, y)[2] > 0.5 && at(x, y)[0] < 0.5;
|
||||
for k in 0..72 {
|
||||
let th = (k as f64) * std::f64::consts::TAU / 72.0;
|
||||
let (dx, dy) = (th.cos(), th.sin());
|
||||
let mut r = 0.0f64;
|
||||
let mut t = 0.0f64;
|
||||
while t < 84.0 {
|
||||
if stroke_at((85.0 + dx * t).round() as i32, (85.0 + dy * t).round() as i32) {
|
||||
r = t;
|
||||
}
|
||||
t += 0.25;
|
||||
}
|
||||
lo = lo.min(r);
|
||||
hi = hi.max(r);
|
||||
}
|
||||
assert!(hi - lo <= 2.0, "the 60 px stroke boundary swings {lo}..{hi} px — a polygon, not a circle (#3646)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inside_stroke_respects_partial_edge_coverage() {
|
||||
// A 25 %-alpha edge column puts the edge 0.75 px further out: a 3 px inside stroke then
|
||||
|
||||
@@ -865,6 +865,10 @@ pub struct Document {
|
||||
pub layers: Vec<Layer>,
|
||||
pub channels: Vec<AlphaChannel>,
|
||||
pub guides: Guides,
|
||||
/// The rulers' zero point in document pixels (`[x, y]`), dragged from the ruler corner. The
|
||||
/// rulers, the Info panel and other position readouts measure from it; `[0, 0]` (the
|
||||
/// image's top-left) is the default.
|
||||
pub ruler_origin: [f64; 2],
|
||||
/// Active selection as a grayscale coverage surface (None = no selection).
|
||||
pub selection: Option<Surface>,
|
||||
pub metadata: Metadata,
|
||||
@@ -952,6 +956,7 @@ impl Document {
|
||||
layers: Vec::new(),
|
||||
channels: Vec::new(),
|
||||
guides: Guides::default(),
|
||||
ruler_origin: [0.0, 0.0],
|
||||
selection: None,
|
||||
metadata: Metadata::default(),
|
||||
global_light: GlobalLight::default(),
|
||||
|
||||
@@ -17,6 +17,9 @@
|
||||
//! Laplacian pyramid, each coefficient from the layer sharpest at that scale
|
||||
//! ([`pyramid::fuse_stack`]; `haloControl` keeps a bright object's defocused glow out of the
|
||||
//! coarse levels).
|
||||
//! Stack Images can also add a hidden Depth layer, the layer each pixel is sharpest in by depth
|
||||
//! from focus ([`photocraft_algo::dff`]): black = the bottom layer, white = the top, so that once
|
||||
//! on a layer mask it drives Lens Blur's depth map.
|
||||
|
||||
use photocraft_algo::panorama::Layout;
|
||||
use photocraft_algo::pyramid;
|
||||
@@ -169,6 +172,10 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(cmd, format!("`haloControl` must be a number from 0 to {}", pyramid::HALO_MAX))),
|
||||
},
|
||||
};
|
||||
let want_depth = p.get("depthMap").and_then(Value::as_bool).unwrap_or(false);
|
||||
if want_depth && method != "stack" {
|
||||
return Err(bad(cmd, "`depthMap` needs `method`: stack"));
|
||||
}
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let doc: std::sync::Arc<Document> = st.doc.clone();
|
||||
let mut area = Rect::EMPTY;
|
||||
@@ -223,9 +230,33 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let blended = seamless.then(|| b.composite.read_region(area));
|
||||
(weights, blended)
|
||||
};
|
||||
// The depth map: the layer each pixel is sharpest in, from the focus volume guided by the
|
||||
// merged picture (or, without one, by the per-pixel pick), as a hidden gray layer, black =
|
||||
// the bottom layer, white = the top, ready for Lens Blur's depth map once on a mask.
|
||||
let depth_px = want_depth.then(|| {
|
||||
let n = fmt.channels();
|
||||
let guide: Vec<f32> = match &blended {
|
||||
Some(px) => (0..w * h)
|
||||
.map(|i| {
|
||||
let c = to_rgba(&fmt, &px[i * n..(i + 1) * n]);
|
||||
0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]
|
||||
})
|
||||
.collect(),
|
||||
None => (0..w * h).map(|i| luma.iter().zip(&weights).map(|(l, wt)| l[i] * wt[i]).sum()).collect(),
|
||||
};
|
||||
let refs: Vec<&[f32]> = luma.iter().map(Vec::as_slice).collect();
|
||||
let dm = photocraft_algo::dff::depth_from_focus(&refs, &guide, w, h, &photocraft_algo::dff::DepthParams::default());
|
||||
let scale = 1.0 / (ids.len() - 1).max(1) as f32;
|
||||
let mut out = vec![0.0f32; w * h * n];
|
||||
for (i, d) in dm.depth.iter().enumerate() {
|
||||
let g = (d * scale).clamp(0.0, 1.0);
|
||||
photocraft_raster::from_rgba_into(&fmt, [g, g, g, 1.0], &mut out[i * n..(i + 1) * n]);
|
||||
}
|
||||
out
|
||||
});
|
||||
let top = *ids.last().ok_or_else(|| EngineError::Other("Auto-Blend needs two or more layers".into()))?;
|
||||
let label = "Auto-Blend Layers";
|
||||
let new_layer = s.edit(label, |doc, active| {
|
||||
let (new_layer, depth_layer) = s.edit(label, |doc, active| {
|
||||
for (id, wt) in ids.iter().zip(&weights) {
|
||||
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
|
||||
let mut mask = LayerMask::hide_all();
|
||||
@@ -233,17 +264,33 @@ fn auto_blend(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
mask.surface.prune();
|
||||
l.mask = Some(mask);
|
||||
}
|
||||
let Some(px) = &blended else { return Ok(None) };
|
||||
let mut below = top;
|
||||
let depth_id = depth_px.as_ref().map(|px| {
|
||||
let mut l = Layer::raster(doc.next_layer_name("Depth"), fmt);
|
||||
l.visible = false;
|
||||
if let Some(surf) = l.surface_mut() {
|
||||
surf.write_region(area, px);
|
||||
surf.prune();
|
||||
}
|
||||
below = doc.insert_above(Some(below), l);
|
||||
below
|
||||
});
|
||||
let Some(px) = &blended else {
|
||||
if depth_id.is_some() {
|
||||
*active = depth_id;
|
||||
}
|
||||
return Ok((None, depth_id));
|
||||
};
|
||||
let mut l = Layer::raster(doc.next_layer_name("Blended"), fmt);
|
||||
if let Some(surf) = l.surface_mut() {
|
||||
surf.write_region(area, px);
|
||||
surf.prune();
|
||||
}
|
||||
let nid = doc.insert_above(Some(top), l);
|
||||
let nid = doc.insert_above(Some(below), l);
|
||||
*active = Some(nid);
|
||||
Ok(Some(nid))
|
||||
Ok((Some(nid), depth_id))
|
||||
})?;
|
||||
Ok(json!({"method": method, "layers": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "blended": new_layer.map(|l| l.0)}))
|
||||
Ok(json!({"method": method, "layers": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "blended": new_layer.map(|l| l.0), "depth": depth_layer.map(|l| l.0)}))
|
||||
}
|
||||
|
||||
macro_rules! spec {
|
||||
@@ -260,7 +307,12 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##,
|
||||
auto_align
|
||||
),
|
||||
spec!("edit.autoBlendLayers", "Auto-Blend Layers…", r##"{"method":"panorama|stack","seamlessTones":bool=true,"haloControl":0..8=2}"##, auto_blend),
|
||||
spec!(
|
||||
"edit.autoBlendLayers",
|
||||
"Auto-Blend Layers…",
|
||||
r##"{"method":"panorama|stack","seamlessTones":bool=true,"haloControl":0..8=2,"depthMap":bool=false}"##,
|
||||
auto_blend
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -533,4 +585,56 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Three layers, each sharp in one third: the Depth layer says which, black to white from
|
||||
/// the bottom layer to the top, hidden, and undone with the rest.
|
||||
#[test]
|
||||
fn auto_blend_stack_depth_map() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 96, "height": 48, "depth": depth, "background": "transparent"})).unwrap();
|
||||
let mut ids = Vec::new();
|
||||
for k in 0..3 {
|
||||
s.execute("layer.new.layer", json!({"name": format!("L{k}")})).unwrap();
|
||||
s.edit("third", |doc, active| {
|
||||
let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
|
||||
for y in 0..48 {
|
||||
for x in 0..96 {
|
||||
let v = if x / 32 == k && ((x / 2) + (y / 2)) % 2 == 0 {
|
||||
0.2
|
||||
} else if x / 32 == k {
|
||||
0.8
|
||||
} else {
|
||||
0.5
|
||||
};
|
||||
surf.fill_rect(Rect::new(x, y, x + 1, y + 1), &[v, v, v, 1.0]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
ids.push(s.active().unwrap().active_layer.unwrap());
|
||||
}
|
||||
select(&mut s, &ids);
|
||||
assert!(s.execute("edit.autoBlendLayers", json!({"method": "panorama", "depthMap": true})).is_err());
|
||||
for seamless in [false, true] {
|
||||
let r = s.execute("edit.autoBlendLayers", json!({"method": "stack", "seamlessTones": seamless, "depthMap": true})).unwrap();
|
||||
let doc = &s.active().unwrap().doc;
|
||||
let d = doc.layer(LayerId(r["depth"].as_u64().unwrap())).unwrap();
|
||||
assert!(!d.visible && d.name.starts_with("Depth"), "depth {depth}: {} visible {} {r}", d.name, d.visible);
|
||||
let surf = d.surface().unwrap();
|
||||
for (x, want) in [(8, 0.0), (48, 0.5), (88, 1.0)] {
|
||||
let px = surf.pixel(x, 24);
|
||||
assert!((px[0] - want).abs() < 0.2 && (px[3] - 1.0).abs() < 1e-3, "depth {depth} seamless {seamless} x {x}: {px:?}");
|
||||
}
|
||||
assert_eq!(r["blended"].is_null(), !seamless);
|
||||
if seamless {
|
||||
// The merged layer sits above the depth layer and is the active one.
|
||||
assert_eq!(s.active().unwrap().active_layer, Some(LayerId(r["blended"].as_u64().unwrap())));
|
||||
}
|
||||
s.undo();
|
||||
assert!(s.active().unwrap().doc.layer(LayerId(r["depth"].as_u64().unwrap())).is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -315,6 +315,60 @@ impl ColorState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether opening `doc` asks about its profile first (Ask When Opening, for a mismatched or
|
||||
/// missing profile), and if so what the prompt shows: the report [`Self::open_policy`]
|
||||
/// would give, with `ask: true` and `action` the answer the policy suggests. Nothing is
|
||||
/// changed: the answer is applied with [`Self::resolve_open`] before the document opens.
|
||||
pub fn open_question(&self, doc: &Document) -> Option<Value> {
|
||||
let space = mode_space(doc.mode);
|
||||
if !matches!(space, ColorSpace::Rgb | ColorSpace::Cmyk | ColorSpace::Gray) {
|
||||
return None;
|
||||
}
|
||||
let working = self.working(doc.mode);
|
||||
let policy = self.settings.policy(doc.mode);
|
||||
let embedded = doc.icc_profile.as_ref().and_then(|b| profile_from_bytes(b).ok()).filter(|p| p.color_space == space);
|
||||
match embedded {
|
||||
Some(emb) => {
|
||||
let linear_hdr =
|
||||
doc.depth == SampleType::F32 && (emb.same_colors(Builtin::LinearSrgb.profile()) || emb.same_colors(photocraft_cms::builtin::linear_gray()));
|
||||
if !self.settings.ask_on_mismatch || emb.same_colors(&working) || linear_hdr {
|
||||
return None;
|
||||
}
|
||||
let action = match policy {
|
||||
Policy::Preserve => "preserve",
|
||||
Policy::Off => "discard",
|
||||
Policy::Convert => "convert",
|
||||
};
|
||||
Some(
|
||||
json!({"embedded": emb.description, "working": working.description, "mismatch": true, "policy": policy.id(), "action": action, "ask": true}),
|
||||
)
|
||||
}
|
||||
None if self.settings.ask_on_missing => {
|
||||
Some(json!({"working": working.description, "policy": policy.id(), "missing": true, "action": "preserve", "ask": true}))
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the answer to an [`Self::open_question`] to a document not opened yet:
|
||||
/// `preserve` (keep the embedded profile, or leave an untagged file as is), `convert` to the
|
||||
/// working space, `discard` the embedded profile, or `assignWorking` (untagged files).
|
||||
pub fn resolve_open(&self, doc: &mut Document, action: &str) -> Result<()> {
|
||||
match action {
|
||||
"preserve" | "useEmbedded" => Ok(()),
|
||||
"convert" | "convertToWorking" => convert_document(doc, &self.working(doc.mode), self.settings.intent(), self.settings.bpc),
|
||||
"discard" | "off" => {
|
||||
doc.icc_profile = None;
|
||||
Ok(())
|
||||
}
|
||||
"assignWorking" => {
|
||||
doc.icc_profile = Some(self.working(doc.mode).to_bytes());
|
||||
Ok(())
|
||||
}
|
||||
other => Err(EngineError::Other(format!("unknown answer `{other}` (preserve|convert|discard|assignWorking)"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Proofing state of a document (defaults: coated CMYK, relative colorimetric + BPC, off).
|
||||
pub fn proof(&self, doc: DocId) -> ProofView {
|
||||
self.proofs.get(&doc).cloned().unwrap_or_else(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
|
||||
@@ -1398,6 +1452,35 @@ mod settings_tests {
|
||||
// The Blend Text Colors Using Gamma test is `tests/text_gamma.rs`: it changes the
|
||||
// process-wide text gamma, which would race every unit test here that composites type.
|
||||
|
||||
#[test]
|
||||
fn open_question_asks_only_when_set_and_resolve_open_applies_each_answer() {
|
||||
let mut s = Session::new();
|
||||
// Ask When Opening off: nothing to ask, mismatched or missing.
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": false, "askOnMissing": false})).unwrap();
|
||||
assert!(s.color.open_question(&tagged("adobe-rgb-compat")).is_none());
|
||||
let mut untagged = tagged("srgb");
|
||||
untagged.icc_profile = None;
|
||||
assert!(s.color.open_question(&untagged).is_none());
|
||||
// On: a mismatch asks, suggesting the policy's answer; a matching profile never asks.
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": true, "askOnMissing": true, "policyRgb": "convert"})).unwrap();
|
||||
let q = s.color.open_question(&tagged("adobe-rgb-compat")).unwrap();
|
||||
assert_eq!((q["mismatch"].as_bool(), q["action"].as_str()), (Some(true), Some("convert")));
|
||||
assert!(q["embedded"].as_str().unwrap().starts_with("Adobe RGB"));
|
||||
assert!(s.color.open_question(&tagged("srgb")).is_none());
|
||||
assert_eq!(s.color.open_question(&untagged).unwrap()["missing"], true);
|
||||
// Asking changes nothing; the answer is applied to the document.
|
||||
let mut d = tagged("adobe-rgb-compat");
|
||||
s.color.resolve_open(&mut d, "preserve").unwrap();
|
||||
assert!(desc(&d).unwrap().starts_with("Adobe RGB"));
|
||||
s.color.resolve_open(&mut d, "convert").unwrap();
|
||||
assert_eq!(desc(&d).as_deref(), Some("sRGB IEC61966-2.1"));
|
||||
s.color.resolve_open(&mut d, "discard").unwrap();
|
||||
assert_eq!(desc(&d), None);
|
||||
s.color.resolve_open(&mut d, "assignWorking").unwrap();
|
||||
assert_eq!(desc(&d).as_deref(), Some("sRGB IEC61966-2.1"));
|
||||
assert!(s.color.resolve_open(&mut d, "explode").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_policies() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -881,6 +881,32 @@ fn guide_cmd(s: &mut Session, p: &Value, op: &str) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Farthest the ruler zero point may sit from the image, in document pixels.
|
||||
const MAX_RULER_ORIGIN: f64 = 1.0e7;
|
||||
|
||||
/// Move the rulers' zero point (`view.setRulerOrigin`), or put it back at the image's top-left
|
||||
/// (`view.resetRulerOrigin`, `p` = None). Undoable like the guides.
|
||||
fn ruler_origin_cmd(s: &mut Session, p: Option<&Value>) -> Result<Value> {
|
||||
let origin = match p {
|
||||
None => [0.0, 0.0],
|
||||
Some(p) => {
|
||||
let axis = |k: &str| {
|
||||
p.get(k)
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|v| v.is_finite() && v.abs() <= MAX_RULER_ORIGIN)
|
||||
.ok_or_else(|| EngineError::Other(format!("`{k}` must be a number of pixels within ±{MAX_RULER_ORIGIN}")))
|
||||
};
|
||||
[axis("x")?, axis("y")?]
|
||||
}
|
||||
};
|
||||
let label = if p.is_some() { "Set Ruler Origin" } else { "Reset Ruler Origin" };
|
||||
s.edit(label, |doc, _| {
|
||||
doc.ruler_origin = origin;
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"x": origin[0], "y": origin[1]}))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
macro_rules! spec {
|
||||
($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => {
|
||||
@@ -987,6 +1013,18 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
spec!("view.deleteGuide", "Delete Guide", &[], None, r##"{"orientation":"horizontal|vertical","index":n}"##, has_doc, |s, p| guide_cmd(s, p, "delete")),
|
||||
spec!("view.clearGuides", "Clear Guides", &["View"], None, "{}", has_doc, |s, p| guide_cmd(s, p, "clear")),
|
||||
spec!(
|
||||
"view.setRulerOrigin",
|
||||
"Set Ruler Origin",
|
||||
&[],
|
||||
None,
|
||||
r##"{"x":px,"y":px} (the rulers' zero point in document pixels; the rulers and Info panel measure from it)"##,
|
||||
has_doc,
|
||||
|s, p| ruler_origin_cmd(s, Some(p))
|
||||
),
|
||||
spec!("view.resetRulerOrigin", "Reset Ruler Origin", &[], None, "{} (zero point back at the image's top-left)", has_doc, |s, _| ruler_origin_cmd(
|
||||
s, None
|
||||
)),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1915,6 +1953,28 @@ mod tests {
|
||||
assert!(s.execute("view.moveGuide", json!({"orientation": "vertical", "index": 3, "position": 1})).is_err());
|
||||
}
|
||||
|
||||
/// #2955: the rulers' zero point is set and reset by command, undoable, and bad params are
|
||||
/// refused without touching the document.
|
||||
#[test]
|
||||
fn ruler_origin_is_set_reset_and_undoable() {
|
||||
let mut s = session();
|
||||
assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]);
|
||||
assert_eq!(s.execute("view.setRulerOrigin", json!({"x": 40, "y": 12.5})).unwrap(), json!({"x": 40.0, "y": 12.5}));
|
||||
assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]);
|
||||
s.execute("view.resetRulerOrigin", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().doc.ruler_origin, [0.0, 0.0]);
|
||||
s.undo();
|
||||
assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]);
|
||||
for bad in [json!({}), json!({"x": 1}), json!({"x": "a", "y": 2}), json!({"x": 1e300, "y": 0}), json!({"x": -2e7, "y": 0}), json!(null), json!([1, 2])]
|
||||
{
|
||||
assert!(s.execute("view.setRulerOrigin", bad.clone()).is_err(), "{bad} is refused");
|
||||
}
|
||||
assert_eq!(s.active().unwrap().doc.ruler_origin, [40.0, 12.5]);
|
||||
let mut empty = Session::new();
|
||||
assert!(empty.execute("view.setRulerOrigin", json!({"x": 1, "y": 2})).is_err());
|
||||
assert!(empty.execute("view.resetRulerOrigin", json!({})).is_err());
|
||||
}
|
||||
|
||||
/// The last guide added in `orientation` for `position`.
|
||||
fn new_guide(s: &mut Session, orientation: &str, position: Value) -> f64 {
|
||||
s.execute("view.newGuide", json!({"orientation": orientation, "position": position})).unwrap();
|
||||
|
||||
@@ -412,7 +412,10 @@ impl Session {
|
||||
/// Open a file in the background: read (for a path) and decode on a worker, with progress
|
||||
/// (per layer for PSD/PSB) and cancellation, then add the document like
|
||||
/// [`Session::open_document`] (Color Settings policies apply). `name` names the document.
|
||||
/// The job's result is `{document, name, warnings, color}`; on wasm it runs inline.
|
||||
/// The job's result is `{document, name, warnings, color}`; on wasm it runs inline. When
|
||||
/// Color Settings ask about the file's profile, the document is held back instead and the
|
||||
/// result is `{held, name, warnings, color}` (`color` the question): take it with
|
||||
/// [`Session::take_held_open`] once answered.
|
||||
pub fn start_open(&mut self, name: &str, source: OpenSource) -> Result<Started> {
|
||||
let label = format!("Opening {name}");
|
||||
let name_w = name.to_string();
|
||||
@@ -438,6 +441,13 @@ impl Session {
|
||||
})
|
||||
},
|
||||
move |s, r: photocraft_io::ImportResult| {
|
||||
// Ask When Opening: held back until the prompt is answered (`take_held_open`). A
|
||||
// developed raw has no embedded profile to ask about.
|
||||
let raw = r.warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));
|
||||
if let Some(question) = s.color.open_question(&r.document).filter(|_| !raw) {
|
||||
let held = s.hold_open(r.document, r.source_read_only);
|
||||
return Ok(json!({"held": held, "name": name_a, "warnings": r.warnings, "color": question}));
|
||||
}
|
||||
let (index, color) = s.open_document(r.document, None);
|
||||
if let Some(st) = s.active_mut() {
|
||||
st.source_read_only = r.source_read_only;
|
||||
|
||||
@@ -463,6 +463,33 @@ fn open_runs_as_a_job_and_cancel_adds_nothing() {
|
||||
assert!(matches!(wait_event(&mut s, id).outcome, JobOutcome::Failed(_)));
|
||||
}
|
||||
|
||||
/// Ask When Opening: a file whose profile doesn't match is decoded but not added; the shell takes
|
||||
/// it once the prompt is answered. Without Ask it opens as usual.
|
||||
#[test]
|
||||
fn an_open_that_asks_about_its_profile_holds_the_document_back() {
|
||||
let mut src = session(8, 8);
|
||||
let mut doc = (*src.active().unwrap().doc).clone();
|
||||
doc.icc_profile = Some(photocraft_cms::Builtin::from_id("adobe-rgb-compat").unwrap().profile().to_bytes());
|
||||
let bytes = Arc::new(photocraft_io::export(&doc, "x.png", &Default::default()).unwrap().bytes);
|
||||
src.close(0);
|
||||
let mut s = Session::new();
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": true, "policyRgb": "preserve"})).unwrap();
|
||||
let id = job(s.start_open("x.png", OpenSource::Bytes(Arc::clone(&bytes))).unwrap());
|
||||
let JobOutcome::Done(v) = wait_event(&mut s, id).outcome else { panic!() };
|
||||
assert!(s.documents().is_empty(), "held back, not opened");
|
||||
assert_eq!((v["color"]["mismatch"].as_bool(), v["color"]["ask"].as_bool(), v["color"]["action"].as_str()), (Some(true), Some(true), Some("preserve")));
|
||||
let held = v["held"].as_u64().unwrap();
|
||||
let (taken, _) = s.take_held_open(held).expect("the held document");
|
||||
assert!(taken.icc_profile.is_some());
|
||||
assert!(s.take_held_open(held).is_none(), "taken once");
|
||||
|
||||
s.execute("edit.colorSettings", json!({"askOnMismatch": false})).unwrap();
|
||||
let id = job(s.start_open("x.png", OpenSource::Bytes(bytes)).unwrap());
|
||||
let JobOutcome::Done(v) = wait_event(&mut s, id).outcome else { panic!() };
|
||||
assert!(v.get("held").is_none());
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wait_job_blocks_until_applied() {
|
||||
let mut s = session(400, 300);
|
||||
|
||||
@@ -639,6 +639,7 @@ fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
|
||||
layers: _,
|
||||
channels,
|
||||
guides: _,
|
||||
ruler_origin: _,
|
||||
selection: _,
|
||||
metadata: _,
|
||||
global_light,
|
||||
|
||||
@@ -460,6 +460,11 @@ pub struct Session {
|
||||
/// A finished live stroke offered to the `paint.stroke` / `paint.pencil` that commits it
|
||||
/// ([`Session::offer_live_stroke`]).
|
||||
pub(crate) live_commit: Option<brush_cmds::LiveCommit>,
|
||||
/// Documents a background open decoded but held back until the user answers the profile
|
||||
/// prompt ([`ColorState::open_question`](color_cmds::ColorState::open_question)): `(id,
|
||||
/// document, source read-only)`. The shell takes them with [`Session::take_held_open`].
|
||||
held_opens: Vec<(u64, Document, bool)>,
|
||||
next_held_open: u64,
|
||||
}
|
||||
|
||||
/// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when
|
||||
@@ -545,6 +550,21 @@ impl Session {
|
||||
i
|
||||
}
|
||||
|
||||
/// Holds a decoded document back from opening (see `held_opens`); returns its id.
|
||||
pub(crate) fn hold_open(&mut self, doc: Document, source_read_only: bool) -> u64 {
|
||||
self.next_held_open = self.next_held_open.wrapping_add(1);
|
||||
self.held_opens.push((self.next_held_open, doc, source_read_only));
|
||||
self.next_held_open
|
||||
}
|
||||
|
||||
/// Takes a document a background open held back for the profile prompt: the document and
|
||||
/// whether its source is read-only. `None` when there is no such document (already taken).
|
||||
pub fn take_held_open(&mut self, id: u64) -> Option<(Document, bool)> {
|
||||
let i = self.held_opens.iter().position(|(h, _, _)| *h == id)?;
|
||||
let (_, doc, read_only) = self.held_opens.remove(i);
|
||||
Some((doc, read_only))
|
||||
}
|
||||
|
||||
pub fn close(&mut self, index: usize) -> Option<DocState> {
|
||||
if index >= self.docs.len() {
|
||||
return None;
|
||||
|
||||
@@ -230,6 +230,7 @@ pub(crate) fn doc_m(d: &Document, sink: &mut dyn Sink) -> DocM {
|
||||
layers: d.layers.iter().map(|l| layer_m(l, sink)).collect(),
|
||||
channels: d.channels.iter().map(|c| channel_m(c, sink)).collect(),
|
||||
guides: d.guides.clone(),
|
||||
ruler_origin: d.ruler_origin,
|
||||
selection: d.selection.as_ref().map(|s| surface_m(s, sink)),
|
||||
metadata: MetadataM {
|
||||
xmp: d.metadata.xmp.clone(),
|
||||
@@ -628,6 +629,7 @@ impl Loader<'_> {
|
||||
layers,
|
||||
channels,
|
||||
guides: m.guides.clone(),
|
||||
ruler_origin: m.ruler_origin,
|
||||
selection: self.opt_surface(&m.selection)?,
|
||||
metadata: md,
|
||||
global_light: m.global_light,
|
||||
|
||||
@@ -46,6 +46,9 @@ pub struct DocM {
|
||||
pub layers: Vec<LayerM>,
|
||||
pub channels: Vec<ChannelM>,
|
||||
pub guides: Guides,
|
||||
/// The rulers' zero point in document pixels (absent in older files: the top-left).
|
||||
#[serde(default)]
|
||||
pub ruler_origin: [f64; 2],
|
||||
pub selection: Option<SurfaceM>,
|
||||
pub metadata: MetadataM,
|
||||
pub global_light: GlobalLight,
|
||||
|
||||
@@ -230,6 +230,7 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
|
||||
});
|
||||
d.guides =
|
||||
Guides { horizontal: vec![10.0, 20.5], vertical: vec![100.25], colors: vec![GuideColor { vertical: true, position: 100.25, rgb: [0x33, 0x66, 0xff] }] };
|
||||
d.ruler_origin = [12.5, -4.25];
|
||||
let mut sel = Surface::new(PixelFormat::GRAY8);
|
||||
scribble(&mut sel, 14, false);
|
||||
d.selection = Some(sel);
|
||||
|
||||
+51
-2
@@ -434,7 +434,15 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool,
|
||||
// composite_with_effects' stroke bands (maps 0 outside, 1 inside)
|
||||
let (in_w, out_w) = stroke_widths(st);
|
||||
if out_w > 0.0 {
|
||||
let d = b.field(if vector_shape { FieldKind::StrokeOutsideVector } else { FieldKind::StrokeOutside }, out_w);
|
||||
// Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646);
|
||||
// the CPU picks the same field by the same width (`stroke_outside_exact`).
|
||||
let kind = match (vector_shape, photocraft_compose::effects::stroke_outside_exact(out_w)) {
|
||||
(true, true) => FieldKind::StrokeOutsideVector,
|
||||
(true, false) => FieldKind::StrokeOutsideVectorChamfer,
|
||||
(false, true) => FieldKind::StrokeOutsideExact,
|
||||
(false, false) => FieldKind::StrokeOutside,
|
||||
};
|
||||
let d = b.field(kind, out_w);
|
||||
let mut s = stage(Kernel::MStroke, Some(d), None, [out_w, 0.0, 0.0, 0.0], 0);
|
||||
s.out = Some(0);
|
||||
b.stages.push(s);
|
||||
@@ -522,7 +530,8 @@ pub(crate) fn field(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, ou
|
||||
/// (the chamfer fields, a sequential sweep) the window is cut into bands that go in parallel. Without
|
||||
/// threads (wasm) there is nothing to spread over, and bands keep the memory small.
|
||||
fn threaded_inside(kind: FieldKind) -> bool {
|
||||
!cfg!(target_arch = "wasm32") && matches!(kind, FieldKind::Outside | FieldKind::Inside | FieldKind::BevelOutside | FieldKind::BevelInside)
|
||||
!cfg!(target_arch = "wasm32")
|
||||
&& matches!(kind, FieldKind::Outside | FieldKind::Inside | FieldKind::BevelOutside | FieldKind::BevelInside | FieldKind::StrokeOutsideExact)
|
||||
}
|
||||
|
||||
/// [`field`] with the halo given (the tests shrink it to see that they notice).
|
||||
@@ -748,7 +757,9 @@ mod tests {
|
||||
FieldKind::ChokeInside,
|
||||
FieldKind::StrokeOutside,
|
||||
FieldKind::StrokeInside,
|
||||
FieldKind::StrokeOutsideExact,
|
||||
FieldKind::StrokeOutsideVector,
|
||||
FieldKind::StrokeOutsideVectorChamfer,
|
||||
] {
|
||||
let reach = 9;
|
||||
let whole = photocraft_compose::effects::distance_field(kind, shape.clone(), w, h, reach as f32);
|
||||
@@ -825,4 +836,42 @@ mod tests {
|
||||
}
|
||||
assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing");
|
||||
}
|
||||
|
||||
/// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact
|
||||
/// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU
|
||||
/// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop
|
||||
/// shadows and softer outer glows keeps the chamfer field (fitted to Photoshop, #224) — so
|
||||
/// routing a wide stroke through the chamfer, or a shadow through the exact field, fails here.
|
||||
#[test]
|
||||
fn a_stroke_uses_the_chamfer_narrow_and_the_exact_field_wide() {
|
||||
use photocraft_color::{BlendMode, Color};
|
||||
use photocraft_doc::{FxCommon, FxPaint, StrokeFx, StrokePosition};
|
||||
let light = GlobalLight::default();
|
||||
let stroke =
|
||||
|size, position| Effect::Stroke(StrokeFx { common: FxCommon::new(BlendMode::Normal, 1.0), size, position, paint: FxPaint::Color(Color::BLACK) });
|
||||
// Narrow (< STROKE_CHAMFER_MAX): the chamfer, exactly as before #3646.
|
||||
let narrow = program(&stroke(6.0, StrokePosition::Outside), &light, false);
|
||||
assert!(narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "a narrow raster outside stroke keeps the chamfer: {:?}", narrow.fields);
|
||||
assert!(!narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact), "…not the exact field: {:?}", narrow.fields);
|
||||
// Wide: the exact transform.
|
||||
let wide = program(&stroke(40.0, StrokePosition::Outside), &light, false);
|
||||
assert!(
|
||||
wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideExact),
|
||||
"a wide raster outside stroke needs the exact outer field: {:?}",
|
||||
wide.fields
|
||||
);
|
||||
assert!(!wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "…not the chamfer field: {:?}", wide.fields);
|
||||
// A shape layer's outline stroke follows the same width rule; the inside edge keeps the chamfer.
|
||||
let vector_narrow = program(&stroke(6.0, StrokePosition::Outside), &light, true);
|
||||
assert!(vector_narrow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVectorChamfer), "{:?}", vector_narrow.fields);
|
||||
let vector_wide = program(&stroke(40.0, StrokePosition::Outside), &light, true);
|
||||
assert!(vector_wide.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutsideVector), "{:?}", vector_wide.fields);
|
||||
let inner = program(&stroke(40.0, StrokePosition::Inside), &light, false);
|
||||
assert!(inner.fields.iter().any(|(k, _)| *k == FieldKind::StrokeInside), "{:?}", inner.fields);
|
||||
// The shadow / softer-glow spread is unchanged: still the chamfer.
|
||||
let Effect::DropShadow(mut s) = Effect::default_drop_shadow() else { unreachable!() };
|
||||
s.spread = 0.5;
|
||||
let shadow = program(&Effect::DropShadow(s), &light, false);
|
||||
assert!(shadow.fields.iter().any(|(k, _)| *k == FieldKind::StrokeOutside), "the shadow spread keeps the chamfer: {:?}", shadow.fields);
|
||||
}
|
||||
}
|
||||
+44
-13
@@ -552,17 +552,18 @@ fn field_reaches(progs: &[fx::MapProgram]) -> HashMap<FieldKind, i32> {
|
||||
want
|
||||
}
|
||||
|
||||
/// Runs `f` inside validation and internal-error scopes and returns the first error raised.
|
||||
/// Runs `f` inside GPU error scopes and returns the first error raised.
|
||||
/// Native wgpu reports errors synchronously; where they only arrive asynchronously (WebGPU) none
|
||||
/// is reported.
|
||||
fn first_error<T>(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option<wgpu::Error>) {
|
||||
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
|
||||
let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
||||
let out = f();
|
||||
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
|
||||
let mut error = None;
|
||||
// Scopes pop in reverse order.
|
||||
for pop in [internal.pop(), validation.pop()] {
|
||||
for pop in [memory.pop(), internal.pop(), validation.pop()] {
|
||||
if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) {
|
||||
error.get_or_insert(e);
|
||||
}
|
||||
@@ -570,6 +571,21 @@ fn first_error<T>(device: &wgpu::Device, f: impl FnOnce() -> T) -> (T, Option<wg
|
||||
(out, error)
|
||||
}
|
||||
|
||||
/// Unwatched native callers need GPU errors to become `Unsupported` instead of reaching wgpu's
|
||||
/// default panic handler. Watched callers keep their fault callbacks, which stop work promptly
|
||||
/// and update the health flag shared with the canvas.
|
||||
fn scoped_work<T>(device: &wgpu::Device, watched: bool, f: impl FnOnce() -> Result<T, Unsupported>) -> Result<T, Unsupported> {
|
||||
// WebGPU errors arrive asynchronously; its callers still use the health callbacks.
|
||||
if watched || cfg!(target_arch = "wasm32") {
|
||||
return f();
|
||||
}
|
||||
let (result, error) = first_error(device, f);
|
||||
match error {
|
||||
Some(error) => Err(Unsupported(format!("GPU work failed: {error}"))),
|
||||
None => result,
|
||||
}
|
||||
}
|
||||
|
||||
impl Compositor {
|
||||
/// Create a compositor with the default accumulation format ([`ACC_FORMAT`]).
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
@@ -902,16 +918,16 @@ impl Compositor {
|
||||
region: Rect,
|
||||
mut sink: impl FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>),
|
||||
) -> Result<Stats, Unsupported> {
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") });
|
||||
let stats = match self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true) {
|
||||
Ok(stats) => stats,
|
||||
Err(error) => {
|
||||
self.prefix.clear();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
queue.submit([encoder.finish()]);
|
||||
Ok(stats)
|
||||
let result = scoped_work(device, self.health.is_some(), || {
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("pc_compose") });
|
||||
let stats = self.encode_inner(device, queue, &mut encoder, doc, region, &mut sink, true)?;
|
||||
queue.submit([encoder.finish()]);
|
||||
Ok(stats)
|
||||
});
|
||||
if result.is_err() {
|
||||
self.discard_failed_work();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Like [`Self::render`] but records into `encoder` without submitting.
|
||||
@@ -924,7 +940,22 @@ impl Compositor {
|
||||
region: Rect,
|
||||
sink: &mut dyn FnMut(&mut wgpu::CommandEncoder, ChunkOut<'_>),
|
||||
) -> Result<Stats, Unsupported> {
|
||||
self.encode_inner(device, queue, encoder, doc, region, sink, false)
|
||||
let result = scoped_work(device, self.health.is_some(), || self.encode_inner(device, queue, encoder, doc, region, sink, false));
|
||||
if result.is_err() {
|
||||
self.discard_failed_work();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn discard_failed_work(&mut self) {
|
||||
// Cache metadata advances while recording. A failed encoder may never execute its
|
||||
// texture uploads or effect maps, so none of those cached pixels can be trusted.
|
||||
self.prefix.clear();
|
||||
self.residents.clear();
|
||||
self.fx.clear();
|
||||
self.patterns.clear();
|
||||
self.temps.clear();
|
||||
self.pool.clear();
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
@@ -81,3 +81,181 @@ fn health_wait_on_a_destroyed_device_is_safe() {
|
||||
assert!(!health.is_ok());
|
||||
assert!(!health.wait(&device, None));
|
||||
}
|
||||
|
||||
fn assert_unwatched_destroyed_device(encode_only: bool) {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = device() else { return };
|
||||
let mut comp = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
let d = Document::with_background("synthetic", Size::new(1, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(0.9, 0.9, 0.9, 1.0));
|
||||
assert!(render_to_vec(&mut comp, &device, &queue, &d, d.bounds()).is_ok());
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
device.destroy();
|
||||
let mut changed = d.clone();
|
||||
changed.layers[0].opacity = 0.4;
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
if encode_only {
|
||||
comp.encode(&device, &queue, &mut encoder, &changed, changed.bounds(), &mut |_, _| {})
|
||||
} else {
|
||||
comp.render(&device, &queue, &changed, changed.bounds(), |_, _| {})
|
||||
}
|
||||
}));
|
||||
assert!(result.is_ok(), "an unwatched device failure must return Unsupported instead of panicking");
|
||||
let error = result.unwrap().expect_err("a destroyed device must not report successful GPU work");
|
||||
assert!(error.0.contains("GPU work failed"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unwatched_destroyed_device_returns_an_error_without_panicking() {
|
||||
assert_unwatched_destroyed_device(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unwatched_encode_on_a_destroyed_device_returns_an_error_without_panicking() {
|
||||
assert_unwatched_destroyed_device(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loss_during_an_unwatched_render_returns_an_error_without_panicking() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = device() else { return };
|
||||
let mut comp = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
comp.set_texture_limit(256);
|
||||
let d = Document::with_background("synthetic", Size::new(512, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(0.9, 0.9, 0.9, 1.0));
|
||||
let mut chunks = 0;
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
comp.render(&device, &queue, &d, d.bounds(), |_, _| {
|
||||
chunks += 1;
|
||||
if chunks == 1 {
|
||||
// A driver reset can arrive after the entry-point health check too.
|
||||
device.destroy();
|
||||
}
|
||||
})
|
||||
}));
|
||||
assert!(chunks > 0, "the injection must occur after GPU work began");
|
||||
assert!(result.is_ok(), "device loss mid-render must return Unsupported instead of panicking");
|
||||
assert!(result.unwrap().is_err(), "a partially failed render must not report success");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_captured_render_error_preserves_the_device_for_a_later_render() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = device() else { return };
|
||||
let mut comp = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
let d = Document::with_background("synthetic", Size::new(1, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(0.9, 0.9, 0.9, 1.0));
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
comp.render(&device, &queue, &d, d.bounds(), |_, _| {
|
||||
// Reject a buffer above the device's valid capability without actually allocating it.
|
||||
let _ = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("synthetic_invalid_buffer"),
|
||||
size: device.limits().max_buffer_size + 1,
|
||||
usage: wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
})
|
||||
}));
|
||||
assert!(result.is_ok(), "GPU validation errors must return Unsupported instead of panicking");
|
||||
let error = result.unwrap().expect_err("an invalid allocation must fail this render");
|
||||
assert!(error.0.contains("synthetic_invalid_buffer"), "{error}");
|
||||
let out = render_to_vec(&mut comp, &device, &queue, &d, d.bounds()).expect("the next fitting render keeps working");
|
||||
let expected = photocraft_compose::flatten(&d);
|
||||
for (cpu, gpu) in expected.px[0].iter().zip(out[0]) {
|
||||
assert!((cpu - gpu).abs() <= 1.0 / 255.0, "the healthy GPU control differs: {cpu} vs {gpu}");
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_recovery_after_invalid_encoder(encode_only: bool) {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = device() else { return };
|
||||
let mut comp = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
let mut d = doc();
|
||||
d.layers[1].effects.items = vec![photocraft_doc::Effect::default_drop_shadow()];
|
||||
// Pipeline creation errors are not proof of missing hardware capabilities: check the
|
||||
// adapter and the features actually enabled on this device before allowing a skip.
|
||||
let required = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING;
|
||||
let features = device.features();
|
||||
for format in [wgpu::TextureFormat::R32Float, wgpu::TextureFormat::R16Float] {
|
||||
let adapter_usages = adapter.get_texture_format_features(format).allowed_usages;
|
||||
let guaranteed_usages = format.guaranteed_format_features(features).allowed_usages;
|
||||
if !adapter_usages.contains(required)
|
||||
|| (!features.contains(wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES) && !guaranteed_usages.contains(required))
|
||||
{
|
||||
eprintln!(
|
||||
"skipping effect-map recovery test: {:?} {format:?} lacks {required:?}; adapter usages={adapter_usages:?}, guaranteed usages={guaranteed_usages:?}, device features={features:?}",
|
||||
adapter.get_info().backend,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
comp.supports(&d).expect("a capable adapter must support the recovery fixture's effect-map pipelines");
|
||||
let src = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 4, usage: wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
|
||||
let dst = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 4, usage: wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
|
||||
let mut injected = false;
|
||||
let mut sink = |encoder: &mut wgpu::CommandEncoder, _: photocraft_gpu::ChunkOut<'_>| {
|
||||
injected = true;
|
||||
// Misaligned copies invalidate the encoder, discarding all recorded effect-map work.
|
||||
encoder.copy_buffer_to_buffer(&src, 0, &dst, 0, 1);
|
||||
if encode_only {
|
||||
// encode does not finish its caller-owned encoder; force an immediate error too.
|
||||
let _ = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("synthetic_invalid_buffer"),
|
||||
size: device.limits().max_buffer_size + 1,
|
||||
usage: wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
let result = if encode_only {
|
||||
let mut encoder = device.create_command_encoder(&Default::default());
|
||||
comp.encode(&device, &queue, &mut encoder, &d, d.bounds(), &mut sink)
|
||||
} else {
|
||||
comp.render(&device, &queue, &d, d.bounds(), sink)
|
||||
};
|
||||
assert!(injected, "the invalid encoder injection must reach the sink");
|
||||
let error = result.expect_err("invalid encoder must fail");
|
||||
assert!(error.0.contains("GPU work failed"), "the injected GPU error must be captured: {error}");
|
||||
let recovered = render_to_vec(&mut comp, &device, &queue, &d, d.bounds()).unwrap();
|
||||
let mut fresh = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
let expected = render_to_vec(&mut fresh, &device, &queue, &d, d.bounds()).unwrap();
|
||||
for (a, b) in recovered.iter().zip(expected.iter()) {
|
||||
for (a, b) in a.iter().zip(b.iter()) {
|
||||
assert!((a - b).abs() <= 1.0 / 255.0, "recovered cached pixels differ: {a} vs {b}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_recovers_effect_maps_after_invalid_encoder() {
|
||||
assert_recovery_after_invalid_encoder(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_recovers_effect_maps_after_invalid_encoder() {
|
||||
assert_recovery_after_invalid_encoder(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loss_during_intermediate_unwatched_submissions_returns_an_error() {
|
||||
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let Some((adapter, device, queue)) = device() else { return };
|
||||
let mut comp = Compositor::try_new_with_format(&device, Compositor::preferred_acc_format(&adapter)).unwrap();
|
||||
comp.set_texture_limit(256);
|
||||
let mut d = Document::with_background("synthetic", Size::new(2048, 1), ColorMode::Rgb, SampleType::U8, Color::rgba(0.9, 0.9, 0.9, 1.0));
|
||||
for _ in 0..300 {
|
||||
let mut layer = d.layers[0].clone();
|
||||
layer.id = photocraft_doc::LayerId::fresh();
|
||||
layer.opacity = 0.5;
|
||||
d.layers.push(layer);
|
||||
}
|
||||
let mut chunks = 0;
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
comp.render(&device, &queue, &d, d.bounds(), |_, _| {
|
||||
chunks += 1;
|
||||
if chunks == 1 {
|
||||
device.destroy();
|
||||
}
|
||||
})
|
||||
}));
|
||||
assert!(chunks > 0);
|
||||
assert!(result.is_ok(), "intermediate submit polling must not escape as a panic");
|
||||
assert!(result.unwrap().is_err());
|
||||
}
|
||||
@@ -298,6 +298,10 @@ fn upsert(raw: &mut Vec<([u8; 4], Vec<u8>)>, key: &[u8; 4], data: Vec<u8>, befor
|
||||
}
|
||||
}
|
||||
|
||||
fn h_of(r: photocraft_geom::Rect) -> usize {
|
||||
r.height() as usize
|
||||
}
|
||||
|
||||
fn psd_mode(m: ColorMode) -> PsdMode {
|
||||
match m {
|
||||
ColorMode::Grayscale => PsdMode::Grayscale,
|
||||
@@ -335,18 +339,28 @@ impl Ex {
|
||||
(-1..self.cc as i16).map(|id| self.encode(id, &[], 0, 0)).collect()
|
||||
}
|
||||
|
||||
fn pixel_channels(&mut self, s: &Surface, name: &str) -> (PsdRect, Vec<ChannelData>) {
|
||||
fn pixel_channels(&self, s: &Surface, name: &str) -> (PsdRect, Vec<ChannelData>, Vec<String>) {
|
||||
let mut warnings = Vec::new();
|
||||
let s = if s.format() != self.fmt {
|
||||
self.warnings.push(format!("layer \"{name}\": pixels converted from {:?} to {:?}", s.format(), self.fmt));
|
||||
warnings.push(format!("layer \"{name}\": pixels converted from {:?} to {:?}", s.format(), self.fmt));
|
||||
s.convert(self.fmt)
|
||||
} else {
|
||||
s.clone()
|
||||
};
|
||||
let r = s.content_bounds();
|
||||
if r.is_empty() {
|
||||
return (PsdRect::default(), self.empty_channels());
|
||||
return (PsdRect::default(), self.empty_channels(), warnings);
|
||||
}
|
||||
// The interleaved gather is the sequential pass for full-canvas layers, so it runs
|
||||
// in row bands on all cores and the band results concatenate in order.
|
||||
let row_len = r.width() as usize;
|
||||
let bands = crate::pixels::bands(h_of(r));
|
||||
let parts =
|
||||
crate::pixels::par_map(bands, |rows| s.to_interleaved(photocraft_geom::Rect::new(r.x0, r.y0 + rows.start as i32, r.x1, r.y0 + rows.end as i32)));
|
||||
let mut bytes = Vec::with_capacity(row_len * h_of(r) * s.format().bytes_per_pixel());
|
||||
for part in parts {
|
||||
bytes.extend_from_slice(&part);
|
||||
}
|
||||
let mut bytes = s.to_interleaved(r);
|
||||
if self.fmt.mode == ColorMode::Lab && self.fmt.sample == SampleType::U16 {
|
||||
crate::pixels::lab16_chroma(&mut bytes, self.cc + 1, false);
|
||||
}
|
||||
@@ -359,7 +373,7 @@ impl Ex {
|
||||
let order: Vec<(i16, &Vec<u8>)> =
|
||||
std::iter::once((-1, &planes[self.cc])).chain(planes.iter().take(self.cc).enumerate().map(|(c, p)| (c as i16, p))).collect();
|
||||
let ch = crate::pixels::par_map(order, |(id, plane)| self.encode(id, plane, w, h));
|
||||
(to_psd_rect(r), ch)
|
||||
(to_psd_rect(r), ch, warnings)
|
||||
}
|
||||
|
||||
fn mask(&self, m: &LayerMask, vector: Option<(f32, f32)>) -> (MaskData, Option<ChannelData>) {
|
||||
@@ -410,10 +424,11 @@ impl Ex {
|
||||
|
||||
fn record(&mut self, l: &Layer, extra: Vec<TaggedBlock>, pixels: Option<&Surface>) -> LayerRecord {
|
||||
let id = self.layer_id(l);
|
||||
let (rect, mut channels) = match pixels {
|
||||
let (rect, mut channels, warnings) = match pixels {
|
||||
Some(s) => self.pixel_channels(s, &l.name),
|
||||
None => (PsdRect::default(), self.empty_channels()),
|
||||
None => (PsdRect::default(), self.empty_channels(), Vec::new()),
|
||||
};
|
||||
self.warnings.extend(warnings);
|
||||
let mut mask = MaskData::None;
|
||||
// Vector mask density/feather live in the mask parameters, with or without a user mask.
|
||||
let vector = l.vector_mask.as_ref().map(|vm| (vm.density, vm.feather));
|
||||
|
||||
@@ -163,6 +163,13 @@ impl Ctx<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Self::channel_plane`] without the warnings sink, so a layer's channels decode
|
||||
/// concurrently (their RLE rows are the bulk of the open time on full-canvas layers).
|
||||
fn channel_plane_decoded(&self, rec: &LayerRecord, id: i16) -> Option<Vec<u8>> {
|
||||
rec.channel(id)?;
|
||||
rec.decode_channel(id, self.file.header.depth, self.file.header.version).ok()
|
||||
}
|
||||
|
||||
fn record_surface(&mut self, rec: &LayerRecord, name: &str) -> Surface {
|
||||
let r = rec.rect;
|
||||
if r.is_empty() || r.size().is_err() {
|
||||
@@ -170,15 +177,28 @@ impl Ctx<'_> {
|
||||
}
|
||||
let (w, h) = r.size().unwrap_or((0, 0));
|
||||
let s = self.fmt.sample;
|
||||
let mut planes = Vec::with_capacity(self.cc + 1);
|
||||
for c in 0..self.cc {
|
||||
planes.push(self.channel_plane(rec, c as i16, name));
|
||||
}
|
||||
planes.push(self.channel_plane(rec, CHANNEL_TRANSPARENCY, name));
|
||||
let ids: Vec<i16> = (0..self.cc as i16).chain([CHANNEL_TRANSPARENCY]).collect();
|
||||
let planes: Vec<Option<Vec<u8>>> = if cfg!(target_arch = "wasm32") {
|
||||
ids.iter().map(|&id| self.channel_plane(rec, id, name)).collect()
|
||||
} else {
|
||||
// The channels decode independently; their RLE rows are the bulk of the open
|
||||
// time for full-canvas layers, so they run side by side and the warnings land
|
||||
// in the same order afterwards.
|
||||
// par_map reuses the crate's worker pool (one OS thread per channel per layer
|
||||
// would spawn thousands on a file with many layers).
|
||||
let decoded: Vec<Option<Vec<u8>>> = crate::pixels::par_map(ids.to_vec(), |id| self.channel_plane_decoded(rec, id));
|
||||
let mut planes: Vec<Option<Vec<u8>>> = Vec::with_capacity(decoded.len());
|
||||
for (&id, p) in ids.iter().zip(decoded) {
|
||||
if p.is_none() && rec.channel(id).is_some() {
|
||||
self.warn(format!("layer \"{name}\": channel {id} could not be decoded; treated as empty"));
|
||||
}
|
||||
planes.push(p);
|
||||
}
|
||||
planes
|
||||
};
|
||||
// A channel that is in the file but could not be decoded leaves the layer empty, as the
|
||||
// warning says. Filling in for it would paint an opaque black layer over the document.
|
||||
let ids = (0..self.cc as i16).chain([CHANNEL_TRANSPARENCY]);
|
||||
if ids.zip(&planes).any(|(id, p)| p.is_none() && rec.channel(id).is_some()) {
|
||||
if ids.iter().zip(planes.iter()).any(|(&id, p)| p.is_none() && rec.channel(id).is_some()) {
|
||||
return Surface::new(self.fmt);
|
||||
}
|
||||
// Only decoded channel data justifies a buffer: the decoders bound their output by the
|
||||
|
||||
@@ -213,7 +213,8 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
|
||||
ctl.progress(TIFF_LAYERS_DONE);
|
||||
warnings.extend(w.into_iter().map(|w| format!("layer data: {w}")));
|
||||
// The profile and XMP are written as TIFF tags, not as resources. EXIF stays a resource
|
||||
// (1058): the TIFF codec has no EXIF directory, and the PSD importer reads it back from there.
|
||||
// (1058), which the PSD importer reads back unchanged; a block rebuilt from the TIFF's own
|
||||
// Exif directory keeps only the Exif, GPS and descriptive tags.
|
||||
let resources: Vec<ImageResource> = file.resources.iter().filter(|r| !matches!(r.id, ids::ICC_PROFILE | ids::XMP)).cloned().collect();
|
||||
let resources = resources_to_bytes(&resources)?;
|
||||
|
||||
@@ -235,10 +236,10 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
|
||||
let mut img = Image::from_raw(w, h, layout, sample, data)?;
|
||||
img.icc = doc.icc_profile.as_ref().map(|i| i.to_vec());
|
||||
img.meta = codecs::Metadata {
|
||||
// EXIF is deliberately not set here: the TIFF codec has no EXIF directory, so the tags
|
||||
// above carry it as resource 1058 and the importer reads them back from there. Handing the
|
||||
// codec a second copy in `meta.exif` bought nothing and made the export claim it would
|
||||
// drop metadata it had in fact kept (#1545).
|
||||
// EXIF is deliberately not set here: the tags above carry it as resource 1058 and the
|
||||
// importer reads it back from there unchanged. A second copy in `meta.exif` (the codec's
|
||||
// Exif directory) would be read back in its place, rebuilt without the thumbnail and IFD0
|
||||
// orientation (#1545).
|
||||
xmp: doc.metadata.xmp.clone().filter(|_| opts.xmp == crate::XmpEmbed::All),
|
||||
text: if opts.xmp == crate::XmpEmbed::All { doc.metadata.text.clone() } else { Vec::new() },
|
||||
dpi: Some((doc.resolution_dpi, doc.resolution_dpi)),
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
//! The parallel RLE/decode paths must not change output bytes: a document exported by this
|
||||
//! branch re-exports byte-equal after a decode/encode cycle, and matches main's exporter
|
||||
//! (verified by the corpus round-trip floors in `corpus.rs`; here the byte-equality of the
|
||||
//! codec layer itself is pinned).
|
||||
|
||||
use photocraft_psd::compression::{Compression, PlaneLayout, decode_planes, encode_planes};
|
||||
use photocraft_psd::header::Version;
|
||||
|
||||
#[test]
|
||||
fn encode_decode_planes_round_trip_exactly() {
|
||||
let mut data: u64 = 0x0123_4567_89ab_cdef;
|
||||
let mut next = move || {
|
||||
data ^= data << 13;
|
||||
data ^= data >> 7;
|
||||
data ^= data << 17;
|
||||
data
|
||||
};
|
||||
for (version, planes, w, h, depth) in
|
||||
[(Version::Psd, 1usize, 640usize, 480usize, 8u16), (Version::Psb, 1, 15000, 10000, 8), (Version::Psd, 4, 513, 65, 8), (Version::Psb, 3, 64, 2049, 16)]
|
||||
{
|
||||
let layout = PlaneLayout { planes, width: w, height: h, depth, version };
|
||||
let n = layout.decoded_len().expect("size");
|
||||
let pattern: Vec<u8> = if h % 2 == 0 { vec![42u8; n] } else { (0..n).map(|i| ((i as u64 ^ next()) % 251) as u8).collect() };
|
||||
let encoded = encode_planes(Compression::Rle, &pattern, &layout).expect("encode");
|
||||
let decoded = decode_planes(Compression::Rle, &encoded, &layout).expect("decode");
|
||||
assert_eq!(decoded, pattern, "{version:?} {planes}x{w}x{h} d{depth}");
|
||||
}
|
||||
}
|
||||
@@ -127,7 +127,7 @@ fn exif() -> Vec<u8> {
|
||||
}
|
||||
|
||||
/// #1545: a layered TIFF carries EXIF as Photoshop resource 1058 and reads it back, so it must
|
||||
/// not report a loss it never makes. A flat TIFF really does lose the tags and still says so.
|
||||
/// not report a loss it never makes. A flat TIFF writes it as its own tags and keeps it too.
|
||||
#[test]
|
||||
fn layered_tiff_keeps_exif_without_claiming_a_loss() {
|
||||
let mut d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);
|
||||
@@ -140,9 +140,13 @@ fn layered_tiff_keeps_exif_without_claiming_a_loss() {
|
||||
let kept = back.metadata.exif.as_deref().expect("EXIF survives the layered export");
|
||||
assert!(kept.windows(ARTIST.len()).any(|w| w == ARTIST), "the Artist tag did not survive: {kept:?}");
|
||||
|
||||
// The control from the issue: the flat path drops it for real, and keeps reporting that.
|
||||
// The flat path writes the EXIF block's tags as the TIFF's own (here IFD0's Artist, which
|
||||
// reads back as the document's Artist text), so it reports no loss either.
|
||||
let flat = tiff(&d, false);
|
||||
assert!(flat.warnings.iter().any(|w| w.contains("EXIF")), "a flat TIFF really does lose EXIF: {:?}", flat.warnings);
|
||||
assert!(!flat.warnings.iter().any(|w| w.contains("EXIF")), "a flat TIFF keeps EXIF: {:?}", flat.warnings);
|
||||
let back = import("x.tif", &flat.bytes).unwrap().document;
|
||||
let artist = std::str::from_utf8(ARTIST).unwrap().trim_end_matches('\0');
|
||||
assert!(back.metadata.text.iter().any(|(k, v)| k == "Artist" && v == artist), "{:?}", back.metadata.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+131
-14
@@ -8,7 +8,7 @@ use std::io::{Read, Write};
|
||||
|
||||
use crate::error::{PsdError, Result};
|
||||
use crate::header::{Version, row_bytes};
|
||||
use crate::io::{Reader, WriteExt};
|
||||
use crate::io::Reader;
|
||||
|
||||
/// Maximum number of decoded bytes a single decode call may produce: 8 GiB on
|
||||
/// 64-bit targets, 2 GiB elsewhere (the same budget as `photocraft-codecs`'
|
||||
@@ -345,21 +345,62 @@ fn encode_rle(decoded: &[u8], layout: &PlaneLayout) -> Result<Vec<u8>> {
|
||||
let rows = layout.rows()?;
|
||||
let rb = layout.row_bytes();
|
||||
let cs = layout.count_size();
|
||||
let mut out = vec![0u8; rows * cs];
|
||||
let mut enc = Vec::new();
|
||||
for row in 0..rows {
|
||||
let start = enc.len();
|
||||
packbits::encode(&decoded[row * rb..(row + 1) * rb], &mut enc);
|
||||
let n = enc.len() - start;
|
||||
if cs == 2 {
|
||||
let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?;
|
||||
out[row * 2..row * 2 + 2].copy_from_slice(&n.to_be_bytes());
|
||||
} else {
|
||||
let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?;
|
||||
out[row * 4..row * 4 + 4].copy_from_slice(&n.to_be_bytes());
|
||||
if rows == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
// Rows are independent, so they pack in parallel chunks and concatenate in order.
|
||||
let threads = if cfg!(target_arch = "wasm32") { 1 } else { std::thread::available_parallelism().map_or(1, |v| v.get()).clamp(1, 32) };
|
||||
let chunk_rows = rows.div_ceil(threads).max(1);
|
||||
struct Chunk {
|
||||
counts: Vec<u8>,
|
||||
packed: Vec<u8>,
|
||||
}
|
||||
let pack_chunk = |first: usize, count: usize| -> Result<Chunk> {
|
||||
let mut chunk = Chunk { counts: vec![0u8; count * cs], packed: Vec::new() };
|
||||
for row in first..first + count {
|
||||
let start = chunk.packed.len();
|
||||
packbits::encode(&decoded[row * rb..(row + 1) * rb], &mut chunk.packed);
|
||||
let n = chunk.packed.len() - start;
|
||||
if cs == 2 {
|
||||
let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?;
|
||||
chunk.counts[(row - first) * 2..(row - first) * 2 + 2].copy_from_slice(&n.to_be_bytes());
|
||||
} else {
|
||||
let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?;
|
||||
chunk.counts[(row - first) * 4..(row - first) * 4 + 4].copy_from_slice(&n.to_be_bytes());
|
||||
}
|
||||
}
|
||||
Ok(chunk)
|
||||
};
|
||||
let chunk_list: Vec<Chunk> = if threads == 1 {
|
||||
vec![pack_chunk(0, rows)?]
|
||||
} else {
|
||||
std::thread::scope(|scope| -> Result<Vec<Chunk>> {
|
||||
let handles: Vec<_> = (0..threads)
|
||||
.map(|t| {
|
||||
let first = t * chunk_rows;
|
||||
let count = chunk_rows.min(rows.saturating_sub(first));
|
||||
scope.spawn(move || pack_chunk(first, count))
|
||||
})
|
||||
.collect();
|
||||
// Join every worker first, then surface the first error like the sequential
|
||||
// path would instead of aborting the scope with a thread panic.
|
||||
let mut all = Vec::with_capacity(threads);
|
||||
for h in handles {
|
||||
all.push(h.join().map_err(|_| PsdError::LimitExceeded("an RLE worker panicked"))??);
|
||||
}
|
||||
Ok(all)
|
||||
})?
|
||||
};
|
||||
let packed_total: usize = chunk_list.iter().map(|c| c.packed.len()).sum();
|
||||
let mut out = vec![0u8; rows * cs + packed_total];
|
||||
let mut counts_at = 0usize;
|
||||
let mut packed_at = rows * cs;
|
||||
for chunk in &chunk_list {
|
||||
out[counts_at..counts_at + chunk.counts.len()].copy_from_slice(&chunk.counts);
|
||||
counts_at += chunk.counts.len();
|
||||
out[packed_at..packed_at + chunk.packed.len()].copy_from_slice(&chunk.packed);
|
||||
packed_at += chunk.packed.len();
|
||||
}
|
||||
out.put(&enc);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -830,3 +871,79 @@ mod tests {
|
||||
assert!(zip_decompress(&[1, 2, 3, 4], 4).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod parallel_rle_equivalence {
|
||||
use super::*;
|
||||
|
||||
/// The parallel row packer's output must be byte-equal to a straightforward sequential
|
||||
/// encoding of the same plane, across depths, row counts around the chunking and data
|
||||
/// shapes (runs, noise, all-default).
|
||||
#[test]
|
||||
fn parallel_rle_matches_sequential() {
|
||||
let mut data: u64 = 0x9e37_79b9_7f4a_7c15;
|
||||
let mut next = move || {
|
||||
data ^= data << 13;
|
||||
data ^= data >> 7;
|
||||
data ^= data << 17;
|
||||
data
|
||||
};
|
||||
let layout_for = |rows: usize, rb: usize, version: Version| PlaneLayout { planes: 1, width: rb, height: rows, depth: 8, version };
|
||||
for (rows, rb, version) in [
|
||||
(0usize, 4usize, Version::Psd),
|
||||
(1, 4, Version::Psd),
|
||||
(7, 4, Version::Psb),
|
||||
(64, 4, Version::Psd),
|
||||
(65, 4, Version::Psb), // chunk boundary
|
||||
(513, 4, Version::Psd), // more rows than threads on most runners
|
||||
(2049, 4, Version::Psb),
|
||||
(2, 4, Version::Psd), // fewer rows than threads
|
||||
(33, 3000, Version::Psd),
|
||||
(31, 20000, Version::Psb),
|
||||
] {
|
||||
let pattern: Vec<u8> = match rows % 3 {
|
||||
0 => vec![7u8; rows * rb], // long runs
|
||||
1 => (0..rows * rb).map(|i| (i * 31 % 251) as u8).collect(), // noise-ish
|
||||
_ => vec![0u8; rows * rb], // all default
|
||||
};
|
||||
let pattern = if pattern.len() != rows * rb { vec![7u8; rows * rb] } else { pattern };
|
||||
let mut data = pattern.clone();
|
||||
if rows % 4 == 0 {
|
||||
// sprinkle runs into the noise
|
||||
for chunk in data.chunks_mut(97) {
|
||||
if let Some(f) = chunk.first_mut() {
|
||||
*f = 200;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = next();
|
||||
let layout = layout_for(rows, rb, version);
|
||||
let parallel = encode_rle(&data, &layout).expect("parallel encode");
|
||||
let sequential = encode_rle_sequential(&data, &layout).expect("sequential encode");
|
||||
assert_eq!(parallel, sequential, "rows {rows} rb {rb}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The pre-parallel encoder, kept as the oracle.
|
||||
fn encode_rle_sequential(decoded: &[u8], layout: &PlaneLayout) -> Result<Vec<u8>> {
|
||||
let rows = layout.rows()?;
|
||||
let rb = layout.row_bytes();
|
||||
let cs = layout.count_size();
|
||||
let mut out = vec![0u8; rows * cs];
|
||||
let mut enc = Vec::new();
|
||||
for row in 0..rows {
|
||||
let start = enc.len();
|
||||
packbits::encode(&decoded[row * rb..(row + 1) * rb], &mut enc);
|
||||
let n = enc.len() - start;
|
||||
if cs == 2 {
|
||||
let n = u16::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row exceeds 65535 bytes (use PSB)"))?;
|
||||
out[row * 2..row * 2 + 2].copy_from_slice(&n.to_be_bytes());
|
||||
} else {
|
||||
let n = u32::try_from(n).map_err(|_| PsdError::LimitExceeded("RLE row too large"))?;
|
||||
out[row * 4..row * 4 + 4].copy_from_slice(&n.to_be_bytes());
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&enc);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,10 @@ Implemented only from public specifications, papers and observation of files:
|
||||
by observation of sample files (bit packing, page layout, sample justification; for RAF the
|
||||
three sample storages and the reversed order of the X-Trans / Bayer layout records, each
|
||||
verified by developing with every candidate phase against the camera's preview).
|
||||
* Panasonic RW2 RawFormat 3/4 (vendor-compressed): the fixed-rate 16 bytes per 14 pixels, the
|
||||
predictor groups with per-parity predictors, the 2/4/8-bit field widths, the page-permuted
|
||||
downward bit order and the black level sitting 15 counts above the recorded tags were all
|
||||
established by observation of sample files.
|
||||
* Demosaicing: Malvar, He & Cutler (ICASSP 2004); Hirakawa & Parks, "Adaptive
|
||||
homogeneity-directed demosaicing" (IEEE TIP 2005); for X-Trans and other non-Bayer CFAs,
|
||||
gradient-weighted green interpolation (Lu & Tan, "Color filter array demosaicking: new method
|
||||
@@ -71,8 +75,9 @@ camera colour tables were copied.
|
||||
| Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files are unsupported (preview fallback) |
|
||||
| Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits, the curve's 512 black level when no BlackLevel tag is written (the first-generation bodies, e.g. the ILCE-7) |
|
||||
| Panasonic / Leica RW2, RawFormat 5 (12- and 14-bit packed) | Decoded, with PanasonicRaw black / white / WB / sensor borders |
|
||||
| Panasonic / Leica RW2, RawFormat 3 and 4 (vendor-compressed, 12-bit) | Decoded; the black level is read 15 counts above the recorded tag; PanasonicRaw white / WB / sensor borders |
|
||||
| Olympus ORF, uncompressed 16-bit (E-1, E-400…) | Decoded, with ImageProcessing black / WB / ValidBits / crop |
|
||||
| Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 4 and older, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead |
|
||||
| Nikon "lossy after split" NEF, Sony "Compressed RAW 2", Pentax compressed PEF, RW2 RawFormat 6 and newer, Olympus compressed ORF | Unsupported: no public description of these codes was found apart from GPL decoder source, which this crate may not use (clean-room). `photocraft-io` opens the embedded JPEG preview instead |
|
||||
| Fujifilm RAF, uncompressed (X-Trans I–V, GFX and Bayer bodies since about 2010) | Decoded: 16-bit containers (either byte order), 12-bit LSB-first packing, 14-bit packing in 32-bit words; X-Trans 6×6 or Bayer 2×2 layout, black, as-shot WB, crop, RawExposureBias, orientation from the preview's EXIF |
|
||||
| Fujifilm compressed RAF, early FinePix / SuperCCD RAF (no CFA TIFF) | Unsupported (no public description of the compression); preview fallback |
|
||||
| CR3 | Native CRX unsupported; bounded JPEG-track/PRVW preview fallback with CMT1 orientation. I/O labels the result as an 8-bit camera preview |
|
||||
|
||||
@@ -32,9 +32,9 @@
|
||||
//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or
|
||||
//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),
|
||||
//! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW),
|
||||
//! Panasonic RW2 (RawFormat 5), uncompressed Olympus ORF and uncompressed
|
||||
//! Fujifilm RAF (Bayer and X-Trans). Everything else reports
|
||||
//! [`RawError::Unsupported`].
|
||||
//! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed),
|
||||
//! uncompressed Olympus ORF and uncompressed Fujifilm RAF (Bayer and
|
||||
//! X-Trans). Everything else reports [`RawError::Unsupported`].
|
||||
//!
|
||||
//! The crate is standalone (no workspace dependencies), does no I/O, builds for
|
||||
//! `wasm32-unknown-unknown` and never panics on hostile input: sizes are
|
||||
|
||||
+228
-29
@@ -1,5 +1,6 @@
|
||||
//! Panasonic / Leica RW2 with the bit-packed sensor layout (PanasonicRaw
|
||||
//! RawFormat 5, written by recent Lumix bodies).
|
||||
//! Panasonic / Leica RW2: the bit-packed stream of recent Lumix bodies
|
||||
//! (PanasonicRaw RawFormat 5) and the vendor-compressed stream of the earlier
|
||||
//! ones (RawFormat 3 and 4).
|
||||
//!
|
||||
//! The container is TIFF-like (`IIU\0`); IFD0 holds Panasonic's own tags,
|
||||
//! whose ids and meanings are public (ExifTool's PanasonicRaw table):
|
||||
@@ -9,7 +10,7 @@
|
||||
//! WB{Red,Green,Blue}Level (0x24–0x26), RawFormat (0x2D) and RawDataOffset
|
||||
//! (0x118).
|
||||
//!
|
||||
//! The packing was established by observation of sample files:
|
||||
//! RawFormat 5 — the packing was established by observation of sample files:
|
||||
//!
|
||||
//! * From RawDataOffset the data is stored in pages of 0x4000 bytes, each
|
||||
//! page split at 0x1FF8 with its second part first (the logical page is
|
||||
@@ -19,8 +20,26 @@
|
||||
//! the least significant bit up, the remaining top bits unused; rows are
|
||||
//! whole blocks.
|
||||
//!
|
||||
//! The older RawFormat 4 (and earlier) store vendor-compressed data, which is
|
||||
//! not decoded.
|
||||
//! RawFormat 3 and 4 — the vendor-compressed layout, also established by
|
||||
//! observation of sample files (verified by decoding whole frames against the
|
||||
//! camera's embedded JPEG and the recorded levels):
|
||||
//!
|
||||
//! * The payload at RawDataOffset is a fixed-rate stream: 16 bytes per 14
|
||||
//! pixels, so a row occupies `width / 14 * 16` bytes and rows are
|
||||
//! byte-aligned. Bits are consumed down from the top of each 0x4000-byte
|
||||
//! page, through the same page split as RawFormat 5 (`(i + 0x4000 - 0x2008)
|
||||
//! % 0x4000`), reading fields LSB-first from the little-endian 16-bit word
|
||||
//! the cursor points at.
|
||||
//! * Pixels arrive in groups of 14 with two predictors carried over from one
|
||||
//! group to the next (even and odd columns). Every third pixel carries a
|
||||
//! 2-bit scale selector `sh` (0, 1, 2 or 4). The first value of each parity
|
||||
//! is absolute (8 + 4 bits); the rest are 8-bit deltas around 0x80 scaled
|
||||
//! by `sh`, wrapping in the low `sh` bits.
|
||||
//! * The decoded samples sit 15 counts above the recorded BlackLevel tags
|
||||
//! (measured on the darkest pixels of sample files), so 15 is added when
|
||||
//! they are read.
|
||||
//!
|
||||
//! Every other RawFormat value is not decoded.
|
||||
|
||||
use crate::error::{RawError, Result};
|
||||
use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
|
||||
@@ -44,6 +63,8 @@ const RAW_DATA_OFFSET: u16 = 0x0118;
|
||||
/// Page size and split point of the stored stream (observed).
|
||||
const PAGE: usize = 0x4000;
|
||||
const SPLIT: usize = 0x1FF8;
|
||||
/// Byte split of the vendor-compressed stream (observed).
|
||||
const COMPRESSED_SPLIT: usize = 0x2008;
|
||||
|
||||
/// Physical offset (relative to RawDataOffset) of logical byte `i`.
|
||||
#[inline]
|
||||
@@ -75,34 +96,13 @@ pub(crate) fn unpack_block(b: &[u8; 16], bits: u32, out: &mut [u16]) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
|
||||
let ifd = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("RW2 has no IFD0"))?;
|
||||
let raw_format = t.tag_uint(&ifd, RAW_FORMAT);
|
||||
if raw_format != Some(5) {
|
||||
let f = raw_format.map(|v| v.to_string()).unwrap_or_else(|| "unknown".into());
|
||||
return Err(RawError::unsupported(format!("Panasonic RW2 raw format {f} (vendor-compressed) is not decoded yet")));
|
||||
}
|
||||
let width = t.tag_uint(&ifd, SENSOR_WIDTH).ok_or_else(|| RawError::malformed("RW2 has no sensor width"))? as usize;
|
||||
let height = t.tag_uint(&ifd, SENSOR_HEIGHT).ok_or_else(|| RawError::malformed("RW2 has no sensor height"))? as usize;
|
||||
let bits = t.tag_uint(&ifd, BITS_PER_SAMPLE).unwrap_or(12);
|
||||
/// Reads the bit-packed RawFormat 5 stream (`src` starts at RawDataOffset).
|
||||
fn decode_packed(src: &[u8], width: usize, height: usize, bits: u32) -> Result<Vec<u16>> {
|
||||
let ppb = pixels_per_block(bits).ok_or_else(|| RawError::unsupported(format!("Panasonic RW2 with {bits}-bit samples")))?;
|
||||
if !width.is_multiple_of(ppb) {
|
||||
return Err(RawError::unsupported(format!("Panasonic RW2 {width} pixels wide (not whole {ppb}-pixel blocks)")));
|
||||
}
|
||||
limits.check(width as u64, height as u64, 2)?;
|
||||
let cfa = match t.tag_uint(&ifd, CFA_PATTERN) {
|
||||
Some(1) => "RGGB",
|
||||
Some(2) => "GRBG",
|
||||
Some(3) => "GBRG",
|
||||
Some(4) => "BGGR",
|
||||
_ => return Err(RawError::unsupported("Panasonic RW2 without a CFA pattern")),
|
||||
};
|
||||
let cfa = Cfa::bayer(cfa).ok_or_else(|| RawError::malformed("bad CFA"))?;
|
||||
let offset =
|
||||
t.tag_uint(&ifd, RAW_DATA_OFFSET).or_else(|| t.tag_uint(&ifd, tag::STRIP_OFFSETS)).ok_or_else(|| RawError::malformed("RW2 has no raw data offset"))?
|
||||
as usize;
|
||||
let row_bytes = width / ppb * 16;
|
||||
let src = t.data.get(offset..).ok_or_else(|| RawError::malformed("RW2 raw data lies outside the file"))?;
|
||||
let need = row_bytes * height;
|
||||
// Whole pages are stored; tolerate a short final page (its missing bytes read as 0).
|
||||
if src.len() < need.saturating_sub(PAGE) {
|
||||
@@ -124,11 +124,138 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// LSB-first bit cursor of the vendor-compressed stream: it walks down from
|
||||
/// the top of each 0x4000-byte page (addressed through `COMPRESSED_SPLIT`)
|
||||
/// and refills by advancing one page.
|
||||
struct Bits<'a> {
|
||||
buf: &'a [u8],
|
||||
base: usize,
|
||||
pos: usize,
|
||||
nbits: u32,
|
||||
}
|
||||
|
||||
impl<'a> Bits<'a> {
|
||||
fn new(buf: &'a [u8], base: usize) -> Self {
|
||||
Bits { buf, base, pos: 0, nbits: 0 }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get(&mut self, num: u32) -> u32 {
|
||||
if num > self.nbits {
|
||||
self.nbits += PAGE as u32 * 8;
|
||||
self.pos += PAGE;
|
||||
}
|
||||
let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0;
|
||||
at = (at + PAGE - COMPRESSED_SPLIT) % PAGE;
|
||||
let at = self.base + at + self.pos - PAGE;
|
||||
self.nbits -= num;
|
||||
// Out-of-range reads (a page short at the end of the file) read as 0.
|
||||
let lo = u32::from(self.buf.get(at).copied().unwrap_or(0));
|
||||
let hi = u32::from(self.buf.get(at + 1).copied().unwrap_or(0));
|
||||
((lo | (hi << 8)) >> (self.nbits & 7)) & ((1u32 << num) - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes one row of the vendor-compressed stream.
|
||||
fn compressed_row(buf: &[u8], row_bytes: usize, row: usize, out: &mut [u16]) {
|
||||
let skip = row_bytes * row;
|
||||
let mut bits = Bits::new(buf, skip / PAGE * PAGE);
|
||||
for _ in 0..(skip % PAGE) {
|
||||
bits.get(8);
|
||||
}
|
||||
let mut sh: i32 = 0;
|
||||
for group in out.as_chunks_mut::<14>().0 {
|
||||
let mut pred = [0i32; 2];
|
||||
let mut nonz = [0i32; 2];
|
||||
for (i, px) in group.iter_mut().enumerate() {
|
||||
if i % 3 == 2 {
|
||||
sh = 4 >> (3 - bits.get(2));
|
||||
}
|
||||
let p = i & 1;
|
||||
if nonz[p] != 0 {
|
||||
let j = bits.get(8) as i32;
|
||||
if j != 0 {
|
||||
pred[p] -= 0x80 << sh;
|
||||
if pred[p] < 0 || sh == 4 {
|
||||
pred[p] &= !(-1 << sh);
|
||||
}
|
||||
pred[p] += j << sh;
|
||||
}
|
||||
} else {
|
||||
nonz[p] = bits.get(8) as i32;
|
||||
if nonz[p] != 0 || i > 11 {
|
||||
pred[p] = (nonz[p] << 4) | bits.get(4) as i32;
|
||||
}
|
||||
}
|
||||
*px = pred[p] as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the vendor-compressed RawFormat 3/4 stream (`src` starts at
|
||||
/// RawDataOffset).
|
||||
fn decode_compressed(src: &[u8], width: usize, height: usize, bits: u32) -> Result<Vec<u16>> {
|
||||
if bits != 12 {
|
||||
return Err(RawError::unsupported(format!("Panasonic RW2 with {bits}-bit compressed samples")));
|
||||
}
|
||||
if !width.is_multiple_of(14) {
|
||||
return Err(RawError::unsupported(format!("Panasonic RW2 {width} pixels wide (not whole 14-pixel blocks)")));
|
||||
}
|
||||
let row_bytes = width / 14 * 16;
|
||||
let need = row_bytes * height;
|
||||
// Whole pages are stored; tolerate a short final page (its missing bytes read as 0).
|
||||
if src.len() < need.saturating_sub(PAGE) {
|
||||
return Err(RawError::malformed("RW2 raw data is truncated"));
|
||||
}
|
||||
let mut data = vec![0u16; width * height];
|
||||
let band = par::band_rows(width);
|
||||
par::chunks_mut(&mut data, band * width, |i, chunk| {
|
||||
for (r, out) in chunk.chunks_exact_mut(width).enumerate() {
|
||||
compressed_row(src, row_bytes, i * band + r, out);
|
||||
}
|
||||
});
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
|
||||
let ifd = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("RW2 has no IFD0"))?;
|
||||
let raw_format = t.tag_uint(&ifd, RAW_FORMAT);
|
||||
let compressed = match raw_format {
|
||||
Some(5) => false,
|
||||
Some(3 | 4) => true,
|
||||
other => {
|
||||
let f = other.map(|v| v.to_string()).unwrap_or_else(|| "unknown".into());
|
||||
return Err(RawError::unsupported(format!("Panasonic RW2 raw format {f} (vendor-compressed) is not decoded yet")));
|
||||
}
|
||||
};
|
||||
let width = t.tag_uint(&ifd, SENSOR_WIDTH).ok_or_else(|| RawError::malformed("RW2 has no sensor width"))? as usize;
|
||||
let height = t.tag_uint(&ifd, SENSOR_HEIGHT).ok_or_else(|| RawError::malformed("RW2 has no sensor height"))? as usize;
|
||||
limits.check(width as u64, height as u64, 2)?;
|
||||
let bits = t.tag_uint(&ifd, BITS_PER_SAMPLE).unwrap_or(12);
|
||||
let cfa = match t.tag_uint(&ifd, CFA_PATTERN) {
|
||||
Some(1) => "RGGB",
|
||||
Some(2) => "GRBG",
|
||||
Some(3) => "GBRG",
|
||||
Some(4) => "BGGR",
|
||||
_ => return Err(RawError::unsupported("Panasonic RW2 without a CFA pattern")),
|
||||
};
|
||||
let cfa = Cfa::bayer(cfa).ok_or_else(|| RawError::malformed("bad CFA"))?;
|
||||
let offset =
|
||||
t.tag_uint(&ifd, RAW_DATA_OFFSET).or_else(|| t.tag_uint(&ifd, tag::STRIP_OFFSETS)).ok_or_else(|| RawError::malformed("RW2 has no raw data offset"))?
|
||||
as usize;
|
||||
let src = t.data.get(offset..).ok_or_else(|| RawError::malformed("RW2 raw data lies outside the file"))?;
|
||||
let data = if compressed { decode_compressed(src, width, height, bits)? } else { decode_packed(src, width, height, bits)? };
|
||||
|
||||
let full = Rect::new(0, 0, width, height);
|
||||
let level = |tg: u16| t.tag_uint(&ifd, tg).map(f64::from);
|
||||
let mut warnings = Vec::new();
|
||||
let black = match BLACK_LEVEL.map(level) {
|
||||
// The compressed variants record a black level 15 counts below the decoded black.
|
||||
let black_offset = if compressed { 15.0 } else { 0.0 };
|
||||
let black_level = |tg: u16| t.tag_uint(&ifd, tg).map(|v| f64::from(v) + black_offset);
|
||||
let black = match BLACK_LEVEL.map(black_level) {
|
||||
[Some(r), Some(g), Some(b)] => {
|
||||
let v = cfa.phase(0, 0).map(|c| [r, g, b][usize::from(c).min(2)] as f32);
|
||||
BlackLevels { rows: 2, cols: 2, values: v.to_vec(), delta_h: Vec::new(), delta_v: Vec::new() }
|
||||
@@ -204,4 +331,76 @@ mod tests {
|
||||
assert_eq!(&out[..9], &[0x3FFF; 9]);
|
||||
assert_eq!(&out[9..], &[0; 3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_bits_walk_down_pages() {
|
||||
// A fresh cursor reads the word at 0x2007 first (the top of the first
|
||||
// page under the compressed split), then walks down.
|
||||
let mut buf = vec![0u8; 0x4000];
|
||||
buf[0x2007] = 0xAC;
|
||||
buf[0x2008] = 0x03;
|
||||
buf[0x2006] = 0x11;
|
||||
buf[0x2017] = 0x55;
|
||||
// A 4-bit field starts in the high nibble of the top word.
|
||||
let mut b = Bits::new(&buf, 0);
|
||||
assert_eq!(b.get(4), 0xA);
|
||||
let mut b = Bits::new(&buf, 0);
|
||||
assert_eq!(b.get(8), 0xAC);
|
||||
assert_eq!(b.get(8), 0x11);
|
||||
// 16 bytes later the cursor wraps to the end of the next 16-byte run.
|
||||
for _ in 0..14 {
|
||||
b.get(8);
|
||||
}
|
||||
assert_eq!(b.get(8), 0x55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_group_walks_predictors() {
|
||||
// One 14-pixel group: both parities start absolute, a delta of 0x80
|
||||
// keeps their value, and the scale selector is written before the
|
||||
// delta of every third pixel. The test writer mirrors `Bits` so the
|
||||
// fields land where the decoder reads them.
|
||||
let mut buf = vec![0u8; 0x4000];
|
||||
{
|
||||
let mut w = TestWriter { buf: &mut buf, pos: 0, nbits: 0 };
|
||||
w.put(0x10, 8);
|
||||
w.put(0x5, 4);
|
||||
w.put(0x2A, 8);
|
||||
w.put(0xA, 4);
|
||||
for i in 2..14 {
|
||||
if i % 3 == 2 {
|
||||
w.put(0, 2);
|
||||
}
|
||||
w.put(0x80, 8);
|
||||
}
|
||||
}
|
||||
let mut out = [0u16; 14];
|
||||
compressed_row(&buf, 16, 0, &mut out);
|
||||
assert_eq!(out, [0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA, 0x105, 0x2AA]);
|
||||
}
|
||||
|
||||
/// Mirror of [`Bits`] for unit tests: deposits fields where the reader
|
||||
/// will pick them up.
|
||||
struct TestWriter<'a> {
|
||||
buf: &'a mut [u8],
|
||||
pos: usize,
|
||||
nbits: u32,
|
||||
}
|
||||
|
||||
impl TestWriter<'_> {
|
||||
fn put(&mut self, v: u32, num: u32) {
|
||||
if num > self.nbits {
|
||||
self.nbits += PAGE as u32 * 8;
|
||||
self.pos += PAGE;
|
||||
}
|
||||
let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0;
|
||||
at = (at + PAGE - COMPRESSED_SPLIT) % PAGE;
|
||||
let at = at + self.pos - PAGE;
|
||||
self.nbits -= num;
|
||||
let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8);
|
||||
let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7));
|
||||
self.buf[at] = cur as u8;
|
||||
self.buf[at + 1] = (cur >> 8) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1113,6 +1113,136 @@ pub fn rw2(width: usize, height: usize, data: &[u16], bits: u32) -> Vec<u8> {
|
||||
b
|
||||
}
|
||||
|
||||
/// Byte split of the vendor-compressed (RawFormat 3/4) stream (see `rw2.rs`).
|
||||
const RW2_COMPRESSED_SPLIT: usize = 0x2008;
|
||||
|
||||
/// Writer for the vendor-compressed RW2 stream: mirrors the decoder's cursor
|
||||
/// (page addressing, downward field order) and deposits every field where the
|
||||
/// reader will pick it up.
|
||||
struct V4Writer<'a> {
|
||||
buf: &'a mut [u8],
|
||||
base: usize,
|
||||
pos: usize,
|
||||
nbits: u32,
|
||||
}
|
||||
|
||||
impl V4Writer<'_> {
|
||||
/// Consumes one byte of the row seek (the decoder reads 8-bit fields).
|
||||
fn skip_byte(&mut self) {
|
||||
if 8 > self.nbits {
|
||||
self.nbits += (RW2_PAGE as u32) * 8;
|
||||
self.pos += RW2_PAGE;
|
||||
}
|
||||
self.nbits -= 8;
|
||||
}
|
||||
|
||||
fn put(&mut self, v: u32, num: u32) {
|
||||
if num > self.nbits {
|
||||
self.nbits += (RW2_PAGE as u32) * 8;
|
||||
self.pos += RW2_PAGE;
|
||||
}
|
||||
let mut at = ((self.nbits - num) >> 3) as usize ^ 0x3FF0;
|
||||
at = (at + RW2_PAGE - RW2_COMPRESSED_SPLIT) % RW2_PAGE;
|
||||
let at = self.base + at + self.pos - RW2_PAGE;
|
||||
self.nbits -= num;
|
||||
let cur = u32::from(self.buf[at]) | (u32::from(self.buf[at + 1]) << 8);
|
||||
let cur = cur | ((v & ((1 << num) - 1)) << (self.nbits & 7));
|
||||
self.buf[at] = cur as u8;
|
||||
self.buf[at + 1] = (cur >> 8) as u8;
|
||||
}
|
||||
|
||||
/// Encodes one row as 14-pixel groups: the scale selector is always 0 and
|
||||
/// the two first pixels of each group are absolute (8 + 4 bits); later
|
||||
/// pixels use the 8-bit delta path. Callers keep values inside 16..4096
|
||||
/// and stepping by at most ±127 between pixels of the same parity.
|
||||
fn row(&mut self, pixels: &[u16]) {
|
||||
for group in pixels.as_chunks::<14>().0 {
|
||||
let mut pred = [0i32; 2];
|
||||
let mut nonz = [0i32; 2];
|
||||
for (i, &px) in group.iter().enumerate() {
|
||||
if i % 3 == 2 {
|
||||
self.put(0, 2); // sh = 0
|
||||
}
|
||||
let p = i & 1;
|
||||
let t = i32::from(px);
|
||||
if nonz[p] == 0 {
|
||||
let nz = (t >> 4) & 0xFF;
|
||||
self.put(nz as u32, 8);
|
||||
if nz != 0 || i > 11 {
|
||||
self.put((t & 0xF) as u32, 4);
|
||||
pred[p] = t;
|
||||
} else {
|
||||
pred[p] = 0;
|
||||
}
|
||||
nonz[p] = nz;
|
||||
} else {
|
||||
let q = (pred[p] - 0x80).max(0);
|
||||
let j = t - q;
|
||||
assert!((1..=0xFF).contains(&j), "{t} is not encodable from {}", pred[p]);
|
||||
self.put(j as u32, 8);
|
||||
pred[p] = q + j;
|
||||
}
|
||||
assert_eq!(pred[p], t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The vendor-compressed (RawFormat 3/4) stream of a whole image; see
|
||||
/// [`V4Writer::row`] for the value constraints.
|
||||
pub fn rw2_v4_pack(data: &[u16], width: usize) -> Vec<u8> {
|
||||
assert_eq!(width % 14, 0);
|
||||
let height = data.len() / width;
|
||||
assert_eq!(data.len(), width * height);
|
||||
let row_bytes = width / 14 * 16;
|
||||
let mut buf = vec![0u8; row_bytes * height + 2 * RW2_PAGE];
|
||||
for (row, pixels) in data.chunks_exact(width).enumerate() {
|
||||
let skip = row_bytes * row;
|
||||
let mut w = V4Writer { buf: &mut buf, base: skip / RW2_PAGE * RW2_PAGE, pos: 0, nbits: 0 };
|
||||
for _ in 0..(skip % RW2_PAGE) {
|
||||
w.skip_byte();
|
||||
}
|
||||
w.row(pixels);
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
/// A synthetic Panasonic RW2 (RawFormat 4, vendor-compressed) with an RGGB
|
||||
/// sensor, a 2-pixel border on every side, black levels 128 / 129 / 130 and
|
||||
/// WB levels 512 / 256 / 384; see [`V4Writer::row`] for the pixel constraints.
|
||||
pub fn rw2_format4(width: usize, height: usize, data: &[u16]) -> Vec<u8> {
|
||||
let mut t = TiffBuilder::default();
|
||||
let raw = t.blob(rw2_v4_pack(data, width));
|
||||
let ifd0 = t.ifd(vec![
|
||||
(0x0002, Val::Short(vec![width as u16])),
|
||||
(0x0003, Val::Short(vec![height as u16])),
|
||||
(0x0004, Val::Short(vec![2])),
|
||||
(0x0005, Val::Short(vec![2])),
|
||||
(0x0006, Val::Short(vec![height as u16 - 2])),
|
||||
(0x0007, Val::Short(vec![width as u16 - 2])),
|
||||
(0x0009, Val::Short(vec![1])),
|
||||
(0x000A, Val::Short(vec![12])),
|
||||
(0x000E, Val::Short(vec![4095])),
|
||||
(0x000F, Val::Short(vec![4095])),
|
||||
(0x0010, Val::Short(vec![4095])),
|
||||
(0x001C, Val::Short(vec![128])),
|
||||
(0x001D, Val::Short(vec![129])),
|
||||
(0x001E, Val::Short(vec![130])),
|
||||
(0x0024, Val::Short(vec![512])),
|
||||
(0x0025, Val::Short(vec![256])),
|
||||
(0x0026, Val::Short(vec![384])),
|
||||
(0x002D, Val::Short(vec![4])),
|
||||
(0x010F, Val::Ascii("Panasonic".into())),
|
||||
(0x0110, Val::Ascii("DC-Synthetic".into())),
|
||||
(0x0112, Val::Short(vec![1])),
|
||||
(0x0118, Val::Blobs(vec![raw])),
|
||||
]);
|
||||
t.chain = vec![ifd0];
|
||||
let mut b = t.build();
|
||||
b[2..4].copy_from_slice(b"U\0");
|
||||
b
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Olympus ORF
|
||||
|
||||
/// A little-endian IFD whose value offsets are relative to `base` (the IFD
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! Sony compressed ARW (cRAW), Panasonic RW2 (RawFormat 5) and uncompressed
|
||||
//! Olympus ORF (with its maker-note preview).
|
||||
|
||||
use photocraft_raw::testgen::{craw_block, mosaic, orf, rw2, scene, sony_craw};
|
||||
use photocraft_raw::testgen::{craw_block, mosaic, orf, rw2, rw2_format4, scene, sony_craw};
|
||||
use photocraft_raw::*;
|
||||
|
||||
const CURVE: [u16; 4] = [8000, 10400, 12900, 14100];
|
||||
@@ -176,13 +176,63 @@ fn patch_ifd0_short(b: &mut [u8], tag: u16, v: u16) {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rw2_compressed_formats_fall_back() {
|
||||
fn rw2_format4_round_trip_is_exact() {
|
||||
let (w, h) = (42, 6);
|
||||
let mut data = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
data.push(200 + 4 * (y as u16) + 3 * (x as u16));
|
||||
}
|
||||
}
|
||||
let b = rw2_format4(w, h, &data);
|
||||
assert_eq!(identify(&b), Some(RawFormat::Rw2));
|
||||
let s = decode(&b, &Limits::default()).unwrap();
|
||||
assert_eq!((s.width, s.height), (w, h));
|
||||
assert_eq!(s.data, data);
|
||||
assert_eq!(s.cfa.as_ref().unwrap().phase(0, 0), [0, 1, 1, 2]);
|
||||
// The compressed variants record a black level 15 counts below the black
|
||||
// of the decoded samples.
|
||||
assert_eq!(s.black.values, vec![143.0, 144.0, 144.0, 145.0]);
|
||||
assert_eq!(s.white, [4095.0; 3]);
|
||||
assert_eq!(s.camera_wb, Some([2.0, 1.0, 1.5]));
|
||||
assert_eq!(s.crop, Rect::new(2, 2, w - 4, h - 4));
|
||||
assert!(s.warnings.is_empty(), "{:?}", s.warnings);
|
||||
let d = develop_sensor(&s, &DevelopOptions::default()).unwrap();
|
||||
assert_eq!((d.width as usize, d.height as usize), (w - 4, h - 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rw2_format4_crosses_pages() {
|
||||
// 16 bytes a row: 1100 rows walk past several 0x4000-byte page boundaries.
|
||||
let (w, h) = (14, 1100);
|
||||
let mut data = Vec::with_capacity(w * h);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
data.push(300 + 16 * ((y % 8) as u16) + 3 * (x as u16));
|
||||
}
|
||||
}
|
||||
let b = rw2_format4(w, h, &data);
|
||||
let s = decode(&b, &Limits::default()).unwrap();
|
||||
assert_eq!(s.data, data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rw2_format4_rejects_other_block_widths() {
|
||||
let (w, h) = (42, 2);
|
||||
let data: Vec<u16> = (0..w * h).map(|i| 200 + (i % 14) as u16 * 3).collect();
|
||||
let mut b = rw2_format4(w, h, &data);
|
||||
patch_ifd0_short(&mut b, 0x0002, 41);
|
||||
assert!(matches!(decode(&b, &Limits::default()), Err(RawError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rw2_undecoded_formats_fall_back() {
|
||||
let data = vec![200u16; 20 * 4];
|
||||
let mut b = rw2(20, 4, &data, 12);
|
||||
assert!(decode(&b, &Limits::default()).is_ok());
|
||||
patch_ifd0_short(&mut b, 0x002D, 4);
|
||||
patch_ifd0_short(&mut b, 0x002D, 6);
|
||||
match decode(&b, &Limits::default()) {
|
||||
Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 4"), "{m}"),
|
||||
Err(RawError::Unsupported(m)) => assert!(m.contains("raw format 6"), "{m}"),
|
||||
other => panic!("expected unsupported, got {other:?}"),
|
||||
}
|
||||
// Width not made of whole blocks.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Synthetic existing preview workload, including proxy creation, command/history and CPU
|
||||
//! flattening. Excludes scheduling, egui frames, display conversion, GPU upload/presentation.
|
||||
use photocraft_color::{Color, ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, LayerContent};
|
||||
use photocraft_geom::{Rect, Size};
|
||||
use photocraft_ui_egui::{filter_dialog, proxy};
|
||||
use serde_json::json;
|
||||
use std::time::Instant;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let n = |key: &str, default| std::env::var(key).ok().and_then(|s| s.parse::<u32>().ok()).unwrap_or(default);
|
||||
let (w, h, reps) = (n("PHOTOCRAFT_UNSHARP_WIDTH", 6000), n("PHOTOCRAFT_UNSHARP_HEIGHT", 4000), n("PHOTOCRAFT_UNSHARP_REPS", 5));
|
||||
if w == 0 || h == 0 || w > 8192 || h > 8192 || !(1..=15).contains(&reps) {
|
||||
return Err("invalid benchmark dimensions/reps".into());
|
||||
}
|
||||
let depth = match n("PHOTOCRAFT_UNSHARP_DEPTH", 8) {
|
||||
8 => SampleType::U8,
|
||||
16 => SampleType::U16,
|
||||
32 => SampleType::F32,
|
||||
_ => return Err("invalid depth".into()),
|
||||
};
|
||||
let mut doc = Document::with_background("Synthetic Unsharp Mask", Size::new(w, h), ColorMode::Rgb, depth, Color::WHITE);
|
||||
let layer = doc.layers.first_mut().ok_or("missing layer")?;
|
||||
let id = layer.id;
|
||||
let LayerContent::Raster(s) = &mut layer.content else { return Err("raster required".into()) };
|
||||
for y in 0..h as i32 {
|
||||
let data: Vec<_> = (0..w as i32)
|
||||
.flat_map(|x| [((x * 7 + y * 13) % 257) as f32 / 256.0, ((x ^ y) % 251) as f32 / 250.0, ((x + y * 11) % 127) as f32 / 126.0, 1.0])
|
||||
.collect();
|
||||
s.write_region(Rect::new(0, y, w as i32, y + 1), &data);
|
||||
}
|
||||
let cmd = "filter.sharpen.unsharpMask";
|
||||
let cases = std::env::var("PHOTOCRAFT_UNSHARP_CASES").unwrap_or_else(|_| "0.6:150:0,3:150:8,10:300:16,30:150:0".into());
|
||||
for case in cases.split(',') {
|
||||
let v: Vec<f64> = case.split(':').map(str::parse).collect::<Result<_, _>>()?;
|
||||
let (&radius, &amount, &threshold) = (v.first().ok_or("radius")?, v.get(1).ok_or("amount")?, v.get(2).ok_or("threshold")?);
|
||||
for reduced in [true, false] {
|
||||
let k = filter_dialog::preview_factor(cmd, &json!({"radius":radius}), proxy::preview_factor(&doc, reduced));
|
||||
let mut times = Vec::new();
|
||||
let mut checksum = 0u64;
|
||||
for rep in 0..reps + 2 {
|
||||
let start = Instant::now();
|
||||
let result = filter_dialog::preview_document(&doc, Some(id), cmd, &json!({"radius":radius,"amount":amount,"threshold":threshold}), k)
|
||||
.ok_or("preview failed")?;
|
||||
let pixels = photocraft_compose::flatten(&result);
|
||||
let ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
// Outside timing: stable hash over the full flattened result, no image file needed.
|
||||
let hash = pixels.px.iter().flatten().fold(0u64, |h, v| h.wrapping_mul(1099511628211).wrapping_add(u64::from(v.to_bits())));
|
||||
if rep == 0 {
|
||||
checksum = hash;
|
||||
} else if checksum != hash {
|
||||
return Err("unstable preview output".into());
|
||||
}
|
||||
if rep >= 2 {
|
||||
times.push(ms);
|
||||
}
|
||||
}
|
||||
let mut sorted = times.clone();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"{}",
|
||||
json!({"width":w,"height":h,"depth":n("PHOTOCRAFT_UNSHARP_DEPTH",8),"radius":radius,"amount":amount,"threshold":threshold,"proxy_factor":k,"runs_ms":times,"median_ms":sorted.get(sorted.len()/2),"checksum":checksum,"workers":rayon::current_num_threads(),"scope":"existing preview_document + CPU flatten; excludes GUI and GPU"})
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
//! Filter › Blur Gallery › Field Blur… as Photoshop's workspace (#3373): pins on the image, each
|
||||
//! with its own blur, interpolated between them. While the dialog is open the image under it takes
|
||||
//! the pointer: a click on the image adds a pin (and selects it), a drag moves a pin, and a drag on
|
||||
//! the selected pin's ring turns its blur up or down (one turn = the full 0–500 px; the arc shows
|
||||
//! the amount). Delete or Backspace removes the selected pin. The dialog shows the selected pin's
|
||||
//! Blur and the Preview switch; OK runs `filter.blurGallery.fieldBlur` with the `pins`.
|
||||
//!
|
||||
//! Everything lives in the dialog's fields, so automation drives it with `ui.dialog.set`: `pins`
|
||||
//! (`[{x, y, blur}]`, x and y as fractions of the filter's bounds) and `__selected`. The bounds are
|
||||
//! the engine's: the selection's when there is one, else the canvas.
|
||||
|
||||
use egui::{Color32, Pos2, Stroke, vec2};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::canvas::ViewXform;
|
||||
|
||||
pub const COMMAND: &str = "filter.blurGallery.fieldBlur";
|
||||
/// Field Blur's range, in pixels.
|
||||
const MAX_BLUR: f64 = 500.0;
|
||||
/// Photoshop's first pin.
|
||||
const DEFAULT_BLUR: f64 = 15.0;
|
||||
/// More pins than anyone places by hand; keeps the params and the per-pixel loop bounded.
|
||||
pub const MAX_PINS: usize = 64;
|
||||
/// Screen radii (points): the pin's dot, how near a press must be to grab it, and its ring.
|
||||
const DOT: f32 = 5.0;
|
||||
const GRAB: f32 = 9.0;
|
||||
const RING: f32 = 24.0;
|
||||
const RING_BAND: f32 = 5.0;
|
||||
|
||||
pub fn owns(fields: &Map<String, Value>) -> bool {
|
||||
fields.get("__command").and_then(Value::as_str) == Some(COMMAND)
|
||||
}
|
||||
|
||||
/// Turn a freshly opened Field Blur dialog into the workspace: one pin in the middle of the
|
||||
/// filter's bounds with the remembered blur, selected.
|
||||
pub fn init(app: &mut PhotocraftApp, fields: &mut Map<String, Value>) {
|
||||
reset(fields);
|
||||
let bounds = app.session.active().map(|st| (st.doc.id, st.doc.bounds(), st.doc.selection.clone()));
|
||||
if let Some((doc, canvas, selection)) = bounds {
|
||||
let b = selection.map(|s| app.cached_bounds(u64::MAX - doc.0, &s)).filter(|b| !b.is_empty()).unwrap_or(canvas);
|
||||
fields.insert("__bounds".into(), json!([b.x0, b.y0, b.x1, b.y1]));
|
||||
}
|
||||
}
|
||||
|
||||
/// One pin in the middle with the dialog's blur, selected. Alt+Cancel (Reset) runs this alone, so
|
||||
/// the bounds captured on opening stay.
|
||||
pub fn reset(fields: &mut Map<String, Value>) {
|
||||
let blur = fields.get("blur").and_then(Value::as_f64).filter(|b| b.is_finite()).unwrap_or(DEFAULT_BLUR).clamp(0.0, MAX_BLUR);
|
||||
fields.remove("centerX");
|
||||
fields.remove("centerY");
|
||||
fields.insert("blur".into(), json!(blur));
|
||||
fields.insert("pins".into(), json!([{"x": 0.5, "y": 0.5, "blur": blur}]));
|
||||
fields.insert("__selected".into(), json!(0));
|
||||
}
|
||||
|
||||
/// Where the dialog first opens (offset from the window's top-left): at the right edge, beside the
|
||||
/// image, as Photoshop docks its Blur Tools panel, so the pins under it stay in view. Moved, it
|
||||
/// reopens where it was left, like any dialog.
|
||||
pub fn first_place(fields: &Map<String, Value>, ctx: &egui::Context) -> Option<egui::Vec2> {
|
||||
owns(fields).then(|| vec2((ctx.content_rect().width() - 480.0).max(0.0), 96.0))
|
||||
}
|
||||
|
||||
/// One pin: position as fractions of the bounds, blur in pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Pin {
|
||||
pub x: f64,
|
||||
pub y: f64,
|
||||
pub blur: f64,
|
||||
}
|
||||
|
||||
/// The pins in `fields`, cleaned (finite, in range, at most [`MAX_PINS`]).
|
||||
pub fn pins(fields: &Map<String, Value>) -> Vec<Pin> {
|
||||
let Some(list) = fields.get("pins").and_then(Value::as_array) else { return Vec::new() };
|
||||
let num = |v: &Value, k: &str, d: f64| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).unwrap_or(d);
|
||||
list.iter()
|
||||
.take(MAX_PINS)
|
||||
.map(|v| Pin { x: num(v, "x", 0.5).clamp(0.0, 1.0), y: num(v, "y", 0.5).clamp(0.0, 1.0), blur: num(v, "blur", DEFAULT_BLUR).clamp(0.0, MAX_BLUR) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn set_pins(fields: &mut Map<String, Value>, pins: &[Pin]) {
|
||||
let list: Vec<Value> = pins.iter().map(|p| json!({"x": p.x, "y": p.y, "blur": p.blur})).collect();
|
||||
fields.insert("pins".into(), Value::Array(list));
|
||||
}
|
||||
|
||||
/// The selected pin's index, if it exists.
|
||||
pub fn selected(fields: &Map<String, Value>) -> Option<usize> {
|
||||
let n = pins(fields).len();
|
||||
fields.get("__selected").and_then(Value::as_u64).map(|i| i as usize).filter(|i| *i < n)
|
||||
}
|
||||
|
||||
fn select(fields: &mut Map<String, Value>, i: Option<usize>) {
|
||||
fields.insert("__selected".into(), i.map_or(Value::Null, |i| json!(i)));
|
||||
// The dialog's Blur (remembered for the next Field Blur) follows the selected pin.
|
||||
if let Some(p) = i.and_then(|i| pins(fields).get(i).copied()) {
|
||||
fields.insert("blur".into(), json!(p.blur));
|
||||
}
|
||||
}
|
||||
|
||||
/// The filter's bounds in document pixels `[x0, y0, x1, y1]`.
|
||||
fn bounds(fields: &Map<String, Value>) -> Option<[f64; 4]> {
|
||||
let b = fields.get("__bounds")?.as_array()?;
|
||||
let v = |i: usize| b.get(i).and_then(Value::as_f64);
|
||||
let r = [v(0)?, v(1)?, v(2)?, v(3)?];
|
||||
(r[2] > r[0] && r[3] > r[1]).then_some(r)
|
||||
}
|
||||
|
||||
fn to_doc(b: [f64; 4], p: Pin) -> [f64; 2] {
|
||||
[b[0] + p.x * (b[2] - b[0]), b[1] + p.y * (b[3] - b[1])]
|
||||
}
|
||||
|
||||
fn from_doc(b: [f64; 4], d: [f64; 2]) -> (f64, f64) {
|
||||
(((d[0] - b[0]) / (b[2] - b[0])).clamp(0.0, 1.0), ((d[1] - b[1]) / (b[3] - b[1])).clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// Remove the selected pin; the one before it (or the new first) is selected.
|
||||
pub fn remove_selected(fields: &mut Map<String, Value>) -> bool {
|
||||
let Some(i) = selected(fields) else { return false };
|
||||
let mut list = pins(fields);
|
||||
list.remove(i);
|
||||
set_pins(fields, &list);
|
||||
select(fields, if list.is_empty() { None } else { Some(i.saturating_sub(1)) });
|
||||
true
|
||||
}
|
||||
|
||||
/// The dialog body: the selected pin's Blur, how to place pins, and Preview.
|
||||
pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
let t = crate::theme::Tokens::get(ui.ctx());
|
||||
match selected(f) {
|
||||
Some(i) => {
|
||||
let mut list = pins(f);
|
||||
if let Some(pin) = list.get_mut(i) {
|
||||
let mut v = pin.blur as f32;
|
||||
if crate::widgets::slider_row(ui, tl!("Blur"), &mut v, 0.0..=MAX_BLUR as f32, "px", None).changed() {
|
||||
pin.blur = f64::from(v.round()).clamp(0.0, MAX_BLUR);
|
||||
set_pins(f, &list);
|
||||
select(f, Some(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
ui.label(egui::RichText::new(tl!("No pin selected")).color(t.text_dim));
|
||||
}
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(tl!("Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin."))
|
||||
.color(t.text_dim)
|
||||
.size(11.5),
|
||||
)
|
||||
.wrap(),
|
||||
);
|
||||
// Delete removes the selected pin, unless a field is being typed in.
|
||||
let typing = ui.ctx().memory(|m| m.focused().is_some());
|
||||
if !typing && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) || i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) {
|
||||
remove_selected(f);
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
if let Some(mut preview) = f.get("__preview").and_then(Value::as_bool) {
|
||||
ui.add_space(4.0);
|
||||
crate::widgets::checkbox(ui, &mut preview, tl!("Preview"));
|
||||
f.insert("__preview".into(), json!(preview));
|
||||
}
|
||||
}
|
||||
|
||||
/// What a press at screen point `at` grabs: the selected pin's ring, a pin, or nothing (a new pin).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Grab {
|
||||
Ring(usize),
|
||||
Pin(usize),
|
||||
New,
|
||||
}
|
||||
|
||||
fn grab(fields: &Map<String, Value>, xf: &ViewXform, at: Pos2) -> Grab {
|
||||
let Some(b) = bounds(fields) else { return Grab::New };
|
||||
let list = pins(fields);
|
||||
let screen = |p: Pin| {
|
||||
let d = to_doc(b, p);
|
||||
xf.to_screen(d[0] as f32, d[1] as f32)
|
||||
};
|
||||
if let Some(i) = selected(fields)
|
||||
&& let Some(p) = list.get(i)
|
||||
&& (screen(*p).distance(at) - RING).abs() <= RING_BAND
|
||||
{
|
||||
return Grab::Ring(i);
|
||||
}
|
||||
list.iter()
|
||||
.enumerate()
|
||||
.map(|(i, p)| (i, screen(*p).distance(at)))
|
||||
.filter(|(_, d)| *d <= GRAB)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map_or(Grab::New, |(i, _)| Grab::Pin(i))
|
||||
}
|
||||
|
||||
/// The pointer on the free image under the dialog: `over` is where it is, `press` where the
|
||||
/// primary button is held (`dialogs::free_press`), both in screen points. Returns whether the
|
||||
/// workspace took it.
|
||||
pub fn canvas(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform, over: Pos2, press: Option<Pos2>) -> bool {
|
||||
let Some(d) = app.ui.dialogs.last_mut().filter(|d| owns(&d.fields)) else { return false };
|
||||
let f = &mut d.fields;
|
||||
let Some(b) = bounds(f) else { return false };
|
||||
let (start, down) = ctx.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_down()));
|
||||
ctx.set_cursor_icon(match grab(f, xf, over) {
|
||||
Grab::Ring(_) => egui::CursorIcon::Alias,
|
||||
Grab::Pin(_) => egui::CursorIcon::Grab,
|
||||
Grab::New => egui::CursorIcon::Crosshair,
|
||||
});
|
||||
if !down && press.is_none() {
|
||||
f.remove("__drag");
|
||||
return true;
|
||||
}
|
||||
let Some(at) = press else { return true };
|
||||
let doc = xf.to_doc(at);
|
||||
let mut list = pins(f);
|
||||
if start {
|
||||
let drag = match grab(f, xf, at) {
|
||||
Grab::Ring(i) => {
|
||||
let c = list.get(i).map(|p| to_doc(b, *p)).unwrap_or(doc);
|
||||
json!({"ring": i, "angle": (doc[1] - c[1]).atan2(doc[0] - c[0])})
|
||||
}
|
||||
Grab::Pin(i) => {
|
||||
select(f, Some(i));
|
||||
let c = list.get(i).map(|p| to_doc(b, *p)).unwrap_or(doc);
|
||||
json!({"pin": i, "dx": c[0] - doc[0], "dy": c[1] - doc[1]})
|
||||
}
|
||||
Grab::New if list.len() < MAX_PINS && (b[0]..=b[2]).contains(&doc[0]) && (b[1]..=b[3]).contains(&doc[1]) => {
|
||||
// A new pin takes the selected pin's blur, as the dialog's Blur shows it.
|
||||
let blur = f.get("blur").and_then(Value::as_f64).filter(|v| v.is_finite()).unwrap_or(DEFAULT_BLUR).clamp(0.0, MAX_BLUR);
|
||||
let (x, y) = from_doc(b, doc);
|
||||
list.push(Pin { x, y, blur });
|
||||
set_pins(f, &list);
|
||||
select(f, Some(list.len() - 1));
|
||||
json!({"pin": list.len() - 1, "dx": 0.0, "dy": 0.0})
|
||||
}
|
||||
Grab::New => return true,
|
||||
};
|
||||
f.insert("__drag".into(), drag);
|
||||
ctx.request_repaint();
|
||||
return true;
|
||||
}
|
||||
let Some(drag) = f.get("__drag").cloned() else { return true };
|
||||
if let Some(i) = drag.get("pin").and_then(Value::as_u64).map(|i| i as usize)
|
||||
&& let Some(p) = list.get_mut(i)
|
||||
{
|
||||
let num = |k: &str| drag.get(k).and_then(Value::as_f64).unwrap_or(0.0);
|
||||
(p.x, p.y) = from_doc(b, [doc[0] + num("dx"), doc[1] + num("dy")]);
|
||||
set_pins(f, &list);
|
||||
} else if let Some(i) = drag.get("ring").and_then(Value::as_u64).map(|i| i as usize)
|
||||
&& let Some(p) = list.get_mut(i)
|
||||
{
|
||||
// The angle turned since the last frame, the short way round: clockwise raises the blur.
|
||||
let c = to_doc(b, *p);
|
||||
let a = (doc[1] - c[1]).atan2(doc[0] - c[0]);
|
||||
let last = drag.get("angle").and_then(Value::as_f64).unwrap_or(a);
|
||||
let turn = (a - last + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI;
|
||||
p.blur = (p.blur + turn / std::f64::consts::TAU * MAX_BLUR).clamp(0.0, MAX_BLUR);
|
||||
set_pins(f, &list);
|
||||
select(f, Some(i));
|
||||
f.insert("__drag".into(), json!({"ring": i, "angle": a}));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
true
|
||||
}
|
||||
|
||||
/// Draw the pins over the image while the workspace is open: a dot per pin (filled when
|
||||
/// selected) and, round the selected one, its ring with the blur as an arc from the top.
|
||||
pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
|
||||
let Some(d) = app.ui.dialogs.last().filter(|d| owns(&d.fields)) else { return };
|
||||
let Some(b) = bounds(&d.fields) else { return };
|
||||
let sel = selected(&d.fields);
|
||||
let (dark, light) = (Stroke::new(3.0, Color32::from_black_alpha(150)), Stroke::new(1.5, Color32::from_white_alpha(235)));
|
||||
for (i, p) in pins(&d.fields).into_iter().enumerate() {
|
||||
let c = to_doc(b, p);
|
||||
let c = xf.to_screen(c[0] as f32, c[1] as f32);
|
||||
if sel == Some(i) {
|
||||
painter.circle_stroke(c, RING, dark);
|
||||
painter.circle_stroke(c, RING, Stroke::new(1.0, Color32::from_white_alpha(140)));
|
||||
let frac = (p.blur / MAX_BLUR) as f32;
|
||||
let steps = (frac * 64.0).ceil().max(1.0) as usize;
|
||||
let arc: Vec<Pos2> = (0..=steps)
|
||||
.map(|k| {
|
||||
let a = -std::f32::consts::FRAC_PI_2 + std::f32::consts::TAU * frac * k as f32 / steps as f32;
|
||||
c + vec2(a.cos(), a.sin()) * RING
|
||||
})
|
||||
.collect();
|
||||
if frac > 0.0 {
|
||||
painter.add(egui::Shape::line(arc.clone(), Stroke::new(4.5, Color32::from_black_alpha(150))));
|
||||
painter.add(egui::Shape::line(arc, Stroke::new(2.5, Color32::WHITE)));
|
||||
}
|
||||
painter.circle(c, DOT, Color32::WHITE, Stroke::new(1.0, Color32::from_black_alpha(180)));
|
||||
} else {
|
||||
painter.circle_stroke(c, DOT, dark);
|
||||
painter.circle_stroke(c, DOT, light);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview proxies run at 1/`k` of the document: the pins' pixel blur scales with them.
|
||||
pub fn scale_for_proxy(params: &mut Value, k: u32) {
|
||||
if k <= 1 {
|
||||
return;
|
||||
}
|
||||
let Some(list) = params.get_mut("pins").and_then(Value::as_array_mut) else { return };
|
||||
for pin in list {
|
||||
if let Some(b) = pin.get("blur").and_then(Value::as_f64) {
|
||||
pin["blur"] = json!(b / f64::from(k));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! #3373: Field Blur's pins are placed, dragged and tuned on the image under the dialog, the
|
||||
//! preview follows them, and OK applies them.
|
||||
|
||||
use egui::{Modifiers, PointerButton, Pos2, pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::blur_pins::{COMMAND, Pin, pins, selected};
|
||||
use crate::canvas::ViewXform;
|
||||
|
||||
/// A 400×300 document at 400 %, so it fills the window round the dialog, with Field Blur open.
|
||||
fn harness(selection: bool) -> Harness<'static, PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
if selection {
|
||||
app.run("select.rect", json!({"x": 100, "y": 50, "width": 200, "height": 100})).unwrap();
|
||||
}
|
||||
app.sync_views();
|
||||
app.ui.extras.rulers = false;
|
||||
let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
|
||||
return;
|
||||
}
|
||||
crate::shortcuts::handle(app, &ctx);
|
||||
egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
|
||||
crate::dialogs::show(app, &ctx);
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(4);
|
||||
let v = &mut h.state_mut().ui.views[0];
|
||||
(v.zoom, v.center, v.fit_pending) = (4.0, [200.0, 150.0], false);
|
||||
crate::filter_dialog::open(h.state_mut(), COMMAND).unwrap();
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn fields(h: &Harness<'static, PhotocraftApp>) -> serde_json::Map<String, serde_json::Value> {
|
||||
h.state().ui.dialogs.last().unwrap().fields.clone()
|
||||
}
|
||||
|
||||
fn xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform {
|
||||
let app = h.state();
|
||||
let v = &app.ui.views[0];
|
||||
ViewXform {
|
||||
rect: crate::rulers::content_rect(app, app.last_canvas_rect),
|
||||
zoom: v.zoom,
|
||||
center: v.center,
|
||||
flip: false,
|
||||
rotation: v.rotation,
|
||||
aspect: app.ui.view.display_aspect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, down: bool) {
|
||||
h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn move_to(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) {
|
||||
h.event(egui::Event::PointerMoved(p));
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn drag(h: &mut Harness<'static, PhotocraftApp>, path: &[Pos2]) {
|
||||
move_to(h, path[0]);
|
||||
button(h, path[0], true);
|
||||
for p in &path[1..] {
|
||||
move_to(h, *p);
|
||||
}
|
||||
button(h, *path.last().unwrap(), false);
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
/// Where pin `p` is on screen.
|
||||
fn on_screen(h: &Harness<'static, PhotocraftApp>, p: Pin, bounds: [f64; 4]) -> Pos2 {
|
||||
let (x, y) = (bounds[0] + p.x * (bounds[2] - bounds[0]), bounds[1] + p.y * (bounds[3] - bounds[1]));
|
||||
xf(h).to_screen(x as f32, y as f32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_opens_with_one_selected_pin_in_the_middle_of_the_bounds() {
|
||||
let h = harness(false);
|
||||
let f = fields(&h);
|
||||
assert_eq!(pins(&f), vec![Pin { x: 0.5, y: 0.5, blur: 15.0 }]);
|
||||
assert_eq!(selected(&f), Some(0));
|
||||
assert_eq!(f["__bounds"], json!([0, 0, 400, 300]));
|
||||
assert!(!f.contains_key("centerX") && !f.contains_key("centerY"), "the pins replace the single centre");
|
||||
// With a selection the pins are fractions of its bounds, as the engine reads them.
|
||||
let h = harness(true);
|
||||
assert_eq!(fields(&h)["__bounds"], json!([100, 50, 300, 150]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pins_are_added_moved_tuned_and_removed_on_the_image() {
|
||||
let mut h = harness(false);
|
||||
let r = h.state().last_canvas_rect;
|
||||
// A click on the free image (left of the dialog) adds a pin there, selected.
|
||||
let a = pos2(r.left() + 80.0, r.bottom() - 80.0);
|
||||
move_to(&mut h, a);
|
||||
button(&mut h, a, true);
|
||||
button(&mut h, a, false);
|
||||
h.run_steps(2);
|
||||
let f = fields(&h);
|
||||
let list = pins(&f);
|
||||
assert_eq!(list.len(), 2, "{list:?}");
|
||||
assert_eq!(selected(&f), Some(1));
|
||||
let at = xf(&h).to_doc(a);
|
||||
assert!((list[1].x - at[0] / 400.0).abs() < 1e-3 && (list[1].y - at[1] / 300.0).abs() < 1e-3, "{:?} vs {at:?}", list[1]);
|
||||
assert_eq!(list[1].blur, 15.0, "a new pin takes the selected pin's blur");
|
||||
// Dragging the pin moves it by the pointer's movement (4 screen points per pixel at 400 %).
|
||||
let b = a + vec2(40.0, -20.0);
|
||||
drag(&mut h, &[a, a + vec2(20.0, -10.0), b]);
|
||||
let moved = pins(&fields(&h))[1];
|
||||
assert!((moved.x - (list[1].x + 10.0 / 400.0)).abs() < 1e-3 && (moved.y - (list[1].y - 5.0 / 300.0)).abs() < 1e-3, "{moved:?}");
|
||||
assert!(fields(&h).get("__drag").is_none(), "the drag ends on release");
|
||||
// A quarter turn clockwise on its ring adds a quarter of the 0–500 px range.
|
||||
let c = on_screen(&h, moved, [0.0, 0.0, 400.0, 300.0]);
|
||||
let ring: Vec<Pos2> = (0..=6).map(|k| c + vec2(24.0 * (k as f32 * 0.2618).cos(), 24.0 * (k as f32 * 0.2618).sin())).collect();
|
||||
drag(&mut h, &ring);
|
||||
let tuned = pins(&fields(&h))[1];
|
||||
assert!((tuned.blur - 140.0).abs() < 2.0, "15 + 125 px: {}", tuned.blur);
|
||||
assert!((tuned.x - moved.x).abs() < 1e-9, "the ring doesn't move the pin");
|
||||
assert_eq!(fields(&h)["blur"], json!(tuned.blur), "the dialog's Blur follows the selected pin");
|
||||
// The preview runs the filter with the pins (computed by the canvas's GPU path in the app;
|
||||
// asked for directly here, as the headless harness has no GPU).
|
||||
assert!(crate::canvas::ensure_filter_preview(h.state_mut(), 0, &egui::Context::default()).is_some());
|
||||
let preview = h.state().filter_preview.as_ref().expect("a live preview");
|
||||
assert_eq!(preview.key.params["pins"].as_array().map(Vec::len), Some(2));
|
||||
// Delete removes the selected pin; OK applies the rest in one step.
|
||||
h.key_press(egui::Key::Delete);
|
||||
h.run_steps(2);
|
||||
assert_eq!(pins(&fields(&h)).len(), 1);
|
||||
assert_eq!(selected(&fields(&h)), Some(0));
|
||||
let id = h.state().ui.dialogs.last().unwrap().id;
|
||||
let steps = h.state().session.active().unwrap().history.past_len();
|
||||
crate::dialogs::confirm(h.state_mut(), id).unwrap();
|
||||
let (cmd, p) = h.state().session.journal.last().cloned().unwrap();
|
||||
assert_eq!(cmd, COMMAND);
|
||||
assert_eq!(p["pins"], json!([{"x": 0.5, "y": 0.5, "blur": 15.0}]), "{p}");
|
||||
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1);
|
||||
}
|
||||
|
||||
/// A click outside the bounds (beside a selection) adds no pin; pins are capped.
|
||||
#[test]
|
||||
fn pins_stay_inside_the_bounds_and_are_capped() {
|
||||
let mut h = harness(true);
|
||||
let r = h.state().last_canvas_rect;
|
||||
let outside = pos2(r.left() + 30.0, r.top() + 30.0);
|
||||
assert!(xf(&h).to_doc(outside)[0] < 100.0, "left of the selection");
|
||||
move_to(&mut h, outside);
|
||||
button(&mut h, outside, true);
|
||||
button(&mut h, outside, false);
|
||||
h.run_steps(2);
|
||||
assert_eq!(pins(&fields(&h)).len(), 1);
|
||||
let many: Vec<_> = (0..200).map(|i| json!({"x": f64::from(i) / 200.0, "y": 0.5, "blur": 1e9})).collect();
|
||||
h.state_mut().ui.dialogs.last_mut().unwrap().fields.insert("pins".into(), json!(many));
|
||||
let list = pins(&fields(&h));
|
||||
assert_eq!(list.len(), crate::blur_pins::MAX_PINS);
|
||||
assert!(list.iter().all(|p| p.blur == 500.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_previews_scale_the_pins_blur() {
|
||||
let mut p = json!({"pins": [{"x": 0.2, "y": 0.3, "blur": 40.0}, {"x": 0.9, "y": 0.9, "blur": 0.0}]});
|
||||
crate::blur_pins::scale_for_proxy(&mut p, 4);
|
||||
assert_eq!(p, json!({"pins": [{"x": 0.2, "y": 0.3, "blur": 10.0}, {"x": 0.9, "y": 0.9, "blur": 0.0}]}));
|
||||
crate::blur_pins::scale_for_proxy(&mut p, 1);
|
||||
assert_eq!(p["pins"][0]["blur"], json!(10.0));
|
||||
}
|
||||
|
||||
/// Alt+Cancel → Reset (#3871) starts the workspace again from one pin in the middle, as when it
|
||||
/// opened, instead of leaving it with no pins; the bounds captured on opening stay.
|
||||
#[test]
|
||||
fn alt_reset_starts_again_from_one_pin() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap();
|
||||
let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone();
|
||||
let bounds = fields["__bounds"].clone();
|
||||
fields.insert("pins".into(), json!([{"x": 0.1, "y": 0.2, "blur": 40.0}, {"x": 0.8, "y": 0.7, "blur": 90.0}]));
|
||||
fields.insert("__selected".into(), json!(1));
|
||||
assert!(crate::dialog_alt_reset::supported(&fields));
|
||||
crate::dialog_alt_reset::apply(&mut app, &egui::Context::default(), &mut fields);
|
||||
assert_eq!(pins(&fields), [Pin { x: 0.5, y: 0.5, blur: 15.0 }]);
|
||||
assert_eq!(selected(&fields), Some(0));
|
||||
assert_eq!(fields["__bounds"], bounds);
|
||||
assert!(!fields.contains_key("centerX") && !fields.contains_key("centerY"), "{fields:?}");
|
||||
}
|
||||
@@ -1435,6 +1435,9 @@ mod tests {
|
||||
let ctx = egui::Context::default();
|
||||
let warnings = app.open_bytes("IMG_0001.dng", &dng).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE)), "{warnings:?}");
|
||||
// A raw has no embedded profile (ProPhoto RGB is the space it is developed into), so Ask
|
||||
// When Opening (on by default) has nothing to ask about.
|
||||
assert!(app.ui.dialogs.is_empty(), "no profile prompt for a raw");
|
||||
let raw = app.pending_raw_open.take().expect("a raw open queues the dialog");
|
||||
open_raw(&mut app, &ctx, raw).unwrap();
|
||||
let d = app.camera_raw.as_ref().unwrap();
|
||||
|
||||
@@ -3214,7 +3214,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
// Select and Mask's Refine Edge Brush paints on the image.
|
||||
let refine_brushing =
|
||||
primary && app.ui.dialogs.last().is_some_and(|d| crate::select_mask_view::owns(&d.fields) && crate::select_mask_view::brush_on(&d.fields));
|
||||
let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing;
|
||||
// Field Blur's pins are placed and dragged on the image (`blur_pins`).
|
||||
let pinning = primary && app.ui.dialogs.last().is_some_and(|d| crate::blur_pins::owns(&d.fields));
|
||||
let hand = app.ui.tool == Tool::Hand && !picking && !range_picking && !refine_brushing && !pinning;
|
||||
if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) {
|
||||
let d = xf.unmap_vec(d) / (view.zoom / ppp);
|
||||
view.center[0] -= d.x;
|
||||
@@ -3238,6 +3240,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
crate::color_picker_ui::sample_at(app, d[0], d[1]);
|
||||
}
|
||||
}
|
||||
} else if pinning
|
||||
&& !middle
|
||||
&& let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect)
|
||||
{
|
||||
let press = crate::dialogs::free_press(&ctx, rect);
|
||||
crate::blur_pins::canvas(app, &ctx, &xf, p, press);
|
||||
} else if refine_brushing
|
||||
&& !middle
|
||||
&& let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect)
|
||||
@@ -4445,6 +4453,7 @@ fn draw_tool_state(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform,
|
||||
crate::tool_feedback::draw_ants(painter, &pts, false);
|
||||
}
|
||||
crate::crop_straighten::draw(app, painter, |p| xf.to_screen(p[0] as f32, p[1] as f32), hover);
|
||||
crate::blur_pins::draw(app, painter, xf);
|
||||
if let Some(c) = app.ui.crop_rect {
|
||||
let deg = crate::crop_ui::angle(app);
|
||||
let shield = crate::crop_shield::current(app, painter.ctx());
|
||||
|
||||
@@ -1386,20 +1386,10 @@ mod tests {
|
||||
app.open_bytes("control.dng", &dng).unwrap();
|
||||
ctx.run_ui(Default::default(), |ui| crate::camera_raw_ui::show(&mut app, ui.ctx())).textures_delta.clear();
|
||||
assert!(app.camera_raw.is_some());
|
||||
// The raw develops in ProPhoto, so opening it also asks about the working-space
|
||||
// mismatch. Answer that prompt through the same control path before editing.
|
||||
assert_eq!(app.ui.dialogs.len(), 1);
|
||||
let mismatch = app.ui.dialogs.first().unwrap();
|
||||
assert_eq!(mismatch.fields["__prefsui"], "mismatch");
|
||||
assert_eq!(mismatch.fields["action"], "preserve");
|
||||
assert_eq!(mismatch.fields["applied"], "preserve");
|
||||
let mismatch_id = mismatch.id;
|
||||
let update = json!({"id":"filter.cameraRaw","params":{"ui":{"set":{"exposure":0.5}}}});
|
||||
assert_eq!(call(&mut app, &ctx, "ui.menu.invoke", update.clone())["ok"], false);
|
||||
let confirmed = call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog":mismatch_id}));
|
||||
assert_eq!(confirmed["ok"], true, "{confirmed}");
|
||||
assert_eq!(confirmed["result"]["action"], "preserve");
|
||||
// A developed raw has no embedded profile to ask about (`open_prompt`), so no profile
|
||||
// prompt stands between the open and the Camera Raw dialog.
|
||||
assert!(app.ui.dialogs.is_empty());
|
||||
let update = json!({"id":"filter.cameraRaw","params":{"ui":{"set":{"exposure":0.5}}}});
|
||||
let original = app.session.active().unwrap().doc.clone();
|
||||
let changed = call(&mut app, &ctx, "ui.menu.invoke", update);
|
||||
assert_eq!(changed["ok"], true, "{changed}");
|
||||
|
||||
@@ -157,7 +157,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
// effects, extends down and right instead of re-centring.
|
||||
let pinned: Option<egui::Vec2> = ctx.data(|m| m.get_temp(id));
|
||||
let place = place_id(&d);
|
||||
let start = pinned.or_else(|| ctx.data_mut(|m| m.get_persisted::<egui::Vec2>(place)));
|
||||
let start = pinned.or_else(|| ctx.data_mut(|m| m.get_persisted::<egui::Vec2>(place))).or_else(|| crate::blur_pins::first_place(&d.fields, ctx));
|
||||
let mut drag = egui::Vec2::ZERO;
|
||||
let mut sizing = false;
|
||||
let area = match start {
|
||||
@@ -305,6 +305,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
// Image Size and Canvas Size open on Width, selected (#2329).
|
||||
DialogKind::Command if fields.contains_key("__sizing") => first_field_focused(ui, id, |ui| crate::sizing::body(ui, &mut fields)),
|
||||
DialogKind::Command if crate::adjust_dialog::owns(&fields) => crate::adjust_dialog::body(app, ui, &mut fields),
|
||||
DialogKind::Command if crate::blur_pins::owns(&fields) => crate::blur_pins::body(ui, &mut fields),
|
||||
DialogKind::Command if fields.contains_key("__filter") => {
|
||||
// Color Settings: the monitor profile in use can change while it is open.
|
||||
if fields.get("__command").and_then(Value::as_str) == Some("edit.colorSettings") {
|
||||
@@ -629,6 +630,10 @@ pub fn cancel(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {
|
||||
if crate::guide_layout_ui::owns(&closed.fields) {
|
||||
app.ui.dialogs.retain(|child| child.fields.get("__dialog").and_then(Value::as_u64) != Some(id));
|
||||
}
|
||||
// Cancel on a profile prompt opens neither its file nor the ones still to come.
|
||||
if crate::open_prompt::owns(&closed.fields) {
|
||||
crate::open_prompt::answer(app, None)?;
|
||||
}
|
||||
app.ui.dialogs.retain(|d| !crate::layer_style::color_picker::child_of(&d.fields, id));
|
||||
app.filter_preview = None;
|
||||
app.color_range = None;
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn open_layer(app: &mut PhotocraftApp, layer: photocraft_doc::LayerId) -> Re
|
||||
let id = open(app)?;
|
||||
if let Some(d) = app.ui.dialogs.iter_mut().find(|d| d.id == id) {
|
||||
d.fields.insert("__layer".into(), json!(layer.0));
|
||||
d.fields.insert("__label".into(), json!(format!("Export As: {}", ldoc.name)));
|
||||
d.fields.insert("__label".into(), json!(crate::i18n::fmt(crate::i18n::t("Export As: {name}"), &[("name", &ldoc.name)])));
|
||||
d.fields.insert("__w".into(), json!(ldoc.size.width));
|
||||
d.fields.insert("__h".into(), json!(ldoc.size.height));
|
||||
}
|
||||
|
||||
@@ -36,12 +36,19 @@ pub enum DropTarget {
|
||||
/// `warnings` from an import, plus one for each font family the active document's type uses that
|
||||
/// isn't installed (#4559): Photoshop warns about missing fonts as a file opens, and the CLI and
|
||||
/// automation already report them; the type would otherwise silently render in a fallback face.
|
||||
pub(crate) fn with_missing_fonts(app: &PhotocraftApp, mut warnings: Vec<String>) -> Vec<String> {
|
||||
if let Some(st) = app.session.active() {
|
||||
for w in photocraft_engine::type_extra_cmds::missing_font_warnings(&st.doc) {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
pub(crate) fn with_missing_fonts(app: &PhotocraftApp, warnings: Vec<String>) -> Vec<String> {
|
||||
match app.session.active() {
|
||||
Some(st) => with_missing_fonts_of(&st.doc, warnings),
|
||||
None => warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`with_missing_fonts`] for `doc` itself: a file held back for its profile prompt
|
||||
/// (`open_prompt`) isn't the active document yet.
|
||||
pub(crate) fn with_missing_fonts_of(doc: &photocraft_doc::Document, mut warnings: Vec<String>) -> Vec<String> {
|
||||
for w in photocraft_engine::type_extra_cmds::missing_font_warnings(doc) {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
warnings
|
||||
@@ -71,9 +78,7 @@ impl PhotocraftApp {
|
||||
crate::jobs_ui::start_open(self, &display_name(path), Some(path.to_string()), crate::jobs_ui::bytes(bytes))?;
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let warnings = self.open_bytes(&display_name(path), bytes)?;
|
||||
self.opened_from(path);
|
||||
Ok(warnings)
|
||||
self.open_bytes_from(&display_name(path), bytes, Some(path))
|
||||
}
|
||||
|
||||
/// Record that the active document was just opened from `path`: File › Save writes back to it
|
||||
|
||||
@@ -435,6 +435,10 @@ pub fn reset_fields(app: &PhotocraftApp, fields: &mut Map<String, Value>) {
|
||||
}
|
||||
}
|
||||
apply_command_defaults(app, &command, fields);
|
||||
// The schema has no default for the Blur Gallery's pins: start again from the opening one.
|
||||
if command == crate::blur_pins::COMMAND {
|
||||
crate::blur_pins::reset(fields);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
|
||||
@@ -454,6 +458,9 @@ pub fn open(app: &mut PhotocraftApp, command: &str) -> Option<u64> {
|
||||
}
|
||||
restore_remembered(app, command, spec.params, &mut fields);
|
||||
apply_command_defaults(app, command, &mut fields);
|
||||
if command == crate::blur_pins::COMMAND {
|
||||
crate::blur_pins::init(app, &mut fields);
|
||||
}
|
||||
if parse_spec(spec.params).iter().any(|p| p.kind == Kind::Document) {
|
||||
// The document picker lists every open document (params refer to them by index).
|
||||
let names: Vec<String> = app.session.documents().iter().map(|d| d.doc.name.clone()).collect();
|
||||
@@ -549,6 +556,10 @@ pub(crate) fn source_label(key: &str) -> String {
|
||||
if key == "localized" {
|
||||
return "Localized Color Clusters".into();
|
||||
}
|
||||
// A name that already reads as text ("iPhone 14 Pro Max", "Web 1920") is not camelCase.
|
||||
if key.contains(' ') {
|
||||
return key.to_string();
|
||||
}
|
||||
// camelCase → "Camel Case"
|
||||
let mut s = String::new();
|
||||
for (i, ch) in key.chars().enumerate() {
|
||||
@@ -906,6 +917,10 @@ pub(crate) fn preview_document_for_target(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Blur Gallery pins carry their blur in document pixels too.
|
||||
if command.starts_with("filter.blurGallery.") {
|
||||
crate::blur_pins::scale_for_proxy(&mut p, run_k);
|
||||
}
|
||||
s.execute(command, p).ok()?;
|
||||
s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))
|
||||
}
|
||||
@@ -964,6 +979,15 @@ pub struct FilterPreviewKey {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Preset names such as "iPhone 14 Pro Max" (the artboard dialog's choices) are text, not
|
||||
/// camelCase keys: they used to read "I Phone 14 Pro Max".
|
||||
#[test]
|
||||
fn display_names_are_not_split_like_camel_case_keys() {
|
||||
assert_eq!(source_label("iPhone 14 Pro Max"), "iPhone 14 Pro Max");
|
||||
assert_eq!(source_label("Web 1920"), "Web 1920");
|
||||
assert_eq!(source_label("centerX"), "Center X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_direction_angles_get_the_dial() {
|
||||
// Every listed command still has a degree `angle` range, so the list cannot go stale.
|
||||
|
||||
@@ -559,6 +559,9 @@
|
||||
Blur Rozostření
|
||||
Blur Gallery Galerie rozostření
|
||||
Field Blur… Rozostření pole…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Není vybrán žádný špendlík
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Kliknutím do obrazu přidáte špendlík; tažením špendlík přesunete, tažením jeho prstence změníte rozostření. Delete odstraní vybraný špendlík.
|
||||
Iris Blur… Rozostření clonou…
|
||||
Tilt-Shift… Tilt-shift…
|
||||
Path Blur… Rozostření podél cesty…
|
||||
@@ -2209,6 +2212,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Není k dispozici žádná cesta, ze které by šlo vytvořit výběr: nakreslete ji nástrojem Pero nebo ji vyberte na panelu Cesty.
|
||||
Cancel opening Zrušit otevírání
|
||||
Cancelled opening {name} Otevírání {name} zrušeno
|
||||
The document “{name}” does not have an embedded {mode} profile. Dokument „{name}“ nemá vložený profil {mode}.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}“ má vložený barevný profil, který neodpovídá aktuálnímu pracovnímu prostoru barev {mode}.
|
||||
Embedded: {embedded} Vložený: {embedded}
|
||||
Working: {working} Pracovní: {working}
|
||||
Developing {name} Vyvolávání {name}
|
||||
Cancelled {label} Zrušeno: {label}
|
||||
Esc to cancel Esc pro zrušení
|
||||
@@ -3667,8 +3674,6 @@ curves Smooth Vyhladit
|
||||
fallback náhradní
|
||||
|
||||
# Composed labels and Navigator zoom context
|
||||
The document does not have an embedded colour profile. Working space: {working}. Dokument nemá vložený barevný profil. Pracovní prostor barev: {working}.
|
||||
The document has an embedded colour profile that does not match the working space.\nEmbedded: {embedded}\nWorking: {working} Dokument má vložený barevný profil, který neodpovídá pracovnímu prostoru barev.\nVložený: {embedded}\nPracovní: {working}
|
||||
Importing {what} from {file}… Importují se {what} ze souboru {file}…
|
||||
brushes štětce
|
||||
gradients přechody
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -558,6 +558,9 @@
|
||||
Blur Weichzeichnen
|
||||
Blur Gallery Weichzeichnen-Galerie
|
||||
Field Blur… Feldweichzeichner…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Kein Pin ausgewählt
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Klicken Sie ins Bild, um einen Pin hinzuzufügen; ziehen Sie einen Pin, um ihn zu verschieben, oder seinen Ring, um die Unschärfe zu ändern. Entf entfernt den ausgewählten Pin.
|
||||
Iris Blur… Irisweichzeichner…
|
||||
Tilt-Shift… Tilt-Shift…
|
||||
Path Blur… Pfadweichzeichner…
|
||||
@@ -1708,7 +1711,7 @@
|
||||
Layer Knocks Out Drop Shadow Ebene stanzt den Schlagschatten aus
|
||||
Legal Legal
|
||||
Letter Letter
|
||||
Light Light
|
||||
Light Hell
|
||||
Line Tool Linien-Werkzeug
|
||||
Linear Linear
|
||||
Linear Burn Linear nachbelichten
|
||||
@@ -2179,6 +2182,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Kein Pfad für eine Auswahl vorhanden: zeichne einen mit dem Stift-Werkzeug oder wähle einen im Pfade-Bedienfeld.
|
||||
Cancel opening Öffnen abbrechen
|
||||
Cancelled opening {name} Öffnen von {name} abgebrochen
|
||||
The document “{name}” does not have an embedded {mode} profile. Das Dokument „{name}“ hat kein eingebettetes {mode}-Profil.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Das Dokument „{name}“ hat ein eingebettetes Farbprofil, das nicht zum aktuellen {mode}-Arbeitsfarbraum passt.
|
||||
Embedded: {embedded} Eingebettet: {embedded}
|
||||
Working: {working} Arbeitsfarbraum: {working}
|
||||
Developing {name} {name} wird entwickelt
|
||||
Cancelled {label} {label} abgebrochen
|
||||
Esc to cancel Esc zum Abbrechen
|
||||
@@ -2741,6 +2748,360 @@ curves Smooth Glätten
|
||||
Light Red Hellrot
|
||||
Medium Blue Mittelblau
|
||||
Light Gray Hellgrau
|
||||
# Status messages, system info and tool names
|
||||
Join the ArtCraft Discord ({url}) Dem ArtCraft-Discord beitreten ({url})
|
||||
Nothing to paste: the clipboard holds no image Nichts einzufügen: Die Zwischenablage enthält kein Bild
|
||||
Graphics adapter: {adapter} Grafikadapter: {adapter}
|
||||
Backend: {backend} ({type}) Backend: {backend} ({type})
|
||||
Driver: {driver} Treiber: {driver}
|
||||
GPU backend preference: {backend} Bevorzugtes GPU-Backend: {backend}
|
||||
Selected at launch: {backend} Beim Start gewählt: {backend}
|
||||
Image compositor: {processor} Bildkompositor: {processor}
|
||||
Window renderer: {renderer} Fensterdarstellung: {renderer}
|
||||
Graphics adapter Grafikadapter
|
||||
Platform: {os} {arch} Plattform: {os} {arch}
|
||||
Monitor profile: {profile} Monitorprofil: {profile}
|
||||
Opened {url} {url} geöffnet
|
||||
{index} of {total} {index} von {total}
|
||||
Export As: {name} Exportieren als: {name}
|
||||
Color Sampler Tool Farbaufnahme-Werkzeug
|
||||
Vertical Type Tool Vertikales Text-Werkzeug
|
||||
Patch Tool Ausbessern-Werkzeug
|
||||
Grid view Rasteransicht
|
||||
List view Listenansicht
|
||||
Proof Setup… Proof einrichten…
|
||||
32-bit Preview Options 32-Bit-Vorschauoptionen
|
||||
# Shortcut editor commands without a menu item
|
||||
Toggle Layer Mask Overlay Ebenenmasken-Überlagerung umschalten
|
||||
Increase Type Size Schriftgröße erhöhen
|
||||
Decrease Type Size Schriftgröße verringern
|
||||
Increase Type Size by 10 Schriftgröße um 10 erhöhen
|
||||
Decrease Type Size by 10 Schriftgröße um 10 verringern
|
||||
Make Selection from Path Auswahl aus Pfad erstellen
|
||||
Target Composite Channel Gesamtkanal als Ziel festlegen
|
||||
Target Channel 3 Kanal 3 als Ziel festlegen
|
||||
Target Channel 4 Kanal 4 als Ziel festlegen
|
||||
Target Channel 5 Kanal 5 als Ziel festlegen
|
||||
Target Channel 6 Kanal 6 als Ziel festlegen
|
||||
Target Channel 7 Kanal 7 als Ziel festlegen
|
||||
Target Channel 8 Kanal 8 als Ziel festlegen
|
||||
Target Channel 9 Kanal 9 als Ziel festlegen
|
||||
Switch Foreground and Background Colors Vorder- und Hintergrundfarbe vertauschen
|
||||
Default Foreground and Background Colors Standardfarben für Vorder- und Hintergrund
|
||||
Fill with Foreground Color Mit Vordergrundfarbe füllen
|
||||
Fill with Background Color Mit Hintergrundfarbe füllen
|
||||
Fill with Foreground Color, Preserve Transparency Mit Vordergrundfarbe füllen, Transparenz erhalten
|
||||
Fill with Background Color, Preserve Transparency Mit Hintergrundfarbe füllen, Transparenz erhalten
|
||||
Decrease Brush Size Pinselgröße verringern
|
||||
Increase Brush Size Pinselgröße erhöhen
|
||||
Decrease Brush Hardness Pinselhärte verringern
|
||||
Increase Brush Hardness Pinselhärte erhöhen
|
||||
Temporary Vorübergehend
|
||||
Space Leertaste
|
||||
Hand Tool (hold) Hand-Werkzeug (gedrückt halten)
|
||||
Zoom In (hold, drag to scrub) Vergrößern (gedrückt halten, zum Zoomen ziehen)
|
||||
Zoom Out (hold) Verkleinern (gedrückt halten)
|
||||
Erase with Brush or Pencil (hold) Mit Pinsel oder Buntstift radieren (gedrückt halten)
|
||||
# Document Info and color profiles
|
||||
Author Title Position des Urhebers
|
||||
Copyright Status Urheberrechtsstatus
|
||||
Unknown Unbekannt
|
||||
Copyrighted Urheberrechtlich geschützt
|
||||
Public Domain Gemeinfrei
|
||||
Copyright Url Urheberrechts-URL
|
||||
Keywords Stichwörter
|
||||
Title Titel
|
||||
Profile Profil
|
||||
Working Arbeitsfarbraum
|
||||
Working-cmyk Arbeits-CMYK
|
||||
Coated-cmyk CMYK (gestrichen)
|
||||
Linear-srgb Lineares sRGB
|
||||
Gray-gamma-2.2 Grau (Gamma 2,2)
|
||||
Adobe-rgb-compat Adobe-RGB-kompatibel
|
||||
Prophoto-compat ProPhoto-kompatibel
|
||||
Display-p3 Display P3
|
||||
Intent Renderpriorität
|
||||
Bpc Schwarzpunktkompensierung
|
||||
Simulate Paper Papierfarbe simulieren
|
||||
# Color Lookup, Shadows/Highlights, channels and Calculations
|
||||
Warming Filter (85) Wärmefilter (85)
|
||||
Lut LUT
|
||||
Cool Kühl
|
||||
Teal Orange Türkis-Orange
|
||||
Faded Film Verblasster Film
|
||||
Day For Night Tag für Nacht
|
||||
Mono Contrast Mono-Kontrast
|
||||
Cross Process Kreuzentwicklung
|
||||
Shadow Amount Stärke der Tiefen
|
||||
Shadow Tone Tonbreite der Tiefen
|
||||
Shadow Radius Radius der Tiefen
|
||||
Highlight Amount Stärke der Lichter
|
||||
Highlight Tone Tonbreite der Lichter
|
||||
Highlight Radius Radius der Lichter
|
||||
Midtone Mitteltöne
|
||||
Black Clip Schwarz beschneiden
|
||||
White Clip Weiß beschneiden
|
||||
Strength Stärke
|
||||
Shadow Schatten
|
||||
Highlight Lichter
|
||||
Intensity Intensität
|
||||
Neutralize Neutralisieren
|
||||
Use Selection In Source Auswahl in der Quelle verwenden
|
||||
Use Selection In Target Auswahl im Ziel verwenden
|
||||
Cw Im Uhrzeigersinn
|
||||
Ccw Gegen den Uhrzeigersinn
|
||||
Nearest Nächster Nachbar
|
||||
Linear Dodge Linear abwedeln
|
||||
Mask Channel Maskenkanal
|
||||
R G B RGB
|
||||
Source Channel Quellkanal
|
||||
Source Invert Quelle invertieren
|
||||
Result Ergebnis
|
||||
Source1 Channel Kanal der Quelle 1
|
||||
Source1 Invert Quelle 1 invertieren
|
||||
Source2 Channel Kanal der Quelle 2
|
||||
Source2 Invert Quelle 2 invertieren
|
||||
Channel1 Kanal 1
|
||||
Channel2 Kanal 2
|
||||
Channel3 Kanal 3
|
||||
Channel4 Kanal 4
|
||||
# Measurement log
|
||||
Label Beschriftung
|
||||
Date and Time Datum und Uhrzeit
|
||||
Scale Units Maßstabseinheiten
|
||||
Scale Factor Maßstabsfaktor
|
||||
Area Fläche
|
||||
Perimeter Umfang
|
||||
Circularity Kreisförmigkeit
|
||||
Gray Value (Minimum) Grauwert (Minimum)
|
||||
Gray Value (Maximum) Grauwert (Maximum)
|
||||
Gray Value (Mean) Grauwert (Mittelwert)
|
||||
Gray Value (Median) Grauwert (Median)
|
||||
Integrated Density Integrierte Dichte
|
||||
Length Länge
|
||||
W: B:
|
||||
A: Wi:
|
||||
# Lens Correction, Blur Gallery and distortion filters
|
||||
Pattern Fill… Musterfüllung…
|
||||
Generic Allgemein
|
||||
Correct Distortion Verzerrung korrigieren
|
||||
Correct Vignette Vignette korrigieren
|
||||
Correct C A Chromatische Aberration korrigieren
|
||||
Auto Scale Automatisch skalieren
|
||||
Distortion Verzerrung
|
||||
Red Cyan Rot/Cyan
|
||||
Blue Yellow Blau/Gelb
|
||||
Vignette Amount Stärke der Vignette
|
||||
Vignette Midpoint Mittelpunkt der Vignette
|
||||
Edge Extension Kantenerweiterung
|
||||
Hexagon Sechseck
|
||||
Pentagon Fünfeck
|
||||
Heptagon Siebeneck
|
||||
Octagon Achteck
|
||||
Blade Curvature Krümmung der Blendenlamellen
|
||||
Depth Map Tiefenkarte
|
||||
Focal Distance Fokusabstand
|
||||
Distribution Verteilung
|
||||
Uniform Gleichmäßig
|
||||
Monochromatic Monochrom
|
||||
Seed Startwert
|
||||
Spin Drehen
|
||||
Draft Entwurf
|
||||
Good Gut
|
||||
Best Beste
|
||||
Center X Mitte X
|
||||
Center Y Mitte Y
|
||||
Circle Kreis
|
||||
Star Stern
|
||||
Cross Kreuz
|
||||
High Hoch
|
||||
Low Niedrig
|
||||
Edge Only Nur Kanten
|
||||
Overlay Edge Kante überlagern
|
||||
Focus Fokus
|
||||
Transition Übergang
|
||||
Speed Geschwindigkeit
|
||||
Taper Verjüngung
|
||||
End X Ende X
|
||||
End Y Ende Y
|
||||
Blur Angle Weichzeichnungswinkel
|
||||
Rectangular To Polar Rechteckig zu Polar
|
||||
Polar To Rectangular Polar zu Rechteckig
|
||||
Undefined Areas Undefinierte Bereiche
|
||||
Wrap Umbrechen
|
||||
Repeat Wiederholen
|
||||
Horizontal Only Nur horizontal
|
||||
Vertical Only Nur vertikal
|
||||
Generators Generatoren
|
||||
Wavelength Min Wellenlänge min.
|
||||
Wavelength Max Wellenlänge max.
|
||||
Amplitude Min Amplitude min.
|
||||
Amplitude Max Amplitude max.
|
||||
Sine Sinus
|
||||
Ridges Grate
|
||||
Pond Ripples Teichwellen
|
||||
Out From Center Von der Mitte nach außen
|
||||
Around Center Um die Mitte
|
||||
Reduce Color Noise Farbrauschen reduzieren
|
||||
Sharpen Details Details schärfen
|
||||
Remove Jpeg Artifact JPEG-Artefakte entfernen
|
||||
Max Radius Maximaler Radius
|
||||
Cell Size Zellengröße
|
||||
Fine Dots Feine Punkte
|
||||
Medium Dots Mittlere Punkte
|
||||
Grainy Dots Körnige Punkte
|
||||
Coarse Dots Grobe Punkte
|
||||
Short Lines Kurze Linien
|
||||
Medium Lines Mittlere Linien
|
||||
Long Lines Lange Linien
|
||||
Short Strokes Kurze Striche
|
||||
Medium Strokes Mittlere Striche
|
||||
Long Strokes Lange Striche
|
||||
# Render filters: Flame, Picture Frame, Tree
|
||||
Flame Type Flammentyp
|
||||
One Flame Along Path Eine Flamme entlang des Pfads
|
||||
Multiple Flames Along Path Mehrere Flammen entlang des Pfads
|
||||
Multiple Flames Path Directions Mehrere Flammen, Pfadrichtungen
|
||||
Multiple Flames Various Length Mehrere Flammen, unterschiedliche Längen
|
||||
Candle Light Kerzenlicht
|
||||
Multiple Flames One Direction Mehrere Flammen, eine Richtung
|
||||
Randomize Length Länge zufällig variieren
|
||||
Interval Abstand
|
||||
Adjust Interval For Loops Abstand für Schleifen anpassen
|
||||
Use Custom Color Eigene Farbe verwenden
|
||||
Jag Zacken
|
||||
Flame Lines Flammenlinien
|
||||
Flame Bottom Alignment Ausrichtung des Flammenfußes
|
||||
Flame Style Flammenstil
|
||||
Violent Heftig
|
||||
Flat Flach
|
||||
Flame Shape Flammenform
|
||||
To Center Zur Mitte
|
||||
Pointed Spitz
|
||||
Randomize Shapes Formen zufällig variieren
|
||||
Fine Fein
|
||||
Frame Rahmen
|
||||
Vine With Flowers Ranke mit Blumen
|
||||
Vine With Leaves Ranke mit Blättern
|
||||
Ivy Efeu
|
||||
Roses Rosen
|
||||
Daisies Gänseblümchen
|
||||
Berries Beeren
|
||||
Bamboo Bambus
|
||||
Waves Wellen
|
||||
Zigzag Zickzack
|
||||
Rope Seil
|
||||
Scallops Muschelrand
|
||||
Double Line Doppellinie
|
||||
Snowflakes Schneeflocken
|
||||
Stars Sterne
|
||||
Hearts Herzen
|
||||
Arrangement Anordnung
|
||||
Thickness Dicke
|
||||
Vine Color Rankenfarbe
|
||||
Flower Color Blütenfarbe
|
||||
Leaf Color Blattfarbe
|
||||
Base Tree Type Baumtyp
|
||||
Light Direction Lichtrichtung
|
||||
Leaves Amount Blattmenge
|
||||
Leaves Size Blattgröße
|
||||
Branches Height Asthöhe
|
||||
Branches Thickness Aststärke
|
||||
Default Leaves Standardblätter
|
||||
Leaves Color Blattfarbe
|
||||
Custom Branch Color Eigene Astfarbe
|
||||
Branches Color Astfarbe
|
||||
Flat Shading Flächige Schattierung
|
||||
# Lens, Lighting Effects, depth and mosaic filters
|
||||
Lens Objektiv
|
||||
Prime35 Festbrennweite 35
|
||||
Prime105 Festbrennweite 105
|
||||
Movie Prime Film-Festbrennweite
|
||||
Light Type Lichttyp
|
||||
Point Punkt
|
||||
Infinite Unendlich
|
||||
Light X Licht X
|
||||
Light Y Licht Y
|
||||
Light Z Licht Z
|
||||
Target X Ziel X
|
||||
Target Y Ziel Y
|
||||
Elevation Höhe
|
||||
Gloss Glanz
|
||||
Metallic Metallisch
|
||||
Ambience Umgebungslicht
|
||||
White Is High Weiß ist hoch
|
||||
Ambient Umgebung
|
||||
Warmth Wärme
|
||||
Softness Weichheit
|
||||
Reduce Noise Rauschen reduzieren
|
||||
Darken Only Nur abdunkeln
|
||||
Lighten Only Nur aufhellen
|
||||
Anisotropic Anisotrop
|
||||
Blocks Blöcke
|
||||
Pyramids Pyramiden
|
||||
Depth Mode Tiefenmodus
|
||||
Random Zufällig
|
||||
Level Based Stufenbasiert
|
||||
Solid Front Faces Einfarbige Vorderseiten
|
||||
Mask Incomplete Blocks Unvollständige Blöcke maskieren
|
||||
Stylization Stilisierung
|
||||
Cleanliness Sauberkeit
|
||||
Bristle Detail Borstendetail
|
||||
Lighting Beleuchtung
|
||||
Shine Glanz
|
||||
Max Offset Maximaler Versatz
|
||||
Unaltered Unverändert
|
||||
Lower Untere
|
||||
Upper Obere
|
||||
Blast Böe
|
||||
Stagger Versetzt
|
||||
From Right Von rechts
|
||||
From Left Von links
|
||||
Eliminate Entfernen
|
||||
Odd Fields Ungerade Halbbilder
|
||||
Even Fields Gerade Halbbilder
|
||||
Create By Erzeugen durch
|
||||
Duplication Duplizieren
|
||||
Kernel Kern
|
||||
Input Mode Eingabemodus
|
||||
Rgb RGB
|
||||
Hsb HSB
|
||||
Hsl HSL
|
||||
Row Order Zeilenreihenfolge
|
||||
Preserve Erhalten
|
||||
Squareness Rechteckigkeit
|
||||
# Find and Replace, image size, Warp and Layer Style blending options
|
||||
Any Beliebig
|
||||
Cmyk CMYK
|
||||
To Nach
|
||||
Dont Enlarge Nicht vergrößern
|
||||
Find Suchen
|
||||
Replace Ersetzen
|
||||
Change Find Ersetzen und suchen
|
||||
Case Sensitive Groß-/Kleinschreibung beachten
|
||||
Whole Word Ganzes Wort
|
||||
Forward Vorwärts
|
||||
Based On Basierend auf
|
||||
General Blending Allgemeine Füllmethode
|
||||
Advanced Blending Erweiterte Füllmethode
|
||||
Blend Interior Effects as Group Innere Effekte als Gruppe überblenden
|
||||
Blend Clipped Layers as Group Ebenen der Schnittmaske als Gruppe überblenden
|
||||
Transparency Shapes Layer Transparenz bestimmt die Ebenenform
|
||||
Layer Mask Hides Effects Ebenenmaske blendet Effekte aus
|
||||
Vector Mask Hides Effects Vektormaske blendet Effekte aus
|
||||
This Layer: Diese Ebene:
|
||||
Underlying Layer: Darunterliegende Ebene:
|
||||
Up Nach oben
|
||||
Checkerboard Schachbrett
|
||||
Arc Lower Bogen unten
|
||||
Arc Upper Bogen oben
|
||||
Bend Biegen
|
||||
Horizontal Distortion Horizontale Verzerrung
|
||||
Vertical Distortion Vertikale Verzerrung
|
||||
Stretch Strecken
|
||||
Map Document Dokument zuordnen
|
||||
Map Path Pfad zuordnen
|
||||
Fuzziness Toleranz
|
||||
Object Finder Objektsucher
|
||||
No object found there — drag a rectangle around it Dort wurde kein Objekt gefunden — ziehen Sie ein Rechteck darum
|
||||
Remove after each stroke Nach jedem Strich entfernen
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -1610,6 +1610,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Δεν υπάρχει διαδρομή για δημιουργία επιλογής: σχεδιάστε μία με το εργαλείο Πένα (Pen Tool) ή επιλέξτε μία στο πλαίσιο Διαδρομές.
|
||||
Cancel opening Ακύρωση ανοίγματος
|
||||
Cancelled opening {name} Ακυρώθηκε το άνοιγμα του {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. Το έγγραφο «{name}» δεν έχει ενσωματωμένο προφίλ {mode}.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Το έγγραφο «{name}» έχει ενσωματωμένο χρωματικό προφίλ που δεν ταιριάζει με τον τρέχοντα χώρο εργασίας {mode}.
|
||||
Embedded: {embedded} Ενσωματωμένο: {embedded}
|
||||
Working: {working} Χώρος εργασίας: {working}
|
||||
Cancelled {label} Ακυρώθηκε: {label}
|
||||
Esc to cancel Esc για ακύρωση
|
||||
Opened {name} Άνοιξε το {name}
|
||||
@@ -2394,6 +2398,9 @@
|
||||
Fibers… Ίνες…
|
||||
Field Blur Θόλωση πεδίου
|
||||
Field Blur… Θόλωση πεδίου…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Δεν έχει επιλεγεί καρφίτσα
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Κάντε κλικ στην εικόνα για να προσθέσετε καρφίτσα· σύρετε μια καρφίτσα για να τη μετακινήσετε ή τον δακτύλιό της για να αλλάξετε τη θόλωση. Το Delete αφαιρεί την επιλεγμένη καρφίτσα.
|
||||
File Info Πληροφορίες αρχείου
|
||||
File Settings Ρυθμίσεις αρχείου
|
||||
Fill Path Γέμισμα διαδρομής
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1029 and column 18.
|
@@ -555,6 +555,9 @@
|
||||
Blur Desenfocar
|
||||
Blur Gallery Galería de desenfoque
|
||||
Field Blur… Desenfoque de campo…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Ningún pin seleccionado
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Haga clic en la imagen para añadir un pin; arrastre un pin para moverlo o su anillo para cambiar el desenfoque. Suprimir elimina el pin seleccionado.
|
||||
Iris Blur… Desenfoque de iris…
|
||||
Tilt-Shift… Cambio de inclinación…
|
||||
Path Blur… Desenfoque de trazado…
|
||||
@@ -2195,6 +2198,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. No hay ningún trazado para crear una selección: dibuje uno con la herramienta Pluma o seleccione uno en el panel Trazados.
|
||||
Cancel opening Cancelar apertura
|
||||
Cancelled opening {name} Se canceló la apertura de {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. El documento «{name}» no tiene un perfil {mode} incrustado.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. El documento «{name}» tiene un perfil de color incrustado que no coincide con el espacio de trabajo {mode} actual.
|
||||
Embedded: {embedded} Incrustado: {embedded}
|
||||
Working: {working} Espacio de trabajo: {working}
|
||||
Developing {name} Revelando {name}
|
||||
Cancelled {label} Se canceló {label}
|
||||
Esc to cancel Esc para cancelar
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -543,6 +543,9 @@
|
||||
Blur Flou
|
||||
Blur Gallery Galerie de flous
|
||||
Field Blur… Flou de champ…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Aucune épingle sélectionnée
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Cliquez dans l’image pour ajouter une épingle ; faites glisser une épingle pour la déplacer, ou son anneau pour modifier le flou. Suppr supprime l’épingle sélectionnée.
|
||||
Iris Blur… Flou d'iris…
|
||||
Tilt-Shift… Inclinaison-décalage…
|
||||
Path Blur… Flou de tracé…
|
||||
@@ -2155,6 +2158,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Aucun tracé à partir duquel créer une sélection : dessinez-en un avec l'outil Plume ou sélectionnez-en un dans le panneau Tracés.
|
||||
Cancel opening Annuler l'ouverture
|
||||
Cancelled opening {name} Ouverture de {name} annulée
|
||||
The document “{name}” does not have an embedded {mode} profile. Le document « {name} » n'a pas de profil {mode} incorporé.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Le document « {name} » a un profil colorimétrique incorporé qui ne correspond pas à l'espace de travail {mode} actuel.
|
||||
Embedded: {embedded} Incorporé : {embedded}
|
||||
Working: {working} Espace de travail : {working}
|
||||
Developing {name} Développement de {name}
|
||||
Cancelled {label} {label} : annulé
|
||||
Esc to cancel Échap pour annuler
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -561,6 +561,8 @@
|
||||
Facet Lapolás
|
||||
Fibers… Szálak…
|
||||
Field Blur… Mezőelmosás…
|
||||
No pin selected Nincs kijelölt tű
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Kattints a képre tű hozzáadásához; húzd a tűt az áthelyezéséhez, vagy a gyűrűjét az elmosás módosításához. A Delete törli a kijelölt tűt.
|
||||
Fill Path… Útvonal kitöltése…
|
||||
Fill Screen Képernyő kitöltése
|
||||
Filter Szűrő
|
||||
@@ -2484,6 +2486,10 @@ navigator Zoom Nagyítás mértéke
|
||||
Camera Raw Filter ({layer}) Camera Raw szűrő ({layer})
|
||||
Camera Raw isn't open A Camera Raw nincs megnyitva
|
||||
Cancelled opening {name} Megnyitás megszakítva: {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. A(z) „{name}” dokumentumnak nincs beágyazott {mode}-profilja.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. A(z) „{name}” dokumentum beágyazott színprofilja nem egyezik az aktuális {mode}-munkaszíntérrel.
|
||||
Embedded: {embedded} Beágyazott: {embedded}
|
||||
Working: {working} Munkaszíntér: {working}
|
||||
Cancelled {label} Megszakítva: {label}
|
||||
Clarity Tisztaság
|
||||
Color Detail Színrészletesség
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -536,6 +536,9 @@
|
||||
Blur Blur
|
||||
Blur Gallery Galeri Blur
|
||||
Field Blur… Field Blur…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Tidak ada pin yang dipilih
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Klik gambar untuk menambah pin; seret pin untuk memindahkannya, atau cincinnya untuk mengubah blur. Delete menghapus pin yang dipilih.
|
||||
Iris Blur… Iris Blur…
|
||||
Tilt-Shift… Tilt-Shift…
|
||||
Path Blur… Path Blur…
|
||||
@@ -2148,6 +2151,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Tidak ada path untuk dibuat seleksi: gambar dengan alat Pen atau pilih salah satu di panel Path.
|
||||
Cancel opening Batalkan pembukaan
|
||||
Cancelled opening {name} Pembukaan {name} dibatalkan
|
||||
The document “{name}” does not have an embedded {mode} profile. Dokumen “{name}” tidak memiliki profil {mode} tertanam.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokumen “{name}” memiliki profil warna tertanam yang tidak cocok dengan working space {mode} saat ini.
|
||||
Embedded: {embedded} Tertanam: {embedded}
|
||||
Working: {working} Working space: {working}
|
||||
Developing {name} Mengembangkan {name}
|
||||
Cancelled {label} {label} dibatalkan
|
||||
Esc to cancel Esc untuk batal
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -551,6 +551,9 @@
|
||||
Blur Sfocatura
|
||||
Blur Gallery Galleria sfocatura
|
||||
Field Blur… Sfocatura campo…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Nessuna puntina selezionata
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Fai clic sull’immagine per aggiungere una puntina; trascina una puntina per spostarla o il suo anello per cambiare la sfocatura. Canc rimuove la puntina selezionata.
|
||||
Iris Blur… Sfocatura diaframma…
|
||||
Tilt-Shift… Miniatura…
|
||||
Path Blur… Sfocatura tracciato…
|
||||
@@ -2191,6 +2194,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nessun tracciato da cui creare selezione: disegnane uno con Penna o selezionane uno nel pannello Tracciati.
|
||||
Cancel opening Annulla apertura
|
||||
Cancelled opening {name} Apertura {name} annullata
|
||||
The document “{name}” does not have an embedded {mode} profile. Il documento “{name}” non ha un profilo {mode} incorporato.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Il documento “{name}” ha un profilo colore incorporato che non corrisponde allo spazio di lavoro {mode} corrente.
|
||||
Embedded: {embedded} Incorporato: {embedded}
|
||||
Working: {working} Di lavoro: {working}
|
||||
Developing {name} Sviluppo di {name}
|
||||
Cancelled {label} {label} annullato
|
||||
Esc to cancel Esc per annullare
|
||||
@@ -4043,8 +4050,6 @@ layerLabel No Color Nessun colore
|
||||
Monitor profile on {display}: {profile} Profilo monitor su {display}: {profile}
|
||||
manual manuale
|
||||
fallback ripiego
|
||||
The document does not have an embedded colour profile. Working space: {working}. Il documento non ha un profilo colore incorporato. Spazio di lavoro: {working}.
|
||||
The document has an embedded colour profile that does not match the working space.\nEmbedded: {embedded}\nWorking: {working} Il documento ha un profilo colore incorporato che non corrisponde allo spazio di lavoro.\nIncorporato: {embedded}\nDi lavoro: {working}
|
||||
Importing {what} from {file}… Importazione di {what} da {file}…
|
||||
brushes pennelli
|
||||
gradients sfumature
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2647 and column 53.
|
@@ -553,6 +553,9 @@
|
||||
Blur ぼかし
|
||||
Blur Gallery ぼかしギャラリー
|
||||
Field Blur… フィールドぼかし…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected ピンが選択されていません
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 画像をクリックしてピンを追加します。ピンをドラッグして移動し、リングをドラッグしてぼかしを変更します。Delete キーで選択したピンを削除します。
|
||||
Iris Blur… 虹彩絞りぼかし…
|
||||
Tilt-Shift… チルトシフト…
|
||||
Path Blur… パスぼかし…
|
||||
@@ -2189,6 +2192,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 選択範囲を作成するパスがありません。ペンツールで描くか、パスパネルでパスを選択してください。
|
||||
Cancel opening 開くのをキャンセル
|
||||
Cancelled opening {name} {name} を開くのをキャンセルしました
|
||||
The document “{name}” does not have an embedded {mode} profile. ドキュメント「{name}」には埋め込み {mode} プロファイルがありません。
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. ドキュメント「{name}」の埋め込みカラープロファイルは、現在の {mode} 作業用スペースと一致しません。
|
||||
Embedded: {embedded} 埋め込み: {embedded}
|
||||
Working: {working} 作業用スペース: {working}
|
||||
Developing {name} {name} を現像中
|
||||
Cancelled {label} {label} をキャンセルしました
|
||||
Esc to cancel Esc キーでキャンセル
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -540,6 +540,9 @@
|
||||
Blur 흐림 효과
|
||||
Blur Gallery 흐림 효과 갤러리
|
||||
Field Blur… 필드 흐림 효과…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected 선택한 핀 없음
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 이미지를 클릭하여 핀을 추가합니다. 핀을 드래그하여 이동하고, 링을 드래그하여 흐림 정도를 바꿉니다. Delete 키로 선택한 핀을 삭제합니다.
|
||||
Iris Blur… 조리개 흐림 효과…
|
||||
Tilt-Shift… 기울기-이동…
|
||||
Path Blur… 패스 흐림 효과…
|
||||
@@ -2150,6 +2153,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 선택 영역으로 만들 패스가 없습니다: 펜 도구로 그리거나 패스 패널에서 선택하세요.
|
||||
Cancel opening 열기 취소
|
||||
Cancelled opening {name} {name} 열기를 취소했습니다
|
||||
The document “{name}” does not have an embedded {mode} profile. 문서 “{name}”에 포함된 {mode} 프로파일이 없습니다.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. 문서 “{name}”에 포함된 색상 프로파일이 현재 {mode} 작업 색상 공간과 일치하지 않습니다.
|
||||
Embedded: {embedded} 포함됨: {embedded}
|
||||
Working: {working} 작업 색상 공간: {working}
|
||||
Developing {name} {name} 현상 중
|
||||
Cancelled {label} {label} 작업을 취소했습니다
|
||||
Esc to cancel Esc 키로 취소
|
||||
|
||||
|
@@ -543,6 +543,9 @@
|
||||
Blur Vervagen
|
||||
Blur Gallery Vervagingsgalerie
|
||||
Field Blur… Veldvervaging…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Geen speld geselecteerd
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Klik in de afbeelding om een speld toe te voegen; sleep een speld om hem te verplaatsen, of zijn ring om de vervaging te wijzigen. Delete verwijdert de geselecteerde speld.
|
||||
Iris Blur… Irisvervaging…
|
||||
Tilt-Shift… Tilt-shift…
|
||||
Path Blur… Padvervaging…
|
||||
@@ -2157,6 +2160,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Geen pad om een selectie van te maken: teken er een met het pengereedschap of selecteer er een in het paneel Paden.
|
||||
Cancel opening Openen annuleren
|
||||
Cancelled opening {name} Openen van {name} geannuleerd
|
||||
The document “{name}” does not have an embedded {mode} profile. Het document “{name}” heeft geen ingesloten {mode}-profiel.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Het document “{name}” heeft een ingesloten kleurprofiel dat niet overeenkomt met de huidige {mode}-werkruimte.
|
||||
Embedded: {embedded} Ingesloten: {embedded}
|
||||
Working: {working} Werkruimte: {working}
|
||||
Developing {name} {name} wordt ontwikkeld
|
||||
Cancelled {label} {label} geannuleerd
|
||||
Esc to cancel Esc om te annuleren
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -552,6 +552,9 @@
|
||||
Blur Rozmycie
|
||||
Blur Gallery Galeria rozmyć
|
||||
Field Blur… Rozmycie pola…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Nie zaznaczono pinezki
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Kliknij obraz, aby dodać pinezkę; przeciągnij pinezkę, aby ją przesunąć, lub jej pierścień, aby zmienić rozmycie. Delete usuwa zaznaczoną pinezkę.
|
||||
Iris Blur… Rozmycie irysowe…
|
||||
Tilt-Shift… Tilt-shift…
|
||||
Path Blur… Rozmycie ścieżki…
|
||||
@@ -2176,6 +2179,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Brak ścieżki, z której można utworzyć zaznaczenie: narysuj ją narzędziem Pióro lub wybierz w panelu Ścieżki.
|
||||
Cancel opening Anuluj otwieranie
|
||||
Cancelled opening {name} Anulowano otwieranie {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. Dokument „{name}” nie ma osadzonego profilu {mode}.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}” ma osadzony profil kolorów, który nie pasuje do bieżącej przestrzeni roboczej {mode}.
|
||||
Embedded: {embedded} Osadzony: {embedded}
|
||||
Working: {working} Przestrzeń robocza: {working}
|
||||
Cancelled {label} Anulowano: {label}
|
||||
Esc to cancel Esc, aby anulować
|
||||
Opened {name} Otworzono: {name}
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -537,6 +537,9 @@
|
||||
Blur Desfoque
|
||||
Blur Gallery Galeria de desfoque
|
||||
Field Blur… Desfoque de campo…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Nenhum alfinete selecionado
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Clique na imagem para adicionar um alfinete; arraste um alfinete para movê-lo ou o anel dele para alterar o desfoque. Delete remove o alfinete selecionado.
|
||||
Iris Blur… Desfoque de íris…
|
||||
Tilt-Shift… Tilt-shift…
|
||||
Path Blur… Desfoque de demarcador…
|
||||
@@ -2151,6 +2154,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nenhum demarcador para criar a seleção: desenhe um com a ferramenta Caneta ou selecione um no painel Demarcadores.
|
||||
Cancel opening Cancelar abertura
|
||||
Cancelled opening {name} Abertura de {name} cancelada
|
||||
The document “{name}” does not have an embedded {mode} profile. O documento “{name}” não tem um perfil {mode} incorporado.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. O documento “{name}” tem um perfil de cores incorporado que não corresponde ao espaço de trabalho {mode} atual.
|
||||
Embedded: {embedded} Incorporado: {embedded}
|
||||
Working: {working} Espaço de trabalho: {working}
|
||||
Developing {name} Revelando {name}
|
||||
Cancelled {label} {label} cancelado
|
||||
Esc to cancel Esc para cancelar
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -343,6 +343,9 @@
|
||||
Oil Paint… Масляная живопись…
|
||||
Blur Gallery Галерея размытия
|
||||
Field Blur… Размытие по полю…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Булавка не выбрана
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Щелкните изображение, чтобы добавить булавку; перетащите булавку, чтобы переместить ее, или ее кольцо, чтобы изменить размытие. Delete удаляет выбранную булавку.
|
||||
Iris Blur… Диафрагменное размытие…
|
||||
Tilt-Shift… Наклон-сдвиг…
|
||||
Path Blur… Размытие по контуру…
|
||||
@@ -2471,6 +2474,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Нет контура для создания выделения: нарисуйте его инструментом «Перо» или выберите на панели «Контуры».
|
||||
Cancel opening Отменить открытие
|
||||
Cancelled opening {name} Открытие {name} отменено
|
||||
The document “{name}” does not have an embedded {mode} profile. В документе «{name}» нет встроенного профиля {mode}.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Встроенный цветовой профиль документа «{name}» не совпадает с текущим рабочим пространством {mode}.
|
||||
Embedded: {embedded} Встроенный: {embedded}
|
||||
Working: {working} Рабочее пространство: {working}
|
||||
Developing {name} Обработка {name}
|
||||
Cancelled {label} {label}: отменено
|
||||
Esc to cancel Esc — отмена
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -533,6 +533,8 @@
|
||||
Blur Zamućenje
|
||||
Blur Gallery Galerija zamućenja
|
||||
Field Blur… Zamućenje polja…
|
||||
No pin selected Nijedna čioda nije izabrana
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Kliknite na sliku da dodate čiodu; prevucite čiodu da je pomerite ili njen prsten da promenite zamućenje. Delete uklanja izabranu čiodu.
|
||||
Iris Blur… Iris zamućenje…
|
||||
Tilt-Shift… Tilt-shift…
|
||||
Path Blur… Zamućenje duž putanje…
|
||||
@@ -2135,6 +2137,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Nema putanje od koje bi se napravila selekcija: nacrtajte je alatkom pero ili je izaberite u panelu Putanje.
|
||||
Cancel opening Otkaži otvaranje
|
||||
Cancelled opening {name} Otkazano otvaranje: {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. Dokument „{name}“ nema ugrađeni {mode} profil.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Dokument „{name}“ ima ugrađeni profil boja koji se ne slaže sa trenutnim {mode} radnim prostorom.
|
||||
Embedded: {embedded} Ugrađeni: {embedded}
|
||||
Working: {working} Radni prostor: {working}
|
||||
Developing {name} Razvijanje: {name}
|
||||
Cancelled {label} Otkazano: {label}
|
||||
Esc to cancel Esc za otkazivanje
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -532,6 +532,8 @@
|
||||
Blur Bulanıklaştırma
|
||||
Blur Gallery Bulanıklaştırma Galerisi
|
||||
Field Blur… Alan Bulanıklığı…
|
||||
No pin selected Seçili pim yok
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Pim eklemek için görüntüye tıklayın; taşımak için pimi, bulanıklığını değiştirmek için halkasını sürükleyin. Delete seçili pimi siler.
|
||||
Iris Blur… İris Bulanıklığı…
|
||||
Tilt-Shift… Tilt-Shift…
|
||||
Path Blur… Yol Bulanıklığı…
|
||||
@@ -2132,6 +2134,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Seçim yapılabilecek yol yok: Kalem aracıyla bir yol çizin veya Yollar panelinden birini seçin.
|
||||
Cancel opening Açılışı iptal et
|
||||
Cancelled opening {name} {name} açılışı iptal edildi
|
||||
The document “{name}” does not have an embedded {mode} profile. '{name}' belgesinde gömülü bir {mode} profili yok.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. '{name}' belgesinin gömülü renk profili geçerli {mode} çalışma alanıyla eşleşmiyor.
|
||||
Embedded: {embedded} Gömülü: {embedded}
|
||||
Working: {working} Çalışma alanı: {working}
|
||||
Developing {name} {name} geliştiriliyor
|
||||
Cancelled {label} {label} iptal edildi
|
||||
Esc to cancel İptal etmek için Esc
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -321,6 +321,9 @@
|
||||
Oil Paint… Олійний живопис…
|
||||
Blur Gallery Галерея розмиття
|
||||
Field Blur… Розмиття поля…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Шпильку не вибрано
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Клацніть зображення, щоб додати шпильку; перетягніть шпильку, щоб перемістити її, або її кільце, щоб змінити розмиття. Delete видаляє вибрану шпильку.
|
||||
Iris Blur… Розмиття діафрагми…
|
||||
Tilt-Shift… Нахил і зсув…
|
||||
Path Blur… Розмиття вздовж контуру…
|
||||
@@ -2444,6 +2447,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. Немає контуру для створення виділення: намалюйте його пером або виберіть на панелі контурів.
|
||||
Cancel opening Скасувати відкриття
|
||||
Cancelled opening {name} Відкриття {name} скасовано
|
||||
The document “{name}” does not have an embedded {mode} profile. Документ «{name}» не має вбудованого профілю {mode}.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Вбудований колірний профіль документа «{name}» не відповідає поточному робочому простору {mode}.
|
||||
Embedded: {embedded} Вбудований: {embedded}
|
||||
Working: {working} Робочий простір: {working}
|
||||
Developing {name} Обробка {name}
|
||||
Cancelled {label} Скасовано: {label}
|
||||
Esc to cancel Esc для скасування
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1387 and column 18.
|
@@ -508,6 +508,9 @@
|
||||
Facet Mặt cắt
|
||||
Fibers… Sợi…
|
||||
Field Blur… Làm mờ vùng…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected Chưa chọn ghim nào
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. Bấm vào ảnh để thêm ghim; kéo ghim để di chuyển, hoặc kéo vòng của ghim để đổi độ mờ. Delete xóa ghim đã chọn.
|
||||
Filter Gallery… Thư viện bộ lọc…
|
||||
Find Edges Tìm cạnh
|
||||
Flame… Ngọn lửa…
|
||||
@@ -1562,6 +1565,10 @@ cameraRaw Shadows Vùng tối
|
||||
Esc to cancel Esc để hủy
|
||||
Cancel opening Hủy mở tệp
|
||||
Cancelled opening {name} Đã hủy mở {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. Tài liệu “{name}” không có hồ sơ {mode} nhúng.
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. Tài liệu “{name}” có hồ sơ màu nhúng không khớp với không gian làm việc {mode} hiện tại.
|
||||
Embedded: {embedded} Nhúng: {embedded}
|
||||
Working: {working} Không gian làm việc: {working}
|
||||
Cancelled {label} Đã hủy {label}
|
||||
Cancel transform (Esc) Hủy biến đổi (Esc)
|
||||
Cancel warp (Esc) Hủy biến dạng (Esc)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -558,6 +558,9 @@
|
||||
Blur 模糊
|
||||
Blur Gallery 模糊库
|
||||
Field Blur… 场景模糊…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected 未选择图钉
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 单击图像以添加图钉;拖动图钉可移动它,拖动其圆环可更改模糊程度。按 Delete 键删除所选图钉。
|
||||
Iris Blur… 光圈模糊…
|
||||
Tilt-Shift… 移轴模糊…
|
||||
Path Blur… 路径模糊…
|
||||
@@ -2256,6 +2259,10 @@ cameraRaw Blending 混合
|
||||
# Layer navigation, copy transforms and cancellable opening (labels added on main since this catalog).
|
||||
Cancel opening 取消打开
|
||||
Cancelled opening {name} 已取消打开 {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. 文档“{name}”没有嵌入的 {mode} 配置文件。
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. 文档“{name}”嵌入的颜色配置文件与当前的 {mode} 工作空间不匹配。
|
||||
Embedded: {embedded} 嵌入:{embedded}
|
||||
Working: {working} 工作空间:{working}
|
||||
Developing {name} 正在处理 {name}
|
||||
Cancelled {label} 已取消 {label}
|
||||
Esc to cancel 按 Esc 取消
|
||||
|
||||
|
@@ -563,6 +563,9 @@
|
||||
Blur 模糊
|
||||
Blur Gallery 模糊收藏館
|
||||
Field Blur… 區域模糊…
|
||||
# Field Blur pins (#3373)
|
||||
No pin selected 未選取圖釘
|
||||
Click the image to add a pin; drag a pin to move it, or its ring to change its blur. Delete removes the selected pin. 按一下影像即可新增圖釘;拖移圖釘可移動它,拖移其圓環可變更模糊程度。按 Delete 鍵刪除所選圖釘。
|
||||
Iris Blur… 光圈模糊…
|
||||
Tilt-Shift… 傾斜偏移…
|
||||
Path Blur… 路徑模糊…
|
||||
@@ -2195,6 +2198,10 @@
|
||||
No path to make a selection from: draw one with the Pen tool or select one in the Paths panel. 沒有可用來建立選取範圍的路徑:請使用鋼筆工具繪製,或在路徑面板中選取一個路徑。
|
||||
Cancel opening 取消開啟
|
||||
Cancelled opening {name} 已取消開啟 {name}
|
||||
The document “{name}” does not have an embedded {mode} profile. 文件「{name}」沒有嵌入的 {mode} 描述檔。
|
||||
The document “{name}” has an embedded color profile that does not match the current {mode} working space. 文件「{name}」嵌入的色彩描述檔與目前的 {mode} 工作空間不符。
|
||||
Embedded: {embedded} 嵌入:{embedded}
|
||||
Working: {working} 工作空間:{working}
|
||||
Developing {name} 正在處理 {name}
|
||||
Cancelled {label} 已取消 {label}
|
||||
Esc to cancel 按 Esc 取消
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -527,38 +527,69 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {
|
||||
/// What [`crate::PhotocraftApp::open_bytes`] does after decoding, for a background open's result
|
||||
/// (`{document, warnings, color}`).
|
||||
fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option<usize>) -> Result<(), String> {
|
||||
let warnings: Vec<String> =
|
||||
v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default();
|
||||
let held = |doc, read_only, question, policy_applied| crate::open_prompt::Held {
|
||||
doc,
|
||||
read_only,
|
||||
name: name.to_string(),
|
||||
path: path.map(str::to_string),
|
||||
warnings: warnings.clone(),
|
||||
bytes: None,
|
||||
slot,
|
||||
question,
|
||||
policy_applied,
|
||||
};
|
||||
// Held back for the profile prompt (Ask When Opening).
|
||||
if let Some(id) = v.get("held").and_then(Value::as_u64) {
|
||||
let (doc, read_only) = app.session.take_held_open(id).ok_or("the open job's document is gone")?;
|
||||
crate::open_prompt::arrive(app, held(doc, read_only, v.get("color").cloned(), false));
|
||||
return Ok(());
|
||||
}
|
||||
let mut index = v.get("document").and_then(Value::as_u64).ok_or("the open job returned no document")? as usize;
|
||||
// An earlier file is waiting on its prompt: this one opens after it, in order.
|
||||
if crate::open_prompt::waiting(app)
|
||||
&& let Some(st) = app.session.close(index)
|
||||
{
|
||||
let read_only = st.source_read_only;
|
||||
let doc = Arc::try_unwrap(st.doc).unwrap_or_else(|d| (*d).clone());
|
||||
crate::open_prompt::arrive(app, held(doc, read_only, None, true));
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(slot) = slot
|
||||
&& let Ok(moved) = app.run("document.move", json!({"document": index, "to": slot}))
|
||||
{
|
||||
index = moved.get("document").and_then(Value::as_u64).map_or(index, |i| i as usize);
|
||||
}
|
||||
let warnings: Vec<String> =
|
||||
v.get("warnings").and_then(Value::as_array).map(|a| a.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default();
|
||||
app.session.set_active(index);
|
||||
after_open(app, name, path, &warnings, None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What every open does once its document is the active one: remember where it came from, say
|
||||
/// so, show the import warnings (a raw opens in Camera Raw first, developed from `path` or
|
||||
/// `bytes`) and fire the "Open Document" script events.
|
||||
pub(crate) fn after_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, warnings: &[String], bytes: Option<&[u8]>) {
|
||||
if let Some(p) = path {
|
||||
app.opened_from(p);
|
||||
}
|
||||
app.sync_views();
|
||||
let warnings = crate::file_open::with_missing_fonts(app, warnings);
|
||||
app.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]);
|
||||
// Fonts the document's type uses that aren't installed join the import warnings (#4559).
|
||||
let warnings = crate::file_open::with_missing_fonts(app, warnings.to_vec());
|
||||
let warnings = warnings.as_slice();
|
||||
let opened = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]);
|
||||
app.ui.status = opened.clone();
|
||||
app.ui.status_error = false;
|
||||
// A raw opens in Camera Raw first; the dialog says how it was developed.
|
||||
if crate::camera_raw_ui::wants_open_dialog(app, &warnings) {
|
||||
crate::camera_raw_ui::queue_open_dialog(app, name, path, None);
|
||||
notices::io_warnings(app, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &crate::camera_raw_ui::without_develop_note(&warnings));
|
||||
if crate::camera_raw_ui::wants_open_dialog(app, warnings) {
|
||||
crate::camera_raw_ui::queue_open_dialog(app, name, path, bytes);
|
||||
notices::io_warnings(app, &opened, &crate::camera_raw_ui::without_develop_note(warnings));
|
||||
} else {
|
||||
notices::io_warnings(app, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings);
|
||||
notices::io_warnings(app, &opened, warnings);
|
||||
}
|
||||
// Script events bound to "Open Document".
|
||||
photocraft_engine::automate_cmds::document_opened(&mut app.session);
|
||||
app.sync_views();
|
||||
let color = v.get("color").cloned().unwrap_or(Value::Null);
|
||||
let ask = color.get("ask").and_then(Value::as_bool) == Some(true);
|
||||
if ask && (color.get("mismatch").and_then(Value::as_bool) == Some(true) || color.get("missing").is_some()) {
|
||||
crate::prefs_ui::open_mismatch(app, &color);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------- drawing
|
||||
|
||||
+41
-24
@@ -27,6 +27,7 @@ pub mod artboard_ui;
|
||||
pub(crate) mod background_redraw;
|
||||
mod blend_keys;
|
||||
pub(crate) mod blend_preview;
|
||||
pub mod blur_pins;
|
||||
mod brand;
|
||||
pub(crate) mod brush_cursor;
|
||||
pub mod brush_panel;
|
||||
@@ -140,6 +141,7 @@ pub mod notices;
|
||||
mod numeric_expression;
|
||||
pub mod object_finder;
|
||||
mod opacity_keys;
|
||||
pub mod open_prompt;
|
||||
pub mod outline;
|
||||
pub mod paint_mouse;
|
||||
pub mod palette;
|
||||
@@ -741,6 +743,9 @@ pub struct PhotocraftApp {
|
||||
pub(crate) save_dirs: HashMap<photocraft_doc::DocId, std::path::PathBuf>,
|
||||
/// A save to an RGB Targa parked behind the Targa Options prompt (see `targa_options_ui`).
|
||||
pub(crate) targa_options: Option<targa_options_ui::Prompt>,
|
||||
/// Files read but not opened yet: the first waits on its profile prompt, the rest behind it
|
||||
/// (see `open_prompt`).
|
||||
pub(crate) held_opens: std::collections::VecDeque<open_prompt::Held>,
|
||||
/// Set once the user has agreed to quit, so the resulting close request goes through.
|
||||
pub(crate) allow_close: bool,
|
||||
/// Pen pressure/tilt from the platform (see `stylus`).
|
||||
@@ -876,6 +881,7 @@ impl PhotocraftApp {
|
||||
tiff_options: None,
|
||||
save_dirs: HashMap::new(),
|
||||
targa_options: None,
|
||||
held_opens: Default::default(),
|
||||
allow_close: false,
|
||||
stylus: Default::default(),
|
||||
background_jobs: false,
|
||||
@@ -1215,6 +1221,12 @@ impl PhotocraftApp {
|
||||
/// shown to the user). Files from disk go through [`open_file`](Self::open_file), which also
|
||||
/// remembers the path. Brush and gradient files go to the preset libraries instead.
|
||||
pub fn open_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
|
||||
self.open_bytes_from(name, bytes, None)
|
||||
}
|
||||
|
||||
/// [`Self::open_bytes`] for a file read from `path` (File › Save writes back there; it goes
|
||||
/// to Open Recent), when known.
|
||||
pub(crate) fn open_bytes_from(&mut self, name: &str, bytes: &[u8], path: Option<&str>) -> Result<Vec<String>, String> {
|
||||
if let Some(r) = preset_files_ui::open(self, name, bytes) {
|
||||
return r.map(|()| Vec::new());
|
||||
}
|
||||
@@ -1222,35 +1234,34 @@ impl PhotocraftApp {
|
||||
// Decoded on a worker: a tab with progress appears now, the document when it's ready
|
||||
// (warnings are shown then).
|
||||
if self.background_jobs {
|
||||
jobs_ui::start_open(self, name, None, jobs_ui::bytes(bytes))?;
|
||||
jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?;
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let import = self.services.import.as_ref().ok_or("no importer configured")?;
|
||||
let max_svg_group_depth = self.session.prefs().file_handling.rasterize_svg_groups_deeper_than as usize;
|
||||
let (doc, warnings) = import(name, bytes, max_svg_group_depth)?;
|
||||
// Edit › Color Settings policies apply on open; mismatches can ask what to do.
|
||||
// No path yet: a bare name isn't a location to save back to (`open_file` sets the path).
|
||||
let (_, color) = self.session.open_document(doc, None);
|
||||
if let Some(st) = self.session.active_mut() {
|
||||
st.source_read_only = photocraft_io::affinity::is_affinity(bytes);
|
||||
}
|
||||
self.sync_views();
|
||||
let warnings = file_open::with_missing_fonts(self, warnings);
|
||||
self.ui.status = crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]);
|
||||
self.ui.status_error = false;
|
||||
if camera_raw_ui::wants_open_dialog(self, &warnings) {
|
||||
camera_raw_ui::queue_open_dialog(self, name, None, Some(bytes));
|
||||
notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &camera_raw_ui::without_develop_note(&warnings));
|
||||
} else {
|
||||
notices::io_warnings(self, &crate::i18n::fmt(tl!("Opened {name}"), &[("name", name)]), &warnings);
|
||||
}
|
||||
// Script events bound to "Open Document".
|
||||
photocraft_engine::automate_cmds::document_opened(&mut self.session);
|
||||
self.sync_views();
|
||||
let ask = color.get("ask").and_then(Value::as_bool) == Some(true);
|
||||
if ask && (color.get("mismatch").and_then(Value::as_bool) == Some(true) || color.get("missing").is_some()) {
|
||||
prefs_ui::open_mismatch(self, &color);
|
||||
}
|
||||
// Edit › Color Settings policies apply on open; Ask When Opening holds the file back
|
||||
// until its prompt is answered, and later files wait behind it (`open_prompt`).
|
||||
// Missing fonts are read from the document itself: it may not be open yet (#4559).
|
||||
let warnings = file_open::with_missing_fonts_of(&doc, warnings);
|
||||
// A developed raw has no embedded profile to ask about.
|
||||
let developed = warnings.iter().any(|w| w.contains(photocraft_io::raw::DEVELOPED_NOTE));
|
||||
let question = self.session.color.open_question(&doc).filter(|_| !developed);
|
||||
let wants_raw = camera_raw_ui::wants_open_dialog(self, &warnings);
|
||||
open_prompt::arrive(
|
||||
self,
|
||||
open_prompt::Held {
|
||||
doc,
|
||||
read_only: photocraft_io::affinity::is_affinity(bytes),
|
||||
name: name.to_string(),
|
||||
path: path.map(str::to_string),
|
||||
warnings: warnings.clone(),
|
||||
bytes: (wants_raw && path.is_none()).then(|| std::sync::Arc::new(bytes.to_vec())),
|
||||
slot: None,
|
||||
question,
|
||||
policy_applied: false,
|
||||
},
|
||||
);
|
||||
Ok(warnings)
|
||||
}
|
||||
|
||||
@@ -2459,6 +2470,9 @@ mod navigator_gpu_tests;
|
||||
#[cfg(test)]
|
||||
mod color_swatch_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod profile_open_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod profile_prompt_tests;
|
||||
|
||||
@@ -2507,6 +2521,9 @@ mod new_layer_button_tests;
|
||||
#[cfg(test)]
|
||||
mod smart_filter_rows_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod blur_pins_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod move_outline_tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Ask When Opening (Edit › Color Settings): a file whose embedded profile doesn't match the
|
||||
//! working space (or that has none) is held back while a prompt asks what to do, as Photoshop
|
||||
//! does: one prompt at a time, naming its file, before that file opens. OK applies the answer to
|
||||
//! that file and opens it, then asks about the next; Cancel opens neither it nor the files still
|
||||
//! to come. Files that finish reading while a prompt is up wait their turn, so they open in order.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_doc::{ColorMode, Document};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
|
||||
/// The field that marks a prompt as this module's.
|
||||
const FIELD: &str = "__heldOpen";
|
||||
|
||||
/// A file read and decoded, waiting to open.
|
||||
pub struct Held {
|
||||
pub doc: Document,
|
||||
/// The source is read-only (an Affinity file): Save doesn't write back to it.
|
||||
pub read_only: bool,
|
||||
pub name: String,
|
||||
pub path: Option<String>,
|
||||
pub warnings: Vec<String>,
|
||||
/// The file's bytes, for Camera Raw to develop from when there is no path.
|
||||
pub bytes: Option<Arc<Vec<u8>>>,
|
||||
/// The tab position a reopened file keeps.
|
||||
pub slot: Option<usize>,
|
||||
/// The profile question ([`photocraft_engine::color_cmds::ColorState::open_question`]), or
|
||||
/// `None` to open without asking.
|
||||
pub question: Option<Value>,
|
||||
/// The Color Settings policy was already applied (a background open added it before it had
|
||||
/// to wait); otherwise opening applies it.
|
||||
pub policy_applied: bool,
|
||||
}
|
||||
|
||||
/// Whether a file that just finished reading has to wait: one earlier in the queue does.
|
||||
pub fn waiting(app: &PhotocraftApp) -> bool {
|
||||
!app.held_opens.is_empty()
|
||||
}
|
||||
|
||||
/// Opens `held` now, or queues it behind the file whose prompt is up.
|
||||
pub fn arrive(app: &mut PhotocraftApp, held: Held) {
|
||||
app.held_opens.push_back(held);
|
||||
advance(app);
|
||||
}
|
||||
|
||||
/// Opens queued files in order until one needs its prompt, which is shown if it isn't yet.
|
||||
fn advance(app: &mut PhotocraftApp) {
|
||||
while let Some(front) = app.held_opens.front() {
|
||||
if front.question.is_some() {
|
||||
if !app.ui.dialogs.iter().any(|d| d.fields.contains_key(FIELD)) {
|
||||
show(app);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some(held) = app.held_opens.pop_front() {
|
||||
// A failure is shown to the user (`open_failed`); the next file still opens.
|
||||
let _ = open(app, held, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the Embedded Profile Mismatch (or missing profile) prompt for the first queued file.
|
||||
fn show(app: &mut PhotocraftApp) {
|
||||
let Some(front) = app.held_opens.front() else { return };
|
||||
let Some(q) = &front.question else { return };
|
||||
// The mode reads as the catalogs name it (French "RVB"); the file name goes in last, so
|
||||
// nothing in it is taken for a placeholder.
|
||||
let mode = tl!(match front.doc.mode {
|
||||
ColorMode::Cmyk => "CMYK",
|
||||
ColorMode::Grayscale => "Gray",
|
||||
_ => "RGB",
|
||||
});
|
||||
let name = front.name.as_str();
|
||||
let working = crate::i18n::fmt(tl!("Working: {working}"), &[("working", q.get("working").and_then(Value::as_str).unwrap_or("?"))]);
|
||||
let missing = q.get("missing").and_then(Value::as_bool) == Some(true);
|
||||
let message = if missing {
|
||||
let what = crate::i18n::fmt(tl!("The document “{name}” does not have an embedded {mode} profile."), &[("mode", mode), ("name", name)]);
|
||||
format!("{what}\n{working}")
|
||||
} else {
|
||||
let what = crate::i18n::fmt(
|
||||
tl!("The document “{name}” has an embedded color profile that does not match the current {mode} working space."),
|
||||
&[("mode", mode), ("name", name)],
|
||||
);
|
||||
let embedded = crate::i18n::fmt(tl!("Embedded: {embedded}"), &[("embedded", q.get("embedded").and_then(Value::as_str).unwrap_or("?"))]);
|
||||
format!("{what}\n{embedded}\n{working}")
|
||||
};
|
||||
let action = q.get("action").and_then(Value::as_str).unwrap_or("preserve").to_string();
|
||||
crate::prefs_ui::open_mismatch(app, &message, &action, missing, FIELD);
|
||||
}
|
||||
|
||||
/// Whether `fields` are one of this module's prompts.
|
||||
pub fn owns(fields: &serde_json::Map<String, Value>) -> bool {
|
||||
fields.contains_key(FIELD)
|
||||
}
|
||||
|
||||
/// The prompt's answer: `Some(action)` (OK) opens the first queued file with it and moves on to
|
||||
/// the next; `None` (Cancel) drops every queued file and stops the reads still running.
|
||||
pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result<Value, String> {
|
||||
let Some(action) = action else {
|
||||
let dropped = app.held_opens.len();
|
||||
let name = app.held_opens.front().map(|h| h.name.clone()).unwrap_or_default();
|
||||
app.held_opens.clear();
|
||||
for job in app.jobs.opens.iter().map(|o| o.job).collect::<Vec<_>>() {
|
||||
app.session.cancel_job(job);
|
||||
}
|
||||
app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]);
|
||||
app.ui.status_error = false;
|
||||
return Ok(json!({"cancelled": dropped}));
|
||||
};
|
||||
let Some(held) = app.held_opens.pop_front() else { return Err("no file is waiting to open".into()) };
|
||||
let r = open(app, held, Some(action));
|
||||
advance(app);
|
||||
r
|
||||
}
|
||||
|
||||
/// Opens a queued file, applying `action` (the prompt's answer) or else the Color Settings
|
||||
/// policy, then does what any open does afterwards.
|
||||
fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result<Value, String> {
|
||||
let Held { mut doc, read_only, name, path, warnings, bytes, slot, question, policy_applied } = held;
|
||||
let index = if question.is_some() || policy_applied {
|
||||
if let Some(action) = action
|
||||
&& let Err(e) = app.session.color.resolve_open(&mut doc, action)
|
||||
{
|
||||
app.open_failed(&name, &e.to_string());
|
||||
return Err(e.to_string());
|
||||
}
|
||||
app.session.add_document(doc, None)
|
||||
} else {
|
||||
app.session.open_document(doc, None).0
|
||||
};
|
||||
if let Some(st) = app.session.active_mut() {
|
||||
st.source_read_only = read_only;
|
||||
}
|
||||
let index = match slot {
|
||||
Some(slot) => app
|
||||
.run("document.move", json!({"document": index, "to": slot}))
|
||||
.ok()
|
||||
.and_then(|m| m.get("document").and_then(Value::as_u64))
|
||||
.map_or(index, |i| i as usize),
|
||||
None => index,
|
||||
};
|
||||
app.session.set_active(index);
|
||||
crate::jobs_ui::after_open(app, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice));
|
||||
Ok(json!({"document": index, "action": action}))
|
||||
}
|
||||
@@ -1784,7 +1784,7 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
empty(ui, tl!("No document"));
|
||||
return;
|
||||
};
|
||||
let (rev, size) = (st.revision, st.doc.size);
|
||||
let (rev, size, origin) = (st.revision, st.doc.size, st.doc.ruler_origin);
|
||||
// Positions and sizes in the ruler unit (Preferences › Units & Rulers).
|
||||
let units = app.session.prefs().units_and_rulers.clone();
|
||||
let dpi = st.doc.resolution_dpi as f64;
|
||||
@@ -1833,8 +1833,9 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
widgets::hairline(ui);
|
||||
ui.columns(2, |cols| {
|
||||
let dash = || "—".to_string();
|
||||
row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64)));
|
||||
row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64)));
|
||||
// Measured from the rulers' zero point (#2955).
|
||||
row(&mut cols[0], "X:", pos.map_or_else(dash, |p| fx(p.0 as f64 - origin[0])));
|
||||
row(&mut cols[0], "Y:", pos.map_or_else(dash, |p| fy(p.1 as f64 - origin[1])));
|
||||
row(&mut cols[1], "W:", sel.map_or_else(dash, |r| fx(r.width() as f64)));
|
||||
row(&mut cols[1], "H:", sel.map_or_else(dash, |r| fy(r.height() as f64)));
|
||||
});
|
||||
|
||||
@@ -994,26 +994,13 @@ pub fn open_shortcuts(app: &mut PhotocraftApp, tab: u64) -> u64 {
|
||||
open_kind(app, "shortcuts", tl!("Keyboard Shortcuts and Menus"), fields)
|
||||
}
|
||||
|
||||
/// Open the Embedded Profile Mismatch prompt for the active document.
|
||||
pub fn open_mismatch(app: &mut PhotocraftApp, report: &Value) -> u64 {
|
||||
let msg = if report.get("missing").and_then(Value::as_bool) == Some(true) {
|
||||
let template = "The document does not have an embedded colour profile. Working space: {working}.";
|
||||
crate::i18n::fmt(tl!(template), &[("working", report["working"].as_str().unwrap_or("?"))])
|
||||
} else {
|
||||
let template = "The document has an embedded colour profile that does not match the working space.\nEmbedded: {embedded}\nWorking: {working}";
|
||||
crate::i18n::fmt(tl!(template), &[("embedded", report["embedded"].as_str().unwrap_or("?")), ("working", report["working"].as_str().unwrap_or("?"))])
|
||||
};
|
||||
let action = match report["action"].as_str() {
|
||||
Some("converted") => "convert",
|
||||
Some("discarded") => "discard",
|
||||
_ => "preserve",
|
||||
};
|
||||
open_kind(
|
||||
app,
|
||||
"mismatch",
|
||||
tl!("Embedded Profile Mismatch"),
|
||||
json!({"message": msg, "action": action, "applied": action, "missing": report.get("missing").is_some()}),
|
||||
)
|
||||
/// Open the Embedded Profile Mismatch prompt for a file waiting to open (`open_prompt`): its
|
||||
/// `message`, the answer selected first (`action`), and `marker`, the field that routes OK and
|
||||
/// Cancel back to `open_prompt`.
|
||||
pub fn open_mismatch(app: &mut PhotocraftApp, message: &str, action: &str, missing: bool, marker: &str) -> u64 {
|
||||
let mut fields = json!({"message": message, "action": action, "missing": missing});
|
||||
fields[marker] = json!(true);
|
||||
open_kind(app, "mismatch", tl!("Embedded Profile Mismatch"), fields)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ bodies
|
||||
@@ -2011,13 +1998,10 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
|
||||
})
|
||||
}
|
||||
}
|
||||
// The file it asks about opens with this answer (`open_prompt`).
|
||||
"mismatch" => {
|
||||
let action = f.get("action").and_then(Value::as_str).unwrap_or("preserve");
|
||||
let applied = f.get("applied").and_then(Value::as_str).unwrap_or("preserve");
|
||||
if action == applied {
|
||||
return Ok(json!({"action": action}));
|
||||
}
|
||||
app.run("color.profileMismatch", json!({"action": action}))
|
||||
crate::open_prompt::answer(app, Some(action))
|
||||
}
|
||||
_ => Err("unknown dialog".into()),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Files opened together whose embedded profile doesn't match the working space (File › Open with
|
||||
//! several selected, Ask When Opening on). Checked in Photoshop 27.11: one Embedded Profile
|
||||
//! Mismatch prompt at a time, naming its file, before that file opens; OK opens it and asks about
|
||||
//! the next; Cancel opens neither it nor the files still to come.
|
||||
|
||||
use crate::{PhotocraftApp, Services};
|
||||
use egui::{Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{NodeT, Queryable},
|
||||
};
|
||||
use photocraft_doc::{Color, ColorMode, Document, SampleType, Size};
|
||||
use photocraft_engine::Session;
|
||||
use serde_json::Value;
|
||||
|
||||
const USE: &str = "Use the embedded profile (instead of the working space)";
|
||||
const CONVERT: &str = "Convert document's colors to the working space";
|
||||
const DISCARD: &str = "Discard the embedded profile (don't color manage)";
|
||||
|
||||
/// A PNG tagged with Adobe RGB, which doesn't match the sRGB working space.
|
||||
fn adobe_png() -> Vec<u8> {
|
||||
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgba(0.2, 0.6, 0.9, 1.0));
|
||||
d.icc_profile = Some(photocraft_cms::Builtin::from_id("adobe-rgb-compat").unwrap().profile().to_bytes());
|
||||
photocraft_io::export(&d, "t.png", &Default::default()).unwrap().bytes
|
||||
}
|
||||
|
||||
fn harness(background: bool) -> Harness<'static, PhotocraftApp> {
|
||||
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
PhotocraftApp::new(
|
||||
Session::new(),
|
||||
Services {
|
||||
import: Some(Box::new(|name, bytes, depth| {
|
||||
photocraft_io::import_with_svg_group_depth(name, bytes, depth).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
|
||||
})),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
});
|
||||
h.state_mut().background_jobs = background;
|
||||
h.run_steps(3);
|
||||
h.state_mut().run("edit.colorSettings", serde_json::json!({"askOnMismatch": true, "policyRgb": "preserve"})).unwrap();
|
||||
h
|
||||
}
|
||||
|
||||
/// Open a.png, b.png and c.png together and let every read finish.
|
||||
fn open_three(h: &mut Harness<'static, PhotocraftApp>) {
|
||||
let png = adobe_png();
|
||||
for name in ["a.png", "b.png", "c.png"] {
|
||||
h.state_mut().open_file(&format!("/pics/{name}"), &png).unwrap();
|
||||
}
|
||||
settle(h);
|
||||
}
|
||||
|
||||
/// Run frames until no open is still reading.
|
||||
fn settle(h: &mut Harness<'static, PhotocraftApp>) {
|
||||
for _ in 0..200 {
|
||||
h.run_steps(2);
|
||||
if h.state().jobs.opens.is_empty() && h.state().session.jobs().is_empty() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
h.run_steps(6);
|
||||
}
|
||||
|
||||
fn docs(h: &Harness<'static, PhotocraftApp>) -> Vec<String> {
|
||||
h.state().session.documents().iter().map(|d| d.doc.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// The one prompt up: its message.
|
||||
fn prompt(h: &Harness<'static, PhotocraftApp>) -> String {
|
||||
let d = &h.state().ui.dialogs;
|
||||
assert_eq!(d.len(), 1, "one prompt at a time");
|
||||
d[0].fields.get("message").and_then(Value::as_str).unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// A real click (pointer events, hit-tested like a mouse).
|
||||
fn click(h: &mut Harness<'static, PhotocraftApp>, label: &str) {
|
||||
let at: Pos2 = h.query_all_by_label(label).find(|n| !n.accesskit_node().is_disabled()).map(|n| n.rect().center()).unwrap();
|
||||
h.event(egui::Event::PointerMoved(at));
|
||||
h.run_steps(1);
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
}
|
||||
settle(h);
|
||||
}
|
||||
|
||||
fn answer(h: &mut Harness<'static, PhotocraftApp>, choice: &str) {
|
||||
click(h, choice);
|
||||
click(h, "OK");
|
||||
}
|
||||
|
||||
fn profile(h: &Harness<'static, PhotocraftApp>, name: &str) -> Option<String> {
|
||||
let st = h.state().session.documents().iter().find(|d| d.doc.name == name).unwrap();
|
||||
st.doc.icc_profile.as_ref().map(|b| photocraft_engine::color_cmds::profile_from_bytes(b).unwrap().description.clone())
|
||||
}
|
||||
|
||||
/// The file the prompt on screen asks about.
|
||||
fn asked(h: &Harness<'static, PhotocraftApp>) -> &'static str {
|
||||
let msg = prompt(h);
|
||||
["a.png", "b.png", "c.png", "d.png"]
|
||||
.into_iter()
|
||||
.find(|n| msg.starts_with(&format!("The document “{n}” has an embedded color profile that does not match the current RGB working space.")))
|
||||
.unwrap_or_else(|| panic!("the prompt names its file: {msg}"))
|
||||
}
|
||||
|
||||
/// Files read on the spot ask in the order they were given. Read in the background, they ask in
|
||||
/// the order their reads finish, which is the same order unless a later read overtakes an earlier
|
||||
/// one: the tests hold either way.
|
||||
fn in_order(background: bool, order: &[&str]) {
|
||||
if !background {
|
||||
assert_eq!(order, &["a.png", "b.png", "c.png"][..order.len()]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_opened_together_ask_one_at_a_time_before_each_opens() {
|
||||
for background in [false, true] {
|
||||
let mut h = harness(background);
|
||||
open_three(&mut h);
|
||||
let mut answered: Vec<&str> = Vec::new();
|
||||
for _ in 0..3 {
|
||||
assert_eq!(docs(&h), answered, "background {background}: a file opens only after its prompt");
|
||||
let name = asked(&h);
|
||||
assert!(!answered.contains(&name), "background {background}: {name} asked twice");
|
||||
answer(&mut h, USE);
|
||||
answered.push(name);
|
||||
}
|
||||
in_order(background, &answered);
|
||||
assert!(h.state().ui.dialogs.is_empty());
|
||||
assert_eq!(docs(&h), answered, "background {background}: each opened when it was answered");
|
||||
assert_eq!(h.state().session.active().map(|d| d.doc.name.as_str()), answered.last().copied());
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt reads in the interface language: its sentence, the Embedded and Working lines and
|
||||
/// the mode's name (French "RVB"). The file's name goes in as it is, braces and all.
|
||||
#[test]
|
||||
fn the_prompt_is_translated_and_still_names_its_file() {
|
||||
let png = adobe_png();
|
||||
for (code, sentence, embedded, working) in [
|
||||
(
|
||||
"en",
|
||||
"The document “shot {mode}.png” has an embedded color profile that does not match the current RGB working space.",
|
||||
"Embedded: Adobe RGB",
|
||||
"Working: sRGB",
|
||||
),
|
||||
(
|
||||
"de",
|
||||
"Das Dokument „shot {mode}.png“ hat ein eingebettetes Farbprofil, das nicht zum aktuellen RGB-Arbeitsfarbraum passt.",
|
||||
"Eingebettet: Adobe RGB",
|
||||
"Arbeitsfarbraum: sRGB",
|
||||
),
|
||||
(
|
||||
"fr",
|
||||
"Le document «NBSPshot {mode}.pngNBSP» a un profil colorimétrique incorporé qui ne correspond pas à l'espace de travail RVB actuel.",
|
||||
"IncorporéNBSP: Adobe RGB",
|
||||
"Espace de travailNBSP: sRGB",
|
||||
),
|
||||
(
|
||||
"ja",
|
||||
"ドキュメント「shot {mode}.png」の埋め込みカラープロファイルは、現在の RGB 作業用スペースと一致しません。",
|
||||
"埋め込み: Adobe RGB",
|
||||
"作業用スペース: sRGB",
|
||||
),
|
||||
] {
|
||||
let services = Services {
|
||||
import: Some(Box::new(|name, bytes, depth| {
|
||||
photocraft_io::import_with_svg_group_depth(name, bytes, depth).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
app.run("edit.colorSettings", serde_json::json!({"askOnMismatch": true, "policyRgb": "preserve"})).unwrap();
|
||||
let lang = crate::i18n::Lang::from_code(code).unwrap();
|
||||
crate::i18n::with_language(lang, || app.open_file("/pics/shot {mode}.png", &png)).unwrap();
|
||||
assert!(app.session.documents().is_empty(), "{code}: held until answered");
|
||||
let message = app.ui.dialogs[0].fields.get("message").and_then(Value::as_str).unwrap().to_string();
|
||||
let lines: Vec<&str> = message.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "{code}: {message}");
|
||||
assert_eq!(lines[0], sentence.replace("NBSP", "\u{a0}"), "{code}");
|
||||
assert!(lines[1].starts_with(&embedded.replace("NBSP", "\u{a0}")), "{code}: {}", lines[1]);
|
||||
assert!(lines[2].starts_with(&working.replace("NBSP", "\u{a0}")), "{code}: {}", lines[2]);
|
||||
}
|
||||
}
|
||||
|
||||
/// #4559 with a held file: type in a font that isn't installed is reported with the import
|
||||
/// warnings while the file still waits for its profile prompt, and shown once when it opens.
|
||||
#[test]
|
||||
fn a_held_file_still_reports_its_missing_fonts() {
|
||||
const MISSING: &str = "NoSuchFamily3471";
|
||||
let warning = format!("font '{MISSING}' is not installed; text may render using a fallback face");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", serde_json::json!({"width": 40, "height": 20})).unwrap();
|
||||
s.execute("type.create", serde_json::json!({"text": "Hi", "x": 2, "y": 12, "size": 10, "font": MISSING})).unwrap();
|
||||
let mut doc = (*s.active().unwrap().doc).clone();
|
||||
doc.icc_profile = Some(photocraft_cms::Builtin::from_id("adobe-rgb-compat").unwrap().profile().to_bytes());
|
||||
let services = Services { import: Some(Box::new(move |_: &str, _: &[u8], _: usize| Ok((doc.clone(), Vec::new())))), ..Default::default() };
|
||||
let mut app = PhotocraftApp::new(Session::new(), services);
|
||||
app.run("edit.colorSettings", serde_json::json!({"askOnMismatch": true, "policyRgb": "preserve"})).unwrap();
|
||||
assert_eq!(app.open_bytes("poster.psd", b"x").unwrap(), vec![warning.clone()]);
|
||||
assert!(app.session.documents().is_empty() && app.ui.notices.is_empty(), "held: nothing shown yet");
|
||||
crate::open_prompt::answer(&mut app, Some("preserve")).unwrap();
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
assert_eq!(app.ui.notices.len(), 1);
|
||||
assert_eq!(app.ui.notices[0].lines, vec![warning]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_answer_applies_to_its_own_file() {
|
||||
for background in [false, true] {
|
||||
let mut h = harness(background);
|
||||
open_three(&mut h);
|
||||
// Whichever file a prompt names gets that file's own answer.
|
||||
let mut answered: Vec<&str> = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let name = asked(&h);
|
||||
answer(
|
||||
&mut h,
|
||||
match name {
|
||||
"a.png" => CONVERT,
|
||||
"b.png" => DISCARD,
|
||||
_ => USE,
|
||||
},
|
||||
);
|
||||
answered.push(name);
|
||||
}
|
||||
in_order(background, &answered);
|
||||
assert_eq!(docs(&h), answered);
|
||||
assert_eq!(profile(&h, "a.png").as_deref(), Some("sRGB IEC61966-2.1"), "background {background}: a converted");
|
||||
assert_eq!(profile(&h, "b.png"), None, "background {background}: b discarded");
|
||||
assert!(profile(&h, "c.png").unwrap().starts_with("Adobe RGB"), "background {background}: c kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_opens_neither_the_file_nor_the_ones_still_to_come() {
|
||||
for background in [false, true] {
|
||||
let mut h = harness(background);
|
||||
open_three(&mut h);
|
||||
let first = asked(&h);
|
||||
in_order(background, &[first]);
|
||||
answer(&mut h, USE);
|
||||
click(&mut h, "Cancel");
|
||||
settle(&mut h);
|
||||
assert!(h.state().ui.dialogs.is_empty(), "background {background}: no prompt left");
|
||||
assert_eq!(docs(&h), [first], "background {background}");
|
||||
// A later open asks again.
|
||||
h.state_mut().open_file("/pics/d.png", &adobe_png()).unwrap();
|
||||
settle(&mut h);
|
||||
assert_eq!(asked(&h), "d.png");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Embedded Profile Mismatch prompts when several files open at once (File › Open with several
|
||||
//! selected): every prompt can be answered with a real click, one after another, even when the
|
||||
//! user clicks while the next file's prompt is appearing.
|
||||
//! Stacked dialogs of the same size in the same place (Embedded Profile Mismatch prompts used to
|
||||
//! stack like this when several files opened at once): each can be answered with a real click,
|
||||
//! one after another, even when an older one has been raised above the live one.
|
||||
|
||||
use crate::{PhotocraftApp, Services};
|
||||
use egui::{Modifiers, PointerButton, Pos2, vec2};
|
||||
@@ -8,16 +8,8 @@ use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{NodeT, Queryable},
|
||||
};
|
||||
use photocraft_doc::{Color, ColorMode, Document, SampleType, Size};
|
||||
use photocraft_engine::Session;
|
||||
|
||||
/// A PNG tagged with Adobe RGB, which doesn't match the sRGB working space.
|
||||
fn adobe_png() -> Vec<u8> {
|
||||
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::rgba(0.2, 0.6, 0.9, 1.0));
|
||||
d.icc_profile = Some(photocraft_cms::Builtin::from_id("adobe-rgb-compat").unwrap().profile().to_bytes());
|
||||
photocraft_io::export(&d, "t.png", &Default::default()).unwrap().bytes
|
||||
}
|
||||
|
||||
fn harness(background: bool) -> Harness<'static, PhotocraftApp> {
|
||||
let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
@@ -36,11 +28,13 @@ fn harness(background: bool) -> Harness<'static, PhotocraftApp> {
|
||||
h
|
||||
}
|
||||
|
||||
/// Open `n` mismatched files in one go and wait until their prompts are up and laid out.
|
||||
/// Stack `n` identical Embedded Profile Mismatch dialogs (same size, same place; only the newest
|
||||
/// is live) and wait until they are up and laid out. Opening files no longer stacks them (they ask
|
||||
/// one at a time, `profile_open_tests`), so they are opened directly.
|
||||
fn open_together(h: &mut Harness<'static, PhotocraftApp>, n: usize) {
|
||||
let png = adobe_png();
|
||||
for i in 0..n {
|
||||
h.state_mut().open_file(&format!("shot{i}.png"), &png).unwrap();
|
||||
let message = "The document “shot.png” has an embedded color profile that does not match the current RGB working space.";
|
||||
for _ in 0..n {
|
||||
crate::prefs_ui::open_mismatch(h.state_mut(), message, "preserve", false, "__stacked");
|
||||
}
|
||||
for _ in 0..100 {
|
||||
h.run_steps(2);
|
||||
|
||||
@@ -322,10 +322,7 @@ mod tests {
|
||||
let ctx = egui::Context::default();
|
||||
let mut enabled = None;
|
||||
let mut disabled = None;
|
||||
let raw = egui::RawInput {
|
||||
events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)],
|
||||
..Default::default()
|
||||
};
|
||||
let raw = egui::RawInput { events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)], ..Default::default() };
|
||||
let mut output = ctx.run_ui(raw, |ui| {
|
||||
enabled = trackpad_delta(ui.ctx(), true);
|
||||
disabled = trackpad_delta(ui.ctx(), false);
|
||||
|
||||
+263
-33
@@ -237,34 +237,59 @@ pub fn finish_drag(app: &mut PhotocraftApp, d: GuideDrag) {
|
||||
/// the document origin as the rotated view draws it, as in Photoshop. Tilted guides then meet the
|
||||
/// rulers near their numbers. Measuring along the rotated axes instead squeezed the ticks into a
|
||||
/// few pixels (or none at 90°) and left the rest of the ruler empty (#3233).
|
||||
fn ruler_xform(xf: &ViewXform) -> ViewXform {
|
||||
///
|
||||
/// The returned mapping measures from the rulers' zero point `zero` (document px, #2955): its
|
||||
/// document coordinates are distances from `zero`, and 0 sits where the canvas draws `zero`.
|
||||
fn ruler_xform(xf: &ViewXform, zero: [f64; 2]) -> ViewXform {
|
||||
let level = ViewXform { rotation: 0.0, ..*xf };
|
||||
// The level view is an axis-aligned scale, so moving the origin by `shift` on screen moves
|
||||
// every point by it: re-centre on the document point that sat `shift` before the centre.
|
||||
let shift = xf.to_screen(0.0, 0.0) - level.to_screen(0.0, 0.0);
|
||||
let (zx, zy) = (zero[0] as f32, zero[1] as f32);
|
||||
// The level view is an axis-aligned scale, so moving the zero point by `shift` on screen moves
|
||||
// every point by it: re-centre on the document point that sat `shift` before the centre, then
|
||||
// count from the zero point.
|
||||
let shift = xf.to_screen(zx, zy) - level.to_screen(zx, zy);
|
||||
let center = level.to_doc(xf.rect.center() - shift);
|
||||
let center = [center[0] as f32 - zx, center[1] as f32 - zy];
|
||||
if !(center[0].is_finite() && center[1].is_finite()) {
|
||||
return level;
|
||||
}
|
||||
ViewXform { center: [center[0] as f32, center[1] as f32], ..level }
|
||||
ViewXform { center, ..level }
|
||||
}
|
||||
|
||||
/// Visible ruler range in ruler units, normalised to `(min, max)` so the tick loop runs for
|
||||
/// flipped views too (#1814). `xf` is the canvas mapping; rotation is ignored (see
|
||||
/// [`ruler_xform`]). Shared by the renderer and its tests.
|
||||
fn ruler_range(xf: &ViewXform, a: Pos2, b: Pos2, axis: usize, px_per_unit: f64) -> (f64, f64) {
|
||||
let rxf = ruler_xform(xf);
|
||||
/// flipped views too (#1814), measured from the zero point `zero`. `xf` is the canvas mapping;
|
||||
/// rotation is ignored (see [`ruler_xform`]). Shared by the renderer and its tests.
|
||||
fn ruler_range(xf: &ViewXform, a: Pos2, b: Pos2, axis: usize, px_per_unit: f64, zero: [f64; 2]) -> (f64, f64) {
|
||||
let rxf = ruler_xform(xf, zero);
|
||||
let d0 = rxf.to_doc(a)[axis];
|
||||
let d1 = rxf.to_doc(b)[axis];
|
||||
let (u0, u1) = (d0 / px_per_unit, d1 / px_per_unit);
|
||||
(u0.min(u1), u0.max(u1))
|
||||
}
|
||||
|
||||
/// Snap a document position to the nearest ruler tick, measured from the zero point `origin`
|
||||
/// (`tick` px apart). Shift-dragging the zero point lands it on a tick, as in Photoshop.
|
||||
fn snap_px_to_tick(px: f64, origin: f64, tick: f64) -> f64 {
|
||||
if !(tick.is_finite() && tick > 0.0) {
|
||||
return px;
|
||||
}
|
||||
origin + ((px - origin) / tick).round() * tick
|
||||
}
|
||||
|
||||
/// Where a zero-point drag from the ruler corner lands for the pointer at document `d`: on the
|
||||
/// nearest ruler tick (`ticks`, px per axis) with Shift, else View › Snap To targets.
|
||||
fn origin_drop(app: &mut PhotocraftApp, d: [f64; 2], shift: bool, origin: [f64; 2], ticks: [f64; 2]) -> [f64; 2] {
|
||||
if shift {
|
||||
[snap_px_to_tick(d[0], origin[0], ticks[0]), snap_px_to_tick(d[1], origin[1], ticks[1])]
|
||||
} else {
|
||||
[crate::snap_ui::snap_guide(app, true, d[0]), crate::snap_ui::snap_guide(app, false, d[1])]
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen coordinate along the ruler (x for the top ruler, y for the left one) of the value `u`
|
||||
/// in ruler units. The inverse of [`ruler_range`]'s mapping.
|
||||
fn ruler_pos(xf: &ViewXform, vertical: bool, u: f64, px_per_unit: f64) -> f32 {
|
||||
/// in ruler units from the zero point `zero`. The inverse of [`ruler_range`]'s mapping.
|
||||
fn ruler_pos(xf: &ViewXform, vertical: bool, u: f64, px_per_unit: f64, zero: [f64; 2]) -> f32 {
|
||||
let px = (u * px_per_unit) as f32;
|
||||
let rxf = ruler_xform(xf);
|
||||
let rxf = ruler_xform(xf, zero);
|
||||
if vertical { rxf.to_screen(0.0, px).y } else { rxf.to_screen(px, 0.0).x }
|
||||
}
|
||||
|
||||
@@ -282,13 +307,14 @@ fn ruler_scale(app: &PhotocraftApp, xf: &ViewXform, y_axis: bool) -> (f64, f64)
|
||||
(px_per_unit, nice_step(60.0 / (zoom as f64 * px_per_unit).max(1e-6), unit == Unit::Pixels))
|
||||
}
|
||||
|
||||
/// `pos` (document px) moved to the nearest tick mark the ruler draws: where a guide lands when
|
||||
/// `pos` (document px) moved to the nearest tick mark the ruler draws (counted from the zero point): where a guide lands when
|
||||
/// Shift is held while dragging it out of a ruler, as in Photoshop (#3770).
|
||||
fn snap_to_tick(app: &PhotocraftApp, xf: &ViewXform, vertical: bool, pos: f64) -> f64 {
|
||||
// A vertical guide sits at an x position, which the top ruler measures.
|
||||
let (px_per_unit, step) = ruler_scale(app, xf, !vertical);
|
||||
let tick = step / 10.0 * px_per_unit;
|
||||
if tick.is_finite() && tick > 0.0 { (pos / tick).round() * tick } else { pos }
|
||||
// Ticks count from the zero point (#2955), which a vertical guide measures along x.
|
||||
let origin = app.session.active().map_or(0.0, |d| d.doc.ruler_origin[usize::from(!vertical)]);
|
||||
snap_px_to_tick(pos, origin, step / 10.0 * px_per_unit)
|
||||
}
|
||||
|
||||
/// The number a ruler prints at the tick `v` (in ruler units). Like Photoshop, rulers show the
|
||||
@@ -317,17 +343,21 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
|
||||
// Preferences › Units & Rulers: labels in the ruler unit (percent of the document's side).
|
||||
let unit = app.session.prefs().units_and_rulers.rulers;
|
||||
let whole = unit == Unit::Pixels;
|
||||
// The zero point (#2955): rulers read 0 there and count the distance from it.
|
||||
let origin = app.session.active().map_or([0.0, 0.0], |d| d.doc.ruler_origin);
|
||||
let mut ticks = [1.0; 2];
|
||||
for vertical in [false, true] {
|
||||
let p = p.with_clip_rect(if vertical { left } else { top });
|
||||
let (px_per_unit, step) = ruler_scale(app, xf, vertical);
|
||||
ticks[usize::from(vertical)] = step * px_per_unit / 10.0;
|
||||
let (u0, u1) = if vertical {
|
||||
ruler_range(xf, left.left_top(), left.left_bottom(), 1, px_per_unit)
|
||||
ruler_range(xf, left.left_top(), left.left_bottom(), 1, px_per_unit, origin)
|
||||
} else {
|
||||
ruler_range(xf, top.left_top(), top.right_top(), 0, px_per_unit)
|
||||
ruler_range(xf, top.left_top(), top.right_top(), 0, px_per_unit, origin)
|
||||
};
|
||||
let mut v = (u0 / step).floor() * step;
|
||||
while v <= u1 {
|
||||
let at = |u: f64| -> f32 { ruler_pos(xf, vertical, u, px_per_unit) };
|
||||
let at = |u: f64| -> f32 { ruler_pos(xf, vertical, u, px_per_unit, origin) };
|
||||
let c = at(v);
|
||||
if vertical {
|
||||
p.line_segment([pos2(left.right() - RULER, c), pos2(left.right(), c)], tick);
|
||||
@@ -360,14 +390,15 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
|
||||
// Drag a new guide out of a ruler; right-click to switch the ruler unit.
|
||||
let mut chosen_unit: Option<&'static str> = None;
|
||||
for (r, vertical, salt) in [(top, false, "ruler-top"), (left, true, "ruler-left"), (corner, false, "ruler-corner")] {
|
||||
// Guides drag out of the top/left rulers; all three sense clicks so the right-click unit
|
||||
// menu opens anywhere on the ruler (the corner only needs the menu).
|
||||
let sense = if salt == "ruler-corner" { Sense::click() } else { Sense::click_and_drag() };
|
||||
let resp = ui.interact(r, ui.id().with(salt), sense);
|
||||
if resp.hovered() && salt != "ruler-corner" {
|
||||
// Guides drag out of the top/left rulers and the zero point out of the corner; all three
|
||||
// sense clicks so the right-click unit menu opens anywhere on the ruler.
|
||||
let resp = ui.interact(r, ui.id().with(salt), Sense::click_and_drag());
|
||||
if salt == "ruler-corner" {
|
||||
corner_origin(app, ui, &resp, &p, xf, origin, ticks);
|
||||
} else if resp.hovered() {
|
||||
ui.ctx().set_cursor_icon(if vertical { egui::CursorIcon::ResizeHorizontal } else { egui::CursorIcon::ResizeVertical });
|
||||
}
|
||||
if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.drag_started()) {
|
||||
if let Some(pos) = resp.interact_pointer_pos().filter(|_| salt != "ruler-corner" && (resp.dragged() || resp.drag_started())) {
|
||||
let d = xf.to_doc(pos);
|
||||
let along = if vertical { d[0] } else { d[1] };
|
||||
let pos = if ui.input(|i| i.modifiers.shift) { snap_to_tick(app, xf, vertical, along) } else { crate::snap_ui::snap_guide(app, vertical, along) };
|
||||
@@ -390,6 +421,41 @@ pub fn draw_rulers(app: &mut PhotocraftApp, ui: &mut egui::Ui, full: Rect, xf: &
|
||||
let _ = Pos2::ZERO;
|
||||
}
|
||||
|
||||
/// The ruler corner: drag the zero point out of it (cross hairs mark where it lands; Shift snaps
|
||||
/// to the ruler ticks), double-click it to put the zero point back at the image's top-left.
|
||||
fn corner_origin(app: &mut PhotocraftApp, ui: &egui::Ui, resp: &egui::Response, p: &egui::Painter, xf: &ViewXform, origin: [f64; 2], ticks: [f64; 2]) {
|
||||
let id = resp.id.with("origin-drag");
|
||||
if resp.hovered() || resp.dragged() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
let _ = app.run("view.resetRulerOrigin", json!({}));
|
||||
return;
|
||||
}
|
||||
// Dropped back on the corner (or a slow click), the zero point stays where it was.
|
||||
if let Some(pos) = resp.interact_pointer_pos().filter(|_| resp.dragged() || resp.drag_started()) {
|
||||
if resp.rect.contains(pos) {
|
||||
ui.data_mut(|d| d.remove_temp::<[f64; 2]>(id));
|
||||
return;
|
||||
}
|
||||
let shift = ui.input(|i| i.modifiers.shift);
|
||||
let at = origin_drop(app, xf.to_doc(pos), shift, origin, ticks);
|
||||
ui.data_mut(|d| d.insert_temp(id, at));
|
||||
// Cross hairs along the document axes through the new zero point, drawn like guides so
|
||||
// they turn with a rotated view.
|
||||
let t = Tokens::get(ui.ctx());
|
||||
for (vertical, pos) in [(true, at[0]), (false, at[1])] {
|
||||
p.line_segment(guide_segment(xf, p.clip_rect(), vertical, pos), Stroke::new(1.0, t.text));
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped()
|
||||
&& let Some(at) = ui.data_mut(|d| d.remove_temp::<[f64; 2]>(id))
|
||||
{
|
||||
let round = |v: f64| (v * 1000.0).round() / 1000.0;
|
||||
let _ = app.run("view.setRulerOrigin", json!({"x": round(at[0]), "y": round(at[1])}));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -433,6 +499,140 @@ mod tests {
|
||||
assert!(failures.is_empty(), "ruler drawing overlaps the origin corner: {failures:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_snaps_the_zero_point_to_ruler_ticks_from_the_current_origin() {
|
||||
assert_eq!(snap_px_to_tick(47.0, 0.0, 10.0), 50.0);
|
||||
assert_eq!(snap_px_to_tick(44.9, 0.0, 10.0), 40.0);
|
||||
// Ticks run from the current zero point, so they sit at 3 + 10k.
|
||||
assert_eq!(snap_px_to_tick(47.0, 3.0, 10.0), 43.0);
|
||||
assert_eq!(snap_px_to_tick(-8.0, 3.0, 10.0), -7.0);
|
||||
// A degenerate tick never panics or moves the point.
|
||||
for tick in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
assert_eq!(snap_px_to_tick(47.5, 3.0, tick), 47.5);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rulers alone in a 400×300 frame at 100 %, centred on a 256×128 document.
|
||||
fn ruler_harness(app: PhotocraftApp) -> (egui_kittest::Harness<'static, PhotocraftApp>, Rect, ViewXform) {
|
||||
let full = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
|
||||
let rect = Rect::from_min_max(full.min + vec2(RULER, RULER), full.max);
|
||||
let xf = ViewXform { rect, zoom: 1.0, center: [128.0, 64.0], flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
let h = egui_kittest::Harness::builder()
|
||||
.with_size(vec2(400.0, 300.0))
|
||||
.with_step_dt(1.0 / 60.0)
|
||||
.build_ui_state(move |ui, app| draw_rulers(app, ui, full, &xf), app);
|
||||
(h, full, xf)
|
||||
}
|
||||
|
||||
fn press(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, pos: Pos2, pressed: bool, modifiers: egui::Modifiers) {
|
||||
h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
fn drag_corner_to(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, full: Rect, to: Pos2, modifiers: egui::Modifiers) {
|
||||
let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center();
|
||||
h.event(egui::Event::ModifiersChanged(modifiers));
|
||||
h.event(egui::Event::PointerMoved(corner));
|
||||
h.run_steps(1);
|
||||
press(h, corner, true, modifiers);
|
||||
for p in [corner + vec2(10.0, 10.0), to] {
|
||||
h.event(egui::Event::PointerMoved(p));
|
||||
h.run_steps(2);
|
||||
}
|
||||
press(h, to, false, modifiers);
|
||||
h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn origin(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> [f64; 2] {
|
||||
h.state().session.active().unwrap().doc.ruler_origin
|
||||
}
|
||||
|
||||
/// #2955: dragging out of the ruler corner sets the zero point (cross hairs while dragging),
|
||||
/// the rulers then read 0 there, Shift snaps it to a tick, and double-clicking the corner
|
||||
/// resets it.
|
||||
#[test]
|
||||
fn dragging_the_ruler_corner_sets_the_zero_point_and_double_click_resets_it() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 256, "height": 128})).unwrap();
|
||||
app.ui.extras.snap = false;
|
||||
let (mut h, full, xf) = ruler_harness(app);
|
||||
h.run_steps(2);
|
||||
let target = xf.to_screen(100.0, 40.0);
|
||||
drag_corner_to(&mut h, full, target, egui::Modifiers::NONE);
|
||||
let o = origin(&h);
|
||||
assert!((o[0] - 100.0).abs() < 0.01 && (o[1] - 40.0).abs() < 0.01, "zero point lands under the pointer: {o:?}");
|
||||
// The top ruler's "0" now sits at the new zero point, "100" (a distance, unsigned as in
|
||||
// Photoshop) at the image's left edge.
|
||||
h.run_steps(2);
|
||||
let labels: Vec<(String, f32)> = h
|
||||
.output()
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| if let egui::Shape::Text(t) = &s.shape { Some((t.galley.text().to_string(), t.pos.x)) } else { None })
|
||||
.collect();
|
||||
let near = |text: &str, x: f32| labels.iter().any(|(t, lx)| t == text && (lx - (x + 2.0)).abs() < 1.0);
|
||||
assert!(near("0", target.x), "a 0 label at the zero point: {labels:?}");
|
||||
assert!(near("100", xf.to_screen(0.0, 0.0).x), "100 at the image's left edge: {labels:?}");
|
||||
|
||||
// Mid-drag, cross hairs run through the pointer across the canvas.
|
||||
let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center();
|
||||
let mid = xf.to_screen(150.0, 90.0);
|
||||
press(&mut h, corner, true, egui::Modifiers::NONE);
|
||||
for p in [corner + vec2(10.0, 10.0), mid] {
|
||||
h.event(egui::Event::PointerMoved(p));
|
||||
h.run_steps(2);
|
||||
}
|
||||
let crosshair = h.output().shapes.iter().any(|s| {
|
||||
matches!(s.shape, egui::Shape::LineSegment { points: [a, b], .. } if (a.x - mid.x).abs() < 0.5 && (b.x - mid.x).abs() < 0.5 && (b.y - a.y).abs() > 200.0)
|
||||
});
|
||||
assert!(crosshair, "a vertical cross-hair line through the pointer while dragging");
|
||||
assert_eq!(origin(&h), o, "the zero point moves on release only");
|
||||
press(&mut h, mid, false, egui::Modifiers::NONE);
|
||||
assert_eq!(origin(&h), [150.0, 90.0]);
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(origin(&h), o, "setting the zero point is undoable");
|
||||
|
||||
// A drag dropped back on the corner leaves it alone.
|
||||
drag_corner_to(&mut h, full, full.min + vec2(4.0, 4.0), egui::Modifiers::NONE);
|
||||
assert_eq!(origin(&h), o);
|
||||
|
||||
// Shift: ticks are 10 px apart at 100 %, measured from the current zero point (100, 40).
|
||||
drag_corner_to(&mut h, full, xf.to_screen(123.0, 57.0), egui::Modifiers::SHIFT);
|
||||
assert_eq!(origin(&h), [120.0, 60.0]);
|
||||
|
||||
for _ in 0..40 {
|
||||
h.step();
|
||||
}
|
||||
let corner = Rect::from_min_size(full.min, vec2(RULER, RULER)).center();
|
||||
h.event(egui::Event::PointerMoved(corner));
|
||||
h.step();
|
||||
for _ in 0..2 {
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert_eq!(origin(&h), [0.0, 0.0], "double-clicking the corner resets the zero point");
|
||||
}
|
||||
|
||||
/// #2955: the Info panel's X/Y are measured from the rulers' zero point.
|
||||
#[test]
|
||||
fn info_panel_position_reads_from_the_zero_point() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.run("view.setRulerOrigin", json!({"x": 20, "y": 5})).unwrap();
|
||||
app.hover_doc = Some([50.5, 20.5]);
|
||||
let mut h = egui_kittest::Harness::builder()
|
||||
.with_size(vec2(260.0, 240.0))
|
||||
.build_ui_state(|ui, app| crate::panels::dock_body(app, ui, crate::dock::Group::Navigator, 2), app);
|
||||
h.run_steps(2);
|
||||
assert!(h.query_by_label("30").is_some() && h.query_by_label("15").is_some(), "X 30, Y 15 from the zero point at (20, 5)");
|
||||
assert!(h.query_by_label("50").is_none(), "not the raw image x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentage_grid_spacing_uses_both_canvas_dimensions() {
|
||||
let mut g = GuidesGridAndSlices { grid_unit: Unit::Percent, gridline_every: 20.0, subdivisions: 2, ..Default::default() };
|
||||
@@ -615,23 +815,23 @@ mod tests {
|
||||
for rotation in [0.0f32, 30.0, 45.0, 90.0, -119.0, 180.0] {
|
||||
for flip in [false, true] {
|
||||
let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 };
|
||||
let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0);
|
||||
let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]);
|
||||
assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}");
|
||||
let (first, last) = if flip { (u1, u0) } else { (u0, u1) };
|
||||
assert!((ruler_pos(&xf, false, first, 1.0) - a.x).abs() < 1e-2, "rotation {rotation}: first tick");
|
||||
assert!((ruler_pos(&xf, false, last, 1.0) - b.x).abs() < 1e-2, "rotation {rotation}: last tick");
|
||||
assert!((ruler_pos(&xf, false, first, 1.0, [0.0; 2]) - a.x).abs() < 1e-2, "rotation {rotation}: first tick");
|
||||
assert!((ruler_pos(&xf, false, last, 1.0, [0.0; 2]) - b.x).abs() < 1e-2, "rotation {rotation}: last tick");
|
||||
// 0 at the projected origin, 500 document px = 500 × zoom screen px further on.
|
||||
let origin = xf.to_screen(0.0, 0.0);
|
||||
assert!((ruler_pos(&xf, false, 0.0, 1.0) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0");
|
||||
assert!((ruler_pos(&xf, true, 0.0, 1.0) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0");
|
||||
assert!((ruler_pos(&xf, false, 0.0, 1.0, [0.0; 2]) - origin.x).abs() < 1e-2, "rotation {rotation}: top ruler 0");
|
||||
assert!((ruler_pos(&xf, true, 0.0, 1.0, [0.0; 2]) - origin.y).abs() < 1e-2, "rotation {rotation}: left ruler 0");
|
||||
let dir = if flip { -1.0 } else { 1.0 };
|
||||
assert!((ruler_pos(&xf, false, 500.0, 1.0) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale");
|
||||
assert!((ruler_pos(&xf, true, 500.0, 1.0) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale");
|
||||
assert!((ruler_pos(&xf, false, 500.0, 1.0, [0.0; 2]) - origin.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale");
|
||||
assert!((ruler_pos(&xf, true, 500.0, 1.0, [0.0; 2]) - origin.y - 250.0).abs() < 1e-2, "rotation {rotation}: left scale");
|
||||
}
|
||||
}
|
||||
// Distances left of / above the origin read without a minus sign, as in Photoshop.
|
||||
let xf = ViewXform { rect, zoom: 0.5, center: [0.0, 0.0], flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0);
|
||||
let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, [0.0; 2]);
|
||||
assert!(u0 < -500.0 && u1 > 500.0, "the view spans the origin: {u0}..{u1}");
|
||||
for (step, whole) in [(100.0, true), (100.0, false), (0.25, false)] {
|
||||
let mut v = (u0 / step).floor() * step;
|
||||
@@ -645,6 +845,31 @@ mod tests {
|
||||
assert_eq!(ruler_label(-0.25, 0.25, false), "0.25");
|
||||
}
|
||||
|
||||
/// #2955 with #3233: a zero point moved off the image's top-left reads 0 where the canvas draws
|
||||
/// it, also on a rotated or flipped view, and the ruler keeps its full length and scale.
|
||||
#[test]
|
||||
fn rulers_count_from_the_zero_point_on_a_rotated_view() {
|
||||
let rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
|
||||
let (a, b) = (rect.left_top(), rect.right_top());
|
||||
let zero = [300.0, 120.0];
|
||||
for rotation in [0.0f32, 30.0, 90.0, -119.0] {
|
||||
for flip in [false, true] {
|
||||
let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip, rotation, aspect: 1.0 };
|
||||
let at = xf.to_screen(zero[0] as f32, zero[1] as f32);
|
||||
assert!((ruler_pos(&xf, false, 0.0, 1.0, zero) - at.x).abs() < 1e-2, "rotation {rotation}: top ruler 0");
|
||||
assert!((ruler_pos(&xf, true, 0.0, 1.0, zero) - at.y).abs() < 1e-2, "rotation {rotation}: left ruler 0");
|
||||
let (u0, u1) = ruler_range(&xf, a, b, 0, 1.0, zero);
|
||||
assert!((u1 - u0 - 1600.0).abs() < 1e-2, "rotation {rotation}: top ruler covers {u0}..{u1}");
|
||||
let dir = if flip { -1.0 } else { 1.0 };
|
||||
assert!((ruler_pos(&xf, false, 500.0, 1.0, zero) - at.x - dir * 250.0).abs() < 1e-2, "rotation {rotation}: top scale");
|
||||
}
|
||||
}
|
||||
// Unrotated, ruler value u sits over document x = zero + u.
|
||||
let xf = ViewXform { rect, zoom: 0.5, center: [1000.0, 700.0], flip: false, rotation: 0.0, aspect: 1.0 };
|
||||
assert!((ruler_pos(&xf, false, -300.0, 1.0, zero) - xf.to_screen(0.0, 0.0).x).abs() < 1e-2);
|
||||
assert!((ruler_pos(&xf, true, 80.0, 1.0, zero) - xf.to_screen(0.0, 200.0).y).abs() < 1e-2);
|
||||
}
|
||||
|
||||
/// #3277: guides belong to the document, so a rotated view draws them along the document
|
||||
/// line; unrotated they still span the whole clip rect.
|
||||
#[test]
|
||||
@@ -674,7 +899,7 @@ mod tests {
|
||||
let top = Rect::from_min_size(rect.min, vec2(rect.width(), RULER));
|
||||
for flip in [false, true] {
|
||||
let xf = ViewXform { rect, zoom: 1.0, center: [400.0, 300.0], flip, rotation: 0.0, aspect: 1.0 };
|
||||
let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0);
|
||||
let (u0, u1) = ruler_range(&xf, top.left_top(), top.right_top(), 0, 1.0, [0.0; 2]);
|
||||
assert!(u0 <= u1, "flip={flip}: u0 ({u0}) must be <= u1 ({u1})");
|
||||
assert!(u1 - u0 > 0.0, "flip={flip}: range is empty");
|
||||
}
|
||||
@@ -717,5 +942,10 @@ mod tests {
|
||||
app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "percent"})).unwrap();
|
||||
assert!((snap_to_tick(&app, &xf, true, 37.0) - 38.4).abs() < 1e-9);
|
||||
assert!((snap_to_tick(&app, &xf, false, 37.0) - 38.4).abs() < 1e-9);
|
||||
// Ticks count from the zero point (#2955): a vertical guide follows the x origin only.
|
||||
let mut app = new_app();
|
||||
app.run("view.setRulerOrigin", json!({"x": 3, "y": 0})).unwrap();
|
||||
assert_eq!(snap_to_tick(&app, &xf, true, 37.0), 33.0);
|
||||
assert_eq!(snap_to_tick(&app, &xf, false, 37.0), 40.0);
|
||||
}
|
||||
}
|
||||
@@ -996,6 +996,10 @@ pub fn reset_form(f: &mut Map<String, Value>) {
|
||||
}
|
||||
|
||||
fn label_of(key: &str) -> String {
|
||||
// A name that already reads as text ("iPhone 14 Pro Max", "Web 1920") is not camelCase.
|
||||
if key.contains(' ') {
|
||||
return tl!(key).to_owned();
|
||||
}
|
||||
let mut out = String::new();
|
||||
for (i, c) in key.chars().enumerate() {
|
||||
if i == 0 {
|
||||
@@ -1026,6 +1030,7 @@ mod label_tests {
|
||||
crate::i18n::with_language(crate::i18n::Lang::EN, || {
|
||||
assert_eq!(label_of("useAntialias"), "Use antialias");
|
||||
assert_eq!(label_of("radius"), "Radius");
|
||||
assert_eq!(label_of("iPhone 14 Pro Max"), "iPhone 14 Pro Max");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,8 +381,7 @@ mod tests {
|
||||
assert!(matches!(legacy.events[0], Event::Zoom(_)));
|
||||
|
||||
// Native magnification takes over before the synthetic gesture times out.
|
||||
let mut native =
|
||||
RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() };
|
||||
let mut native = RawInput { time: Some(1.1), events: vec![Event::Zoom(1.1), wheel(Vec2::new(0.0, 0.25), CTRL)], ..Default::default() };
|
||||
fold_legacy_pinch(&ctx, &mut native);
|
||||
assert!(matches!(native.events[0], Event::Zoom(f) if (f - 1.1).abs() < 1e-5));
|
||||
assert!(matches!(native.events[1], Event::MouseWheel { .. }));
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G11: Batch subfolders, naming, stop/log, cancel landed, AUTO-219-5 done; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G11: Batch subfolders, naming, stop/log, cancel landed, AUTO-219-5 done; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
|
||||
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
|
||||
@@ -70,6 +70,8 @@ what an agent can't finish alone.
|
||||
(TOOL-214-15); Vanishing Point plane editor (TOOL-214-14); Content-Aware Move's live preview
|
||||
of the result (TOOL-213-4; Transform On Drop and Content-Aware Scale through the transform box,
|
||||
TOOL-214-7, are done).
|
||||
Blur Gallery: Field Blur has its on-canvas pins (2026-10-11, #3373); Iris, Tilt-Shift, Spin and
|
||||
Path Blur still edit their pins as parameter dialogs.
|
||||
- **Evidence:** scorecard rows above, all partial or missing.
|
||||
- **Impact:** these are the tools retouchers and compositors use daily; a slider dialog is not a
|
||||
substitute.
|
||||
@@ -278,6 +280,7 @@ what an agent can't finish alone.
|
||||
| 2026-10-12 | minor | G11: Load/Save Actions `.atn` landed (AUTO-219-2 partial); remaining panel work listed |
|
||||
| 2026-10-12 | minor | Refreshed against main: G5 items fixed by #2480, #2327, #2609, #2684, #2675, #2556, #2396, #2527, #2625 and TOOL-214-5/#2442; G7 TOOL-214-7 and Transform On Drop done; G2 #2377 fixed (#2417); G9 UI scale (UI-217-9) and Stamp Visible (UI-217-22) done, prefs 27 of 156; G10 #2225 done (#2482); G13 Khmer, Lao, Myanmar fallback (#3259); G14 CR3 line; G17 Windows ARM64 done (DIST-220-2) |
|
||||
| 2026-10-12 | minor | G11: Batch subfolders, open documents, naming template, stop/log, progress and cancel landed (AUTO-219-5 done) |
|
||||
| 2026-10-11 | minor | G7: Field Blur pins are placed, dragged and tuned on the image (#3373); the other Blur Gallery filters remain dialogs |
|
||||
| 2026-10-11 | minor | D5100 image area and Camera Raw tuning validation; G14 remains open |
|
||||
| 2026-10-11 | minor | G13: Czech dynamic UI text localized; engine messages and native review remain open |
|
||||
| 2026-10-11 | minor | G8: triple/quadruple/five-click type selection done (TYPE-218-8, #3493); Type evidence recounted |
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
# Roadmap
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Photomerge implementation status corrected; real-world quality validation remains open) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (adaptive Unsharp Mask performance evidence linked; Photomerge status correction retained; alpha gate, focus and estimates unchanged) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
- UI.5: Panels can detach, join other tab groups, split, resize and redock through shared docking transactions. Custom layouts persist with workspaces, respect workspace locking, and retain collapse flags for intact native groups.
|
||||
|
||||
@@ -72,6 +72,9 @@ Ranked; each item links to its gap entry. Pick from the top unless an issue is a
|
||||
Photoshop re-open check (FILE-216-4); Photoshop-oracle floor 133/256 → 200+. 150–250 h.
|
||||
2. **Performance budgets** ([G2](gaps.md#g2-interactive-performance)): the 22 over-budget
|
||||
scenarios, the P12 GPU crash at 150 layers, brush and cursor lag (#2619, #2566). 200–350 h.
|
||||
Local adaptive [Unsharp Mask optimisation](unsharp-mask-performance.md) improves native
|
||||
threshold-zero 24 MP RGBA CPU application by 37–102x at radii 300–1000, with measured
|
||||
rounding differences and an exact fallback; no published budget is closed by that measurement.
|
||||
3. **User bug backlog** ([G3](gaps.md#g3-user-reported-bug-backlog)): 579 open issues, most from
|
||||
0.5/0.6 users; triage weekly, fix regressions first. 250–400 h.
|
||||
4. **Brush and transform feel** ([G4](gaps.md#g4-brush-feel), [G5](gaps.md#g5-transform-handles-and-modifiers)):
|
||||
@@ -113,6 +116,7 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-11 | minor | Linked adaptive Unsharp Mask performance and quality evidence; milestones, alpha gate and estimates unchanged |
|
||||
| 2026-10-10 | minor | Photomerge is implemented; real-world quality validation remains open |
|
||||
| 2026-10-10 | minor | Alpha gate table (core-workflow gate from the progress-docs standard): passes, stage stays alpha |
|
||||
| 2026-10-10 | major | Progress-docs standard: honest assessment and dated measurements moved to `target-app-parity.md`, Affinity notes to `file-format-parity.md`; new Current focus and estimates; `parity.md` renamed `parity-checklist.md` |
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Unsharp Mask performance
|
||||
|
||||
Large-radius native Unsharp Mask uses separable FFT convolution with the original
|
||||
discrete Gaussian coefficients and the existing `rustfft` dependency. A streamed
|
||||
separable path preserves the original tap order for exact processing.
|
||||
|
||||
FFT is eligible for radii 64–1000 with at least 65,536 output pixels, a nonzero
|
||||
amount and a zero or negative threshold. Positive thresholds, unstable samples,
|
||||
unsupported geometry and insufficient scratch use the exact path. WebAssembly
|
||||
retains exact processing. Alpha, selections, edges and cancellation are preserved.
|
||||
Smart Sharpen, High Pass and shared blur math are unchanged.
|
||||
|
||||
FFT changes summation order and permits small rounding differences. The measured
|
||||
maximum was one 8-bit storage level, approximately one 16-bit level, and 8.762e-6
|
||||
for the HDR fixture. Exact-path comparisons were byte-identical. Transform axes
|
||||
are capped at 32,768; FFT scratch grouping has a 1 GiB budget, excluding document
|
||||
tiles. This is not a whole-process memory limit.
|
||||
|
||||
Before/after numbers, benchmark methodology, numerical tolerances and preview
|
||||
measurement limits are recorded in [PR #2987](https://github.com/storytold/photocraft/pull/2987).
|
||||
The comparisons use synthetic images and measure CPU computation, not slider
|
||||
event-to-screen latency. No published performance budget or rendering-parity
|
||||
floor is raised by these measurements.
|
||||
Reference in new issue
Block a user