mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Live gradients: Gradient tool makes editable Gradient Fill layers (on-canvas handles, stops, midpoints) + Classic mode (#180) (#197)
This commit is contained in:
1 parent
8bac8926a3
commit
26cbc95c42
33 files changed
+2614
-211
No files matched your search
@@ -111,16 +111,6 @@ fn composite_area(
|
||||
}
|
||||
|
||||
/// Gradient tool over `area` (the selection bounds or canvas).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Per-pixel dither noise in [0, 1) from a position hash (decorrelated, no visible pattern).
|
||||
fn dither_noise(x: i32, y: i32) -> f32 {
|
||||
let mut h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (y as u32).wrapping_mul(0x85EB_CA77);
|
||||
h ^= h >> 15;
|
||||
h = h.wrapping_mul(0x2C1B_3C6D);
|
||||
h ^= h >> 12;
|
||||
f32::from((h & 0xFFFF) as u16) / 65535.0
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn paint_gradient(
|
||||
s: &mut Surface,
|
||||
@@ -145,7 +135,7 @@ pub fn paint_gradient(
|
||||
let mut c = sample_stops(stops, if reverse { 1.0 - t } else { t });
|
||||
if dither {
|
||||
// One quantisation step of monochromatic noise breaks 8-bit banding without speckle.
|
||||
let n = (dither_noise(x, y) - 0.5) / 255.0;
|
||||
let n = (photocraft_color::dither_noise(x, y) - 0.5) / 255.0;
|
||||
for ch in c.iter_mut().take(3) {
|
||||
*ch = (*ch + n).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,17 @@ pub mod convert;
|
||||
|
||||
pub use blend::BlendMode;
|
||||
|
||||
/// Per-pixel gradient dither noise in `[0, 1)` from a position hash (decorrelated, no visible
|
||||
/// pattern). Shared by the Gradient tool and Gradient Fill layers (and mirrored in the GPU
|
||||
/// compositor), so a live gradient dithers exactly like the painted one.
|
||||
pub fn dither_noise(x: i32, y: i32) -> f32 {
|
||||
let mut h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (y as u32).wrapping_mul(0x85EB_CA77);
|
||||
h ^= h >> 15;
|
||||
h = h.wrapping_mul(0x2C1B_3C6D);
|
||||
h ^= h >> 12;
|
||||
f32::from((h & 0xFFFF) as u16) / 65535.0
|
||||
}
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Storage type of one channel sample.
|
||||
|
||||
@@ -417,6 +417,22 @@ fn offset(angle: f32, distance: f32) -> (f32, f32) {
|
||||
((-a.cos() * distance).round(), (a.sin() * distance).round())
|
||||
}
|
||||
|
||||
/// The lengths a 100 % gradient at `angle` spans in a `w` × `h` frame: the chord (Linear and
|
||||
/// Reflected) and the ellipse-norm length (Radial, Angle, Diamond; its half is the radius).
|
||||
pub fn gradient_units(angle: f32, w: f32, h: f32) -> (f32, f32) {
|
||||
let (s, c) = angle.to_radians().sin_cos();
|
||||
// Gradient length: the bounds' extent along the angle as an ellipse
|
||||
// norm (a unit gradient scaled to the bounds); fitted on psd-tools
|
||||
// gradient-styles.psd (cached Photoshop renderings of every style).
|
||||
let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0);
|
||||
// Linear / Reflected span the chord of the bounds through their centre along the angle:
|
||||
// min(w / |cos|, h / |sin|). A 45° gradient on a 29 px square runs 41 px (psd-tools
|
||||
// shape-fx2), an 87° one on a 600 × 60 text line 60 px (layer_effects); axis-aligned angles
|
||||
// span the width / height.
|
||||
let chord = (w / c.abs().max(1e-6)).min(h / s.abs().max(1e-6)).max(1.0);
|
||||
(chord, len)
|
||||
}
|
||||
|
||||
/// Gradient parameter `t` in `0..=1` for pixel centre `(x, y)` inside `bounds`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, offset: (f32, f32), bounds: Rect, x: f32, y: f32) -> f32 {
|
||||
@@ -429,15 +445,8 @@ pub fn gradient_t(style: GradientStyle, angle: f32, scale: f32, reverse: bool, o
|
||||
// Distance along the gradient direction (y axis points down).
|
||||
let along = dx * c - dy * s;
|
||||
let across = dx * s + dy * c;
|
||||
// Gradient length: the bounds' extent along the angle as an ellipse
|
||||
// norm (a unit gradient scaled to the bounds); fitted on psd-tools
|
||||
// gradient-styles.psd (cached Photoshop renderings of every style).
|
||||
let len = ((c * w).powi(2) + (s * h).powi(2)).sqrt().max(1.0) * scale.max(1e-3);
|
||||
// Linear / Reflected span the chord of the bounds through their centre along the angle:
|
||||
// min(w / |cos|, h / |sin|). A 45° gradient on a 29 px square runs 41 px (psd-tools
|
||||
// shape-fx2), an 87° one on a 600 × 60 text line 60 px (layer_effects); axis-aligned angles
|
||||
// span the width / height.
|
||||
let chord = (w / c.abs().max(1e-6)).min(h / s.abs().max(1e-6)).max(1.0) * scale.max(1e-3);
|
||||
let (chord, len) = gradient_units(angle, w, h);
|
||||
let (chord, len) = (chord * scale.max(1e-3), len * scale.max(1e-3));
|
||||
// Linear / Reflected sample the pixel's top-left corner, half a pixel before its centre
|
||||
// (with the whole-pixel end points of `fill_layout`: layer_effects' overlay 5.8 → 1.8/255,
|
||||
// shape-fx2 2.8 → 1.1/255, gradient-fill.psd 1.9 → 0.5/255).
|
||||
|
||||
@@ -123,6 +123,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_centres_snap_like_the_frame_centre() {
|
||||
// A zero offset is the plain layout exactly.
|
||||
let f = Rect::new(0, 0, 7, 5);
|
||||
for style in [GradientStyle::Linear, GradientStyle::Reflected] {
|
||||
assert_eq!(gradient_layout(style, 30.0, 1.0, (0.0, 0.0), f), fill_gradient_layout(style, 30.0, 1.0, f));
|
||||
}
|
||||
// Moving the centre by whole pixels moves the snapped layout by the same pixels.
|
||||
let big = Rect::new(0, 0, 40, 20);
|
||||
let (a0, s0, o0) = gradient_layout(GradientStyle::Linear, 30.0, 0.5, (0.0, 0.0), big);
|
||||
let (a1, s1, o1) = gradient_layout(GradientStyle::Linear, 30.0, 0.5, (0.25, -0.1), big);
|
||||
assert!((a0 - a1).abs() < 1e-4 && (s0 - s1).abs() < 1e-4, "{a0} {a1} {s0} {s1}");
|
||||
assert!((o1.0 - o0.0 - 0.25).abs() < 1e-4 && (o1.1 - o0.1 + 0.1).abs() < 1e-4, "{o0:?} {o1:?}");
|
||||
// Non-snapping styles and bad offsets pass through.
|
||||
assert_eq!(gradient_layout(GradientStyle::Radial, 30.0, 1.0, (0.2, 0.1), big), (30.0, 1.0, (0.2, 0.1)));
|
||||
let (_, _, o) = gradient_layout(GradientStyle::Linear, 30.0, 1.0, (f32::NAN, 0.0), big);
|
||||
assert!(o.0.is_nan());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_frames_barely_move_and_bad_input_is_harmless() {
|
||||
let f = Rect::new(0, 0, 3000, 2000);
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Gradient Fill layers: their colour ramp (colour stops with midpoints, opacity stops, dither)
|
||||
//! and the on-canvas geometry of the Gradient tool's live gradients, where a start and an end
|
||||
//! point stand for the fill's angle, scale and centre offset.
|
||||
//!
|
||||
//! The mapping matches the Gradient tool's destructive drag (`photocraft_algo::paint`): a
|
||||
//! Linear gradient runs from the start (t = 0) to the end point (t = 1); Radial, Angle,
|
||||
//! Reflected and Diamond gradients are centred on the start point and reach t = 1 at the end
|
||||
//! point's distance. A fill made from a drag therefore renders the same pixels as painting that
|
||||
//! drag (see the tests).
|
||||
|
||||
use photocraft_doc::{Fill, GradientStyle};
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
use crate::effects::gradient_units;
|
||||
|
||||
/// Smallest gradient length a handle drag produces (pixels), so the fill stays invertible.
|
||||
const MIN_LEN: f32 = 0.5;
|
||||
|
||||
/// A gradient fill's colour ramp, prepared for one render (colours converted once, while the
|
||||
/// document's CMYK profile is active).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Ramp {
|
||||
color: Vec<(f32, [f32; 4])>,
|
||||
mids: Vec<f32>,
|
||||
opacity: Vec<(f32, f32)>,
|
||||
}
|
||||
|
||||
impl Ramp {
|
||||
/// The ramp of a gradient fill (`None` for other fills).
|
||||
pub fn new(f: &Fill) -> Option<Ramp> {
|
||||
let Fill::Gradient { stops, opacity_stops, midpoints, .. } = f else { return None };
|
||||
let mut color: Vec<(f32, [f32; 4])> = stops
|
||||
.iter()
|
||||
.map(|(p, c)| {
|
||||
let rgb = c.to_rgb();
|
||||
(*p, [rgb[0], rgb[1], rgb[2], c.alpha])
|
||||
})
|
||||
.collect();
|
||||
color.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut opacity = opacity_stops.clone();
|
||||
opacity.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
Some(Ramp { color, mids: midpoints.clone(), opacity })
|
||||
}
|
||||
|
||||
/// Colour and alpha at `t` (`0..=1`).
|
||||
pub fn sample(&self, t: f32) -> [f32; 4] {
|
||||
let mut c = sample_color(&self.color, &self.mids, t);
|
||||
if !self.opacity.is_empty() {
|
||||
c[3] *= sample_opacity(&self.opacity, t);
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a segment of relative position `u` lands once its midpoint is `m` (0.5 = unchanged):
|
||||
/// the colour is half-way at `m`, linear on either side.
|
||||
pub fn midpoint_remap(u: f32, m: f32) -> f32 {
|
||||
let m = m.clamp(0.05, 0.95);
|
||||
if (m - 0.5).abs() < 1e-6 {
|
||||
u
|
||||
} else if u <= m {
|
||||
0.5 * u / m
|
||||
} else {
|
||||
0.5 + 0.5 * (u - m) / (1.0 - m)
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_color(stops: &[(f32, [f32; 4])], mids: &[f32], t: f32) -> [f32; 4] {
|
||||
let (Some(first), Some(last)) = (stops.first(), stops.last()) else { return [0.0; 4] };
|
||||
if t <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
for (i, w) in stops.windows(2).enumerate() {
|
||||
let (a, b) = (&w[0], &w[1]);
|
||||
if t <= b.0 {
|
||||
let u = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
let k = midpoint_remap(u, mids.get(i).copied().unwrap_or(0.5));
|
||||
return std::array::from_fn(|c| a.1[c] + (b.1[c] - a.1[c]) * k);
|
||||
}
|
||||
}
|
||||
last.1
|
||||
}
|
||||
|
||||
fn sample_opacity(stops: &[(f32, f32)], t: f32) -> f32 {
|
||||
let (Some(first), Some(last)) = (stops.first(), stops.last()) else { return 1.0 };
|
||||
if t <= first.0 {
|
||||
return first.1;
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
if t <= w[1].0 {
|
||||
let u = if w[1].0 > w[0].0 { (t - w[0].0) / (w[1].0 - w[0].0) } else { 0.0 };
|
||||
return w[0].1 + (w[1].1 - w[0].1) * u;
|
||||
}
|
||||
}
|
||||
last.1
|
||||
}
|
||||
|
||||
/// Adds one level of the shared dither noise to a colour (as the Gradient tool does).
|
||||
pub fn dither(c: &mut [f32; 4], x: i32, y: i32) {
|
||||
let n = (photocraft_color::dither_noise(x, y) - 0.5) / 255.0;
|
||||
for ch in c.iter_mut().take(3) {
|
||||
*ch = (*ch + n).clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders a gradient fill over `rect`, laid out in `frame` (row-major RGBA).
|
||||
pub fn render(f: &Fill, rect: Rect, frame: Rect) -> Vec<[f32; 4]> {
|
||||
let mut px = vec![[0.0f32; 4]; rect.width() as usize * rect.height() as usize];
|
||||
let (Some(ramp), Fill::Gradient { angle, scale, style, reverse, offset, dither: dith, .. }) = (Ramp::new(f), f) else { return px };
|
||||
let w = rect.width() as usize;
|
||||
if w == 0 {
|
||||
return px;
|
||||
}
|
||||
// Linear and Reflected end points on whole pixels, as Photoshop (crate::fill_layout).
|
||||
let (angle, scale, offset) = &crate::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame);
|
||||
let row = |y: i32, out: &mut [[f32; 4]]| {
|
||||
for (i, p) in out.iter_mut().enumerate() {
|
||||
let x = rect.x0 + i as i32;
|
||||
let t = crate::effects::gradient_t(*style, *angle, *scale, *reverse, *offset, frame, x as f32 + 0.5, y as f32 + 0.5);
|
||||
*p = ramp.sample(t);
|
||||
if *dith {
|
||||
dither(p, x, y);
|
||||
}
|
||||
}
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
px.par_chunks_mut(w).enumerate().for_each(|(j, out)| row(rect.y0 + j as i32, out));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
for (j, out) in px.chunks_mut(w).enumerate() {
|
||||
row(rect.y0 + j as i32, out);
|
||||
}
|
||||
px
|
||||
}
|
||||
|
||||
fn frame_dims(frame: Rect) -> (f32, f32) {
|
||||
(frame.width().max(1) as f32, frame.height().max(1) as f32)
|
||||
}
|
||||
|
||||
/// The centre a gradient is laid out around: the frame's centre moved by `offset`.
|
||||
fn centre(offset: (f32, f32), frame: Rect) -> [f32; 2] {
|
||||
let (w, h) = frame_dims(frame);
|
||||
[frame.x0 as f32 + w / 2.0 + offset.0 * w, frame.y0 as f32 + h / 2.0 + offset.1 * h]
|
||||
}
|
||||
|
||||
/// The gradient's reach from its centre at scale 1: the full chord for Linear, half the chord
|
||||
/// for Reflected, the radius for the others.
|
||||
fn unit_reach(style: GradientStyle, angle: f32, frame: Rect) -> f32 {
|
||||
let (w, h) = frame_dims(frame);
|
||||
let (chord, len) = gradient_units(angle, w, h);
|
||||
match style {
|
||||
GradientStyle::Linear => chord,
|
||||
GradientStyle::Reflected => chord / 2.0,
|
||||
GradientStyle::Radial | GradientStyle::Angle | GradientStyle::Diamond => len / 2.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The start and end points (document pixels) of a gradient laid out in `frame`.
|
||||
pub fn handles(style: GradientStyle, angle: f32, scale: f32, offset: (f32, f32), frame: Rect) -> ([f32; 2], [f32; 2]) {
|
||||
let c = centre(offset, frame);
|
||||
let (s, co) = angle.to_radians().sin_cos();
|
||||
let dir = [co, -s];
|
||||
let reach = unit_reach(style, angle, frame) * scale.max(1e-3);
|
||||
match style {
|
||||
GradientStyle::Linear => {
|
||||
let h = reach / 2.0;
|
||||
([c[0] - dir[0] * h, c[1] - dir[1] * h], [c[0] + dir[0] * h, c[1] + dir[1] * h])
|
||||
}
|
||||
_ => (c, [c[0] + dir[0] * reach, c[1] + dir[1] * reach]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The handles of a gradient fill in `frame` (`None` for other fills).
|
||||
pub fn fill_handles(f: &Fill, frame: Rect) -> Option<([f32; 2], [f32; 2])> {
|
||||
match f {
|
||||
Fill::Gradient { style, angle, scale, offset, .. } => Some(handles(*style, *angle, *scale, *offset, frame)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Angle (degrees), scale and centre offset that put a gradient's start and end points at
|
||||
/// `from` and `to` in `frame` (inverse of [`handles`]). A zero-length drag keeps the direction
|
||||
/// of `fallback_angle`.
|
||||
pub fn from_handles(style: GradientStyle, from: [f32; 2], to: [f32; 2], frame: Rect, fallback_angle: f32) -> (f32, f32, (f32, f32)) {
|
||||
let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
|
||||
let len = dx.hypot(dy);
|
||||
let angle = if len > 1e-4 { (-dy).atan2(dx).to_degrees() } else { fallback_angle };
|
||||
let len = len.max(MIN_LEN);
|
||||
let c = match style {
|
||||
GradientStyle::Linear => [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0],
|
||||
_ => from,
|
||||
};
|
||||
let (w, h) = frame_dims(frame);
|
||||
let offset = ((c[0] - frame.x0 as f32 - w / 2.0) / w, (c[1] - frame.y0 as f32 - h / 2.0) / h);
|
||||
let scale = len / unit_reach(style, angle, frame);
|
||||
(angle, scale, offset)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_doc::Color;
|
||||
|
||||
const STYLES: [GradientStyle; 5] = [GradientStyle::Linear, GradientStyle::Radial, GradientStyle::Angle, GradientStyle::Reflected, GradientStyle::Diamond];
|
||||
|
||||
#[test]
|
||||
fn handles_round_trip() {
|
||||
let frame = Rect::new(10, -4, 210, 96);
|
||||
for style in STYLES {
|
||||
for (from, to) in [([30.0, 40.0], [180.0, 10.0]), ([100.0, 50.0], [100.0, 90.0]), ([5.0, 5.0], [-40.0, 70.0])] {
|
||||
let (a, s, o) = from_handles(style, from, to, frame, 0.0);
|
||||
let (f2, t2) = handles(style, a, s, o, frame);
|
||||
for (p, q) in [(from, f2), (to, t2)] {
|
||||
assert!((p[0] - q[0]).abs() < 1e-2 && (p[1] - q[1]).abs() < 1e-2, "{style:?}: {p:?} vs {q:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_map_to_the_ends_of_the_ramp() {
|
||||
let frame = Rect::new(0, 0, 100, 60);
|
||||
let (a, s, o) = from_handles(GradientStyle::Linear, [20.0, 30.0], [80.0, 30.0], frame, 0.0);
|
||||
// Linear gradients sample each pixel's top-left corner (effects::gradient_t): the pixel
|
||||
// whose corner is the handle, centred half a pixel further, is where t is 0 or 1.
|
||||
let t = |x: f32| crate::effects::gradient_t(GradientStyle::Linear, a, s, false, o, frame, x + 0.5, 30.5);
|
||||
assert!(t(20.0).abs() < 1e-4 && (t(80.0) - 1.0).abs() < 1e-4 && (t(50.0) - 0.5).abs() < 1e-4);
|
||||
let (a, s, o) = from_handles(GradientStyle::Radial, [40.0, 20.0], [40.0, 50.0], frame, 0.0);
|
||||
let r = |x: f32, y: f32| crate::effects::gradient_t(GradientStyle::Radial, a, s, false, o, frame, x, y);
|
||||
assert!(r(40.0, 20.0) < 1e-4 && (r(70.0, 20.0) - 1.0).abs() < 1e-3 && (r(55.0, 20.0) - 0.5).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ramp_midpoints_and_opacity() {
|
||||
let f = Fill::Gradient {
|
||||
stops: vec![(1.0, Color::WHITE), (0.0, Color::BLACK)],
|
||||
angle: 0.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Linear,
|
||||
reverse: false,
|
||||
opacity_stops: vec![(0.0, 1.0), (1.0, 0.0)],
|
||||
midpoints: vec![0.25],
|
||||
offset: (0.0, 0.0),
|
||||
dither: false,
|
||||
align: true,
|
||||
};
|
||||
let r = Ramp::new(&f).unwrap();
|
||||
// Unsorted stops are sorted; the midpoint puts 50 % gray at t = 0.25.
|
||||
assert!((r.sample(0.25)[0] - 0.5).abs() < 1e-5);
|
||||
assert!((r.sample(0.25)[3] - 0.75).abs() < 1e-5);
|
||||
assert_eq!(r.sample(1.0), [1.0, 1.0, 1.0, 0.0]);
|
||||
assert_eq!(midpoint_remap(0.3, 0.5), 0.3);
|
||||
assert!(Ramp::new(&Fill::Solid(Color::BLACK)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_handles_empty_and_degenerate_rects() {
|
||||
let f = Fill::gradient(vec![], 0.0, 0.0, GradientStyle::Angle, true);
|
||||
assert!(render(&f, Rect::new(0, 0, 0, 5), Rect::new(0, 0, 0, 0)).is_empty());
|
||||
let px = render(&f, Rect::new(0, 0, 3, 2), Rect::new(0, 0, 0, 0));
|
||||
assert_eq!(px.len(), 6);
|
||||
}
|
||||
}
|
||||
+38
-42
@@ -20,6 +20,7 @@ pub mod adjust;
|
||||
pub mod bounds;
|
||||
pub mod effects;
|
||||
pub mod fill_layout;
|
||||
pub mod gradient_fill;
|
||||
pub mod masks;
|
||||
pub mod multichannel;
|
||||
pub mod pattern;
|
||||
@@ -674,6 +675,10 @@ pub fn surface_to_buffer(s: &Surface, rect: Rect) -> Buffer {
|
||||
/// the vector mask's path; otherwise the canvas.
|
||||
pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect {
|
||||
let mut frame = canvas;
|
||||
// "Align with layer" off: the canvas (the Gradient tool's live gradients).
|
||||
if let LayerContent::Fill(Fill::Gradient { align: false, .. }) = &layer.content {
|
||||
return frame;
|
||||
}
|
||||
if let Some(m) = &layer.mask
|
||||
&& m.enabled
|
||||
&& m.surface.default_pixel().first().is_some_and(|v| *v <= 0.0)
|
||||
@@ -709,27 +714,8 @@ fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedP
|
||||
let rgb = c.to_rgb();
|
||||
Buffer::filled(rect, [rgb[0], rgb[1], rgb[2], c.alpha])
|
||||
}
|
||||
Fill::Gradient { stops, angle, scale, style, reverse } => {
|
||||
// Convert once per render call, while its document CMYK profile is active.
|
||||
let stops: Vec<_> = stops
|
||||
.iter()
|
||||
.map(|(p, c)| {
|
||||
let rgb = c.to_rgb();
|
||||
(*p, [rgb[0], rgb[1], rgb[2], c.alpha])
|
||||
})
|
||||
.collect();
|
||||
// Gradient geometry relative to the layer's frame, independent of the render rect.
|
||||
let (angle, scale, offset) = fill_layout::fill_gradient_layout(*style, *angle, *scale, canvas);
|
||||
let mut b = Buffer::transparent(rect);
|
||||
for y in rect.y0..rect.y1 {
|
||||
for x in rect.x0..rect.x1 {
|
||||
let t = effects::gradient_t(*style, angle, scale, *reverse, offset, canvas, x as f32 + 0.5, y as f32 + 0.5);
|
||||
let i = ((y - rect.y0) as usize) * rect.width() as usize + (x - rect.x0) as usize;
|
||||
b.px[i] = sample_stops(&stops, t);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
// Gradient geometry relative to the layer's frame, independent of the render rect.
|
||||
Fill::Gradient { .. } => Buffer { rect, px: gradient_fill::render(f, rect, canvas) },
|
||||
// Laid out from the layer's frame when linked; transparent if the pattern is missing.
|
||||
Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) {
|
||||
Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) },
|
||||
@@ -738,27 +724,6 @@ fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedP
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] {
|
||||
match stops {
|
||||
[] => [0.0; 4],
|
||||
[only] => only.1,
|
||||
_ => {
|
||||
if t <= stops[0].0 {
|
||||
return stops[0].1;
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
let (a, b) = (&w[0], &w[1]);
|
||||
if t <= b.0 {
|
||||
let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 0.0 };
|
||||
let (ca, cb) = (a.1, b.1);
|
||||
return std::array::from_fn(|i| ca[i] + (cb[i] - ca[i]) * k);
|
||||
}
|
||||
}
|
||||
stops[stops.len() - 1].1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when a pixel-backed layer has nothing to contribute in `rect`:
|
||||
/// no allocated tiles there, a transparent default, and no effects (which
|
||||
/// could reach in from outside). Clipped layers depend on the base, so they
|
||||
@@ -870,6 +835,37 @@ pub fn transparent_outside(layer: &Layer) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `layer` replaces everything beneath it in its stack: a visible, unclipped fill layer
|
||||
/// in Normal mode at full opacity and fill, without masks, effects, channel restrictions or Blend
|
||||
/// If, whose fill is opaque everywhere (a solid colour, or a gradient whose colour and opacity
|
||||
/// stops are all opaque). Normal blending at alpha 1 returns the layer's colour exactly, so the
|
||||
/// layers below can be skipped (the live Gradient tool's preview recomposites the whole canvas on
|
||||
/// every pointer move).
|
||||
pub fn occludes_below(layer: &Layer, mode: photocraft_color::ColorMode) -> bool {
|
||||
let LayerContent::Fill(f) = &layer.content else { return false };
|
||||
let opaque = match f {
|
||||
Fill::Solid(c) => c.alpha >= 1.0,
|
||||
Fill::Gradient { stops, opacity_stops, .. } => {
|
||||
!stops.is_empty() && stops.iter().all(|(_, c)| c.alpha >= 1.0) && opacity_stops.iter().all(|(_, o)| *o >= 1.0)
|
||||
}
|
||||
Fill::Pattern { .. } => false,
|
||||
};
|
||||
// A cached render in use (a PSD's stored fill pixels) may not be opaque.
|
||||
let cached = layer.fill_cache.as_ref().is_some_and(|c| c.fill == *f);
|
||||
opaque
|
||||
&& !cached
|
||||
&& layer.visible
|
||||
&& !layer.clipped
|
||||
&& layer.blend == photocraft_color::BlendMode::Normal
|
||||
&& layer.opacity >= 1.0
|
||||
&& layer.fill_opacity >= 1.0
|
||||
&& !layer.mask.as_ref().is_some_and(|m| m.enabled)
|
||||
&& !layer.vector_mask.as_ref().is_some_and(|m| m.enabled)
|
||||
&& !effects::has_effects(layer)
|
||||
&& layer.excluded_channels == 0
|
||||
&& !blend_if_active(layer, mode)
|
||||
}
|
||||
|
||||
/// Whether Blending Options › Blend If changes how `layer` composites in a `mode` document.
|
||||
/// RGB documents test Gray and R, G, B; grayscale (and duotone) documents their one channel.
|
||||
/// Other modes composite in display RGB, where ranges over their own channels have no exact
|
||||
|
||||
@@ -57,13 +57,7 @@ fn filled_shape_stroke_follows_the_outline_where_the_fill_fades_out() {
|
||||
let mut d = doc(40, 40);
|
||||
let mut transparent = Color::rgb(1.0, 0.0, 0.0);
|
||||
transparent.alpha = 0.0;
|
||||
let fade = Fill::Gradient {
|
||||
stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, transparent)],
|
||||
angle: 0.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Linear,
|
||||
reverse: false,
|
||||
};
|
||||
let fade = Fill::gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, transparent)], 0.0, 1.0, GradientStyle::Linear, false);
|
||||
let mut l = shape(10.0, 30.0, fade, None);
|
||||
l.effects.items = vec![stroke(3.0, StrokePosition::Outside, blue()), stroke(2.0, StrokePosition::Inside, FxPaint::Color(Color::rgb(0.0, 1.0, 0.0)))];
|
||||
d.layers.push(l);
|
||||
|
||||
@@ -311,13 +311,7 @@ fn solid_and_gradient_fill_layers() {
|
||||
d.layers.push(Layer::new("fill", LayerContent::Fill(Fill::Solid(Color::rgb(0.0, 0.0, 1.0)))));
|
||||
assert!(close4(px(&d, 5, 0), [0.0, 0.0, 1.0, 1.0]));
|
||||
|
||||
let g = Fill::Gradient {
|
||||
stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)],
|
||||
angle: 0.0,
|
||||
scale: 1.0,
|
||||
style: photocraft_doc::GradientStyle::Linear,
|
||||
reverse: false,
|
||||
};
|
||||
let g = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, photocraft_doc::GradientStyle::Linear, false);
|
||||
let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
|
||||
let buf = render_fill(&g, Rect::new(0, 0, 10, 1), Rect::new(0, 0, 10, 1), &patterns);
|
||||
// tile independence: a 1px render of the right edge equals the full render
|
||||
@@ -1175,7 +1169,7 @@ fn small_gradient_fill_matches_photoshop_at_all_depths() {
|
||||
let stops = vec![(0.0, Color::rgb(0.0, 0.0, 0.0)), (1.0, Color::rgb(1.0, 1.0, 1.0))];
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut d = Document::new("g", Size::new(4, 4), ColorMode::Rgb, depth);
|
||||
let fill = Fill::Gradient { stops: stops.clone(), angle: 30.0, scale: 1.0, style: photocraft_doc::GradientStyle::Reflected, reverse: false };
|
||||
let fill = Fill::gradient(stops.clone(), 30.0, 1.0, photocraft_doc::GradientStyle::Reflected, false);
|
||||
d.layers.push(Layer::new("g", LayerContent::Fill(fill)));
|
||||
let out = flatten(&d);
|
||||
for y in 0..4usize {
|
||||
|
||||
+27
-1
@@ -174,13 +174,31 @@ pub struct Group {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Fill {
|
||||
Solid(Color),
|
||||
/// Gradient between stops at `angle` degrees (`style` geometry, optionally reversed).
|
||||
/// Gradient between stops at `angle` degrees (`style` geometry, optionally reversed), laid
|
||||
/// out in the layer's frame (or the canvas when `align` is off), its centre moved by `offset`.
|
||||
Gradient {
|
||||
stops: Vec<(f32, Color)>,
|
||||
angle: f32,
|
||||
scale: f32,
|
||||
style: GradientStyle,
|
||||
reverse: bool,
|
||||
/// Opacity stops `(location, opacity)` (both `0..=1`); empty = each colour stop's alpha.
|
||||
/// When set, a pixel's alpha is the colour's alpha times the opacity at that location.
|
||||
#[serde(default)]
|
||||
opacity_stops: Vec<(f32, f32)>,
|
||||
/// Colour midpoints, one per segment between consecutive (sorted) colour stops: where
|
||||
/// the segment is half-way (`0..=1` of the segment). Missing entries are 0.5.
|
||||
#[serde(default)]
|
||||
midpoints: Vec<f32>,
|
||||
/// Centre offset as a fraction of the frame (PSD `Ofst`).
|
||||
#[serde(default)]
|
||||
offset: (f32, f32),
|
||||
/// Dither (breaks 8-bit banding with one level of noise).
|
||||
#[serde(default)]
|
||||
dither: bool,
|
||||
/// "Align with layer": lay out in the layer's frame (its masks' bounds), else the canvas.
|
||||
#[serde(default = "effects::yes")]
|
||||
align: bool,
|
||||
},
|
||||
/// A pattern from [`Document::patterns`] (looked up by `id`, then `name`).
|
||||
Pattern {
|
||||
@@ -200,6 +218,14 @@ pub enum Fill {
|
||||
},
|
||||
}
|
||||
|
||||
impl Fill {
|
||||
/// A gradient fill with the classic settings: opaque stops at their alpha, 50 % midpoints,
|
||||
/// centred, no dither, aligned with the layer.
|
||||
pub fn gradient(stops: Vec<(f32, Color)>, angle: f32, scale: f32, style: GradientStyle, reverse: bool) -> Fill {
|
||||
Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops: Vec::new(), midpoints: Vec::new(), offset: (0.0, 0.0), dither: false, align: true }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TextLayer {
|
||||
pub text: String,
|
||||
|
||||
@@ -52,8 +52,12 @@ fn map_angle(a: &Affine, deg: f32) -> f32 {
|
||||
}
|
||||
|
||||
fn map_fill(a: &Affine, f: &mut Fill) {
|
||||
if let Fill::Gradient { angle, .. } = f {
|
||||
if let Fill::Gradient { angle, offset, .. } = f {
|
||||
*angle = map_angle(a, *angle);
|
||||
// The centre offset (a fraction of the frame) turns with the canvas: exact for 90° turns
|
||||
// and flips, where the frame's sides swap with the axes.
|
||||
let (ox, oy) = (f64::from(offset.0), f64::from(offset.1));
|
||||
*offset = ((a.m[0] * ox + a.m[2] * oy) as f32, (a.m[1] * ox + a.m[3] * oy) as f32);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -626,13 +626,13 @@ fn build() -> Vec<CommandSpec> {
|
||||
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
|
||||
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
|
||||
let id = s.edit("New Gradient Fill Layer", |doc, active| {
|
||||
let fill = Fill::Gradient {
|
||||
stops: vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))],
|
||||
let fill = Fill::gradient(
|
||||
vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))],
|
||||
angle,
|
||||
scale: 1.0,
|
||||
1.0,
|
||||
style,
|
||||
reverse,
|
||||
};
|
||||
);
|
||||
let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)));
|
||||
*active = Some(id);
|
||||
Ok(id)
|
||||
@@ -939,6 +939,7 @@ fn build() -> Vec<CommandSpec> {
|
||||
v.extend(crate::filters::specs());
|
||||
v.extend(crate::filters_ext::specs());
|
||||
v.extend(crate::gallery_cmds::specs());
|
||||
v.extend(crate::gradient_fill_cmds::specs());
|
||||
v.extend(crate::type_cmds::specs());
|
||||
v.extend(crate::transform_cmds::specs());
|
||||
v.extend(crate::vector_cmds::specs());
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
//! Live gradients: the Gradient tool's non-destructive mode (Photoshop 2023+). A drag makes a
|
||||
//! Gradient Fill layer above the active layer, masked by the selection, whose start and end
|
||||
//! points, colour stops, opacity stops and midpoints stay editable on canvas afterwards. The
|
||||
//! classic destructive mode is `paint.gradient`.
|
||||
//!
|
||||
//! A live gradient is laid out on the canvas ("Align with layer" off), so its handles stay put
|
||||
//! when its mask changes. Its start/end points are stored as the fill's angle, scale and centre
|
||||
//! offset (`photocraft_compose::gradient_fill`), which is what a PSD Gradient Fill holds, and it
|
||||
//! renders the same pixels as painting the same drag with `paint.gradient`.
|
||||
//!
|
||||
//! Every edit is one command, so one history step per gesture: the UI previews a drag with
|
||||
//! [`apply_set`] and commits it once on release.
|
||||
|
||||
use photocraft_color::Color;
|
||||
use photocraft_compose::gradient_fill as gf;
|
||||
use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId, LayerMask};
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::commands::{CommandSpec, blend_from_str, layer_param};
|
||||
use crate::presets::gradients::GradientPreset;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
pub const CREATE: &str = "gradient.fill.create";
|
||||
pub const SET: &str = "gradient.fill.set";
|
||||
pub const STOP: &str = "gradient.fill.stop";
|
||||
pub const GET: &str = "gradient.fill.get";
|
||||
|
||||
/// Largest coordinate accepted for a start/end point (pixels).
|
||||
const MAX_COORD: f32 = 1.0e7;
|
||||
/// Scale range of a gradient fill (a fraction): Photoshop allows 10–150 % (the PSD stores a
|
||||
/// percentage). A handle drag past it clamps, so the far handle stops where the scale does.
|
||||
const SCALE_RANGE: (f32, f32) = (0.1, 1.5);
|
||||
|
||||
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
}
|
||||
|
||||
fn num(p: &Value, k: &str) -> Option<f32> {
|
||||
p.get(k).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite())
|
||||
}
|
||||
|
||||
fn point(cmd: &str, p: &Value, k: &str) -> Result<Option<[f32; 2]>> {
|
||||
let Some(v) = p.get(k) else { return Ok(None) };
|
||||
let a = v.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(cmd, format!("`{k}` is [x, y]")))?;
|
||||
let c = |i: usize| a.get(i).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite() && v.abs() <= MAX_COORD);
|
||||
match (c(0), c(1)) {
|
||||
(Some(x), Some(y)) => Ok(Some([x, y])),
|
||||
_ => Err(bad(cmd, format!("`{k}` needs finite coordinates within ±{MAX_COORD}"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn style_param(cmd: &str, p: &Value) -> Result<Option<GradientStyle>> {
|
||||
match p.get("style") {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::String(s)) => match s.to_ascii_lowercase().as_str() {
|
||||
"linear" => Ok(Some(GradientStyle::Linear)),
|
||||
"radial" => Ok(Some(GradientStyle::Radial)),
|
||||
"angle" => Ok(Some(GradientStyle::Angle)),
|
||||
"reflected" => Ok(Some(GradientStyle::Reflected)),
|
||||
"diamond" => Ok(Some(GradientStyle::Diamond)),
|
||||
o => Err(bad(cmd, format!("unknown style `{o}` (linear|radial|angle|reflected|diamond)"))),
|
||||
},
|
||||
Some(_) => Err(bad(cmd, "`style` is a string")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn style_name(s: GradientStyle) -> &'static str {
|
||||
match s {
|
||||
GradientStyle::Linear => "linear",
|
||||
GradientStyle::Radial => "radial",
|
||||
GradientStyle::Angle => "angle",
|
||||
GradientStyle::Reflected => "reflected",
|
||||
GradientStyle::Diamond => "diamond",
|
||||
}
|
||||
}
|
||||
|
||||
/// A stop colour: `"#rrggbb"`, `"#rrggbbaa"`, `[r, g, b, a?]` (0..1), `"foreground"` or
|
||||
/// `"background"`.
|
||||
fn parse_color(v: &Value, fg: [f32; 4], bg: [f32; 4]) -> Option<Color> {
|
||||
let c = match v {
|
||||
Value::String(s) if s == "foreground" => fg,
|
||||
Value::String(s) if s == "background" => bg,
|
||||
Value::String(s) => {
|
||||
let h = s.trim_start_matches('#');
|
||||
let b = |i: usize| h.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0);
|
||||
match h.len() {
|
||||
6 => [b(0)?, b(2)?, b(4)?, 1.0],
|
||||
8 => [b(0)?, b(2)?, b(4)?, b(6)?],
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Value::Array(a) if (3..=4).contains(&a.len()) => {
|
||||
let f = |i: usize| a.get(i).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite());
|
||||
[f(0)?, f(1)?, f(2)?, if a.len() == 4 { f(3)? } else { 1.0 }]
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let c = c.map(|v| v.clamp(0.0, 1.0));
|
||||
Some(Color::rgba(c[0], c[1], c[2], c[3]))
|
||||
}
|
||||
|
||||
fn hex(c: &Color) -> String {
|
||||
let rgb = c.to_rgb();
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
if c.alpha >= 1.0 {
|
||||
format!("#{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]))
|
||||
} else {
|
||||
format!("#{:02x}{:02x}{:02x}{:02x}", q(rgb[0]), q(rgb[1]), q(rgb[2]), q(c.alpha))
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient a `gradient.fill.create` uses: a preset (`"gradient"`), explicit `"stops"`
|
||||
/// (+ `"transparency"`), else the current gradient (Gradients panel).
|
||||
fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<GradientPreset> {
|
||||
if let Some(name) = p.get("gradient").and_then(Value::as_str) {
|
||||
let groups = &s.presets.gradients;
|
||||
return groups
|
||||
.iter()
|
||||
.flat_map(|g| g.items.iter())
|
||||
.find(|g| g.name.eq_ignore_ascii_case(name))
|
||||
.cloned()
|
||||
.ok_or_else(|| bad(cmd, format!("no gradient preset \"{name}\" (see gradient.presets.list)")));
|
||||
}
|
||||
if p.get("stops").is_some() {
|
||||
return GradientPreset::from_params("Custom", p, cmd);
|
||||
}
|
||||
Ok(s.presets.gradient.clone())
|
||||
}
|
||||
|
||||
/// The fill and frame of gradient fill layer `id`.
|
||||
fn gradient_of(s: &Session, id: LayerId, cmd: &str) -> Result<(Fill, Rect)> {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
|
||||
match &l.content {
|
||||
LayerContent::Fill(f @ Fill::Gradient { .. }) => Ok((f.clone(), photocraft_compose::fill_frame(l, d.doc.bounds()))),
|
||||
_ => Err(bad(cmd, format!("layer \"{}\" is not a gradient fill layer", l.name))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the active layer is a gradient fill layer (the commands' `enabled`).
|
||||
pub fn has_gradient_fill(s: &Session) -> std::result::Result<(), String> {
|
||||
let l = crate::active_layer_of(s)?;
|
||||
if matches!(l.content, LayerContent::Fill(Fill::Gradient { .. })) { Ok(()) } else { Err("the active layer is not a gradient fill layer".into()) }
|
||||
}
|
||||
|
||||
fn has_doc(s: &Session) -> std::result::Result<(), String> {
|
||||
s.active().map(|_| ()).ok_or_else(|| "no document open".into())
|
||||
}
|
||||
|
||||
fn clamp_scale(v: f32) -> f32 {
|
||||
v.clamp(SCALE_RANGE.0, SCALE_RANGE.1)
|
||||
}
|
||||
|
||||
/// The frame a gradient fill of `layer` (with `align`) is laid out in.
|
||||
fn frame_with_align(layer: &Layer, f: &Fill, canvas: Rect) -> Rect {
|
||||
let mut l = layer.clone();
|
||||
l.content = LayerContent::Fill(f.clone());
|
||||
photocraft_compose::fill_frame(&l, canvas)
|
||||
}
|
||||
|
||||
/// Applies `gradient.fill.set` params to a gradient fill (`layer` gives its frame; `fg`/`bg`
|
||||
/// resolve stop colours). Pure, so the canvas previews a handle drag with exactly what the
|
||||
/// command will commit.
|
||||
pub fn apply_set(layer: &Layer, f: &Fill, canvas: Rect, p: &Value, fg: [f32; 4], bg: [f32; 4]) -> Result<Fill> {
|
||||
const CMD: &str = SET;
|
||||
let mut out = f.clone();
|
||||
let Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } = &mut out else {
|
||||
return Err(bad(CMD, "not a gradient fill"));
|
||||
};
|
||||
let old_frame = frame_with_align(layer, f, canvas);
|
||||
let old_handles = gf::handles(*style, *angle, *scale, *offset, old_frame);
|
||||
if let Some(v) = p.get("align") {
|
||||
*align = v.as_bool().ok_or_else(|| bad(CMD, "`align` is a boolean"))?;
|
||||
}
|
||||
let new_style = style_param(CMD, p)?;
|
||||
let explicit_geometry = ["angle", "scale", "offset"].iter().any(|k| p.get(*k).is_some());
|
||||
if let Some(a) = p.get("angle") {
|
||||
*angle = a.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).ok_or_else(|| bad(CMD, "`angle` is a number (degrees)"))?.rem_euclid(360.0);
|
||||
if *angle > 180.0 {
|
||||
*angle -= 360.0;
|
||||
}
|
||||
}
|
||||
if p.get("scale").is_some() {
|
||||
let v = num(p, "scale").filter(|v| *v > 0.0).ok_or_else(|| bad(CMD, "`scale` is a positive percentage"))?;
|
||||
*scale = clamp_scale(v / 100.0);
|
||||
}
|
||||
if let Some(o) = p.get("offset") {
|
||||
let a = o.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(CMD, "`offset` is [x%, y%]"))?;
|
||||
let c = |i: usize| a.get(i).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite() && v.abs() <= 1.0e5);
|
||||
let (Some(x), Some(y)) = (c(0), c(1)) else { return Err(bad(CMD, "`offset` needs finite percentages")) };
|
||||
*offset = (x / 100.0, y / 100.0);
|
||||
}
|
||||
if let Some(v) = p.get("reverse") {
|
||||
*reverse = v.as_bool().ok_or_else(|| bad(CMD, "`reverse` is a boolean"))?;
|
||||
}
|
||||
if let Some(v) = p.get("dither") {
|
||||
*dither = v.as_bool().ok_or_else(|| bad(CMD, "`dither` is a boolean"))?;
|
||||
}
|
||||
let from = point(CMD, p, "from")?;
|
||||
let to = point(CMD, p, "to")?;
|
||||
let frame = {
|
||||
let tmp = Fill::Gradient {
|
||||
stops: Vec::new(),
|
||||
angle: *angle,
|
||||
scale: *scale,
|
||||
style: *style,
|
||||
reverse: *reverse,
|
||||
opacity_stops: Vec::new(),
|
||||
midpoints: Vec::new(),
|
||||
offset: *offset,
|
||||
dither: *dither,
|
||||
align: *align,
|
||||
};
|
||||
frame_with_align(layer, &tmp, canvas)
|
||||
};
|
||||
// A style change alone keeps the handles where they are (they are what the user placed).
|
||||
let style_changed = new_style.is_some_and(|ns| ns != *style);
|
||||
if let Some(ns) = new_style {
|
||||
*style = ns;
|
||||
}
|
||||
if from.is_some() || to.is_some() || (style_changed && !explicit_geometry) {
|
||||
let cur = if from.is_some() || to.is_some() { gf::handles(*style, *angle, *scale, *offset, frame) } else { old_handles };
|
||||
let (a, s, o) = gf::from_handles(*style, from.unwrap_or(cur.0), to.unwrap_or(cur.1), frame, *angle);
|
||||
(*angle, *scale, *offset) = (a, clamp_scale(s), o);
|
||||
}
|
||||
if let Some(v) = p.get("stops") {
|
||||
let arr = v.as_array().ok_or_else(|| bad(CMD, "`stops` is [[location, colour], …]"))?;
|
||||
let mut new = Vec::with_capacity(arr.len());
|
||||
for s in arr {
|
||||
let pair = s.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(CMD, "a stop is [location 0..1, colour]"))?;
|
||||
let t = pair.first().and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite()).ok_or_else(|| bad(CMD, "stop location is a number"))?;
|
||||
let c = pair
|
||||
.get(1)
|
||||
.and_then(|c| parse_color(c, fg, bg))
|
||||
.ok_or_else(|| bad(CMD, "stop colour is \"#rrggbb\", [r,g,b,a], \"foreground\" or \"background\""))?;
|
||||
new.push((t.clamp(0.0, 1.0), c));
|
||||
}
|
||||
if new.len() < 2 {
|
||||
return Err(bad(CMD, "a gradient needs at least 2 colour stops"));
|
||||
}
|
||||
if new.len() > 1024 {
|
||||
return Err(bad(CMD, "too many colour stops (max 1024)"));
|
||||
}
|
||||
new.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if new.len() != stops.len() {
|
||||
midpoints.clear();
|
||||
}
|
||||
*stops = new;
|
||||
}
|
||||
if let Some(v) = p.get("transparency") {
|
||||
let arr = v.as_array().ok_or_else(|| bad(CMD, "`transparency` is [[location, opacity %], …]"))?;
|
||||
let mut new = Vec::with_capacity(arr.len());
|
||||
for s in arr {
|
||||
let pair = s.as_array().filter(|a| a.len() == 2).ok_or_else(|| bad(CMD, "an opacity stop is [location 0..1, opacity 0..100]"))?;
|
||||
let f = |i: usize| pair.get(i).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite());
|
||||
let (Some(t), Some(o)) = (f(0), f(1)) else { return Err(bad(CMD, "opacity stops are numbers")) };
|
||||
new.push((t.clamp(0.0, 1.0), (o / 100.0).clamp(0.0, 1.0)));
|
||||
}
|
||||
if new.len() > 1024 {
|
||||
return Err(bad(CMD, "too many opacity stops (max 1024)"));
|
||||
}
|
||||
new.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
*opacity_stops = new;
|
||||
}
|
||||
if let Some(v) = p.get("midpoints") {
|
||||
let arr = v.as_array().ok_or_else(|| bad(CMD, "`midpoints` is [0..1, …] (one per segment)"))?;
|
||||
let mids: Option<Vec<f32>> = arr.iter().map(|m| m.as_f64().map(|v| v as f32).filter(|v| v.is_finite()).map(|v| v.clamp(0.05, 0.95))).collect();
|
||||
let mids = mids.ok_or_else(|| bad(CMD, "midpoints are numbers"))?;
|
||||
if mids.len() > stops.len().saturating_sub(1) {
|
||||
return Err(bad(CMD, format!("{} midpoints for {} segments", mids.len(), stops.len().saturating_sub(1))));
|
||||
}
|
||||
*midpoints = mids;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The Gradient Fill layer `gradient.fill.create` adds to `doc` for `p` (also the canvas's live
|
||||
/// preview of a Gradient tool drag): laid out on the canvas, so the handles land exactly where
|
||||
/// the drag was, and masked by the selection (Photoshop keeps the selection, as a mask).
|
||||
pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result<Layer> {
|
||||
const CMD: &str = CREATE;
|
||||
let from = point(CMD, p, "from")?.ok_or_else(|| bad(CMD, "missing `from` [x, y]"))?;
|
||||
let to = point(CMD, p, "to")?.ok_or_else(|| bad(CMD, "missing `to` [x, y]"))?;
|
||||
let style = style_param(CMD, p)?.unwrap_or_default();
|
||||
let g = preset_param(s, p, CMD)?;
|
||||
let (stops, opacity_stops) = g.fill_stops(s.tools.foreground, s.tools.background);
|
||||
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
|
||||
let dither = p.get("dither").and_then(Value::as_bool).unwrap_or(true);
|
||||
let opacity = num(p, "opacity").unwrap_or(100.0).clamp(0.0, 100.0) / 100.0;
|
||||
let blend = match p.get("mode").and_then(Value::as_str) {
|
||||
None | Some("") => photocraft_color::BlendMode::Normal,
|
||||
Some(m) => blend_from_str(m).ok_or_else(|| bad(CMD, format!("unknown blend mode `{m}`")))?,
|
||||
};
|
||||
let canvas = doc.bounds();
|
||||
if canvas.is_empty() {
|
||||
return Err(bad(CMD, "the document is empty"));
|
||||
}
|
||||
let (angle, scale, offset) = gf::from_handles(style, from, to, canvas, 0.0);
|
||||
let fill = Fill::Gradient { stops, angle, scale: clamp_scale(scale), style, reverse, opacity_stops, midpoints: Vec::new(), offset, dither, align: false };
|
||||
let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
|
||||
l.opacity = opacity;
|
||||
l.blend = blend;
|
||||
if let Some(sel) = &doc.selection {
|
||||
l.mask = Some(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() });
|
||||
}
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let layer = {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
new_layer(s, &d.doc, p)?
|
||||
};
|
||||
let id = s.edit("New Gradient Fill Layer", |doc, active| {
|
||||
let id = doc.insert_above(*active, layer);
|
||||
*active = Some(id);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "layer": id.0 }))
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, p)?;
|
||||
let (fill, _) = gradient_of(s, id, SET)?;
|
||||
let (fg, bg) = (s.tools.foreground, s.tools.background);
|
||||
let (layer, canvas) = {
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
(d.doc.layer(id).cloned().ok_or(EngineError::NoLayer(id))?, d.doc.bounds())
|
||||
};
|
||||
let new = apply_set(&layer, &fill, canvas, p, fg, bg)?;
|
||||
if new != fill {
|
||||
replace_fill(s, id, "Edit Gradient Fill", new)?;
|
||||
}
|
||||
describe(s, id)
|
||||
}
|
||||
|
||||
fn replace_fill(s: &mut Session, id: LayerId, label: &str, new: Fill) -> Result<()> {
|
||||
s.edit(label, |doc, _| {
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
l.content = LayerContent::Fill(new);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Sorted colour stops paired with the midpoint of the segment that follows each.
|
||||
fn paired(stops: &[(f32, Color)], mids: &[f32]) -> Vec<(f32, Color, f32)> {
|
||||
let mut v: Vec<(f32, Color, f32)> = stops.iter().enumerate().map(|(i, (t, c))| (*t, *c, mids.get(i).copied().unwrap_or(0.5))).collect();
|
||||
v.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
v
|
||||
}
|
||||
|
||||
fn unpair(v: Vec<(f32, Color, f32)>) -> (Vec<(f32, Color)>, Vec<f32>) {
|
||||
let mut v = v;
|
||||
v.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let n = v.len();
|
||||
let mids: Vec<f32> = v.iter().take(n.saturating_sub(1)).map(|s| s.2).collect();
|
||||
let mids = if mids.iter().all(|m| (m - 0.5).abs() < 1e-6) { Vec::new() } else { mids };
|
||||
(v.into_iter().map(|(t, c, _)| (t, c)).collect(), mids)
|
||||
}
|
||||
|
||||
/// Applies a `gradient.fill.stop` edit to a gradient fill. Pure (see [`apply_set`]).
|
||||
pub fn apply_stop(f: &Fill, p: &Value, fg: [f32; 4], bg: [f32; 4]) -> Result<Fill> {
|
||||
const CMD: &str = STOP;
|
||||
let mut out = f.clone();
|
||||
let Fill::Gradient { stops, opacity_stops, midpoints, .. } = &mut out else { return Err(bad(CMD, "not a gradient fill")) };
|
||||
let action = p.get("action").and_then(Value::as_str).ok_or_else(|| bad(CMD, "missing `action` (add|move|delete|color|opacity|midpoint)"))?;
|
||||
let opacity_kind = match p.get("kind").and_then(Value::as_str).unwrap_or("color") {
|
||||
"color" => false,
|
||||
"opacity" => true,
|
||||
o => return Err(bad(CMD, format!("unknown kind `{o}` (color|opacity)"))),
|
||||
};
|
||||
let index = || -> Result<usize> {
|
||||
p.get("index").and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad(CMD, "missing `index` (a stop number from 0)"))
|
||||
};
|
||||
let location = || num(p, "location").map(|v| v.clamp(0.0, 1.0)).ok_or_else(|| bad(CMD, "missing `location` (0..1)"));
|
||||
let ramp = gf::Ramp::new(f).ok_or_else(|| bad(CMD, "not a gradient fill"))?;
|
||||
if opacity_kind {
|
||||
// Opacity stops: an empty list means "opaque" (two 100 % stops when first edited).
|
||||
let mut os = opacity_stops.clone();
|
||||
if os.is_empty() {
|
||||
os = vec![(0.0, 1.0), (1.0, 1.0)];
|
||||
}
|
||||
os.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let opacity = || num(p, "opacity").map(|v| (v / 100.0).clamp(0.0, 1.0)).ok_or_else(|| bad(CMD, "missing `opacity` (0..100)"));
|
||||
match action {
|
||||
"add" => {
|
||||
let t = location()?;
|
||||
let a = num(p, "opacity").map_or_else(|| ramp.sample(t)[3] / ramp_color_alpha(f, t), |v| (v / 100.0).clamp(0.0, 1.0));
|
||||
os.push((t, a.clamp(0.0, 1.0)));
|
||||
}
|
||||
"move" => {
|
||||
let i = index()?;
|
||||
let t = location()?;
|
||||
os.get_mut(i).ok_or_else(|| bad(CMD, format!("no opacity stop {i}")))?.0 = t;
|
||||
}
|
||||
"delete" => {
|
||||
let i = index()?;
|
||||
if i >= os.len() {
|
||||
return Err(bad(CMD, format!("no opacity stop {i}")));
|
||||
}
|
||||
if os.len() <= 2 {
|
||||
return Err(bad(CMD, "a gradient keeps at least 2 opacity stops"));
|
||||
}
|
||||
os.remove(i);
|
||||
}
|
||||
"opacity" => {
|
||||
let i = index()?;
|
||||
let a = opacity()?;
|
||||
os.get_mut(i).ok_or_else(|| bad(CMD, format!("no opacity stop {i}")))?.1 = a;
|
||||
}
|
||||
o => return Err(bad(CMD, format!("unknown action `{o}` for opacity stops (add|move|delete|opacity)"))),
|
||||
}
|
||||
os.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if os.len() > 1024 {
|
||||
return Err(bad(CMD, "too many opacity stops (max 1024)"));
|
||||
}
|
||||
*opacity_stops = os;
|
||||
return Ok(out);
|
||||
}
|
||||
let mut v = paired(stops, midpoints);
|
||||
match action {
|
||||
"add" => {
|
||||
let t = location()?;
|
||||
// A new stop takes the colour the gradient has there (Photoshop), unless given.
|
||||
let c = match p.get("color") {
|
||||
Some(c) => parse_color(c, fg, bg).ok_or_else(|| bad(CMD, "bad `color`"))?,
|
||||
None => {
|
||||
let s = ramp.sample(t);
|
||||
Color::rgba(s[0], s[1], s[2], ramp_color_alpha(f, t))
|
||||
}
|
||||
};
|
||||
// Splitting a segment resets its midpoint.
|
||||
if let Some(prev) = v.iter_mut().rev().find(|s| s.0 <= t) {
|
||||
prev.2 = 0.5;
|
||||
}
|
||||
v.push((t, c, 0.5));
|
||||
if v.len() > 1024 {
|
||||
return Err(bad(CMD, "too many colour stops (max 1024)"));
|
||||
}
|
||||
}
|
||||
"move" => {
|
||||
let i = index()?;
|
||||
let t = location()?;
|
||||
v.get_mut(i).ok_or_else(|| bad(CMD, format!("no colour stop {i}")))?.0 = t;
|
||||
}
|
||||
"delete" => {
|
||||
let i = index()?;
|
||||
if i >= v.len() {
|
||||
return Err(bad(CMD, format!("no colour stop {i}")));
|
||||
}
|
||||
if v.len() <= 2 {
|
||||
return Err(bad(CMD, "a gradient keeps at least 2 colour stops"));
|
||||
}
|
||||
v.remove(i);
|
||||
}
|
||||
"color" => {
|
||||
let i = index()?;
|
||||
let c = p.get("color").and_then(|c| parse_color(c, fg, bg)).ok_or_else(|| bad(CMD, "missing or bad `color`"))?;
|
||||
v.get_mut(i).ok_or_else(|| bad(CMD, format!("no colour stop {i}")))?.1 = c;
|
||||
}
|
||||
"midpoint" => {
|
||||
let i = index()?;
|
||||
let m = num(p, "location").ok_or_else(|| bad(CMD, "missing `location` (0..1 of the segment)"))?.clamp(0.05, 0.95);
|
||||
if i + 1 >= v.len() {
|
||||
return Err(bad(CMD, format!("no segment {i} (there are {})", v.len().saturating_sub(1))));
|
||||
}
|
||||
if let Some(s) = v.get_mut(i) {
|
||||
s.2 = m;
|
||||
}
|
||||
}
|
||||
o => return Err(bad(CMD, format!("unknown action `{o}` (add|move|delete|color|midpoint)"))),
|
||||
}
|
||||
let (st, mids) = unpair(v);
|
||||
*stops = st;
|
||||
*midpoints = mids;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The colour stops' own alpha at `t` (without the opacity stops).
|
||||
fn ramp_color_alpha(f: &Fill, t: f32) -> f32 {
|
||||
let Fill::Gradient { stops, midpoints, .. } = f else { return 1.0 };
|
||||
let bare = Fill::Gradient {
|
||||
stops: stops.clone(),
|
||||
angle: 0.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Linear,
|
||||
reverse: false,
|
||||
opacity_stops: Vec::new(),
|
||||
midpoints: midpoints.clone(),
|
||||
offset: (0.0, 0.0),
|
||||
dither: false,
|
||||
align: true,
|
||||
};
|
||||
gf::Ramp::new(&bare).map_or(1.0, |r| r.sample(t)[3]).max(1e-6)
|
||||
}
|
||||
|
||||
fn stop(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, p)?;
|
||||
let (fill, _) = gradient_of(s, id, STOP)?;
|
||||
let new = apply_stop(&fill, p, s.tools.foreground, s.tools.background)?;
|
||||
if new != fill {
|
||||
replace_fill(s, id, "Edit Gradient Fill", new)?;
|
||||
}
|
||||
describe(s, id)
|
||||
}
|
||||
|
||||
/// A gradient fill layer's settings as JSON (`gradient.fill.get`).
|
||||
pub fn describe_fill(f: &Fill, frame: Rect) -> Value {
|
||||
let Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } = f else { return Value::Null };
|
||||
let (from, to) = gf::handles(*style, *angle, *scale, *offset, frame);
|
||||
json!({
|
||||
"style": style_name(*style),
|
||||
"angle": angle,
|
||||
"scale": scale * 100.0,
|
||||
"offset": [offset.0 * 100.0, offset.1 * 100.0],
|
||||
"reverse": reverse,
|
||||
"dither": dither,
|
||||
"align": align,
|
||||
"from": from,
|
||||
"to": to,
|
||||
"stops": stops.iter().map(|(t, c)| json!([t, hex(c)])).collect::<Vec<_>>(),
|
||||
"transparency": opacity_stops.iter().map(|(t, a)| json!([t, a * 100.0])).collect::<Vec<_>>(),
|
||||
"midpoints": midpoints,
|
||||
})
|
||||
}
|
||||
|
||||
fn describe(s: &Session, id: LayerId) -> Result<Value> {
|
||||
let (f, frame) = gradient_of(s, id, GET)?;
|
||||
let mut v = describe_fill(&f, frame);
|
||||
v["layer"] = json!(id.0);
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, p)?;
|
||||
describe(s, id)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
CommandSpec {
|
||||
id: CREATE,
|
||||
label: "Gradient (Live)",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"from":[x,y],"to":[x,y],"style":"linear|radial|angle|reflected|diamond"="linear","gradient":preset name?,"stops":[[t,"#rrggbb"|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]? (default: the current gradient),"reverse":bool=false,"dither":bool=true,"opacity":0..100=100,"mode":"normal|multiply|…"="normal"} → {"layer":id}; a Gradient Fill layer above the active layer, masked by the selection"##,
|
||||
enabled: has_doc,
|
||||
run: create,
|
||||
journal: true,
|
||||
},
|
||||
CommandSpec {
|
||||
id: SET,
|
||||
label: "Edit Gradient Fill",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"layer":id?,"from":[x,y]?,"to":[x,y]?,"style":"linear|radial|angle|reflected|diamond"?,"angle":deg?,"scale":%?,"offset":[x%,y%]?,"reverse":bool?,"dither":bool?,"align":bool?,"stops":[[t,"#rrggbb"|"#rrggbbaa"|[r,g,b,a]|"foreground"|"background"],…]?,"transparency":[[t,0..100],…]?,"midpoints":[0.05..0.95 per segment]?} → the gradient (see gradient.fill.get)"##,
|
||||
enabled: has_gradient_fill,
|
||||
run: set,
|
||||
journal: true,
|
||||
},
|
||||
CommandSpec {
|
||||
id: STOP,
|
||||
label: "Edit Gradient Stop",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"layer":id?,"action":"add|move|delete|color|opacity|midpoint","kind":"color|opacity"="color","index":stop (midpoint: segment) number,"location":0..1 (midpoint: of the segment),"color":"#rrggbb"|[r,g,b,a]|"foreground"|"background" (add: default the colour there),"opacity":0..100} → the gradient"##,
|
||||
enabled: has_gradient_fill,
|
||||
run: stop,
|
||||
journal: true,
|
||||
},
|
||||
CommandSpec {
|
||||
id: GET,
|
||||
label: "Gradient Fill Settings",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"layer":id?} → {"style","angle","scale":%,"offset":[%,%],"reverse","dither","align","from":[x,y],"to":[x,y],"stops":[[t,"#hex"]],"transparency":[[t,%]],"midpoints":[…]}"##,
|
||||
enabled: has_gradient_fill,
|
||||
run: get,
|
||||
journal: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,283 @@
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
fn session(depth: u32, background: &str) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 48, "height": 32, "depth": depth, "background": background})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn active_fill(s: &Session) -> Fill {
|
||||
let d = s.active().unwrap();
|
||||
match &d.doc.layer(d.active_layer.unwrap()).unwrap().content {
|
||||
LayerContent::Fill(f) => f.clone(),
|
||||
other => panic!("not a fill layer: {}", other.kind_name()),
|
||||
}
|
||||
}
|
||||
|
||||
fn layer_count(s: &Session) -> usize {
|
||||
s.active().unwrap().doc.layers.len()
|
||||
}
|
||||
|
||||
const STYLES: [&str; 5] = ["linear", "radial", "angle", "reflected", "diamond"];
|
||||
|
||||
#[test]
|
||||
fn create_makes_a_canvas_aligned_fill_layer_with_the_drag_as_handles() {
|
||||
let mut s = session(8, "white");
|
||||
let r = s
|
||||
.execute(
|
||||
CREATE,
|
||||
json!({"from": [14, 16], "to": [34, 8], "style": "radial", "stops": [[0, "#ff0000"], [1, "#0000ff"]], "opacity": 50, "mode": "multiply"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(layer_count(&s), 2);
|
||||
let d = s.active().unwrap();
|
||||
let l = d.doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap();
|
||||
assert_eq!(d.active_layer, Some(l.id));
|
||||
assert!(l.mask.is_none(), "no selection, no mask");
|
||||
assert_eq!(l.opacity, 0.5);
|
||||
assert_eq!(l.blend, photocraft_color::BlendMode::Multiply);
|
||||
let Fill::Gradient { style, align, dither, .. } = active_fill(&s) else { panic!() };
|
||||
assert_eq!(style, GradientStyle::Radial);
|
||||
assert!(!align && dither);
|
||||
let g = s.execute(GET, json!({})).unwrap();
|
||||
let (from, to) = (g["from"].as_array().unwrap(), g["to"].as_array().unwrap());
|
||||
for (v, want) in from.iter().chain(to).zip([14.0, 16.0, 34.0, 8.0]) {
|
||||
assert!((v.as_f64().unwrap() - want).abs() < 1e-3, "{g}");
|
||||
}
|
||||
// One undo step removes the layer.
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(layer_count(&s), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_masks_the_layer_with_the_selection() {
|
||||
let mut s = session(8, "white");
|
||||
s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 8})).unwrap();
|
||||
s.execute(CREATE, json!({"from": [0, 0], "to": [48, 0]})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
|
||||
let m = l.mask.as_ref().expect("selection becomes the mask");
|
||||
assert_eq!(m.value(5, 5), 1.0);
|
||||
assert_eq!(m.value(30, 20), 0.0);
|
||||
// Still laid out on the canvas, not the mask's bounds.
|
||||
assert_eq!(photocraft_compose::fill_frame(l, d.doc.bounds()), d.doc.bounds());
|
||||
// The composite outside the selection is the white background.
|
||||
let flat = photocraft_compose::flatten(&d.doc);
|
||||
assert_eq!(flat.px[20 * 48 + 30], [1.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
/// Pixel parity: a live gradient composites exactly like painting the same drag.
|
||||
fn parity(depth: u32, background: &str, extra: Value, select: bool, tol: f32) {
|
||||
for style in STYLES {
|
||||
for (from, to) in [([10.0, 9.0], [34.0, 22.0]), ([30.0, 16.0], [22.0, 3.0])] {
|
||||
let mut p = json!({"from": from, "to": to, "style": style});
|
||||
for (k, v) in extra.as_object().unwrap() {
|
||||
p[k] = v.clone();
|
||||
}
|
||||
let run = |live: bool| {
|
||||
let mut s = session(depth, background);
|
||||
if background != "transparent" {
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
}
|
||||
if select {
|
||||
s.execute("select.rect", json!({"x": 6, "y": 3, "width": 30, "height": 22, "ellipse": true, "antiAlias": true})).unwrap();
|
||||
}
|
||||
// Linear and Reflected fill layers sample each pixel's top-left corner
|
||||
// (compose::effects::gradient_t, fitted on Photoshop's fills); the painted
|
||||
// gradient samples centres, so its drag is half a pixel further along.
|
||||
let mut p = p.clone();
|
||||
if !live && matches!(style, "linear" | "reflected") {
|
||||
p["from"] = json!([from[0] + 0.5, from[1] + 0.5]);
|
||||
p["to"] = json!([to[0] + 0.5, to[1] + 0.5]);
|
||||
}
|
||||
s.execute(if live { CREATE } else { "paint.gradient" }, p).unwrap();
|
||||
photocraft_compose::flatten(&s.active().unwrap().doc)
|
||||
};
|
||||
let (classic, live) = (run(false), run(true));
|
||||
let mut worst = 0.0f32;
|
||||
for (a, b) in classic.px.iter().zip(&live.px) {
|
||||
for c in 0..4 {
|
||||
worst = worst.max((a[c] * a[3] - b[c] * b[3]).abs());
|
||||
}
|
||||
}
|
||||
assert!(worst <= tol, "{style} {from:?}->{to:?} {extra} select={select} depth={depth}: worst {worst}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_gradient_renders_like_the_classic_gradient() {
|
||||
let stops = json!({"stops": [[0, "#ff2000"], [0.4, "#20c040"], [1, "#1010e0"]], "dither": false});
|
||||
parity(32, "transparent", stops.clone(), false, 1e-4);
|
||||
parity(8, "transparent", stops.clone(), false, 0.51 / 255.0);
|
||||
parity(8, "white", json!({"stops": [[0, "#ff2000"], [1, "#1010e0"]], "reverse": true, "dither": true}), true, 1.01 / 255.0);
|
||||
parity(16, "transparent", json!({"gradient": "Foreground to Transparent", "dither": true}), false, 1.01 / 255.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_moves_handles_and_restyles_in_one_undo_step() {
|
||||
let mut s = session(8, "white");
|
||||
s.execute(CREATE, json!({"from": [4, 4], "to": [40, 4]})).unwrap();
|
||||
let before = active_fill(&s);
|
||||
let h0 = s.active().unwrap().history.past_len();
|
||||
let g = s.execute(SET, json!({"to": [20, 22]})).unwrap();
|
||||
assert!((g["to"][0].as_f64().unwrap() - 20.0).abs() < 1e-3 && (g["from"][0].as_f64().unwrap() - 4.0).abs() < 1e-3, "{g}");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), h0 + 1);
|
||||
// Changing the style alone keeps the handles where they are.
|
||||
let g = s.execute(SET, json!({"style": "angle"})).unwrap();
|
||||
assert_eq!(g["style"], "angle");
|
||||
assert!((g["to"][1].as_f64().unwrap() - 22.0).abs() < 1e-3, "{g}");
|
||||
let g = s.execute(SET, json!({"angle": 45, "scale": 80, "offset": [10, -5], "reverse": true, "dither": false, "midpoints": [0.3]})).unwrap();
|
||||
assert_eq!(g["angle"], 45.0);
|
||||
assert!((g["scale"].as_f64().unwrap() - 80.0).abs() < 1e-3);
|
||||
assert_eq!(g["reverse"], true);
|
||||
// Each edit is one step: three undos restore the original.
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
}
|
||||
assert_eq!(active_fill(&s), before);
|
||||
// A no-op set adds no history.
|
||||
let h = s.active().unwrap().history.past_len();
|
||||
s.execute(SET, json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len(), h);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_add_move_recolour_delete_and_midpoints() {
|
||||
let mut s = session(8, "white");
|
||||
s.execute(CREATE, json!({"from": [0, 0], "to": [48, 0], "stops": [[0, "#000000"], [1, "#ffffff"]], "dither": false})).unwrap();
|
||||
let stops = |s: &Session| match active_fill(s) {
|
||||
Fill::Gradient { stops, midpoints, opacity_stops, .. } => (stops, midpoints, opacity_stops),
|
||||
_ => panic!("not a gradient fill"),
|
||||
};
|
||||
// Add: the new stop takes the colour the gradient has there.
|
||||
let g = s.execute(STOP, json!({"action": "add", "location": 0.5})).unwrap();
|
||||
assert_eq!(g["stops"].as_array().unwrap().len(), 3);
|
||||
let (st, _, _) = stops(&s);
|
||||
assert!((st[1].1.c[0] - 0.5).abs() < 1e-3);
|
||||
s.execute(STOP, json!({"action": "color", "index": 1, "color": "#ff0000"})).unwrap();
|
||||
assert_eq!(stops(&s).0[1].1.to_rgb(), [1.0, 0.0, 0.0]);
|
||||
s.execute(STOP, json!({"action": "midpoint", "index": 0, "location": 0.25})).unwrap();
|
||||
assert_eq!(stops(&s).1, vec![0.25, 0.5]);
|
||||
// Moving a stop past another re-sorts them (the midpoint travels with its stop).
|
||||
s.execute(STOP, json!({"action": "move", "index": 0, "location": 0.75})).unwrap();
|
||||
let (st, mids, _) = stops(&s);
|
||||
assert_eq!(st.iter().map(|x| x.0).collect::<Vec<_>>(), vec![0.5, 0.75, 1.0]);
|
||||
assert_eq!(mids, vec![0.5, 0.25]);
|
||||
s.execute(STOP, json!({"action": "delete", "index": 2})).unwrap();
|
||||
assert_eq!(stops(&s).0.len(), 2);
|
||||
assert!(s.execute(STOP, json!({"action": "delete", "index": 0})).is_err(), "keeps 2 stops");
|
||||
// Opacity stops start from an opaque pair.
|
||||
s.execute(STOP, json!({"action": "opacity", "kind": "opacity", "index": 1, "opacity": 25})).unwrap();
|
||||
assert_eq!(stops(&s).2, vec![(0.0, 1.0), (1.0, 0.25)]);
|
||||
s.execute(STOP, json!({"action": "add", "kind": "opacity", "location": 0.5})).unwrap();
|
||||
assert!((stops(&s).2[1].1 - 0.625).abs() < 1e-4);
|
||||
// Each edit is one undo step.
|
||||
let n = s.active().unwrap().history.past_len();
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(s.active().unwrap().history.past_len() + 1, n);
|
||||
assert_eq!(stops(&s).2.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_equals_the_committed_edit() {
|
||||
let mut s = session(8, "white");
|
||||
s.execute(CREATE, json!({"from": [4, 4], "to": [40, 20], "style": "diamond"})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
let l = d.doc.layer(d.active_layer.unwrap()).unwrap().clone();
|
||||
let LayerContent::Fill(f) = &l.content else { panic!() };
|
||||
let p = json!({"from": [10, 12], "to": [30, 2]});
|
||||
let preview = apply_set(&l, f, d.doc.bounds(), &p, [0.0; 4], [1.0; 4]).unwrap();
|
||||
s.execute(SET, p).unwrap();
|
||||
assert_eq!(active_fill(&s), preview);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_gradient_still_paints_pixels() {
|
||||
let mut s = session(8, "white");
|
||||
s.execute("paint.gradient", json!({"from": [0, 0], "to": [48, 0], "colors": ["#000000", "#ffffff"], "dither": false})).unwrap();
|
||||
assert_eq!(layer_count(&s), 1, "no fill layer");
|
||||
let d = s.active().unwrap();
|
||||
let px = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(1, 5);
|
||||
assert!(px[0] < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands_fail_gracefully() {
|
||||
let mut empty = Session::new();
|
||||
for id in [CREATE, SET, STOP, GET] {
|
||||
assert!(empty.execute(id, json!({"from": [0, 0], "to": [1, 1]})).is_err(), "{id} without a document");
|
||||
}
|
||||
let mut s = session(8, "white");
|
||||
// Not a gradient fill layer.
|
||||
for id in [SET, STOP, GET] {
|
||||
assert!(s.execute(id, json!({})).is_err(), "{id} on a pixel layer");
|
||||
}
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"from": [0, 0]}),
|
||||
json!({"from": [0], "to": [1, 1]}),
|
||||
json!({"from": [f64::MAX, 0], "to": [1, 1]}),
|
||||
json!({"from": ["a", 0], "to": [1, 1]}),
|
||||
json!({"from": [0, 0], "to": [1, 1], "style": "spiral"}),
|
||||
json!({"from": [0, 0], "to": [1, 1], "style": 3}),
|
||||
json!({"from": [0, 0], "to": [1, 1], "gradient": "No Such Preset"}),
|
||||
json!({"from": [0, 0], "to": [1, 1], "stops": []}),
|
||||
json!({"from": [0, 0], "to": [1, 1], "mode": "nonsense"}),
|
||||
] {
|
||||
assert!(s.execute(CREATE, p.clone()).is_err(), "create {p}");
|
||||
}
|
||||
// A zero-length drag still makes a valid gradient.
|
||||
s.execute(CREATE, json!({"from": [3, 3], "to": [3, 3]})).unwrap();
|
||||
for p in [
|
||||
json!({"layer": 999_999}),
|
||||
json!({"from": [0]}),
|
||||
json!({"to": [1e30, 0]}),
|
||||
json!({"angle": "x"}),
|
||||
json!({"scale": 0}),
|
||||
json!({"scale": -5}),
|
||||
json!({"offset": [1]}),
|
||||
json!({"offset": ["a", "b"]}),
|
||||
json!({"reverse": 1}),
|
||||
json!({"stops": [[0, "#000000"]]}),
|
||||
json!({"stops": [[0, "#zzzzzz"], [1, "#ffffff"]]}),
|
||||
json!({"stops": [[0, [1, 2]], [1, "#ffffff"]]}),
|
||||
json!({"stops": "x"}),
|
||||
json!({"transparency": [[0]]}),
|
||||
json!({"midpoints": [0.5, 0.5, 0.5]}),
|
||||
json!({"midpoints": ["x"]}),
|
||||
json!({"style": "spiral"}),
|
||||
json!({"align": "no"}),
|
||||
] {
|
||||
assert!(s.execute(SET, p.clone()).is_err(), "set {p}");
|
||||
}
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"action": "explode"}),
|
||||
json!({"action": "add"}),
|
||||
json!({"action": "move", "index": 99, "location": 0.5}),
|
||||
json!({"action": "delete", "index": 99}),
|
||||
json!({"action": "color", "index": 0}),
|
||||
json!({"action": "color", "index": 0, "color": 7}),
|
||||
json!({"action": "midpoint", "index": 1, "location": 0.5}),
|
||||
json!({"action": "midpoint", "index": 0}),
|
||||
json!({"action": "add", "kind": "sparkle", "location": 0.5}),
|
||||
json!({"action": "color", "kind": "opacity", "index": 0}),
|
||||
json!({"action": "opacity", "kind": "opacity", "index": 7, "opacity": 3}),
|
||||
json!({"action": "delete", "kind": "opacity", "index": 0}),
|
||||
json!({"action": "move", "index": -1, "location": 0.5}),
|
||||
] {
|
||||
assert!(s.execute(STOP, p.clone()).is_err(), "stop {p}");
|
||||
}
|
||||
// Huge-but-finite values clamp instead of failing.
|
||||
s.execute(SET, json!({"scale": 1e30, "angle": 1e9, "offset": [1e4, -1e4]})).unwrap();
|
||||
let g = s.execute(GET, json!({})).unwrap();
|
||||
assert!(g["scale"].as_f64().unwrap().is_finite() && g["from"][0].as_f64().unwrap().is_finite());
|
||||
// Scale stays within Photoshop's 10–150 %, also for a handle dragged far away.
|
||||
assert!((g["scale"].as_f64().unwrap() - 150.0).abs() < 1e-3, "{g}");
|
||||
let g = s.execute(SET, json!({"from": [0, 0], "to": [1e6, 0]})).unwrap();
|
||||
assert!((g["scale"].as_f64().unwrap() - 150.0).abs() < 1e-3, "{g}");
|
||||
let g = s.execute(SET, json!({"scale": 1})).unwrap();
|
||||
assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{g}");
|
||||
}
|
||||
@@ -33,6 +33,7 @@ pub mod filters_ext;
|
||||
mod frame_cmds;
|
||||
pub mod fx_view_cmds;
|
||||
pub mod gallery_cmds;
|
||||
pub mod gradient_fill_cmds;
|
||||
pub mod group_view_cmds;
|
||||
pub mod image_cmds;
|
||||
pub mod inspect;
|
||||
|
||||
@@ -122,6 +122,27 @@ impl GradientPreset {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Colour stops (live colours resolved now, sorted, opaque) and opacity stops (sorted; empty
|
||||
/// when fully opaque) kept apart, as an editable Gradient Fill layer holds them.
|
||||
pub fn fill_stops(&self, fg: [f32; 4], bg: [f32; 4]) -> FillStops {
|
||||
let rgb = |c: StopColor| match c {
|
||||
StopColor::Foreground => Color::rgb(fg[0], fg[1], fg[2]),
|
||||
StopColor::Background => Color::rgb(bg[0], bg[1], bg[2]),
|
||||
StopColor::Rgb(c) => Color::rgb(c[0], c[1], c[2]),
|
||||
};
|
||||
let mut cs: Vec<(f32, Color)> = self.stops.iter().map(|(t, c)| (t.clamp(0.0, 1.0), rgb(*c))).collect();
|
||||
cs.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if cs.is_empty() {
|
||||
cs = vec![(0.0, rgb(StopColor::Foreground)), (1.0, rgb(StopColor::Background))];
|
||||
}
|
||||
let mut os: Vec<(f32, f32)> = self.opacity.iter().map(|(t, a)| (t.clamp(0.0, 1.0), a.clamp(0.0, 1.0))).collect();
|
||||
os.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) {
|
||||
os.clear();
|
||||
}
|
||||
(cs, os)
|
||||
}
|
||||
|
||||
/// Stops for a Gradient Fill layer / overlay (live colours resolved now, like Photoshop).
|
||||
pub fn doc_stops(&self, fg: [f32; 4], bg: [f32; 4]) -> Vec<(f32, Color)> {
|
||||
self.resolve(fg, bg).into_iter().map(|(t, c)| (t, Color::rgba(c[0], c[1], c[2], c[3]))).collect()
|
||||
@@ -307,6 +328,9 @@ pub fn builtin() -> Vec<Group<GradientPreset>> {
|
||||
/// RGBA stops `(location, colour)` ready to paint.
|
||||
pub type Stops = Vec<(f32, [f32; 4])>;
|
||||
|
||||
/// Colour stops and opacity stops of a Gradient Fill layer.
|
||||
pub type FillStops = (Vec<(f32, Color)>, Vec<(f32, f32)>);
|
||||
|
||||
const CMD_SELECT: &str = "gradient.presets.select";
|
||||
|
||||
/// Gradient for the Gradient tool: `"gradient": preset name`, else explicit `"stops"`, else the
|
||||
@@ -361,12 +385,14 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true)
|
||||
&& let Some(id) = active_gradient_fill(s)
|
||||
{
|
||||
let stops_new = g.doc_stops(s.tools.foreground, s.tools.background);
|
||||
let (stops_new, opacity_new) = g.fill_stops(s.tools.foreground, s.tools.background);
|
||||
s.edit("Change Gradient Fill", |doc, _| {
|
||||
if let Some(l) = doc.layer_mut(id)
|
||||
&& let LayerContent::Fill(Fill::Gradient { stops, .. }) = &mut l.content
|
||||
&& let LayerContent::Fill(Fill::Gradient { stops, opacity_stops, midpoints, .. }) = &mut l.content
|
||||
{
|
||||
*stops = stops_new;
|
||||
*opacity_stops = opacity_new;
|
||||
midpoints.clear();
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -384,7 +410,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
|
||||
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
|
||||
let id = s.edit("New Gradient Fill Layer", |doc, active| {
|
||||
let fill = Fill::Gradient { stops, angle, scale, style, reverse };
|
||||
let fill = Fill::gradient(stops, angle, scale, style, reverse);
|
||||
let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)));
|
||||
*active = Some(id);
|
||||
Ok(id)
|
||||
|
||||
@@ -187,7 +187,7 @@ pub fn path_json(p: &Path) -> Value {
|
||||
fn fill_json(f: &Fill) -> Value {
|
||||
match f {
|
||||
Fill::Solid(c) => json!(hex(c)),
|
||||
Fill::Gradient { stops, angle, scale, style, reverse } => json!({ "gradient": {
|
||||
Fill::Gradient { stops, angle, scale, style, reverse, .. } => json!({ "gradient": {
|
||||
"stops": stops.iter().map(|(t, c)| json!([t, hex(c)])).collect::<Vec<_>>(),
|
||||
"angle": angle, "scale": scale * 100.0, "style": format!("{style:?}").to_ascii_lowercase(), "reverse": reverse } }),
|
||||
Fill::Pattern { name, scale, .. } => json!({ "pattern": name, "scale": scale * 100.0 }),
|
||||
@@ -216,13 +216,13 @@ fn parse_fill(v: &Value) -> std::result::Result<Option<Fill>, String> {
|
||||
"diamond" => GradientStyle::Diamond,
|
||||
_ => GradientStyle::Linear,
|
||||
};
|
||||
return Ok(Some(Fill::Gradient {
|
||||
return Ok(Some(Fill::gradient(
|
||||
stops,
|
||||
angle: f64p(g, "angle").unwrap_or(90.0) as f32,
|
||||
scale: f64p(g, "scale").unwrap_or(100.0) as f32 / 100.0,
|
||||
f64p(g, "angle").unwrap_or(90.0) as f32,
|
||||
f64p(g, "scale").unwrap_or(100.0) as f32 / 100.0,
|
||||
style,
|
||||
reverse: g.get("reverse").and_then(Value::as_bool).unwrap_or(false),
|
||||
}));
|
||||
g.get("reverse").and_then(Value::as_bool).unwrap_or(false),
|
||||
)));
|
||||
}
|
||||
if let Some(name) = v.get("pattern").and_then(Value::as_str) {
|
||||
return Ok(Some(Fill::Pattern {
|
||||
|
||||
@@ -103,6 +103,11 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {
|
||||
scale: 1.5,
|
||||
style: GradientStyle::default(),
|
||||
reverse: true,
|
||||
opacity_stops: vec![(0.0, 1.0), (1.0, 0.25)],
|
||||
midpoints: vec![0.3],
|
||||
offset: (0.1, -0.2),
|
||||
dither: true,
|
||||
align: false,
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -620,10 +620,24 @@ fn gradient_t(d: vec2<i32>) -> f32 {
|
||||
return t;
|
||||
}
|
||||
|
||||
// photocraft_color::dither_noise: the gradient dither's position hash, in [0, 1).
|
||||
fn dither_noise(d: vec2<i32>) -> f32 {
|
||||
var h = (bitcast<u32>(d.x) * 0x9E3779B1u) ^ (bitcast<u32>(d.y) * 0x85EBCA77u);
|
||||
h = h ^ (h >> 15u);
|
||||
h = h * 0x2C1B3C6Du;
|
||||
h = h ^ (h >> 12u);
|
||||
return f32(h & 0xFFFFu) / 65535.0;
|
||||
}
|
||||
|
||||
fn layer_texel(d: vec2<i32>) -> vec4<f32> {
|
||||
if ((op.flags & F_GRADIENT) != 0u) {
|
||||
let t = gradient_t(d);
|
||||
return vec4(lut(0, t), lut(1, t), lut(2, t), lut(3, t));
|
||||
var c = vec4(lut(0, t), lut(1, t), lut(2, t), lut(3, t));
|
||||
// p2.w: dither (gradient fills).
|
||||
if (op.p2.w > 0.5) {
|
||||
c = vec4(clamp(c.rgb + (dither_noise(d) - 0.5) / 255.0, vec3(0.0), vec3(1.0)), c.a);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
if ((op.flags & F_TEX) != 0u) {
|
||||
let q = d - op.tex_origin;
|
||||
|
||||
+54
-13
@@ -315,7 +315,10 @@ pub fn plan(doc: &Document) -> Result<Plan<'_>, Unsupported> {
|
||||
}
|
||||
let mut p = Planner::new(DocCtx::of(doc));
|
||||
let root = p.clear();
|
||||
let root = p.stack(&doc.layers, root)?;
|
||||
// Start at the topmost layer that hides everything beneath it (an opaque fill layer): the
|
||||
// layers below can't change the result, so they cost no passes or uploads.
|
||||
let start = doc.layers.iter().rposition(|l| photocraft_compose::occludes_below(l, doc.mode)).unwrap_or(0);
|
||||
let root = p.stack(doc.layers.get(start..).unwrap_or(&doc.layers), root)?;
|
||||
Ok(p.finish(root))
|
||||
}
|
||||
|
||||
@@ -805,25 +808,19 @@ impl<'a> Planner<'a> {
|
||||
let rgb = c.to_rgb();
|
||||
p.color = [rgb[0], rgb[1], rgb[2], c.alpha];
|
||||
}
|
||||
Fill::Gradient { stops, angle, scale, style, reverse } => {
|
||||
Fill::Gradient { angle, scale, style, reverse, offset, dither, .. } => {
|
||||
p.gradient = true;
|
||||
// compose::render_fill: whole-pixel end points (fill_layout).
|
||||
let (angle, scale, offset) = photocraft_compose::fill_layout::fill_gradient_layout(*style, *angle, *scale, frame);
|
||||
let (angle, scale, offset) = photocraft_compose::fill_layout::gradient_layout(*style, *angle, *scale, *offset, frame);
|
||||
p.params[0] = [angle, scale, if *reverse { 1.0 } else { 0.0 }, style_index(*style)];
|
||||
let c = frame;
|
||||
p.params[1] = [c.x0 as f32, c.y0 as f32, c.width() as f32, c.height() as f32];
|
||||
p.params[2][0] = offset.0;
|
||||
p.params[2][1] = offset.1;
|
||||
let conv: Vec<(f32, [f32; 4])> = stops
|
||||
.iter()
|
||||
.map(|(t, c)| {
|
||||
let r = c.to_rgb();
|
||||
(*t, [r[0], r[1], r[2], c.alpha])
|
||||
})
|
||||
.collect();
|
||||
// p2.xy: centre offset; p2.w: dither (the shared position hash, see the shader).
|
||||
p.params[2] = [offset.0, offset.1, 0.0, if *dither { 1.0 } else { 0.0 }];
|
||||
let ramp = photocraft_compose::gradient_fill::Ramp::new(f);
|
||||
let mut rows = vec![[0.0f32; 4096]; 4];
|
||||
for k in 0..4096 {
|
||||
let v = sample_stops4(&conv, k as f32 / 4095.0);
|
||||
let v = ramp.as_ref().map_or([0.0; 4], |r| r.sample(k as f32 / 4095.0));
|
||||
for (ch, row) in rows.iter_mut().enumerate() {
|
||||
row[k] = v[ch];
|
||||
}
|
||||
@@ -1638,6 +1635,50 @@ mod tests {
|
||||
assert!(p.slots <= 6, "{} slots", p.slots);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_fill_layers_skip_what_they_cover() {
|
||||
let opaque = || Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 30.0, 1.0, photocraft_doc::GradientStyle::Linear, false);
|
||||
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
for i in 0..4 {
|
||||
// Small painted layers (empty ones plan no passes at all).
|
||||
let mut l = Layer::raster(format!("l{i}"), d.pixel_format());
|
||||
l.surface_mut().unwrap().fill_rect(Rect::new(i, i, i + 2, i + 2), &[0.0, 0.0, 1.0, 1.0]);
|
||||
d.layers.push(l);
|
||||
}
|
||||
d.layers.push(Layer::new("g", LayerContent::Fill(opaque())));
|
||||
let mut top = Layer::raster("top", d.pixel_format());
|
||||
top.clipped = true;
|
||||
d.layers.push(top);
|
||||
// Clear, then the fill and its clipped layer: the background and four rasters are skipped.
|
||||
let skipped = plan(&d).unwrap().passes.len();
|
||||
let mut alone = d.clone();
|
||||
alone.layers.drain(..5);
|
||||
assert_eq!(skipped, plan(&alone).unwrap().passes.len());
|
||||
// Anything that lets the layers below show through keeps them.
|
||||
let see_through: [fn(&mut Layer); 6] = [
|
||||
|l| l.opacity = 0.99,
|
||||
|l| l.fill_opacity = 0.5,
|
||||
|l| l.blend = BlendMode::Multiply,
|
||||
|l| l.visible = false,
|
||||
|l| l.excluded_channels = 1,
|
||||
|l| {
|
||||
if let LayerContent::Fill(Fill::Gradient { opacity_stops, .. }) = &mut l.content {
|
||||
opacity_stops.push((1.0, 0.5));
|
||||
}
|
||||
},
|
||||
];
|
||||
for (k, f) in see_through.iter().enumerate() {
|
||||
let mut d2 = d.clone();
|
||||
f(&mut d2.layers[5]);
|
||||
assert!(plan(&d2).unwrap().passes.len() > skipped, "case {k}: the layers below are planned");
|
||||
assert!(!photocraft_compose::occludes_below(&d2.layers[5], ColorMode::Rgb), "case {k}");
|
||||
}
|
||||
let mut translucent = d.clone();
|
||||
translucent.layers[5].content = LayerContent::Fill(Fill::Solid(Color::rgba(1.0, 0.0, 0.0, 0.5)));
|
||||
assert!(!photocraft_compose::occludes_below(&translucent.layers[5], ColorMode::Rgb));
|
||||
assert!(photocraft_compose::occludes_below(&d.layers[5], ColorMode::Rgb));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_if_falls_back_to_the_cpu() {
|
||||
let mut d = Document::with_background("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
|
||||
+40
-10
@@ -350,19 +350,55 @@ fn fills_and_dissolve() {
|
||||
for style in [GradientStyle::Linear, GradientStyle::Radial, GradientStyle::Angle, GradientStyle::Reflected, GradientStyle::Diamond] {
|
||||
let mut d = base_doc(64, 48);
|
||||
let stops = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.6, Color::rgb(0.0, 1.0, 0.2)), (1.0, Color::rgb(0.1, 0.1, 0.9))];
|
||||
let mut l = Layer::new("grad", LayerContent::Fill(Fill::Gradient { stops, angle: 30.0, scale: 0.8, style, reverse: style == GradientStyle::Radial }));
|
||||
let mut l = Layer::new("grad", LayerContent::Fill(Fill::gradient(stops, 30.0, 0.8, style, style == GradientStyle::Radial)));
|
||||
l.opacity = 0.9;
|
||||
d.layers.push(l);
|
||||
check(&mut g, &d, &format!("gradient {style:?}"));
|
||||
// A live gradient (Gradient tool): canvas-aligned, offset, midpoints, opacity stops,
|
||||
// dither, masked by a selection.
|
||||
let mut d = base_doc(64, 48);
|
||||
let stops = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.6, Color::rgb(0.0, 1.0, 0.2)), (1.0, Color::rgb(0.1, 0.1, 0.9))];
|
||||
let fill = Fill::Gradient {
|
||||
stops,
|
||||
angle: -20.0,
|
||||
scale: 0.6,
|
||||
style,
|
||||
reverse: false,
|
||||
opacity_stops: vec![(0.0, 1.0), (1.0, 0.3)],
|
||||
midpoints: vec![0.3, 0.7],
|
||||
offset: (0.15, -0.1),
|
||||
dither: true,
|
||||
align: false,
|
||||
};
|
||||
let mut l = Layer::new("live", LayerContent::Fill(fill));
|
||||
l.mask = Some(mask(Rect::new(8, 4, 40, 40), 13, 0.0));
|
||||
d.layers.push(l);
|
||||
check(&mut g, &d, &format!("live gradient {style:?}"));
|
||||
}
|
||||
// Tiny frames, where the whole-pixel end points (compose::fill_layout) change the angle
|
||||
// and centre.
|
||||
for (w, h, style, angle) in [(4, 4, GradientStyle::Reflected, 30.0), (7, 5, GradientStyle::Linear, 30.0), (9, 4, GradientStyle::Linear, -60.0)] {
|
||||
let mut d = base_doc(w, h);
|
||||
let stops = vec![(0.0, Color::rgb(0.0, 0.0, 0.7)), (0.5, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(1.0, 1.0, 0.0))];
|
||||
d.layers.push(Layer::new("grad", LayerContent::Fill(Fill::Gradient { stops, angle, scale: 1.0, style, reverse: false })));
|
||||
d.layers.push(Layer::new("grad", LayerContent::Fill(Fill::gradient(stops, angle, 1.0, style, false))));
|
||||
check(&mut g, &d, &format!("small gradient {w}x{h} {style:?} {angle}"));
|
||||
}
|
||||
// An opaque, dithered gradient over everything (the GPU skips the layers it hides), with a
|
||||
// clipped layer and an adjustment above it.
|
||||
let mut d = base_doc(64, 48);
|
||||
d.layers.push(noise_layer("under", PixelFormat::RGBA8, Rect::new(5, 5, 50, 40), 17, 0.4));
|
||||
let stops = vec![(0.0, Color::rgb(0.9, 0.2, 0.1)), (1.0, Color::rgb(0.1, 0.3, 0.9))];
|
||||
let mut cover = Fill::gradient(stops, 70.0, 0.7, GradientStyle::Linear, false);
|
||||
if let Fill::Gradient { dither, offset, .. } = &mut cover {
|
||||
*dither = true;
|
||||
*offset = (0.1, -0.05);
|
||||
}
|
||||
d.layers.push(Layer::new("cover", LayerContent::Fill(cover)));
|
||||
let mut clip = noise_layer("clip", PixelFormat::RGBA8, Rect::new(10, 10, 30, 30), 23, 0.2);
|
||||
clip.clipped = true;
|
||||
d.layers.push(clip);
|
||||
d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));
|
||||
check(&mut g, &d, "opaque gradient over everything");
|
||||
let mut d = base_doc(64, 48);
|
||||
let mut l = noise_layer("dis", PixelFormat::RGBA8, Rect::new(0, 0, 64, 48), 41, 0.2);
|
||||
l.blend = BlendMode::Dissolve;
|
||||
@@ -982,13 +1018,7 @@ fn stroke_effects_on_filled_and_stroked_shapes() {
|
||||
let fill = if fill_kind == 0 {
|
||||
Fill::Solid(Color::rgb(0.3, 0.6, 0.9))
|
||||
} else {
|
||||
Fill::Gradient {
|
||||
stops: vec![(0.0, Color::rgb(0.9, 0.3, 0.1)), (1.0, clear)],
|
||||
angle: 20.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Linear,
|
||||
reverse: false,
|
||||
}
|
||||
Fill::gradient(vec![(0.0, Color::rgb(0.9, 0.3, 0.1)), (1.0, clear)], 20.0, 1.0, GradientStyle::Linear, false)
|
||||
};
|
||||
let stroke_v = vector_stroke.then(|| ShapeStroke {
|
||||
width: 3.0,
|
||||
@@ -1368,7 +1398,7 @@ fn big_doc() -> Document {
|
||||
grp.opacity = 0.9;
|
||||
d.layers.push(grp);
|
||||
let stops = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.6, Color::rgb(0.0, 1.0, 0.2)), (1.0, Color::rgb(0.1, 0.1, 0.9))];
|
||||
let mut grad = Layer::new("grad", LayerContent::Fill(Fill::Gradient { stops, angle: 30.0, scale: 0.8, style: GradientStyle::Radial, reverse: false }));
|
||||
let mut grad = Layer::new("grad", LayerContent::Fill(Fill::gradient(stops, 30.0, 0.8, GradientStyle::Radial, false)));
|
||||
grad.opacity = 0.3;
|
||||
grad.blend = BlendMode::Overlay;
|
||||
d.layers.push(grad);
|
||||
|
||||
+121
-74
@@ -183,6 +183,47 @@ pub(crate) type Stops = (Vec<(f32, Color)>, Vec<(f32, f32)>);
|
||||
/// Stops of a `Grdn` descriptor, baked to Photoshop's interpolation (smoothness `Intr`, stop
|
||||
/// midpoints, and the parent's `gs99` interpolation method when given).
|
||||
pub(crate) fn gradient_stops_with(grad: &Descriptor, method: Option<&[u8]>) -> Stops {
|
||||
let raw = gradient_stops_raw(grad);
|
||||
let stops = if raw.stops.len() >= 2 {
|
||||
crate::gradient_bake::bake(raw.stops, &raw.mids, raw.smooth, crate::gradient_bake::Method::from_code(method))
|
||||
} else {
|
||||
raw.stops
|
||||
};
|
||||
(stops, raw.opacity)
|
||||
}
|
||||
|
||||
/// A `Grdn` descriptor's stops as stored: colour stops (sorted), the midpoint of each segment
|
||||
/// between them, opacity stops and the smoothness (`Intr`, `0..=1`).
|
||||
pub(crate) struct RawStops {
|
||||
pub stops: Vec<(f32, Color)>,
|
||||
pub mids: Vec<f32>,
|
||||
pub opacity: Vec<(f32, f32)>,
|
||||
pub smooth: f32,
|
||||
}
|
||||
|
||||
/// Stops of a gradient fill layer, kept editable: when Photoshop's interpolation is plain
|
||||
/// (no smoothness, Classic method) the stops stay as they are with their midpoints, else they
|
||||
/// are baked like [`gradient_stops_with`] (midpoints folded in). Opacity stops that are all
|
||||
/// 100 % come back empty.
|
||||
pub(crate) fn gradient_stops_editable(grad: &Descriptor, method: Option<&[u8]>) -> RawStops {
|
||||
let mut raw = gradient_stops_raw(grad);
|
||||
let m = crate::gradient_bake::Method::from_code(method);
|
||||
// Lab stops (Lab documents) interpolate in L*a*b*, which only baking reproduces.
|
||||
let lab = raw.stops.iter().all(|(_, c)| c.mode == photocraft_color::ColorMode::Lab);
|
||||
if raw.stops.len() >= 2 && (raw.smooth > 0.0 || m != crate::gradient_bake::Method::Classic || lab) {
|
||||
raw.stops = crate::gradient_bake::bake(std::mem::take(&mut raw.stops), &raw.mids, raw.smooth, m);
|
||||
raw.mids.clear();
|
||||
}
|
||||
if raw.mids.iter().all(|m| (m - 0.5).abs() < 1e-3) {
|
||||
raw.mids.clear();
|
||||
}
|
||||
if raw.opacity.iter().all(|o| (o.1 - 1.0).abs() < 1e-4) {
|
||||
raw.opacity.clear();
|
||||
}
|
||||
raw
|
||||
}
|
||||
|
||||
fn gradient_stops_raw(grad: &Descriptor) -> RawStops {
|
||||
let mut stops = Vec::new();
|
||||
let mut mids = Vec::new();
|
||||
let mut opacity = Vec::new();
|
||||
@@ -200,9 +241,12 @@ pub(crate) fn gradient_stops_with(grad: &Descriptor, method: Option<&[u8]>) -> S
|
||||
// Midpoint k applies to the segment after stop k.
|
||||
let mut order: Vec<usize> = (0..stops.len()).collect();
|
||||
order.sort_by(|a, b| stops[*a].0.total_cmp(&stops[*b].0));
|
||||
let mids: Vec<f32> = order.iter().skip(1).map(|i| mids[*i]).collect();
|
||||
let mids: Vec<f32> = order.iter().skip(1).map(|i| mids.get(*i).copied().unwrap_or(0.5)).collect();
|
||||
let smooth = num(grad.get("Intr")).map_or(0.0, |v| (v / 4096.0) as f32);
|
||||
let stops = if stops.len() >= 2 { crate::gradient_bake::bake(stops, &mids, smooth, crate::gradient_bake::Method::from_code(method)) } else { stops };
|
||||
let mut sorted: Vec<(f32, Color)> = order.iter().filter_map(|i| stops.get(*i).cloned()).collect();
|
||||
if sorted.len() != stops.len() {
|
||||
sorted = stops;
|
||||
}
|
||||
if let Some(Value::List(items)) = grad.get("Trns") {
|
||||
for it in items {
|
||||
if let Value::Descriptor(s) = it {
|
||||
@@ -211,20 +255,32 @@ pub(crate) fn gradient_stops_with(grad: &Descriptor, method: Option<&[u8]>) -> S
|
||||
}
|
||||
}
|
||||
}
|
||||
(stops, opacity)
|
||||
RawStops { stops: sorted, mids, opacity, smooth }
|
||||
}
|
||||
|
||||
/// A `Grdn` descriptor for colour and opacity stops.
|
||||
pub(crate) fn gradient_desc(stops: &[(f32, Color)], opacity: &[(f32, f32)]) -> Descriptor {
|
||||
gradient_desc_with(stops, opacity, &[])
|
||||
}
|
||||
|
||||
/// [`gradient_desc`] with colour midpoints (one per segment between the sorted stops; each is
|
||||
/// stored on the stop that ends its segment, as [`gradient_stops_with`] reads it).
|
||||
pub(crate) fn gradient_desc_with(stops: &[(f32, Color)], opacity: &[(f32, f32)], mids: &[f32]) -> Descriptor {
|
||||
let mut stops = stops.to_vec();
|
||||
if !mids.is_empty() {
|
||||
stops.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
}
|
||||
let clrs = stops
|
||||
.iter()
|
||||
.map(|(t, c)| {
|
||||
.enumerate()
|
||||
.map(|(i, (t, c))| {
|
||||
let mid = i.checked_sub(1).and_then(|k| mids.get(k)).copied().unwrap_or(0.5);
|
||||
Value::Descriptor(
|
||||
Descriptor::new("Clrt")
|
||||
.with("Clr ", Value::Descriptor(color_to_desc(c)))
|
||||
.with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") })
|
||||
.with("Lctn", Value::Integer((t * 4096.0).round() as i32))
|
||||
.with("Mdpn", Value::Integer(50)),
|
||||
.with("Mdpn", Value::Integer((mid.clamp(0.05, 0.95) * 100.0).round() as i32)),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -271,48 +327,6 @@ fn smoothed_opacity_stops(grad: &Descriptor) -> Vec<(f32, f32)> {
|
||||
baked.into_iter().map(|(t, c)| (t, c.to_rgb()[0])).collect()
|
||||
}
|
||||
|
||||
/// Piecewise-linear value of sorted `(location, v)` stops at `t` (clamped at the ends).
|
||||
fn lerp_stops<T: Copy>(stops: &[(f32, T)], t: f32, mix: impl Fn(T, T, f32) -> T) -> Option<T> {
|
||||
let first = stops.first()?;
|
||||
if t <= first.0 {
|
||||
return Some(first.1);
|
||||
}
|
||||
for w in stops.windows(2) {
|
||||
let (a, b) = (w[0], w[1]);
|
||||
if t <= b.0 {
|
||||
let k = if b.0 > a.0 { (t - a.0) / (b.0 - a.0) } else { 1.0 };
|
||||
return Some(mix(a.1, b.1, k));
|
||||
}
|
||||
}
|
||||
stops.last().map(|s| s.1)
|
||||
}
|
||||
|
||||
/// Folds a gradient's opacity stops into its colour stops' alpha (the model keeps one stop
|
||||
/// list): stops at every colour and opacity location, colours and opacities each interpolated
|
||||
/// linearly. Without opacity stops (or all opaque) the colour stops are returned unchanged.
|
||||
/// psd-tools layers-minimal/gradient-fill.psd ("Color to Transparent", no stored pixels).
|
||||
pub(crate) fn with_opacity_stops(stops: Vec<(f32, Color)>, opacity: &[(f32, f32)]) -> Vec<(f32, Color)> {
|
||||
let mut op: Vec<(f32, f32)> = opacity.iter().copied().filter(|(t, a)| t.is_finite() && a.is_finite()).collect();
|
||||
if op.iter().all(|(_, a)| *a >= 1.0) || stops.is_empty() {
|
||||
return stops;
|
||||
}
|
||||
op.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut sorted = stops;
|
||||
sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut locs: Vec<f32> = sorted.iter().map(|s| s.0).chain(op.iter().map(|s| s.0)).collect();
|
||||
locs.sort_by(f32::total_cmp);
|
||||
locs.dedup();
|
||||
let mix_color =
|
||||
|a: Color, b: Color, k: f32| Color { c: std::array::from_fn(|i| a.c[i] + (b.c[i] - a.c[i]) * k), alpha: a.alpha + (b.alpha - a.alpha) * k, ..a };
|
||||
locs.into_iter()
|
||||
.filter_map(|t| {
|
||||
let c = lerp_stops(&sorted, t, mix_color)?;
|
||||
let a = lerp_stops(&op, t, |a, b, k| a + (b - a) * k)?;
|
||||
Some((t, Color { alpha: (c.alpha * a).clamp(0.0, 1.0), ..c }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Parses a fill block (`SoCo`, `GdFl`, `PtFl`).
|
||||
pub fn parse_fill(key: &[u8; 4], data: &[u8]) -> Option<Fill> {
|
||||
// Block data may carry trailing padding after the descriptor.
|
||||
@@ -328,13 +342,31 @@ pub fn fill_from_desc(key: &[u8; 4], d: &Descriptor) -> Option<Fill> {
|
||||
b"GdFl" => {
|
||||
let angle = num(d.get("Angl")).unwrap_or(90.0) as f32;
|
||||
let scale = num(d.get("Scl ")).map_or(1.0, |v| v as f32 / 100.0);
|
||||
let (mut stops, _) = get_desc(d, "Grad").map(|g| gradient_stops_with(g, enum_of(d, "gs99"))).unwrap_or_default();
|
||||
let opacity = get_desc(d, "Grad").map(smoothed_opacity_stops).unwrap_or_default();
|
||||
let raw = get_desc(d, "Grad").map(|g| gradient_stops_editable(g, enum_of(d, "gs99")));
|
||||
let (mut stops, midpoints) = raw.map(|r| (r.stops, r.mids)).unwrap_or_default();
|
||||
// Opacity stops with Photoshop's smoothness and opacity midpoints applied (raw when
|
||||
// the interpolation is plain); none when fully opaque.
|
||||
let mut opacity_stops = get_desc(d, "Grad").map(smoothed_opacity_stops).unwrap_or_default();
|
||||
if opacity_stops.iter().all(|o| o.1 >= 1.0 - 1e-4) {
|
||||
opacity_stops.clear();
|
||||
}
|
||||
if stops.is_empty() {
|
||||
stops = vec![(0.0, Color::BLACK), (1.0, Color::WHITE)];
|
||||
}
|
||||
let stops = with_opacity_stops(stops, &opacity);
|
||||
Some(Fill::Gradient { stops, angle, scale, style: gradient_style(d), reverse: bool_of(d, "Rvrs") })
|
||||
let pct = |o: &Descriptor, k: &str| num(o.get(k)).map_or(0.0, |v| v as f32 / 100.0);
|
||||
let offset = get_desc(d, "Ofst").map_or((0.0, 0.0), |o| (pct(o, "Hrzn"), pct(o, "Vrtc")));
|
||||
Some(Fill::Gradient {
|
||||
stops,
|
||||
angle,
|
||||
scale,
|
||||
style: gradient_style(d),
|
||||
reverse: bool_of(d, "Rvrs"),
|
||||
opacity_stops,
|
||||
midpoints,
|
||||
offset,
|
||||
dither: bool_of(d, "Dthr"),
|
||||
align: !matches!(d.get("Algn"), Some(Value::Boolean(false))),
|
||||
})
|
||||
}
|
||||
b"PtFl" => {
|
||||
let (name, id) = pattern_ref(d);
|
||||
@@ -356,15 +388,25 @@ pub fn write_fill(f: &Fill) -> ([u8; 4], Vec<u8>) {
|
||||
pub fn fill_to_desc(f: &Fill) -> ([u8; 4], Descriptor) {
|
||||
match f {
|
||||
Fill::Solid(c) => (*b"SoCo", Descriptor::new("null").with("Clr ", Value::Descriptor(color_to_desc(c)))),
|
||||
Fill::Gradient { stops, angle, scale, style, reverse } => {
|
||||
Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops, midpoints, offset, dither, align } => {
|
||||
let prc = |v: f32| Value::UnitFloat { unit: *b"#Prc", value: f64::from(v * 100.0) };
|
||||
let mut d = Descriptor::new("null")
|
||||
.with("Angl", Value::UnitFloat { unit: *b"#Ang", value: f64::from(*angle) })
|
||||
.with("Type", gradient_style_value(*style))
|
||||
.with("Scl ", Value::UnitFloat { unit: *b"#Prc", value: f64::from(scale * 100.0) })
|
||||
.with("Grad", Value::Descriptor(gradient_desc(stops, &[])));
|
||||
.with("Scl ", prc(*scale))
|
||||
.with("Grad", Value::Descriptor(gradient_desc_with(stops, opacity_stops, midpoints)));
|
||||
if *reverse {
|
||||
d = d.with("Rvrs", Value::Boolean(true));
|
||||
}
|
||||
if *dither {
|
||||
d = d.with("Dthr", Value::Boolean(true));
|
||||
}
|
||||
if !*align {
|
||||
d = d.with("Algn", Value::Boolean(false));
|
||||
}
|
||||
if *offset != (0.0, 0.0) {
|
||||
d = d.with("Ofst", Value::Descriptor(Descriptor::new("Pnt ").with("Hrzn", prc(offset.0)).with("Vrtc", prc(offset.1))));
|
||||
}
|
||||
(*b"GdFl", d)
|
||||
}
|
||||
Fill::Pattern { name, scale, id, angle, link, phase } => {
|
||||
@@ -503,28 +545,26 @@ pub fn effects_enabled(lfx2: &[u8]) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// psd-tools layers-minimal/gradient-fill.psd ("Color to Transparent", no stored pixels): a
|
||||
/// gradient fill's opacity stops reach the model (as stop alpha) and survive a write.
|
||||
/// gradient fill's opacity stops reach the model (as its opacity stops; written from stop
|
||||
/// alpha) and survive a write; the ramp's alpha follows them.
|
||||
#[test]
|
||||
fn gradient_fill_opacity_stops_become_alpha() {
|
||||
use photocraft_color::Color;
|
||||
use photocraft_doc::{Fill, GradientStyle};
|
||||
let red = Color::rgba(1.0, 0.0, 0.0, 1.0);
|
||||
let f = Fill::Gradient {
|
||||
stops: vec![(0.0, red), (1.0, Color { alpha: 0.0, ..red })],
|
||||
angle: 90.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Linear,
|
||||
reverse: false,
|
||||
};
|
||||
let f = Fill::gradient(vec![(0.0, red), (1.0, Color { alpha: 0.0, ..red })], 90.0, 1.0, GradientStyle::Linear, false);
|
||||
let (k, data) = super::write_fill(&f);
|
||||
let Some(Fill::Gradient { stops, .. }) = super::parse_fill(&k, &data) else { panic!("gradient") };
|
||||
let alpha_at = |t: f32| stops.iter().min_by(|a, b| (a.0 - t).abs().total_cmp(&(b.0 - t).abs())).map(|s| s.1.alpha).unwrap();
|
||||
assert_eq!(alpha_at(0.0), 1.0);
|
||||
assert!(alpha_at(1.0) < 0.01, "{stops:?}");
|
||||
let back = super::parse_fill(&k, &data).unwrap();
|
||||
let Fill::Gradient { stops, opacity_stops, .. } = &back else { panic!("gradient") };
|
||||
assert_eq!(opacity_stops, &vec![(0.0, 1.0), (1.0, 0.0)]);
|
||||
assert!(stops.iter().all(|s| s.1.c[0] == 1.0 && s.1.c[1] == 0.0));
|
||||
// Opaque gradients keep their colour stops untouched.
|
||||
let opaque = super::with_opacity_stops(vec![(0.0, red), (1.0, Color::WHITE)], &[(0.0, 1.0), (1.0, 1.0)]);
|
||||
assert_eq!(opaque, vec![(0.0, red), (1.0, Color::WHITE)]);
|
||||
let ramp = photocraft_compose::gradient_fill::Ramp::new(&back).unwrap();
|
||||
assert_eq!(ramp.sample(0.0)[3], 1.0);
|
||||
assert!(ramp.sample(1.0)[3] < 0.01);
|
||||
// Opaque gradients come back without opacity stops.
|
||||
let (k, data) = super::write_fill(&Fill::gradient(vec![(0.0, red), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false));
|
||||
let Some(Fill::Gradient { opacity_stops, .. }) = super::parse_fill(&k, &data) else { panic!("gradient") };
|
||||
assert!(opacity_stops.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -642,12 +682,19 @@ mod tests {
|
||||
Fill::Solid(Color::rgb(1.0, 0.5, 0.0)),
|
||||
Fill::Solid(Color { mode: ColorMode::Cmyk, c: [0.1, 0.2, 0.3, 0.4], alpha: 1.0 }),
|
||||
Fill::Solid(Color::gray(0.25)),
|
||||
Fill::gradient(vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))], 45.0, 1.0, GradientStyle::Reflected, true),
|
||||
// A live gradient (Gradient tool): canvas-aligned, offset, midpoints, opacity, dither.
|
||||
Fill::Gradient {
|
||||
stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))],
|
||||
angle: 45.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Reflected,
|
||||
reverse: true,
|
||||
stops: vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.5, Color::rgb(0.0, 1.0, 0.0)), (1.0, Color::rgb(0.0, 0.0, 1.0))],
|
||||
angle: -33.5,
|
||||
scale: 2.25,
|
||||
style: GradientStyle::Radial,
|
||||
reverse: false,
|
||||
opacity_stops: vec![(0.0, 1.0), (0.25, 0.5), (1.0, 0.0)],
|
||||
midpoints: vec![0.25, 0.75],
|
||||
offset: (0.125, -0.375),
|
||||
dither: true,
|
||||
align: false,
|
||||
},
|
||||
Fill::Pattern { name: "Bubbles".into(), scale: 0.5, id: "abc".into(), angle: 30.0, link: false, phase: (3.0, -2.0) },
|
||||
] {
|
||||
|
||||
@@ -262,13 +262,13 @@ fn gradient_and_pattern_fills_roundtrip() {
|
||||
let mut d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);
|
||||
d.layers.push(Layer::new(
|
||||
"grad",
|
||||
LayerContent::Fill(Fill::Gradient {
|
||||
stops: vec![(0.0, photocraft_color::Color::rgb(1.0, 0.0, 0.0)), (1.0, photocraft_color::Color::rgb(0.0, 0.0, 1.0))],
|
||||
angle: 30.0,
|
||||
scale: 1.0,
|
||||
style: GradientStyle::Diamond,
|
||||
reverse: true,
|
||||
}),
|
||||
LayerContent::Fill(Fill::gradient(
|
||||
vec![(0.0, photocraft_color::Color::rgb(1.0, 0.0, 0.0)), (1.0, photocraft_color::Color::rgb(0.0, 0.0, 1.0))],
|
||||
30.0,
|
||||
1.0,
|
||||
GradientStyle::Diamond,
|
||||
true,
|
||||
)),
|
||||
));
|
||||
d.layers.push(Layer::new(
|
||||
"pat",
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use eframe::wgpu;
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_doc::{Document, LayerContent};
|
||||
use photocraft_engine::Session;
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::{Value, json};
|
||||
@@ -96,19 +96,24 @@ impl Bench {
|
||||
let st = s.active().expect("document");
|
||||
let doc = st.doc.clone();
|
||||
let region = if full { doc.bounds() } else { st.last_damage.map_or(doc.bounds(), |r| r.inflate(reach(&doc.layers)).intersect(&doc.bounds())) };
|
||||
self.render(&doc, region)
|
||||
}
|
||||
|
||||
/// GPU (or CPU fallback) composite of `region` of `doc`, waited on.
|
||||
fn render(&mut self, doc: &Document, region: Rect) -> f64 {
|
||||
if region.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let t = Instant::now();
|
||||
match &mut self.gpu {
|
||||
Some(g) => {
|
||||
if g.comp.render(&g.device, &g.queue, &doc, region, |_, _| {}).is_err() {
|
||||
std::hint::black_box(photocraft_compose::render(&doc, region));
|
||||
if g.comp.render(&g.device, &g.queue, doc, region, |_, _| {}).is_err() {
|
||||
std::hint::black_box(photocraft_compose::render(doc, region));
|
||||
}
|
||||
let _ = g.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None });
|
||||
}
|
||||
None => {
|
||||
std::hint::black_box(photocraft_compose::render(&doc, region));
|
||||
std::hint::black_box(photocraft_compose::render(doc, region));
|
||||
}
|
||||
}
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
@@ -411,6 +416,45 @@ fn main() {
|
||||
ms(t)
|
||||
});
|
||||
|
||||
// ---- live gradient ------------------------------------------------------------------------
|
||||
// A Gradient tool drag in live mode: each pointer move previews a shallow copy of the document
|
||||
// with the edited fill (gradient_ui::display_doc, through gradient_fill_cmds::apply_set) and
|
||||
// recomposites the whole canvas, since the fill covers it. Release commits one command.
|
||||
exec(&mut s, "gradient.fill.create", json!({"from": [w as f32 * 0.2, h as f32 * 0.5], "to": [w as f32 * 0.8, h as f32 * 0.5]}));
|
||||
let gid = s.active().and_then(|st| st.active_layer).expect("gradient layer");
|
||||
let mut k = 0;
|
||||
b.time("live gradient preview doc (no refresh)", |_| {
|
||||
k += 1;
|
||||
let to = [w as f32 * (0.6 + 0.03 * (k % 10) as f32), h as f32 * (0.3 + 0.04 * (k % 7) as f32)];
|
||||
let t = Instant::now();
|
||||
let d = doc(&s);
|
||||
let l = d.layer(gid).expect("layer");
|
||||
let LayerContent::Fill(f) = &l.content else { panic!("not a fill") };
|
||||
let f = photocraft_engine::gradient_fill_cmds::apply_set(l, f, d.bounds(), &json!({"to": to}), [0.0, 0.0, 0.0, 1.0], [1.0; 4]).expect("set");
|
||||
let mut shown = (*d).clone();
|
||||
shown.layer_mut(gid).expect("layer").content = LayerContent::Fill(f);
|
||||
std::hint::black_box(&shown);
|
||||
ms(t)
|
||||
});
|
||||
b.time("live gradient drag update (preview + full refresh)", |b| {
|
||||
k += 1;
|
||||
let to = [w as f32 * (0.6 + 0.03 * (k % 10) as f32), h as f32 * (0.3 + 0.04 * (k % 7) as f32)];
|
||||
let t = Instant::now();
|
||||
let d = doc(&s);
|
||||
let l = d.layer(gid).expect("layer");
|
||||
let LayerContent::Fill(f) = &l.content else { panic!("not a fill") };
|
||||
let f = photocraft_engine::gradient_fill_cmds::apply_set(l, f, d.bounds(), &json!({"to": to}), [0.0, 0.0, 0.0, 1.0], [1.0; 4]).expect("set");
|
||||
let mut shown = (*d).clone();
|
||||
shown.layer_mut(gid).expect("layer").content = LayerContent::Fill(f);
|
||||
ms(t) + b.render(&shown, shown.bounds())
|
||||
});
|
||||
b.time("live gradient release (gradient.fill.set + refresh)", |b| {
|
||||
k += 1;
|
||||
let t = Instant::now();
|
||||
exec(&mut s, "gradient.fill.set", json!({"layer": gid.0, "to": [w as f32 * (0.6 + 0.03 * (k % 10) as f32), h as f32 * 0.4]}));
|
||||
ms(t) + b.refresh(&s, false)
|
||||
});
|
||||
|
||||
if let Some(out) = arg(&args, "--json") {
|
||||
let rows: Vec<Value> = b
|
||||
.rows
|
||||
|
||||
@@ -225,6 +225,10 @@ fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Arc<Document>
|
||||
if let Some(shown) = crate::adjust_preview::display_doc(app, idx) {
|
||||
return shown;
|
||||
}
|
||||
// Gradient tool (live) drag, or a stop dragged in the Properties panel.
|
||||
if let Some(shown) = crate::gradient_ui::display_doc(app, idx) {
|
||||
return shown;
|
||||
}
|
||||
// Move tool drag: the moving layers at the pointer.
|
||||
if let Some(shown) = crate::move_ui::display_doc(app, idx) {
|
||||
return shown;
|
||||
@@ -1318,6 +1322,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
crate::retouch_ui::draw_source_marker(app, &painter, &xf);
|
||||
crate::vector_ui::draw_overlay(app, &painter, &xf, &doc);
|
||||
crate::analysis_ui::draw_overlay(app, &painter, &xf);
|
||||
crate::gradient_ui::draw_overlay(app, &painter, &xf);
|
||||
crate::slice_ui::draw_overlay(app, &painter, &xf);
|
||||
// Tool cursors (Photoshop-style).
|
||||
let guide_hover = response.hover_pos().filter(|_| tool == Tool::Move).and_then(|p| {
|
||||
@@ -1684,6 +1689,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
|
||||
if crate::crop_ui::pointer(app, ev, mods) {
|
||||
return;
|
||||
}
|
||||
// Gradient tool, live mode: draw and edit Gradient Fill layers.
|
||||
if crate::gradient_ui::pointer(app, ev, mods) {
|
||||
return;
|
||||
}
|
||||
let tool = app.ui.tool;
|
||||
if tool == Tool::Eyedropper {
|
||||
match ev {
|
||||
|
||||
@@ -118,6 +118,23 @@ pub fn open(app: &mut PhotocraftApp, target: &str) -> u64 {
|
||||
app.ui.open_dialog(DialogKind::Command, f)
|
||||
}
|
||||
|
||||
/// Open the picker on `rgb` for something other than the tool colours: OK runs `command` with
|
||||
/// `params` plus `"color": "#rrggbb"` (e.g. a gradient stop's colour).
|
||||
pub fn open_for_command(app: &mut PhotocraftApp, label: &str, rgb: [f32; 3], command: &str, params: Value) -> u64 {
|
||||
let hsv = rgb_to_hsv(rgb);
|
||||
let mut f = Map::new();
|
||||
f.insert("__colorPicker".into(), json!("command"));
|
||||
f.insert("__label".into(), json!(label));
|
||||
f.insert("__command".into(), json!(command));
|
||||
f.insert("__params".into(), params);
|
||||
f.insert("color".into(), json!(hex(rgb)));
|
||||
f.insert("__orig".into(), json!(hex(rgb)));
|
||||
f.insert("__hsv".into(), json!(hsv));
|
||||
f.insert("__mode".into(), json!("h"));
|
||||
f.insert("__webOnly".into(), json!(false));
|
||||
app.ui.open_dialog(DialogKind::Command, f)
|
||||
}
|
||||
|
||||
pub fn owns(f: &Map<String, Value>) -> bool {
|
||||
f.contains_key("__colorPicker")
|
||||
}
|
||||
@@ -314,6 +331,11 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, rgb: [f32;
|
||||
pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {
|
||||
let target = f.get("__colorPicker").and_then(Value::as_str).unwrap_or("foreground");
|
||||
let color = f.get("color").and_then(Value::as_str).unwrap_or("#000000");
|
||||
if let Some(cmd) = f.get("__command").and_then(Value::as_str) {
|
||||
let mut p = f.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
p["color"] = json!(color);
|
||||
return app.run(cmd, p);
|
||||
}
|
||||
app.run("tools.setColors", json!({ target: color }))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,960 @@
|
||||
//! Gradient tool, live mode (Photoshop 2023+ "Gradient" vs "Classic gradient"): a drag makes a
|
||||
//! Gradient Fill layer (`gradient.fill.create`), and with a gradient fill layer selected the canvas
|
||||
//! shows its widget: start and end handles (drag to move, ⇧ snaps the angle to 45°), the colour
|
||||
//! stops along the line (drag to move, drag off the line to delete, double-click for the Color
|
||||
//! Picker), midpoint diamonds between them, a click on the line adds a stop, and dragging the line
|
||||
//! moves the whole gradient. A drag elsewhere redraws the selected gradient. Radial and Angle
|
||||
//! gradients show their circle, Diamond its square, Reflected its mirrored half.
|
||||
//!
|
||||
//! Every gesture previews live through the regular canvas path (a shallow copy of the document
|
||||
//! with the edited fill, so the GPU canvas just re-runs its gradient pass) and commits one command
|
||||
//! on release: one history step. The Properties panel's stops editor ([`properties`]) previews
|
||||
//! through the same path.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use photocraft_compose::gradient_fill as gf;
|
||||
use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId};
|
||||
use photocraft_engine::gradient_fill_cmds as cmds;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::canvas::{ToolEvent, ViewXform};
|
||||
use crate::state::Tool;
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets;
|
||||
|
||||
/// Id of the temporary layer previewing a new gradient while it is drawn.
|
||||
pub const PREVIEW_LAYER: LayerId = LayerId(u64::MAX - 78);
|
||||
/// Tag of this module's canvas preview keys.
|
||||
const TAG: u64 = 1 << 58;
|
||||
/// Screen distance (points) within which a handle, stop or the line is grabbed.
|
||||
const GRAB: f32 = 8.0;
|
||||
/// Screen distance from the line past which a dragged stop is deleted.
|
||||
const TEAR_OFF: f32 = 36.0;
|
||||
/// Seconds between two clicks of a double-click.
|
||||
const DOUBLE_CLICK: f64 = 0.45;
|
||||
|
||||
/// What a pointer press grabbed on the widget.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Grab {
|
||||
Start,
|
||||
End,
|
||||
/// A colour stop (index in sorted order).
|
||||
Stop(usize),
|
||||
/// The midpoint of the segment after colour stop `i`.
|
||||
Mid(usize),
|
||||
/// The line at gradient location `t`.
|
||||
Line(f32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Drag {
|
||||
/// Drawing a new gradient, or redrawing the selected one.
|
||||
Draw { from: [f32; 2], to: [f32; 2], redraw: Option<LayerId> },
|
||||
/// Editing the selected gradient: the command (and params) to commit on release.
|
||||
Edit { layer: LayerId, grab: Grab, down: [f32; 2], moved: bool, commit: Option<(&'static str, Value)> },
|
||||
}
|
||||
|
||||
/// Live-gradient interaction state (not saved).
|
||||
#[derive(Default)]
|
||||
pub struct LiveGradient {
|
||||
drag: Option<Drag>,
|
||||
last_click: Option<(Grab, f64)>,
|
||||
/// Pending edit from the Properties panel's stops editor (previewed like a canvas drag).
|
||||
panel: Option<(LayerId, &'static str, Value)>,
|
||||
/// Cached preview document by key.
|
||||
preview: Option<(u64, Arc<Document>)>,
|
||||
}
|
||||
|
||||
/// Whether the Gradient tool is in its live (Gradient Fill layer) mode.
|
||||
/// Painting into a layer mask, an alpha channel or the Quick Mask stays classic (pixels), except
|
||||
/// that a selected gradient fill layer is always edited live (selecting it targets its mask).
|
||||
pub fn live_mode(app: &PhotocraftApp) -> bool {
|
||||
if app.ui.tool != Tool::Gradient || app.ui.tool_options.gradient_classic {
|
||||
return false;
|
||||
}
|
||||
match crate::canvas::paint_target(app).as_str() {
|
||||
Some("pixels") => true,
|
||||
Some("mask") => active_gradient(app).is_some(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The active layer when it is a gradient fill layer: (layer, its frame, the canvas).
|
||||
fn active_gradient(app: &PhotocraftApp) -> Option<(Layer, Rect32, photocraft_geom::Rect)> {
|
||||
let st = app.session.active()?;
|
||||
let l = st.doc.layer(st.active_layer?)?;
|
||||
if !matches!(l.content, LayerContent::Fill(Fill::Gradient { .. })) || !l.visible {
|
||||
return None;
|
||||
}
|
||||
let canvas = st.doc.bounds();
|
||||
Some((l.clone(), photocraft_compose::fill_frame(l, canvas), canvas))
|
||||
}
|
||||
|
||||
type Rect32 = photocraft_geom::Rect;
|
||||
|
||||
fn fill_of(l: &Layer) -> Option<&Fill> {
|
||||
match &l.content {
|
||||
LayerContent::Fill(f @ Fill::Gradient { .. }) => Some(f),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill an in-progress edit shows (`None` when it can't apply, e.g. a stale index).
|
||||
fn edited_fill(app: &PhotocraftApp, layer: &Layer, canvas: Rect32, cmd: &str, p: &Value) -> Option<Fill> {
|
||||
let f = fill_of(layer)?;
|
||||
let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);
|
||||
match cmd {
|
||||
cmds::SET => cmds::apply_set(layer, f, canvas, p, fg, bg).ok(),
|
||||
cmds::STOP => cmds::apply_stop(f, p, fg, bg).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Options-bar params of a new live gradient.
|
||||
fn create_params(app: &PhotocraftApp, from: [f32; 2], to: [f32; 2]) -> Value {
|
||||
let o = &app.ui.tool_options;
|
||||
json!({"from": from, "to": to, "style": o.gradient_style, "reverse": o.gradient_reverse, "dither": o.gradient_dither, "opacity": o.fill_opacity})
|
||||
}
|
||||
|
||||
fn dist(a: [f32; 2], b: [f32; 2]) -> f32 {
|
||||
(a[0] - b[0]).hypot(a[1] - b[1])
|
||||
}
|
||||
|
||||
/// Position on the segment `s`→`e` at fraction `u`.
|
||||
fn lerp(s: [f32; 2], e: [f32; 2], u: f32) -> [f32; 2] {
|
||||
[s[0] + (e[0] - s[0]) * u, s[1] + (e[1] - s[1]) * u]
|
||||
}
|
||||
|
||||
/// Fraction along `s`→`e` of `p`'s projection (clamped) and `p`'s distance from the line.
|
||||
fn project(s: [f32; 2], e: [f32; 2], p: [f32; 2]) -> (f32, f32) {
|
||||
let (dx, dy) = (e[0] - s[0], e[1] - s[1]);
|
||||
let l2 = dx * dx + dy * dy;
|
||||
if l2 <= 1e-9 {
|
||||
return (0.0, dist(s, p));
|
||||
}
|
||||
let u = (((p[0] - s[0]) * dx + (p[1] - s[1]) * dy) / l2).clamp(0.0, 1.0);
|
||||
(u, dist(lerp(s, e, u), p))
|
||||
}
|
||||
|
||||
/// The widget's geometry for a gradient fill: handles, stop positions, midpoint positions.
|
||||
struct Widget {
|
||||
style: GradientStyle,
|
||||
start: [f32; 2],
|
||||
end: [f32; 2],
|
||||
reverse: bool,
|
||||
/// Sorted colour stops: (location, rgba).
|
||||
stops: Vec<(f32, [f32; 4])>,
|
||||
mids: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Widget {
|
||||
fn new(f: &Fill, frame: Rect32) -> Option<Widget> {
|
||||
let Fill::Gradient { stops, midpoints, reverse, style, .. } = f else { return None };
|
||||
let (start, end) = gf::fill_handles(f, frame)?;
|
||||
let mut st: Vec<(f32, [f32; 4])> = stops
|
||||
.iter()
|
||||
.map(|(t, c)| {
|
||||
let rgb = c.to_rgb();
|
||||
(*t, [rgb[0], rgb[1], rgb[2], c.alpha])
|
||||
})
|
||||
.collect();
|
||||
st.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
Some(Widget { style: *style, start, end, reverse: *reverse, stops: st, mids: midpoints.clone() })
|
||||
}
|
||||
|
||||
/// Fraction along the line of gradient location `t`.
|
||||
fn u_of(&self, t: f32) -> f32 {
|
||||
if self.reverse { 1.0 - t } else { t }
|
||||
}
|
||||
|
||||
fn at(&self, t: f32) -> [f32; 2] {
|
||||
lerp(self.start, self.end, self.u_of(t))
|
||||
}
|
||||
|
||||
fn mid_location(&self, i: usize) -> Option<f32> {
|
||||
let (a, b) = (self.stops.get(i)?.0, self.stops.get(i + 1)?.0);
|
||||
(b - a > 1e-4).then(|| a + (b - a) * self.mids.get(i).copied().unwrap_or(0.5))
|
||||
}
|
||||
|
||||
/// What `p` (document pixels) grabs, with `tol` the grab distance in document pixels.
|
||||
fn hit(&self, p: [f32; 2], tol: f32) -> Option<Grab> {
|
||||
if dist(p, self.end) <= tol {
|
||||
return Some(Grab::End);
|
||||
}
|
||||
if dist(p, self.start) <= tol {
|
||||
return Some(Grab::Start);
|
||||
}
|
||||
let near = |q: [f32; 2]| dist(p, q) <= tol;
|
||||
if let Some(i) = self.stops.iter().position(|s| near(self.at(s.0))) {
|
||||
return Some(Grab::Stop(i));
|
||||
}
|
||||
if let Some(i) = (0..self.stops.len().saturating_sub(1)).find(|i| self.mid_location(*i).is_some_and(|t| near(self.at(t)))) {
|
||||
return Some(Grab::Mid(i));
|
||||
}
|
||||
let (u, d) = project(self.start, self.end, p);
|
||||
(d <= tol).then_some(Grab::Line(if self.reverse { 1.0 - u } else { u }))
|
||||
}
|
||||
}
|
||||
|
||||
/// Pointer input for the Gradient tool in live mode. Returns true when consumed.
|
||||
pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
|
||||
if !live_mode(app) {
|
||||
app.gradient.drag = None;
|
||||
return false;
|
||||
}
|
||||
let zoom = app.current_zoom().max(0.01);
|
||||
match ev {
|
||||
ToolEvent::Down { x, y, .. } => {
|
||||
let p = [x as f32, y as f32];
|
||||
let active = active_gradient(app);
|
||||
let grab = active.as_ref().and_then(|(l, frame, _)| Widget::new(fill_of(l)?, *frame)?.hit(p, GRAB / zoom));
|
||||
app.gradient.drag = Some(match (grab, active) {
|
||||
(Some(grab), Some((l, ..))) => Drag::Edit { layer: l.id, grab, down: p, moved: false, commit: None },
|
||||
(_, active) => Drag::Draw { from: p, to: p, redraw: active.map(|a| a.0.id) },
|
||||
});
|
||||
}
|
||||
ToolEvent::Move { x, y, .. } => drag_to(app, [x as f32, y as f32], mods),
|
||||
ToolEvent::Up { x, y } => {
|
||||
drag_to(app, [x as f32, y as f32], mods);
|
||||
finish(app);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn drag_to(app: &mut PhotocraftApp, p: [f32; 2], mods: egui::Modifiers) {
|
||||
let zoom = app.current_zoom().max(0.01);
|
||||
let active = active_gradient(app);
|
||||
let Some(drag) = app.gradient.drag.as_mut() else { return };
|
||||
// ⇧: 45° gradient angles, the same snap as the classic drag (stroke_constraint.rs).
|
||||
let snap = |from: [f32; 2], to: [f32; 2]| -> [f32; 2] {
|
||||
if !mods.shift {
|
||||
return to;
|
||||
}
|
||||
let c = crate::stroke_constraint::snap45([f64::from(from[0]), f64::from(from[1])], [f64::from(to[0]), f64::from(to[1])]);
|
||||
[c[0] as f32, c[1] as f32]
|
||||
};
|
||||
match drag {
|
||||
Drag::Draw { from, to, .. } => *to = snap(*from, p),
|
||||
Drag::Edit { layer, grab, down, moved, commit } => {
|
||||
if dist(*down, p) * zoom >= 2.0 {
|
||||
*moved = true;
|
||||
}
|
||||
if !*moved {
|
||||
return;
|
||||
}
|
||||
let Some(w) = active.as_ref().filter(|a| a.0.id == *layer).and_then(|(l, frame, _)| Widget::new(fill_of(l)?, *frame)) else { return };
|
||||
let id = layer.0;
|
||||
*commit = match *grab {
|
||||
Grab::Start => Some((cmds::SET, json!({"layer": id, "from": snap(w.end, p)}))),
|
||||
Grab::End => Some((cmds::SET, json!({"layer": id, "to": snap(w.start, p)}))),
|
||||
Grab::Line(_) => {
|
||||
let (dx, dy) = (p[0] - down[0], p[1] - down[1]);
|
||||
Some((cmds::SET, json!({"layer": id, "from": [w.start[0] + dx, w.start[1] + dy], "to": [w.end[0] + dx, w.end[1] + dy]})))
|
||||
}
|
||||
Grab::Stop(i) => {
|
||||
let (u, d) = project(w.start, w.end, p);
|
||||
if d * zoom > TEAR_OFF && w.stops.len() > 2 {
|
||||
Some((cmds::STOP, json!({"layer": id, "action": "delete", "index": i})))
|
||||
} else {
|
||||
Some((cmds::STOP, json!({"layer": id, "action": "move", "index": i, "location": w.u_of(u)})))
|
||||
}
|
||||
}
|
||||
Grab::Mid(i) => {
|
||||
let t = w.u_of(project(w.start, w.end, p).0);
|
||||
match (w.stops.get(i), w.stops.get(i + 1)) {
|
||||
(Some(a), Some(b)) if b.0 - a.0 > 1e-4 => {
|
||||
Some((cmds::STOP, json!({"layer": id, "action": "midpoint", "index": i, "location": ((t - a.0) / (b.0 - a.0)).clamp(0.05, 0.95)})))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(app: &mut PhotocraftApp) {
|
||||
let Some(drag) = app.gradient.drag.take() else { return };
|
||||
let zoom = app.current_zoom().max(0.01);
|
||||
match drag {
|
||||
Drag::Draw { from, to, redraw } => {
|
||||
if dist(from, to) * zoom < 2.0 {
|
||||
return;
|
||||
}
|
||||
let _ = match redraw {
|
||||
Some(id) => app.run(cmds::SET, json!({"layer": id.0, "from": from, "to": to})),
|
||||
None => {
|
||||
let p = create_params(app, from, to);
|
||||
app.run(cmds::CREATE, p)
|
||||
}
|
||||
};
|
||||
}
|
||||
Drag::Edit { commit: Some((cmd, p)), moved: true, .. } => {
|
||||
let _ = app.run(cmd, p);
|
||||
}
|
||||
Drag::Edit { layer, grab, moved: false, .. } => click(app, layer, grab),
|
||||
Drag::Edit { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A click (no drag) on the widget: the line adds a stop; a double-click on a stop (or on an end
|
||||
/// handle, for the stop there) opens the Color Picker.
|
||||
fn click(app: &mut PhotocraftApp, layer: LayerId, grab: Grab) {
|
||||
let now = app.last_frame_time;
|
||||
let double = app.gradient.last_click.is_some_and(|(g, t)| g == grab && now - t <= DOUBLE_CLICK);
|
||||
app.gradient.last_click = Some((grab, now));
|
||||
match grab {
|
||||
Grab::Line(t) => {
|
||||
let _ = app.run(cmds::STOP, json!({"layer": layer.0, "action": "add", "location": t}));
|
||||
}
|
||||
Grab::Stop(i) if double => edit_stop_color(app, layer, i),
|
||||
Grab::Start | Grab::End if double => {
|
||||
let Some((l, frame, _)) = active_gradient(app) else { return };
|
||||
let Some(w) = fill_of(&l).and_then(|f| Widget::new(f, frame)) else { return };
|
||||
// The stop at that end of the line.
|
||||
let at_start = (grab == Grab::Start) != w.reverse;
|
||||
let i = if at_start { 0 } else { w.stops.len().saturating_sub(1) };
|
||||
edit_stop_color(app, layer, i);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the Color Picker on colour stop `i`; OK runs `gradient.fill.stop` (one history step).
|
||||
pub fn edit_stop_color(app: &mut PhotocraftApp, layer: LayerId, i: usize) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let Some(Fill::Gradient { stops, .. }) = st.doc.layer(layer).and_then(fill_of) else { return };
|
||||
let mut sorted = stops.clone();
|
||||
sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let Some((_, c)) = sorted.get(i) else { return };
|
||||
app.gradient.last_click = None;
|
||||
crate::color_picker_ui::open_for_command(
|
||||
app,
|
||||
"Color Picker (Stop Color)",
|
||||
c.to_rgb(),
|
||||
cmds::STOP,
|
||||
json!({"layer": layer.0, "action": "color", "index": i}),
|
||||
);
|
||||
}
|
||||
|
||||
fn preview_key(revision: u64, what: &str) -> u64 {
|
||||
let h = what.bytes().fold(revision.wrapping_mul(0x9e37_79b9_7f4a_7c15), |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b)));
|
||||
(h & (TAG - 1)) | TAG
|
||||
}
|
||||
|
||||
/// The document to show while a gradient is drawn or edited (`canvas::display_doc`).
|
||||
pub fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {
|
||||
if app.session.active_index() != Some(idx) {
|
||||
return None;
|
||||
}
|
||||
let st = app.session.active()?;
|
||||
let (doc, revision) = (st.doc.clone(), st.revision);
|
||||
let edit: Option<(LayerId, &'static str, Value)> = match &app.gradient.drag {
|
||||
Some(Drag::Draw { from, to, redraw }) if live_mode(app) && dist(*from, *to) >= 1.0 => match redraw {
|
||||
Some(id) => Some((*id, cmds::SET, json!({"from": from, "to": to}))),
|
||||
None => Some((PREVIEW_LAYER, cmds::CREATE, create_params(app, *from, *to))),
|
||||
},
|
||||
Some(Drag::Edit { layer, commit: Some((cmd, p)), moved: true, .. }) if live_mode(app) => Some((*layer, *cmd, p.clone())),
|
||||
_ => app.gradient.panel.clone(),
|
||||
};
|
||||
let Some((layer, cmd, p)) = edit else {
|
||||
app.gradient.preview = None;
|
||||
return None;
|
||||
};
|
||||
let key = preview_key(revision, &format!("{}{cmd}{p}", layer.0));
|
||||
if let Some((k, d)) = &app.gradient.preview
|
||||
&& *k == key
|
||||
{
|
||||
return Some((d.clone(), key));
|
||||
}
|
||||
let mut shown = (*doc).clone();
|
||||
if cmd == cmds::CREATE {
|
||||
let mut l = cmds::new_layer(&app.session, &doc, &p).ok()?;
|
||||
l.id = PREVIEW_LAYER;
|
||||
let above = app.session.active().and_then(|s| s.active_layer);
|
||||
shown.insert_above(above, l);
|
||||
} else {
|
||||
let l = doc.layer(layer)?;
|
||||
let f = edited_fill(app, l, doc.bounds(), cmd, &p)?;
|
||||
shown.layer_mut(layer)?.content = LayerContent::Fill(f);
|
||||
}
|
||||
let shown = Arc::new(shown);
|
||||
app.gradient.preview = Some((key, shown.clone()));
|
||||
Some((shown, key))
|
||||
}
|
||||
|
||||
/// The fill and frame the widget shows: the one being drawn or edited, else the selected one.
|
||||
fn shown_fill(app: &PhotocraftApp) -> Option<(Fill, Rect32, Option<Grab>)> {
|
||||
let st = app.session.active()?;
|
||||
let canvas = st.doc.bounds();
|
||||
match &app.gradient.drag {
|
||||
Some(Drag::Draw { from, to, redraw: None }) => {
|
||||
let l = cmds::new_layer(&app.session, &st.doc, &create_params(app, *from, *to)).ok()?;
|
||||
let f = fill_of(&l)?.clone();
|
||||
Some((f, photocraft_compose::fill_frame(&l, canvas), Some(Grab::End)))
|
||||
}
|
||||
Some(Drag::Draw { from, to, redraw: Some(id) }) => {
|
||||
let l = st.doc.layer(*id)?;
|
||||
let f = edited_fill(app, l, canvas, cmds::SET, &json!({"from": from, "to": to}))?;
|
||||
Some((f, photocraft_compose::fill_frame(l, canvas), Some(Grab::End)))
|
||||
}
|
||||
Some(Drag::Edit { layer, grab, commit, .. }) => {
|
||||
let l = st.doc.layer(*layer)?;
|
||||
let f = match commit {
|
||||
Some((cmd, p)) => match edited_fill(app, l, canvas, cmd, p) {
|
||||
Some(f) => f,
|
||||
None => fill_of(l)?.clone(),
|
||||
},
|
||||
None => fill_of(l)?.clone(),
|
||||
};
|
||||
// A torn-off stop no longer exists: highlight nothing.
|
||||
let deleting = commit.as_ref().is_some_and(|(_, p)| p["action"] == "delete");
|
||||
Some((f, photocraft_compose::fill_frame(l, canvas), (!deleting).then_some(*grab)))
|
||||
}
|
||||
None => {
|
||||
let (l, frame, _) = active_gradient(app)?;
|
||||
Some((fill_of(&l)?.clone(), frame, None))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn c32(c: [f32; 4]) -> Color32 {
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Color32::from_rgb(q(c[0]), q(c[1]), q(c[2]))
|
||||
}
|
||||
|
||||
fn line(painter: &egui::Painter, a: Pos2, b: Pos2) {
|
||||
painter.line_segment([a, b], Stroke::new(3.0, Color32::from_black_alpha(90)));
|
||||
painter.line_segment([a, b], Stroke::new(1.5, Color32::WHITE));
|
||||
}
|
||||
|
||||
fn diamond(painter: &egui::Painter, c: Pos2, r: f32, fill: Color32, outline: Color32) {
|
||||
let pts = vec![pos2(c.x, c.y - r), pos2(c.x + r, c.y), pos2(c.x, c.y + r), pos2(c.x - r, c.y)];
|
||||
painter.add(egui::Shape::convex_polygon(pts, fill, Stroke::new(1.0, outline)));
|
||||
}
|
||||
|
||||
/// Draws the live gradient widget over the canvas.
|
||||
pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform) {
|
||||
if !live_mode(app) {
|
||||
return;
|
||||
}
|
||||
let Some((fill, frame, grabbed)) = shown_fill(app) else { return };
|
||||
let Some(w) = Widget::new(&fill, frame) else { return };
|
||||
let accent = Tokens::get(painter.ctx()).accent;
|
||||
let sp = |p: [f32; 2]| xf.to_screen(p[0], p[1]);
|
||||
let (s, e) = (sp(w.start), sp(w.end));
|
||||
let r = s.distance(e);
|
||||
let shadow = Stroke::new(3.0, Color32::from_black_alpha(90));
|
||||
let white = Stroke::new(1.5, Color32::WHITE);
|
||||
match w.style {
|
||||
GradientStyle::Radial | GradientStyle::Angle => {
|
||||
painter.circle_stroke(s, r, shadow);
|
||||
painter.circle_stroke(s, r, white);
|
||||
}
|
||||
GradientStyle::Diamond => {
|
||||
let d = e - s;
|
||||
let n = vec2(-d.y, d.x);
|
||||
let pts = vec![s + d, s + n, s - d, s - n, s + d];
|
||||
painter.add(egui::Shape::line(pts.clone(), shadow));
|
||||
painter.add(egui::Shape::line(pts, white));
|
||||
}
|
||||
GradientStyle::Reflected => {
|
||||
let m = s - (e - s);
|
||||
painter.add(egui::Shape::dashed_line(&[s, m], Stroke::new(1.5, Color32::WHITE), 5.0, 4.0));
|
||||
}
|
||||
GradientStyle::Linear => {}
|
||||
}
|
||||
line(painter, s, e);
|
||||
// Midpoints.
|
||||
for i in 0..w.stops.len().saturating_sub(1) {
|
||||
if let Some(t) = w.mid_location(i) {
|
||||
let sel = grabbed == Some(Grab::Mid(i));
|
||||
diamond(painter, sp(w.at(t)), 4.5, if sel { accent } else { Color32::WHITE }, Color32::from_black_alpha(160));
|
||||
}
|
||||
}
|
||||
// End handles, then the colour stops (a stop at an end sits inside its handle).
|
||||
for (p, g) in [(s, Grab::Start), (e, Grab::End)] {
|
||||
let ring = if grabbed == Some(g) { accent } else { Color32::WHITE };
|
||||
painter.circle_stroke(p, 8.0, Stroke::new(3.5, Color32::from_black_alpha(90)));
|
||||
painter.circle_stroke(p, 8.0, Stroke::new(2.0, ring));
|
||||
}
|
||||
for (i, (t, c)) in w.stops.iter().enumerate() {
|
||||
let p = sp(w.at(*t));
|
||||
let sel = grabbed == Some(Grab::Stop(i));
|
||||
painter.circle_filled(p, 5.0, c32(*c));
|
||||
painter.circle_stroke(p, 5.5, Stroke::new(1.5, if sel { accent } else { Color32::WHITE }));
|
||||
painter.circle_stroke(p, 6.8, Stroke::new(1.0, Color32::from_black_alpha(110)));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options bar
|
||||
|
||||
/// A ramp of RGBA stops over a checkerboard in `r`.
|
||||
fn paint_ramp(p: &egui::Painter, r: Rect, sample: impl Fn(f32) -> [f32; 4]) {
|
||||
widgets::checker(p, r, 5.0);
|
||||
let n = 64;
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for k in 0..=n {
|
||||
let u = k as f32 / n as f32;
|
||||
let c = sample(u);
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
let col = Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3]));
|
||||
let x = r.left() + u * r.width();
|
||||
mesh.colored_vertex(pos2(x, r.top()), col);
|
||||
mesh.colored_vertex(pos2(x, r.bottom()), col);
|
||||
if k > 0 {
|
||||
let i = (2 * k) as u32;
|
||||
mesh.add_triangle(i - 2, i - 1, i);
|
||||
mesh.add_triangle(i - 1, i + 1, i);
|
||||
}
|
||||
}
|
||||
p.add(mesh);
|
||||
}
|
||||
|
||||
/// Side, in pixels, of a gradient fill layer's thumbnail texture.
|
||||
const THUMB_PX: u32 = 64;
|
||||
|
||||
/// Pixels of a gradient fill's Layers-panel thumbnail: the fill as it lays out (style, angle,
|
||||
/// scale, offset, reverse, stops, midpoints and opacity) in a square, as Photoshop shows it.
|
||||
/// `None` for other fills.
|
||||
pub fn thumbnail_image(f: &Fill) -> Option<egui::ColorImage> {
|
||||
let Fill::Gradient { .. } = f else { return None };
|
||||
let n = THUMB_PX as i32;
|
||||
let square = photocraft_geom::Rect::new(0, 0, n, n);
|
||||
// No dither: it is invisible at this size and would only add noise.
|
||||
let mut plain = f.clone();
|
||||
if let Fill::Gradient { dither, .. } = &mut plain {
|
||||
*dither = false;
|
||||
}
|
||||
let px = gf::render(&plain, square, square);
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
let rgba: Vec<Color32> = px.iter().map(|c| Color32::from_rgba_unmultiplied(q(c[0]), q(c[1]), q(c[2]), q(c[3]))).collect();
|
||||
Some(egui::ColorImage::new([THUMB_PX as usize; 2], rgba))
|
||||
}
|
||||
|
||||
/// Paints a gradient fill layer's thumbnail into `rect` over a checkerboard (opacity stops show
|
||||
/// through), cached per layer until its fill changes. Returns `false` for other fills.
|
||||
pub fn paint_thumbnail(ui: &egui::Ui, layer: LayerId, f: &Fill, rect: Rect) -> bool {
|
||||
if !matches!(f, Fill::Gradient { .. }) {
|
||||
return false;
|
||||
}
|
||||
let ctx = ui.ctx();
|
||||
let key = egui::Id::new(("gradient-thumb", layer.0));
|
||||
let cached: Option<(Fill, egui::TextureHandle)> = ctx.data(|d| d.get_temp(key));
|
||||
let tex = match cached {
|
||||
Some((cf, t)) if cf == *f => t,
|
||||
_ => {
|
||||
let Some(img) = thumbnail_image(f) else { return false };
|
||||
let t = ctx.load_texture(format!("gradient-thumb-{}", layer.0), img, egui::TextureOptions::LINEAR);
|
||||
ctx.data_mut(|d| d.insert_temp(key, (f.clone(), t.clone())));
|
||||
t
|
||||
}
|
||||
};
|
||||
if ui.is_rect_visible(rect) {
|
||||
let p = ui.painter();
|
||||
widgets::checker(p, rect, 5.0);
|
||||
p.image(tex.id(), rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Options-bar swatch of the current gradient (live mode uses the Gradients panel selection).
|
||||
pub fn preset_swatch(ui: &mut egui::Ui, stops: &[(f32, [f32; 4])]) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(96.0, 20.0), Sense::hover());
|
||||
paint_ramp(ui.painter(), r, |u| photocraft_algo::paint::sample_stops(stops, u));
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
|
||||
let _ = resp.on_hover_text("The current gradient (pick one in Window › Gradients)");
|
||||
}
|
||||
|
||||
/// Live mode: style, reverse and dither changes in the options bar also edit the selected
|
||||
/// gradient fill layer (one history step each), as in Photoshop.
|
||||
pub fn options_changed(app: &mut PhotocraftApp, before: &crate::state::ToolOptions) {
|
||||
let o = app.ui.tool_options.clone();
|
||||
if o.gradient_classic
|
||||
|| (o.gradient_style == before.gradient_style && o.gradient_reverse == before.gradient_reverse && o.gradient_dither == before.gradient_dither)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some((l, ..)) = active_gradient(app) else { return };
|
||||
let mut p = json!({"layer": l.id.0});
|
||||
if o.gradient_style != before.gradient_style {
|
||||
p["style"] = json!(o.gradient_style);
|
||||
}
|
||||
if o.gradient_reverse != before.gradient_reverse {
|
||||
p["reverse"] = json!(o.gradient_reverse);
|
||||
}
|
||||
if o.gradient_dither != before.gradient_dither {
|
||||
p["dither"] = json!(o.gradient_dither);
|
||||
}
|
||||
let _ = app.run(cmds::SET, p);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Properties panel
|
||||
|
||||
/// Width of the Properties label column ("Style", "Angle", "Scale").
|
||||
const PROP_LABEL_W: f32 = 38.0;
|
||||
|
||||
/// Commits a numeric field once (drag released, Enter, focus lost); `None` while editing.
|
||||
fn field(ui: &mut egui::Ui, id: &str, current: f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32) -> Option<f32> {
|
||||
let key = egui::Id::new(("gradient-fill-field", id));
|
||||
let mut v = ui.data(|d| d.get_temp::<f32>(key)).unwrap_or(current);
|
||||
let resp = widgets::value_field(ui, &mut v, range, suffix, width);
|
||||
if resp.dragged() || resp.has_focus() {
|
||||
ui.data_mut(|d| d.insert_temp(key, v));
|
||||
return None;
|
||||
}
|
||||
ui.data_mut(|d| d.remove::<f32>(key));
|
||||
(resp.drag_stopped() || resp.lost_focus() || resp.changed()).then_some(v).filter(|v| (*v - current).abs() > 1e-3)
|
||||
}
|
||||
|
||||
fn label(ui: &mut egui::Ui, text: &str) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (r, _) = ui.allocate_exact_size(vec2(PROP_LABEL_W, 22.0), Sense::hover());
|
||||
ui.painter().text(pos2(r.left(), r.center().y), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(12.0), t.text_dim);
|
||||
}
|
||||
|
||||
/// Properties panel sections for a gradient fill layer (`props_layout::section` headers):
|
||||
/// "Gradient" (the stops editor) and "Gradient Options" (style, angle, scale, reverse, dither,
|
||||
/// "Align with layer", Reset Alignment). Every change is one `gradient.fill.*` command.
|
||||
pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {
|
||||
use crate::props_layout::{COL_GAP, LABEL_GAP, field_width, section};
|
||||
let Some(Fill::Gradient { angle, scale, style, reverse, dither, align, .. }) = fill_of(layer).cloned() else { return };
|
||||
let id = layer.id.0;
|
||||
let mut runs: Vec<Value> = Vec::new();
|
||||
if section(ui, "gradient-fill", "Gradient") {
|
||||
stops_editor(app, ui, layer);
|
||||
ui.add_space(crate::theme::ROW_GAP);
|
||||
}
|
||||
if section(ui, "gradient-fill-options", "Gradient Options") {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = LABEL_GAP;
|
||||
label(ui, "Style");
|
||||
let mut s = cmds::style_name(style).to_string();
|
||||
let opts: Vec<(String, &str)> =
|
||||
[("linear", "Linear"), ("radial", "Radial"), ("angle", "Angle"), ("reflected", "Reflected"), ("diamond", "Diamond")]
|
||||
.iter()
|
||||
.map(|(k, l)| (k.to_string(), *l))
|
||||
.collect();
|
||||
// Full width, lined up with the fields and Reset Alignment below.
|
||||
let w = ui.available_width().max(60.0);
|
||||
if widgets::dropdown(ui, "gradient-fill-style", &mut s, &opts, w) {
|
||||
runs.push(json!({"style": s}));
|
||||
}
|
||||
});
|
||||
ui.add_space(crate::theme::ROW_GAP);
|
||||
// Two label+field columns filling the panel.
|
||||
let w = field_width(ui.available_width(), 2, PROP_LABEL_W);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = LABEL_GAP;
|
||||
label(ui, "Angle");
|
||||
if let Some(v) = field(ui, &format!("angle{id}"), angle, -180.0..=180.0, "°", w) {
|
||||
runs.push(json!({"angle": v}));
|
||||
}
|
||||
ui.add_space(COL_GAP - LABEL_GAP);
|
||||
label(ui, "Scale");
|
||||
if let Some(v) = field(ui, &format!("scale{id}"), scale * 100.0, 10.0..=150.0, "%", w) {
|
||||
runs.push(json!({"scale": v}));
|
||||
}
|
||||
});
|
||||
ui.add_space(crate::theme::ROW_GAP);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let mut r = reverse;
|
||||
if widgets::checkbox(ui, &mut r, "Reverse").changed() {
|
||||
runs.push(json!({"reverse": r}));
|
||||
}
|
||||
let mut d = dither;
|
||||
if widgets::checkbox(ui, &mut d, "Dither").changed() {
|
||||
runs.push(json!({"dither": d}));
|
||||
}
|
||||
let mut a = align;
|
||||
if widgets::checkbox(ui, &mut a, "Align with layer").changed() {
|
||||
runs.push(json!({"align": a}));
|
||||
}
|
||||
});
|
||||
ui.add_space(crate::theme::ROW_GAP);
|
||||
if widgets::secondary_button(ui, "Reset Alignment", ui.available_width()).on_hover_text("Centre the gradient (offset 0, 0)").clicked() {
|
||||
runs.push(json!({"offset": [0, 0]}));
|
||||
}
|
||||
ui.add_space(crate::theme::ROW_GAP);
|
||||
}
|
||||
for mut p in runs {
|
||||
p["layer"] = json!(id);
|
||||
let _ = app.run(cmds::SET, p);
|
||||
}
|
||||
}
|
||||
|
||||
/// Which marker of the stops editor is being dragged.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Marker {
|
||||
Color(usize),
|
||||
Opacity(usize),
|
||||
Mid(usize),
|
||||
}
|
||||
|
||||
/// Photoshop's Gradient Editor strip: opacity stops above the ramp, colour stops and midpoints
|
||||
/// below. Drag a stop to move it (off the strip to delete it), click above / below to add one,
|
||||
/// double-click a colour stop for the Color Picker.
|
||||
fn stops_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {
|
||||
let Some(f) = fill_of(layer).cloned() else { return };
|
||||
let Fill::Gradient { stops, .. } = &f else { return };
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let id = layer.id;
|
||||
let w = ui.available_width().max(120.0);
|
||||
let (outer, resp) = ui.allocate_exact_size(vec2(w, 58.0), Sense::click_and_drag());
|
||||
let bar = Rect::from_min_max(pos2(outer.left() + 8.0, outer.top() + 16.0), pos2(outer.right() - 8.0, outer.top() + 40.0));
|
||||
let x_of = |loc: f32| bar.left() + loc.clamp(0.0, 1.0) * bar.width();
|
||||
let loc_of = |x: f32| ((x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0);
|
||||
// The ramp being shown (with a pending drag's edit applied).
|
||||
let pending = app.gradient.panel.clone().filter(|(l, ..)| *l == id);
|
||||
let shown = pending.as_ref().and_then(|(_, cmd, p)| edited_fill(app, layer, Rect32::new(0, 0, 1, 1), cmd, p)).unwrap_or_else(|| f.clone());
|
||||
if let Some(ramp) = gf::Ramp::new(&shown) {
|
||||
paint_ramp(ui.painter(), bar, |u| ramp.sample(u));
|
||||
}
|
||||
ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Outside);
|
||||
let (ss, os, mids) = match &shown {
|
||||
Fill::Gradient { stops, opacity_stops, midpoints, .. } => (stops.clone(), opacity_stops.clone(), midpoints.clone()),
|
||||
_ => (Vec::new(), Vec::new(), Vec::new()),
|
||||
};
|
||||
let mut sorted = ss.clone();
|
||||
sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let ops: Vec<(f32, f32)> = if os.is_empty() { vec![(0.0, 1.0), (1.0, 1.0)] } else { os.clone() };
|
||||
let key = egui::Id::new(("gradient-stops-drag", id.0));
|
||||
let dragging: Option<Marker> = ui.data(|d| d.get_temp(key));
|
||||
// Markers.
|
||||
let p = ui.painter();
|
||||
for (i, (loc, c)) in sorted.iter().enumerate() {
|
||||
let x = x_of(*loc);
|
||||
let sel = dragging == Some(Marker::Color(i));
|
||||
let tip = pos2(x, bar.bottom() + 1.0);
|
||||
let body = Rect::from_center_size(pos2(x, bar.bottom() + 10.0), vec2(10.0, 10.0));
|
||||
p.add(egui::Shape::convex_polygon(
|
||||
vec![tip, pos2(x + 5.0, body.top()), pos2(x - 5.0, body.top())],
|
||||
if sel { t.accent } else { t.text_dim },
|
||||
Stroke::NONE,
|
||||
));
|
||||
p.rect_filled(
|
||||
body,
|
||||
1.0,
|
||||
c32({
|
||||
let r = c.to_rgb();
|
||||
[r[0], r[1], r[2], 1.0]
|
||||
}),
|
||||
);
|
||||
p.rect_stroke(body, 1.0, Stroke::new(1.0, if sel { t.accent } else { t.text_dim }), StrokeKind::Outside);
|
||||
}
|
||||
for i in 0..sorted.len().saturating_sub(1) {
|
||||
let (a, b) = (sorted[i].0, sorted[i + 1].0);
|
||||
if b - a > 1e-3 {
|
||||
let m = mids.get(i).copied().unwrap_or(0.5);
|
||||
let sel = dragging == Some(Marker::Mid(i));
|
||||
diamond(p, pos2(x_of(a + (b - a) * m), bar.bottom() + 6.0), 3.0, if sel { t.accent } else { t.text_faint }, t.text_faint);
|
||||
}
|
||||
}
|
||||
for (i, (loc, a)) in ops.iter().enumerate() {
|
||||
let x = x_of(*loc);
|
||||
let sel = dragging == Some(Marker::Opacity(i));
|
||||
let body = Rect::from_center_size(pos2(x, bar.top() - 10.0), vec2(10.0, 10.0));
|
||||
p.add(egui::Shape::convex_polygon(
|
||||
vec![pos2(x, bar.top() - 1.0), pos2(x + 5.0, body.bottom()), pos2(x - 5.0, body.bottom())],
|
||||
if sel { t.accent } else { t.text_dim },
|
||||
Stroke::NONE,
|
||||
));
|
||||
p.rect_filled(body, 1.0, Color32::from_gray((a.clamp(0.0, 1.0) * 255.0) as u8));
|
||||
p.rect_stroke(body, 1.0, Stroke::new(1.0, if sel { t.accent } else { t.text_dim }), StrokeKind::Outside);
|
||||
}
|
||||
// Interaction.
|
||||
let hit = |pos: Pos2| -> Option<Marker> {
|
||||
if pos.y > bar.bottom() {
|
||||
if let Some(i) = sorted.iter().position(|(l, _)| (x_of(*l) - pos.x).abs() <= 6.0 && pos.y >= bar.bottom() + 3.0) {
|
||||
return Some(Marker::Color(i));
|
||||
}
|
||||
return (0..sorted.len().saturating_sub(1))
|
||||
.find(|i| {
|
||||
let (a, b) = (sorted[*i].0, sorted[*i + 1].0);
|
||||
(x_of(a + (b - a) * mids.get(*i).copied().unwrap_or(0.5)) - pos.x).abs() <= 4.0 && b - a > 1e-3
|
||||
})
|
||||
.map(Marker::Mid);
|
||||
}
|
||||
if pos.y < bar.top() {
|
||||
return ops.iter().position(|(l, _)| (x_of(*l) - pos.x).abs() <= 6.0).map(Marker::Opacity);
|
||||
}
|
||||
None
|
||||
};
|
||||
if resp.drag_started()
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
&& let Some(m) = hit(pos)
|
||||
{
|
||||
ui.data_mut(|d| d.insert_temp(key, m));
|
||||
}
|
||||
let dragging: Option<Marker> = ui.data(|d| d.get_temp(key));
|
||||
if let (Some(m), Some(pos)) = (dragging, resp.interact_pointer_pos()) {
|
||||
let off = if pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0 { 1.0 } else { 0.0 };
|
||||
let loc = loc_of(pos.x);
|
||||
let edit = match m {
|
||||
Marker::Color(i) if off > 0.0 && stops.len() > 2 => json!({"action": "delete", "index": i}),
|
||||
Marker::Color(i) => json!({"action": "move", "index": i, "location": loc}),
|
||||
Marker::Opacity(i) if off > 0.0 && ops.len() > 2 => json!({"action": "delete", "kind": "opacity", "index": i}),
|
||||
Marker::Opacity(i) => json!({"action": "move", "kind": "opacity", "index": i, "location": loc}),
|
||||
Marker::Mid(i) => {
|
||||
let (a, b) = (sorted.get(i).map_or(0.0, |s| s.0), sorted.get(i + 1).map_or(1.0, |s| s.0));
|
||||
json!({"action": "midpoint", "index": i, "location": ((loc - a) / (b - a).max(1e-4)).clamp(0.05, 0.95)})
|
||||
}
|
||||
};
|
||||
let mut edit = edit;
|
||||
edit["layer"] = json!(id.0);
|
||||
if resp.dragged() {
|
||||
app.gradient.panel = Some((id, cmds::STOP, edit));
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped() {
|
||||
ui.data_mut(|d| d.remove::<Marker>(key));
|
||||
if let Some((_, cmd, p)) = app.gradient.panel.take() {
|
||||
let _ = app.run(cmd, p);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if resp.double_clicked()
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
&& let Some(Marker::Color(i)) = hit(pos)
|
||||
{
|
||||
edit_stop_color(app, id, i);
|
||||
return;
|
||||
}
|
||||
if resp.clicked()
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
&& hit(pos).is_none()
|
||||
{
|
||||
let loc = loc_of(pos.x);
|
||||
let p = if pos.y < bar.center().y {
|
||||
json!({"layer": id.0, "action": "add", "kind": "opacity", "location": loc})
|
||||
} else {
|
||||
json!({"layer": id.0, "action": "add", "location": loc})
|
||||
};
|
||||
let _ = app.run(cmds::STOP, p);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn app_with_gradient(style: &str) -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 120})).unwrap();
|
||||
app.ui.tool = Tool::Gradient;
|
||||
app.ui.tool_options.gradient_style = style.into();
|
||||
app
|
||||
}
|
||||
|
||||
fn mods() -> egui::Modifiers {
|
||||
egui::Modifiers::NONE
|
||||
}
|
||||
|
||||
fn drag(app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2]) {
|
||||
crate::canvas::tool_event(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, mods());
|
||||
crate::canvas::tool_event(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, mods());
|
||||
crate::canvas::tool_event(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, mods());
|
||||
crate::canvas::tool_event(app, ToolEvent::Up { x: b[0], y: b[1] }, mods());
|
||||
}
|
||||
|
||||
fn get(app: &mut PhotocraftApp) -> Value {
|
||||
app.run(cmds::GET, json!({})).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thumbnails_show_the_gradient() {
|
||||
use photocraft_color::Color;
|
||||
// Black to white, left to right: the left edge is dark, the right light, top = bottom.
|
||||
let f = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false);
|
||||
let img = thumbnail_image(&f).unwrap();
|
||||
let n = img.size[0];
|
||||
let at = |x: usize, y: usize| img.pixels[y * n + x];
|
||||
assert!(at(0, n / 2).r() < 10 && at(n - 1, n / 2).r() > 245, "{:?} {:?}", at(0, n / 2), at(n - 1, n / 2));
|
||||
assert_eq!(at(n / 3, 0), at(n / 3, n - 1));
|
||||
// Reverse flips colour and opacity alike; a transparent stop lets the checkerboard through.
|
||||
let mut r = f.clone();
|
||||
if let Fill::Gradient { reverse, opacity_stops, .. } = &mut r {
|
||||
*reverse = true;
|
||||
*opacity_stops = vec![(0.0, 1.0), (1.0, 0.0)];
|
||||
}
|
||||
let img = thumbnail_image(&r).unwrap();
|
||||
let (left, right) = (img.pixels[n / 2 * n], img.pixels[n / 2 * n + n - 1]);
|
||||
assert!(left.a() < 10 && right.r() < 10 && right.a() > 245, "{left:?} {right:?}");
|
||||
// A radial thumbnail is centred.
|
||||
let rad = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Radial, false);
|
||||
let img = thumbnail_image(&rad).unwrap();
|
||||
assert!(img.pixels[n / 2 * n + n / 2].r() < img.pixels[0].r());
|
||||
assert!(thumbnail_image(&Fill::Solid(Color::WHITE)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_drag_creates_a_fill_layer_and_handles_edit_it() {
|
||||
let mut app = app_with_gradient("linear");
|
||||
drag(&mut app, [20.0, 60.0], [180.0, 60.0]);
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), 2, "a Gradient Fill layer");
|
||||
let g = get(&mut app);
|
||||
assert!((g["to"][0].as_f64().unwrap() - 180.0).abs() < 1e-3);
|
||||
// Drag the end handle: one history step.
|
||||
let before = app.session.active().unwrap().history.past_len();
|
||||
drag(&mut app, [180.0, 60.0], [150.0, 100.0]);
|
||||
let g = get(&mut app);
|
||||
assert!((g["to"][0].as_f64().unwrap() - 150.0).abs() < 1e-3 && (g["to"][1].as_f64().unwrap() - 100.0).abs() < 1e-3, "{g}");
|
||||
assert_eq!(app.session.active().unwrap().history.past_len(), before + 1);
|
||||
// Click on the line adds a stop; dragging it off the line deletes it.
|
||||
let (s, e) = ([20.0, 60.0], [150.0, 100.0]);
|
||||
// A third of the way (the midpoint diamond sits half-way).
|
||||
let mid = [s[0] + (e[0] - s[0]) / 3.0, s[1] + (e[1] - s[1]) / 3.0];
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: mid[0], y: mid[1], pressure: 1.0 }, mods());
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: mid[0], y: mid[1] }, mods());
|
||||
assert_eq!(get(&mut app)["stops"].as_array().unwrap().len(), 3);
|
||||
drag(&mut app, mid, [mid[0], mid[1] - 80.0]);
|
||||
assert_eq!(get(&mut app)["stops"].as_array().unwrap().len(), 2);
|
||||
// A drag away from the widget redraws the selected gradient (no new layer).
|
||||
drag(&mut app, [100.0, 10.0], [100.0, 110.0]);
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), 2);
|
||||
assert!((get(&mut app)["from"][1].as_f64().unwrap() - 10.0).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_snaps_live_drags_to_45_degrees() {
|
||||
let mut app = app_with_gradient("linear");
|
||||
let shift = egui::Modifiers::SHIFT;
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, shift);
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 70.0, y: 62.0, pressure: 1.0 }, shift);
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 84.0 }, shift);
|
||||
let g = get(&mut app);
|
||||
let (fx, fy, tx, ty) = (g["from"][0].as_f64().unwrap(), g["from"][1].as_f64().unwrap(), g["to"][0].as_f64().unwrap(), g["to"][1].as_f64().unwrap());
|
||||
assert!(((tx - fx) - (ty - fy)).abs() < 1e-2 && tx > 80.0, "45°: {g}");
|
||||
// Dragging the end handle with ⇧ snaps too (horizontal here).
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: tx, y: ty, pressure: 1.0 }, shift);
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 26.0 }, shift);
|
||||
let g = get(&mut app);
|
||||
assert!((g["to"][1].as_f64().unwrap() - fy).abs() < 1e-2, "horizontal: {g}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classic_mode_paints_pixels() {
|
||||
let mut app = app_with_gradient("linear");
|
||||
app.ui.tool_options.gradient_classic = true;
|
||||
drag(&mut app, [20.0, 60.0], [180.0, 60.0]);
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "no fill layer in classic mode");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_shows_the_drag_before_commit() {
|
||||
let mut app = app_with_gradient("radial");
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }, mods());
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Move { x: 140.0, y: 60.0, pressure: 1.0 }, mods());
|
||||
let (doc, key) = display_doc(&mut app, 0).expect("a preview while drawing");
|
||||
assert!(key & TAG != 0);
|
||||
assert!(doc.layer(PREVIEW_LAYER).is_some(), "the new layer previews");
|
||||
assert_eq!(app.session.active().unwrap().doc.layers.len(), 1, "nothing committed yet");
|
||||
crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 140.0, y: 60.0 }, mods());
|
||||
assert!(display_doc(&mut app, 0).is_none());
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,10 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {
|
||||
ui.add_space(ROW_GAP);
|
||||
}
|
||||
}
|
||||
// Gradient fills: their gradient first, as in Photoshop's Properties panel.
|
||||
if matches!(layer.content, LayerContent::Fill(photocraft_doc::Fill::Gradient { .. })) {
|
||||
crate::gradient_ui::properties(app, ui, layer);
|
||||
}
|
||||
if section(ui, "align", "Align and Distribute") {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
|
||||
@@ -42,6 +42,7 @@ pub mod file_ui;
|
||||
pub mod filter_dialog;
|
||||
pub mod gallery_ui;
|
||||
pub mod gpu_canvas;
|
||||
pub mod gradient_ui;
|
||||
mod icon_data;
|
||||
pub mod icons;
|
||||
pub mod layer_menu_ui;
|
||||
@@ -273,6 +274,8 @@ pub struct PhotocraftApp {
|
||||
pub(crate) style_preview: Option<(u64, Option<std::sync::Arc<Document>>)>,
|
||||
/// Liquify dialog, Puppet Warp and Perspective Warp sessions (distort_ui).
|
||||
pub(crate) distort: distort_ui::Distort,
|
||||
/// Gradient tool live-mode drags and previews (gradient_ui).
|
||||
pub(crate) gradient: gradient_ui::LiveGradient,
|
||||
/// Filter › Camera Raw Filter dialog (camera_raw_ui).
|
||||
pub(crate) camera_raw: Option<camera_raw_ui::CameraRawDialog>,
|
||||
/// Filter › Adaptive Wide Angle dialog (wide_angle_ui).
|
||||
@@ -368,6 +371,7 @@ impl PhotocraftApp {
|
||||
move_mods: Default::default(),
|
||||
style_preview: None,
|
||||
distort: Default::default(),
|
||||
gradient: Default::default(),
|
||||
camera_raw: None,
|
||||
wide_angle: None,
|
||||
tone_hist: None,
|
||||
|
||||
@@ -580,9 +580,20 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.sample_all_layers, "All Layers");
|
||||
}
|
||||
Tool::Gradient if t.pro => {
|
||||
gradient_swatch(ui, app.session.tools.foreground, app.session.tools.background);
|
||||
// Live "Gradient" (a Gradient Fill layer) or "Classic gradient" (pixels).
|
||||
let mut classic = app.ui.tool_options.gradient_classic;
|
||||
if widgets::dropdown(ui, "gradient-mode", &mut classic, &[(false, "Gradient"), (true, "Classic gradient")], 118.0) {
|
||||
app.ui.tool_options.gradient_classic = classic;
|
||||
}
|
||||
let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);
|
||||
if classic {
|
||||
gradient_swatch(ui, fg, bg);
|
||||
} else {
|
||||
crate::gradient_ui::preset_swatch(ui, &app.session.presets.gradient.resolve(fg, bg));
|
||||
}
|
||||
widgets::vline(ui, 22.0);
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
let before = app.ui.tool_options.clone();
|
||||
for (style, icon, tip) in [
|
||||
("linear", "blend", "Linear Gradient"),
|
||||
("radial", "circle", "Radial Gradient"),
|
||||
@@ -600,6 +611,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, "Reverse");
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, "Dither");
|
||||
// Live mode: the options also change a selected gradient fill layer.
|
||||
crate::gradient_ui::options_changed(app, &before);
|
||||
}
|
||||
Tool::Crop if t.pro => {
|
||||
let o = &mut app.ui.tool_options;
|
||||
@@ -1575,10 +1588,11 @@ fn draw_layer_thumb(app: &mut PhotocraftApp, ctx: &egui::Context, ui: &egui::Ui,
|
||||
p.rect_filled(rect, if t.pro { 0.0 } else { 6.0 }, Color32::from_gray(if t.pro { 222 } else { 236 }));
|
||||
icons::paint(ui, rect, "type", 20.0, Color32::from_gray(40));
|
||||
}
|
||||
// Gradient fills show the gradient itself (Photoshop); solid ones their colour.
|
||||
LayerContent::Fill(f) if crate::gradient_ui::paint_thumbnail(ui, l.id, f, rect) => {}
|
||||
LayerContent::Fill(f) => {
|
||||
let c = match f {
|
||||
photocraft_doc::Fill::Solid(c) => c.to_rgba8(),
|
||||
photocraft_doc::Fill::Gradient { stops, .. } => stops.first().map(|s| s.1.to_rgba8()).unwrap_or([0; 4]),
|
||||
_ => [128, 128, 128, 255],
|
||||
};
|
||||
p.rect_filled(rect, 6.0, Color32::from_rgba_unmultiplied(c[0], c[1], c[2], c[3]));
|
||||
@@ -1866,6 +1880,10 @@ fn properties_body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
// Transform, Align, the kind's sections and Quick Actions.
|
||||
crate::layer_props_ui::properties(app, ui, layer);
|
||||
} else {
|
||||
if matches!(layer.content, LayerContent::Fill(photocraft_doc::Fill::Gradient { .. })) {
|
||||
crate::gradient_ui::properties(app, ui, layer);
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
layer_controls(app, ui, layer);
|
||||
if matches!(layer.content, LayerContent::Text(_)) {
|
||||
crate::type_tool::type_properties(app, ui);
|
||||
|
||||
@@ -312,6 +312,9 @@ pub struct ToolOptions {
|
||||
pub gradient_reverse: bool,
|
||||
/// Gradient tool: dither to reduce 8-bit banding (Photoshop default on).
|
||||
pub gradient_dither: bool,
|
||||
/// Gradient tool mode: false = "Gradient" (live: a Gradient Fill layer, editable on canvas),
|
||||
/// true = "Classic gradient" (paints the pixels).
|
||||
pub gradient_classic: bool,
|
||||
pub fill_opacity: f32,
|
||||
/// Paint Bucket fill source: false = Foreground colour, true = Pattern (Patterns panel selection).
|
||||
pub bucket_fill_pattern: bool,
|
||||
@@ -410,6 +413,7 @@ impl Default for ToolOptions {
|
||||
gradient_style: "linear".into(),
|
||||
gradient_reverse: false,
|
||||
gradient_dither: true,
|
||||
gradient_classic: false,
|
||||
fill_opacity: 100.0,
|
||||
bucket_fill_pattern: false,
|
||||
type_font: "Inter".into(),
|
||||
|
||||
@@ -220,6 +220,8 @@ mod tests {
|
||||
fn shift_gradient_snaps_to_45_degrees() {
|
||||
let mut app = app();
|
||||
app.ui.tool = Tool::Gradient;
|
||||
// The destructive drag (live gradients snap in gradient_ui.rs, with the same helper).
|
||||
app.ui.tool_options.gradient_classic = true;
|
||||
let shift = egui::Modifiers::SHIFT;
|
||||
tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, shift);
|
||||
tool_event(&mut app, ToolEvent::Move { x: 60.0, y: 52.0, pressure: 1.0 }, shift);
|
||||
|
||||
@@ -226,7 +226,7 @@ impl Paint {
|
||||
};
|
||||
match f {
|
||||
Fill::Solid(c) => Paint::Solid(rgba(c)),
|
||||
Fill::Gradient { stops, angle, scale, style, reverse } => Paint::Gradient {
|
||||
Fill::Gradient { stops, angle, scale, style, reverse, .. } => Paint::Gradient {
|
||||
stops: stops.iter().map(|(p, c)| (*p, rgba(c))).collect(),
|
||||
style: *style,
|
||||
angle: *angle,
|
||||
|
||||
@@ -216,13 +216,7 @@ fn render_shape_formats_and_paint() {
|
||||
fn gradient_fill_spans_bounds() {
|
||||
let sh = ShapeLayer {
|
||||
path: shapes::rect(0.0, 0.0, 100.0, 10.0),
|
||||
fill: Some(Fill::Gradient {
|
||||
stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)],
|
||||
angle: 0.0,
|
||||
scale: 1.0,
|
||||
style: photocraft_doc::GradientStyle::Linear,
|
||||
reverse: false,
|
||||
}),
|
||||
fill: Some(Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, photocraft_doc::GradientStyle::Linear, false)),
|
||||
..Default::default()
|
||||
};
|
||||
let rgba = CompiledShape::new(&sh, DEFAULT_TOLERANCE).render_rgba(Rect::new(0, 0, 100, 10));
|
||||
|
||||
Reference in new issue
Block a user