mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-21 01:52:49 +01:00
chore: merge main into m8/light-theme
This commit is contained in:
commit
f1bc0804d4
50 files changed
+2835
-203
No files matched your search
+1
-1
@@ -19,7 +19,7 @@ shaders or SDK code).
|
||||
| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | <https://github.com/source-foundry/Hack> | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) |
|
||||
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (26 files: align, distribute, layer, mask and masked layer, width tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage) | Align panel, layer-type, Width tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone and Bind tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
|
||||
| `assets/icons/anicraft-*.svg` (27 files: align, distribute, layer, mask and masked layer, width tool, gradient transform tool, camera, brush, paint brush, eraser, eyedropper, muted sound, magnet, bone, bind, edit multiple frames, insert frame, keyframe and blank keyframe, clip to the stage) | Align panel, layer-type, Width tool, Gradient Transform tool, Camera, Brush, Paint Brush, Eraser, Eyedropper, Bone and Bind tool icons, the timeline's mute toggle, Snap to Objects, Edit Multiple Frames, the timeline's Insert Frame / Keyframe / Blank Keyframe buttons, Clip Content Outside the Stage | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style (the muted sound keeps the speaker of Lucide's `volume-2`, ISC, crossed out) | MIT OR Apache-2.0 |
|
||||
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `crates/svg/fixtures/soft-masks-text-paths.svg` | SVG import test drawing (an alpha and a luminance mask, text on a path) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
|
||||
@@ -13,6 +13,25 @@
|
||||
* `anicraft --theme light` (also `dark`, `high-contrast`) previews a theme for one run.
|
||||
* Every palette is checked by the contrast test (WCAG AA text, 3:1 controls and focus).
|
||||
|
||||
* **Gradient editor, the Gradient Transform tool and Lock Fill** (M1, ADR 0074; #208, #203).
|
||||
* **Added**: gradients in the colour picker. The fill's picker (the Tools panel's Fill square,
|
||||
and every Fill swatch in Properties) starts with the fill's type: None, Solid, Linear,
|
||||
Radial or Bitmap. A gradient shows a bar of colour stops (click to add, drag to move, drag
|
||||
off to remove; arrow keys and Delete on a focused stop), overflow (Extend, Reflect, Repeat),
|
||||
Linear RGB and a radial gradient's focal point, above the same swatches, mixer and hex
|
||||
field, which then set the picked stop's colour and opacity. A gradient's swatch in
|
||||
Properties shows its ramp. One picker, as Animate has one Color panel; the fill's No Colour
|
||||
is its type None.
|
||||
* **Added**: the **Gradient Transform** tool (**F**): move, turn, stretch and resize a gradient,
|
||||
move a radial gradient's focal point, and scale, turn and skew a bitmap fill. Each drag is
|
||||
one undo step.
|
||||
* **Added**: **Lock Fill** for the Paint Bucket and the Brush. Without it, gradients and bitmaps
|
||||
are fitted to each shape, as in Animate; the Eyedropper turns it on for what it picks.
|
||||
* **Added**: commands `paint.set_fill`, `paint.transform_fill` and `paint.lock_fill`, for
|
||||
scripts, the CLI and MCP.
|
||||
* **Improved**: gradients keep their overflow, Linear RGB, focal point and elliptical shape
|
||||
from Animate files and SVG drawings, on the GPU stage and in SVG export (HTML canvas draws
|
||||
them as near as canvas can). Radial gradients on skewed shapes are now drawn exactly.
|
||||
* **Dockable panels and workspaces** (M8, ADR 0075, fixes #249).
|
||||
* Drag any panel's tab to dock it on any side of the stage (the timeline above the stage, for
|
||||
example), stack it with other panels as a tab, or float it in a window of its own (inside
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="7" width="14" height="14" rx="2" />
|
||||
<path d="M8 7 L8 21" />
|
||||
<path d="M11.5 7 L11.5 21" />
|
||||
<path d="M14.3 7 L14.3 21" />
|
||||
<path d="M17 7 L19.2 4.8" />
|
||||
<circle cx="20.3" cy="3.7" r="1.5" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 403 B |
+20
-4
@@ -705,10 +705,26 @@ fn sliced_shape(s: &Shape, own: &Affine, sl: &Slicing) -> (Arc<Path>, Affine, Op
|
||||
let stroke = s.stroke.as_ref().map(|st| if (k - 1.0).abs() > 1e-6 { st.scaled(k) } else { st.clone() });
|
||||
let at = |p: anicraft_geom::Vec2| sl.map.map(own.apply(p));
|
||||
let size = k * sl.scale.mean_scale();
|
||||
let fill = s.fill.as_ref().map(|f| match f {
|
||||
Paint::Linear { start, end, stops } => Paint::Linear { start: at(*start), end: at(*end), stops: stops.clone() },
|
||||
Paint::Radial { center, radius, stops } => Paint::Radial { center: at(*center), radius: radius * size, stops: stops.clone() },
|
||||
Paint::Solid(_) | Paint::Bitmap { .. } => f.clone(),
|
||||
let fill = s.fill.as_ref().map(|f| {
|
||||
let mut f = f.clone();
|
||||
match &mut f {
|
||||
Paint::Linear { start, end, .. } => {
|
||||
*start = at(*start);
|
||||
*end = at(*end);
|
||||
}
|
||||
Paint::Radial { center, radius, matrix, .. } => {
|
||||
// The ring's shape (its matrix's linear part) stays, round the mapped centre.
|
||||
let c = at(matrix.apply(*center));
|
||||
let l = Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] };
|
||||
if *matrix != Affine::IDENTITY {
|
||||
*matrix = Affine::translate(c.x, c.y).mul(&l).mul(&Affine::translate(-c.x, -c.y));
|
||||
}
|
||||
*center = c;
|
||||
*radius *= size;
|
||||
}
|
||||
Paint::Solid(_) | Paint::Bitmap { .. } => {}
|
||||
}
|
||||
f
|
||||
});
|
||||
(path, sl.post, fill, stroke)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Gradient options, fill frames and fitting (ADR 0074).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn stops() -> Vec<GradientStop> {
|
||||
vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }]
|
||||
}
|
||||
|
||||
fn near(a: &Affine, b: &Affine) -> bool {
|
||||
a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-4 * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_maps_positions_onto_the_ramp() {
|
||||
for (t, pad, reflect, repeat) in [(-0.25, 0.0, 0.25, 0.75), (0.0, 0.0, 0.0, 0.0), (0.4, 0.4, 0.4, 0.4), (1.25, 1.0, 0.75, 0.25), (2.5, 1.0, 0.5, 0.5), (-1.5, 0.0, 0.5, 0.5)] {
|
||||
assert!((Spread::Pad.apply(t) - pad).abs() < 1e-6, "pad {t}");
|
||||
assert!((Spread::Reflect.apply(t) - reflect).abs() < 1e-6, "reflect {t}");
|
||||
assert!((Spread::Repeat.apply(t) - repeat).abs() < 1e-6, "repeat {t}");
|
||||
}
|
||||
for s in Spread::ALL {
|
||||
assert_eq!(s.apply(f32::NAN), 0.0);
|
||||
assert!((0.0..=1.0).contains(&s.apply(f32::INFINITY)));
|
||||
assert_eq!(Spread::from_key(s.key()), Some(s));
|
||||
}
|
||||
assert_eq!(Spread::from_key("pad"), Some(Spread::Pad));
|
||||
assert_eq!(Spread::from_key("mirror"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_round_trip_for_every_fill_kind() {
|
||||
// Linear: x from start to end, y square to it at the same length.
|
||||
let lin = Paint::linear(Vec2::new(10.0, 20.0), Vec2::new(30.0, 20.0), stops());
|
||||
let f = lin.frame(None).unwrap();
|
||||
assert!(near(&f, &Affine { m: [10.0, 0.0, 0.0, 10.0, 20.0, 20.0] }), "{f:?}");
|
||||
assert_eq!(lin.with_frame(&f, None), lin);
|
||||
// Radial: a circle stays a plain circle, with no matrix.
|
||||
let rad = Paint::radial(Vec2::new(5.0, 6.0), 4.0, stops());
|
||||
let f = rad.frame(None).unwrap();
|
||||
assert!(near(&f, &Affine { m: [4.0, 0.0, 0.0, 4.0, 5.0, 6.0] }));
|
||||
assert_eq!(rad.with_frame(&f, None), rad);
|
||||
// A turned ellipse keeps its centre and its x axis's length as the radius.
|
||||
let ell = Affine::translate(50.0, 40.0).mul(&Affine::rotate(0.5)).mul(&Affine::scale(30.0, 10.0));
|
||||
let p = rad.with_frame(&ell, None);
|
||||
match &p {
|
||||
Paint::Radial { center, radius, matrix, .. } => {
|
||||
assert!(center.distance(Vec2::new(50.0, 40.0)) < 1e-4);
|
||||
assert!((radius - 30.0).abs() < 1e-4);
|
||||
assert!(near(&matrix.mul(&Affine::translate(center.x, center.y)), &Affine::translate(center.x, center.y).mul(&Affine { m: [matrix.m[0], matrix.m[1], matrix.m[2], matrix.m[3], 0.0, 0.0] })), "the matrix turns about the centre");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert!(near(&p.frame(None).unwrap(), &ell));
|
||||
// Bitmap: the box onto one copy of the image.
|
||||
let bmp = Paint::Bitmap { bitmap: BitmapId(1), repeat: true, matrix: Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0)) };
|
||||
let f = bmp.frame(Some((10.0, 6.0))).unwrap();
|
||||
assert!(f.apply(Vec2::new(-1.0, -1.0)).distance(Vec2::new(3.0, 4.0)) < 1e-4, "top-left of the image");
|
||||
assert!(f.apply(Vec2::new(1.0, 1.0)).distance(Vec2::new(23.0, 16.0)) < 1e-4, "bottom-right");
|
||||
assert_eq!(bmp.frame(None), None, "a bitmap needs its size");
|
||||
assert!(near(&match bmp.with_frame(&f, Some((10.0, 6.0))) {
|
||||
Paint::Bitmap { matrix, .. } => matrix,
|
||||
_ => Affine::IDENTITY,
|
||||
}, &Affine::translate(3.0, 4.0).mul(&Affine::scale(2.0, 2.0))));
|
||||
// Solid colours have no frame; a frame that isn't finite changes nothing.
|
||||
assert_eq!(Paint::Solid(Rgba::WHITE).frame(None), None);
|
||||
assert_eq!(rad.with_frame(&Affine { m: [f32::NAN, 0.0, 0.0, 1.0, 0.0, 0.0] }, None), rad);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_gradients_follow_any_transform_exactly() {
|
||||
// A skew turns the circle into a tilted ellipse: the frame is carried exactly, focal point
|
||||
// and all.
|
||||
let mut rad = Paint::radial(Vec2::new(10.0, 0.0), 5.0, stops());
|
||||
if let Paint::Radial { focal, .. } = &mut rad {
|
||||
*focal = 0.5;
|
||||
}
|
||||
let skew = Affine { m: [1.0, 0.0, 0.7, 2.0, 3.0, -1.0] };
|
||||
let moved = rad.transformed(&skew);
|
||||
assert!(near(&moved.frame(None).unwrap(), &skew.mul(&rad.frame(None).unwrap())));
|
||||
assert!(matches!(moved, Paint::Radial { focal, .. } if focal == 0.5));
|
||||
// A plain move keeps a plain circle.
|
||||
assert!(matches!(rad.transformed(&Affine::translate(4.0, 4.0)), Paint::Radial { matrix, .. } if matrix == Affine::IDENTITY));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fitting_places_a_fill_on_the_shape() {
|
||||
let b = Rect { min: Vec2::new(0.0, 0.0), max: Vec2::new(200.0, 100.0) };
|
||||
match Paint::linear(Vec2::ZERO, Vec2::new(1.0, 1.0), stops()).fitted(&b) {
|
||||
Paint::Linear { start, end, .. } => assert_eq!((start, end), (Vec2::new(0.0, 50.0), Vec2::new(200.0, 50.0))),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
match Paint::radial(Vec2::ZERO, 1.0, stops()).fitted(&b) {
|
||||
Paint::Radial { center, radius, matrix, .. } => assert_eq!((center, radius, matrix), (Vec2::new(100.0, 50.0), 100.0, Affine::IDENTITY)),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
let bmp = Paint::Bitmap { bitmap: BitmapId(2), repeat: false, matrix: Affine::scale(3.0, 3.0) };
|
||||
assert_eq!(bmp.fitted(&b), Paint::Bitmap { bitmap: BitmapId(2), repeat: true, matrix: Affine::IDENTITY });
|
||||
// Stops and options stay; an empty box changes nothing.
|
||||
let mut rep = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops());
|
||||
if let Paint::Linear { spread, linear_rgb, .. } = &mut rep {
|
||||
*spread = Spread::Repeat;
|
||||
*linear_rgb = true;
|
||||
}
|
||||
assert!(matches!(rep.fitted(&b), Paint::Linear { spread: Spread::Repeat, linear_rgb: true, .. }));
|
||||
assert_eq!(rep.fitted(&Rect::EMPTY), rep);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_files_open_and_plain_gradients_are_stored_as_before() {
|
||||
let old = r#"{"Radial":{"center":{"x":1.0,"y":2.0},"radius":3.0,"stops":[{"offset":0.0,"color":{"r":0.0,"g":0.0,"b":0.0,"a":1.0}}]}}"#;
|
||||
let p: Paint = serde_json::from_str(old).unwrap();
|
||||
assert!(matches!(p, Paint::Radial { spread: Spread::Pad, linear_rgb: false, focal, matrix, .. } if focal == 0.0 && matrix == Affine::IDENTITY));
|
||||
let back = serde_json::to_string(&p).unwrap();
|
||||
assert!(!back.contains("spread") && !back.contains("focal") && !back.contains("matrix") && !back.contains("linear_rgb"), "{back}");
|
||||
// Set options are written, and read back.
|
||||
let mut q = Paint::linear(Vec2::ZERO, Vec2::new(1.0, 0.0), stops());
|
||||
if let Paint::Linear { spread, linear_rgb, .. } = &mut q {
|
||||
*spread = Spread::Reflect;
|
||||
*linear_rgb = true;
|
||||
}
|
||||
let text = serde_json::to_string(&q).unwrap();
|
||||
assert!(text.contains("\"spread\":\"reflect\"") && text.contains("\"linear_rgb\":true"), "{text}");
|
||||
assert_eq!(serde_json::from_str::<Paint>(&text).unwrap(), q);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_gradients_tween_through_their_frames() {
|
||||
let a = Paint::radial(Vec2::ZERO, 10.0, stops());
|
||||
let b = a.with_frame(&Affine::translate(100.0, 0.0).mul(&Affine::scale(30.0, 10.0)), None);
|
||||
let mid = a.lerp(&b, 0.5);
|
||||
assert!(near(&mid.frame(None).unwrap(), &Affine { m: [20.0, 0.0, 0.0, 10.0, 50.0, 0.0] }), "{mid:?}");
|
||||
}
|
||||
+230
-11
@@ -106,12 +106,103 @@ pub struct GradientStop {
|
||||
pub color: Rgba,
|
||||
}
|
||||
|
||||
/// What a gradient shows past its ends (Animate's Overflow / Flow, SVG's `spreadMethod`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Spread {
|
||||
/// The end colours carry on (Animate's Extend, SVG's `pad`).
|
||||
#[default]
|
||||
Pad,
|
||||
/// The ramp mirrors back and forth.
|
||||
Reflect,
|
||||
/// The ramp starts again.
|
||||
Repeat,
|
||||
}
|
||||
|
||||
impl Spread {
|
||||
pub const ALL: [Spread; 3] = [Spread::Pad, Spread::Reflect, Spread::Repeat];
|
||||
pub fn is_pad(&self) -> bool {
|
||||
*self == Spread::Pad
|
||||
}
|
||||
/// The key commands and files use (`extend` is Animate's name for `pad`).
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Spread::Pad => "extend",
|
||||
Spread::Reflect => "reflect",
|
||||
Spread::Repeat => "repeat",
|
||||
}
|
||||
}
|
||||
pub fn from_key(s: &str) -> Option<Spread> {
|
||||
match s {
|
||||
"extend" | "pad" => Some(Spread::Pad),
|
||||
"reflect" => Some(Spread::Reflect),
|
||||
"repeat" => Some(Spread::Repeat),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Gradient position `t` (0 at the start, 1 at the end) → where on the ramp, in `0..=1`.
|
||||
/// Non-finite positions read the start.
|
||||
pub fn apply(self, t: f32) -> f32 {
|
||||
if !t.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
match self {
|
||||
Spread::Pad => t.clamp(0.0, 1.0),
|
||||
Spread::Repeat => {
|
||||
let f = t.rem_euclid(1.0);
|
||||
// `rem_euclid` can round up to exactly 1 for tiny negative values.
|
||||
if f >= 1.0 { 0.0 } else { f }
|
||||
}
|
||||
Spread::Reflect => {
|
||||
let m = t.rem_euclid(2.0);
|
||||
(if m > 1.0 { 2.0 - m } else { m }).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Most stops a fill gradient may have (Animate allows 15).
|
||||
pub const MAX_GRADIENT_STOPS: usize = 15;
|
||||
/// How far the focal point may sit from the centre, as a share of the radius (a focal point on
|
||||
/// the ring itself is undefined; Animate's focal ratio runs to ±1 too).
|
||||
pub const MAX_FOCAL: f32 = 0.98;
|
||||
|
||||
/// How a region is painted. Gradient geometry is in the element's local space.
|
||||
///
|
||||
/// Gradients may carry options that older files don't have (ADR 0074): what shows past the ends
|
||||
/// (`spread`), interpolation in linear light (`linear_rgb`), and for a radial gradient a focal
|
||||
/// point and a `matrix` that turns its circle into any ellipse. Each is written only when set,
|
||||
/// so a plain gradient is stored as before.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum Paint {
|
||||
Solid(Rgba),
|
||||
Linear { start: Vec2, end: Vec2, stops: Vec<GradientStop> },
|
||||
Radial { center: Vec2, radius: f32, stops: Vec<GradientStop> },
|
||||
Linear {
|
||||
start: Vec2,
|
||||
end: Vec2,
|
||||
stops: Vec<GradientStop>,
|
||||
#[serde(default, skip_serializing_if = "Spread::is_pad")]
|
||||
spread: Spread,
|
||||
/// Mix the stops in linear light (Animate's "Linear RGB"), not in sRGB.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
linear_rgb: bool,
|
||||
},
|
||||
/// The circle of `radius` round `center`, carried by `matrix` (an ellipse at any angle).
|
||||
Radial {
|
||||
center: Vec2,
|
||||
radius: f32,
|
||||
stops: Vec<GradientStop>,
|
||||
#[serde(default, skip_serializing_if = "Spread::is_pad")]
|
||||
spread: Spread,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
linear_rgb: bool,
|
||||
/// Where the ramp starts, along the gradient's own x axis from the centre, as a share
|
||||
/// of the radius in `-MAX_FOCAL..=MAX_FOCAL` (Animate's focal point ratio).
|
||||
#[serde(default, skip_serializing_if = "is_zero")]
|
||||
focal: f32,
|
||||
/// Gradient space → shape space (identity: the plain circle).
|
||||
#[serde(default, skip_serializing_if = "is_identity")]
|
||||
matrix: Affine,
|
||||
},
|
||||
/// A bitmap, its pixel (x, y) at local `matrix · (x, y)`; `repeat` tiles it, otherwise it
|
||||
/// shows once (an imported image is a rectangle of exactly its size, with no matrix).
|
||||
Bitmap {
|
||||
@@ -128,7 +219,19 @@ fn is_identity(m: &Affine) -> bool {
|
||||
*m == Affine::IDENTITY
|
||||
}
|
||||
|
||||
/// The canonical box a fill's frame maps: `-1..=1` on both axes (Animate's gradient square).
|
||||
pub const FRAME_BOX: Rect = Rect { min: Vec2 { x: -1.0, y: -1.0 }, max: Vec2 { x: 1.0, y: 1.0 } };
|
||||
|
||||
impl Paint {
|
||||
/// A linear gradient from `start` to `end`, with no options.
|
||||
pub fn linear(start: Vec2, end: Vec2, stops: Vec<GradientStop>) -> Paint {
|
||||
Paint::Linear { start, end, stops, spread: Spread::Pad, linear_rgb: false }
|
||||
}
|
||||
/// A radial gradient: the circle of `radius` round `center`, with no options.
|
||||
pub fn radial(center: Vec2, radius: f32, stops: Vec<GradientStop>) -> Paint {
|
||||
Paint::Radial { center, radius, stops, spread: Spread::Pad, linear_rgb: false, focal: 0.0, matrix: Affine::IDENTITY }
|
||||
}
|
||||
|
||||
/// A representative colour (first stop for gradients) for swatches and the properties panel.
|
||||
pub fn primary_color(&self) -> Rgba {
|
||||
match self {
|
||||
@@ -138,18 +241,119 @@ impl Paint {
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's colour stops.
|
||||
pub fn stops(&self) -> Option<&[GradientStop]> {
|
||||
match self {
|
||||
Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => Some(stops),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn stops_mut(&mut self) -> Option<&mut Vec<GradientStop>> {
|
||||
match self {
|
||||
Paint::Linear { stops, .. } | Paint::Radial { stops, .. } => Some(stops),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn is_gradient(&self) -> bool {
|
||||
matches!(self, Paint::Linear { .. } | Paint::Radial { .. })
|
||||
}
|
||||
|
||||
/// The paint carried by `m` (its geometry moved from one space to another), so a shape in
|
||||
/// the new space shows it where it was: gradient ends and centre are mapped, a radial
|
||||
/// gradient's radius scales by the mean scale, a bitmap's matrix is composed.
|
||||
/// the new space shows it where it was: gradient ends are mapped, a radial gradient's and a
|
||||
/// bitmap's matrix is composed (exact under any transform).
|
||||
pub fn transformed(&self, m: &Affine) -> Paint {
|
||||
match self {
|
||||
Paint::Solid(_) => self.clone(),
|
||||
Paint::Linear { start, end, stops } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone() },
|
||||
Paint::Radial { center, radius, stops } => Paint::Radial { center: m.apply(*center), radius: radius * m.mean_scale(), stops: stops.clone() },
|
||||
Paint::Linear { start, end, stops, spread, linear_rgb } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb },
|
||||
Paint::Radial { .. } => match self.frame(None) {
|
||||
Some(f) => self.with_frame(&m.mul(&f), None),
|
||||
None => self.clone(),
|
||||
},
|
||||
Paint::Bitmap { bitmap, repeat, matrix } => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: m.mul(matrix) },
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill's frame: the map from [`FRAME_BOX`] to the paint's space, which the Gradient
|
||||
/// Transform tool edits (ADR 0074).
|
||||
///
|
||||
/// * Linear: x from −1 at the start to 1 at the end, y square to it at the same scale.
|
||||
/// * Radial: the unit circle onto the gradient's ring (x is its own axis, where the focal
|
||||
/// point sits).
|
||||
/// * Bitmap: the box onto one copy of the image (`image` is its size in pixels).
|
||||
///
|
||||
/// `None` for solid colours and a bitmap of unknown size.
|
||||
pub fn frame(&self, image: Option<(f32, f32)>) -> Option<Affine> {
|
||||
match self {
|
||||
Paint::Solid(_) => None,
|
||||
Paint::Linear { start, end, .. } => {
|
||||
let mid = start.lerp(*end, 0.5);
|
||||
let h = (*end - *start) * 0.5;
|
||||
Some(Affine { m: [h.x, h.y, -h.y, h.x, mid.x, mid.y] })
|
||||
}
|
||||
Paint::Radial { center, radius, matrix, .. } => Some(matrix.mul(&Affine::translate(center.x, center.y)).mul(&Affine::scale(*radius, *radius))),
|
||||
Paint::Bitmap { matrix, .. } => {
|
||||
let (w, h) = image?;
|
||||
Some(matrix.mul(&Affine::translate(w * 0.5, h * 0.5)).mul(&Affine::scale(w * 0.5, h * 0.5)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This paint with its frame set to `f` (see [`Paint::frame`]); the stops and options stay.
|
||||
/// A linear gradient keeps only the frame's x axis. A radial gradient is stored as a
|
||||
/// circle when `f` is one, else with a matrix about its centre. Solid colours (and bitmaps
|
||||
/// without a size) are returned unchanged.
|
||||
pub fn with_frame(&self, f: &Affine, image: Option<(f32, f32)>) -> Paint {
|
||||
let finite = f.m.iter().all(|v| v.is_finite());
|
||||
if !finite {
|
||||
return self.clone();
|
||||
}
|
||||
match self {
|
||||
Paint::Solid(_) => self.clone(),
|
||||
Paint::Linear { stops, spread, linear_rgb, .. } => Paint::Linear { start: f.apply(Vec2::new(-1.0, 0.0)), end: f.apply(Vec2::new(1.0, 0.0)), stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb },
|
||||
Paint::Radial { stops, spread, linear_rgb, focal, .. } => {
|
||||
let center = f.apply(Vec2::ZERO);
|
||||
let [a, b, c, d, ..] = f.m;
|
||||
let radius = Vec2::new(a, b).length();
|
||||
let (matrix, radius) = if radius > 1e-9 {
|
||||
// The linear part with the x axis's length taken out, about the centre.
|
||||
let l = Affine { m: [a / radius, b / radius, c / radius, d / radius, 0.0, 0.0] };
|
||||
let plain = (l.m[0] - 1.0).abs() < 1e-6 && l.m[1].abs() < 1e-6 && l.m[2].abs() < 1e-6 && (l.m[3] - 1.0).abs() < 1e-6;
|
||||
if plain { (Affine::IDENTITY, radius) } else { (Affine::translate(center.x, center.y).mul(&l).mul(&Affine::translate(-center.x, -center.y)), radius) }
|
||||
} else {
|
||||
(Affine::IDENTITY, 0.0)
|
||||
};
|
||||
Paint::Radial { center, radius, stops: stops.clone(), spread: *spread, linear_rgb: *linear_rgb, focal: *focal, matrix }
|
||||
}
|
||||
Paint::Bitmap { bitmap, repeat, .. } => match image {
|
||||
Some((w, h)) if w > 0.0 && h > 0.0 => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: f.mul(&Affine::scale(2.0 / w, 2.0 / h)).mul(&Affine::translate(-w * 0.5, -h * 0.5)) },
|
||||
_ => self.clone(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// This gradient or bitmap placed on `bounds` (shape space), as Animate pours an unlocked
|
||||
/// fill: a linear gradient across the width, left to right; a radial one centred, its
|
||||
/// ring touching the longer side; a bitmap tiled from the top-left at its own size.
|
||||
/// The stops and options stay.
|
||||
pub fn fitted(&self, bounds: &Rect) -> Paint {
|
||||
if bounds.is_empty() || !(bounds.min.is_finite() && bounds.max.is_finite()) {
|
||||
return self.clone();
|
||||
}
|
||||
let c = bounds.center();
|
||||
match self {
|
||||
Paint::Solid(_) => self.clone(),
|
||||
Paint::Linear { .. } => {
|
||||
let hw = (bounds.width() * 0.5).max(0.5);
|
||||
self.with_frame(&Affine { m: [hw, 0.0, 0.0, hw, c.x, c.y] }, None)
|
||||
}
|
||||
Paint::Radial { .. } => {
|
||||
let r = (bounds.width().max(bounds.height()) * 0.5).max(0.5);
|
||||
self.with_frame(&Affine { m: [r, 0.0, 0.0, r, c.x, c.y] }, None)
|
||||
}
|
||||
Paint::Bitmap { bitmap, .. } => Paint::Bitmap { bitmap: *bitmap, repeat: true, matrix: Affine::translate(bounds.min.x, bounds.min.y) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lerp(&self, o: &Paint, t: f32) -> Paint {
|
||||
let lerp_stops = |a: &[GradientStop], b: &[GradientStop]| -> Option<Vec<GradientStop>> {
|
||||
(a.len() == b.len()).then(|| {
|
||||
@@ -158,13 +362,24 @@ impl Paint {
|
||||
};
|
||||
match (self, o) {
|
||||
(Paint::Solid(a), Paint::Solid(b)) => Paint::Solid(a.lerp(*b, t)),
|
||||
(Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => match lerp_stops(a, b) {
|
||||
Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops },
|
||||
(Paint::Linear { start: s0, end: e0, stops: a, spread, linear_rgb }, Paint::Linear { start: s1, end: e1, stops: b, .. }) => match lerp_stops(a, b) {
|
||||
Some(stops) => Paint::Linear { start: s0.lerp(*s1, t), end: e0.lerp(*e1, t), stops, spread: *spread, linear_rgb: *linear_rgb },
|
||||
None => self.clone(),
|
||||
},
|
||||
(Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => match lerp_stops(a, b) {
|
||||
Some(stops) => Paint::Radial { center: c0.lerp(*c1, t), radius: anicraft_geom::lerp(*r0, *r1, t), stops },
|
||||
None => self.clone(),
|
||||
(Paint::Radial { stops: a, .. }, Paint::Radial { stops: b, focal: f1, .. }) => match (lerp_stops(a, b), self.frame(None), o.frame(None)) {
|
||||
(Some(stops), Some(fa), Some(fb)) => {
|
||||
let mut m = [0.0; 6];
|
||||
for (k, v) in m.iter_mut().enumerate() {
|
||||
*v = anicraft_geom::lerp(fa.m[k], fb.m[k], t);
|
||||
}
|
||||
let mut p = self.with_frame(&Affine { m }, None);
|
||||
if let Paint::Radial { stops: s, focal, .. } = &mut p {
|
||||
*s = stops;
|
||||
*focal = anicraft_geom::lerp(*focal, *f1, t);
|
||||
}
|
||||
p
|
||||
}
|
||||
_ => self.clone(),
|
||||
},
|
||||
_ => self.clone(),
|
||||
}
|
||||
@@ -1795,6 +2010,10 @@ fn sanitize_scripts(layer: &mut Arc<Layer>) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "gradient_tests.rs"]
|
||||
mod gradient_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "camera_tests.rs"]
|
||||
mod camera_tests;
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn demo() -> Document {
|
||||
let ball_id = SymbolId(d.alloc_id());
|
||||
let ball_shape = Shape::filled(
|
||||
Path::ellipse(0.0, 0.0, 48.0, 48.0),
|
||||
Paint::Radial { center: Vec2::new(-16.0, -18.0), radius: 70.0, stops: stops(&[(0.0, 0xfff1c4), (0.35, 0xff8a3d), (1.0, 0xb3261e)]) },
|
||||
Paint::radial(Vec2::new(-16.0, -18.0), 70.0, stops(&[(0.0, 0xfff1c4), (0.35, 0xff8a3d), (1.0, 0xb3261e)])),
|
||||
)
|
||||
.with_stroke(Rgba::hex(0x5a1410), 3.0);
|
||||
let ball_el = el(&mut d, "ball body", Affine::IDENTITY, ElementKind::Shape(ball_shape));
|
||||
@@ -101,7 +101,7 @@ pub fn demo() -> Document {
|
||||
// Sun: pulses with an ease in-out.
|
||||
let sun_layer_id = d.alloc_id();
|
||||
let sun_inst = ElementId(d.alloc_id());
|
||||
let sun_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::Radial { center: Vec2::ZERO, radius: 90.0, stops: stops(&[(0.0, 0xfffbe0), (0.6, 0xffd36b), (1.0, 0xffa94d)]) });
|
||||
let sun_shape = Shape::filled(Path::ellipse(0.0, 0.0, 90.0, 90.0), Paint::radial(Vec2::ZERO, 90.0, stops(&[(0.0, 0xfffbe0), (0.6, 0xffd36b), (1.0, 0xffa94d)])));
|
||||
let sun_keys = [(0u32, 24u32, 1.0f32), (24, 23, 1.15), (47, 1, 1.0)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -132,7 +132,7 @@ pub fn demo() -> Document {
|
||||
Affine::IDENTITY,
|
||||
ElementKind::Shape(Shape::filled(
|
||||
Path::rect(0.0, 0.0, w, h),
|
||||
Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(0.0, h), stops: stops(&[(0.0, 0x27407a), (0.55, 0x8a79c9), (1.0, 0xf7b98b)]) },
|
||||
Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(0.0, h), stops(&[(0.0, 0x27407a), (0.55, 0x8a79c9), (1.0, 0xf7b98b)])),
|
||||
)),
|
||||
);
|
||||
let mut sky = layer(sky_id, "Sky", 0x7e57c2, vec![key(0, LEN, vec![sky_el], None)]);
|
||||
|
||||
@@ -186,13 +186,20 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param("the stroke is too small to paint".into()));
|
||||
}
|
||||
let c = path.bounds().center();
|
||||
let local = path.transformed(&Affine::translate(-c.x, -c.y));
|
||||
// A gradient or bitmap in the fill swatch paints too, locked or fitted (ADR 0074), unless a
|
||||
// colour was given or pressure sets the opacity.
|
||||
let fill = match &s.style.fill_paint {
|
||||
Some(_) if p.get("color").is_none_or(Value::is_null) && color.a >= 1.0 => s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()),
|
||||
_ => Paint::Solid(color),
|
||||
};
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(path.transformed(&Affine::translate(-c.x, -c.y))), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(fill), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
|
||||
};
|
||||
if s.editable_keyframe()?.elements.len() >= 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
|
||||
@@ -108,9 +108,9 @@ fn rect_params(p: &Value) -> Result<(f32, f32, f32, f32)> {
|
||||
/// (Object Drawing), it merges with the raw shapes it touches (ADR 0031), and the pieces of it
|
||||
/// that come out are selected.
|
||||
pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, fill: Option<Paint>, stroke: Option<Stroke>, object: bool) -> Result<Value> {
|
||||
// A gradient or bitmap from the fill swatch is in stage space: it stays where it is on the
|
||||
// stage (Animate's Lock Fill after the Eyedropper).
|
||||
let fill = fill.map(|f| f.transformed(&Affine::translate(-origin.x, -origin.y)));
|
||||
// A gradient or bitmap from the fill swatch is in stage space: with Lock Fill it stays where
|
||||
// it is on the stage, else it is fitted to the new shape (ADR 0074).
|
||||
let fill = fill.map(|f| if s.style.lock_fill || matches!(f, Paint::Solid(_)) { f.transformed(&Affine::translate(-origin.x, -origin.y)) } else { f.fitted(&local.bounds()) });
|
||||
let merge = !object && crate::merge::can_merge(stroke.as_ref());
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Paint Bucket, Ink Bottle and Eyedropper.
|
||||
//! Paint Bucket, Ink Bottle and Eyedropper; the fill swatch's gradients and bitmaps, Lock Fill
|
||||
//! and the Gradient Transform tool (ADR 0074).
|
||||
//!
|
||||
//! AniCraft shapes are independent objects (like object drawing), so a fill for an area
|
||||
//! enclosed by several shapes has to be found, not looked up:
|
||||
@@ -18,7 +19,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, DisplayItem, Element, ElementId, ElementKind, Paint, Shape, Stroke};
|
||||
use anicraft_doc::{BitmapId, ColorEffect, DisplayItem, Element, ElementId, ElementKind, GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Shape, Spread, Stroke};
|
||||
use anicraft_geom::trace::contours;
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2, fit_curve};
|
||||
use anicraft_render::raster::{Coverage, IRect};
|
||||
@@ -42,6 +43,25 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?, cap?, join?, miter?, style?, dash?, dash_offset?, dot_spacing?} (the tool's line style unless given; see stroke.set_style)", true, ink),
|
||||
c("paint.pick", "Eyedropper", "", None, "{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings", false, pick_style),
|
||||
c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, |s, p| s.each_layer(false, |s| apply_style(s, p))),
|
||||
c(
|
||||
"paint.set_fill",
|
||||
"Fill",
|
||||
"",
|
||||
None,
|
||||
"{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: \"#rrggbb\" | \"#rrggbbaa\"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}",
|
||||
true,
|
||||
set_fill,
|
||||
),
|
||||
c(
|
||||
"paint.transform_fill",
|
||||
"Gradient Transform",
|
||||
"",
|
||||
None,
|
||||
"{element?: id (default: the selected shapes with a gradient or bitmap fill), frame?: [a, b, c, d, e, f] (the fill's frame in the space being edited: the box -1..1 onto a linear gradient's span, a radial gradient's ring or one copy of a bitmap), or changes made in this order: scale_x?, scale_y?, scale? (along the frame's own axes), skew_x?, skew_y? (degrees, along its axes), rotate? (degrees, about its centre), move?: [dx, dy], center?: [x, y]; focal?: -0.98..0.98 (radial)} moves, turns, scales or skews where a gradient or bitmap fill lies, as the Gradient Transform tool (F) does → {changed, frames: [[a, b, c, d, e, f], ..]}",
|
||||
true,
|
||||
|s, p| s.each_layer(false, |s| transform_fill(s, p)),
|
||||
),
|
||||
c("paint.lock_fill", "Lock Fill", "", None, "{on?: bool (default: toggle)} Lock Fill: a gradient or bitmap from the fill swatch is poured where it lies on the stage, running on across shapes; off, each shape gets it fitted to its bounds → {on}", false, lock_fill),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -79,8 +99,9 @@ fn element_shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> {
|
||||
|
||||
fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
// The fill swatch (a picked gradient or bitmap stays where it is on the stage).
|
||||
let paint = opt_color(p, "color")?.map_or_else(|| s.style.fill_paint(), Paint::Solid);
|
||||
// The fill swatch: a gradient or bitmap stays where it is on the stage with Lock Fill, else
|
||||
// it is fitted to the shape it fills (ADR 0074).
|
||||
let given = opt_color(p, "color")?.map(Paint::Solid);
|
||||
let gap = opt_f32(p, "gap")?.unwrap_or(0.0);
|
||||
if !(0.0..=1000.0).contains(&gap) {
|
||||
return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into()));
|
||||
@@ -90,8 +111,12 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// 1. On a fill: recolour it. A raw fill then joins the fills of its new colour it touches.
|
||||
if let Some((id, true)) = pick(&items, at, 0.0) {
|
||||
let to_local = items.iter().find(|i| i.element == id).and_then(|i| i.transform.inverse()).unwrap_or(Affine::IDENTITY);
|
||||
let style = s.style.clone();
|
||||
let sh = element_shape_mut(s, id)?;
|
||||
sh.fill = Some(paint.transformed(&to_local));
|
||||
sh.fill = Some(match &given {
|
||||
Some(c) => c.clone(),
|
||||
None => style.fill_paint_for(&to_local, &sh.path.bounds()),
|
||||
});
|
||||
if sh.merge {
|
||||
crate::cmds_raw::remerge_in_place(s, &[id])?;
|
||||
return Ok(json!({"recolored": id.0, "merged": true}));
|
||||
@@ -114,7 +139,7 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
|
||||
kind: ElementKind::Shape(Shape { fill: Some(given.unwrap_or_else(|| s.style.fill_paint_for(&Affine::translate(-c.x, -c.y), &local.bounds()))), path: Arc::new(local), stroke: None, fill_rule: FillRule::EvenOdd, merge: !object }),
|
||||
};
|
||||
if !object {
|
||||
// Raw: behind the drawing, so it takes only what is empty and joins the fills of its
|
||||
@@ -376,6 +401,10 @@ fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
st.fill = color;
|
||||
st.fill_paint = (!matches!(paint, Paint::Solid(_))).then(|| paint.clone());
|
||||
// As in Animate, a picked gradient or bitmap is locked where it was on the stage.
|
||||
if st.fill_paint.is_some() {
|
||||
st.lock_fill = true;
|
||||
}
|
||||
st.use_fill = true;
|
||||
Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": color.to_hex()}))
|
||||
}
|
||||
@@ -416,7 +445,6 @@ fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param("apply the fill, the stroke or both".into()));
|
||||
}
|
||||
let style = s.style.clone();
|
||||
let paint = style.fill_paint();
|
||||
let line = style.new_stroke(style.stroke, style.stroke_width);
|
||||
let mut changed = 0;
|
||||
for e in s.selected_elements_mut()? {
|
||||
@@ -427,7 +455,7 @@ fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& sh.fill.is_some()
|
||||
&& let Some(m) = to_local
|
||||
{
|
||||
sh.fill = Some(paint.transformed(&m));
|
||||
sh.fill = Some(style.fill_paint_for(&m, &sh.path.bounds()));
|
||||
hit = true;
|
||||
}
|
||||
// Raw fills stay fill-only: the lines round them are shapes of their own (ADR 0031).
|
||||
@@ -442,3 +470,328 @@ fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
Ok(json!({"changed": changed}))
|
||||
}
|
||||
|
||||
// ----- the fill swatch, Lock Fill and the Gradient Transform tool (ADR 0074) ---------------
|
||||
|
||||
/// Animate's default gradient: white to black.
|
||||
fn default_stops() -> Vec<GradientStop> {
|
||||
vec![GradientStop { offset: 0.0, color: Rgba::WHITE }, GradientStop { offset: 1.0, color: Rgba::BLACK }]
|
||||
}
|
||||
|
||||
/// The `stops` param: 2 to 15 stops, each `{offset, color}`, put in order of offset.
|
||||
fn opt_stops(p: &Value) -> Result<Option<Vec<GradientStop>>> {
|
||||
let bad = || EngineError::Param(format!("param 'stops' must be a list of 2 to {MAX_GRADIENT_STOPS} stops like {{\"offset\": 0.5, \"color\": \"#ff8800\"}}"));
|
||||
let list = match p.get("stops") {
|
||||
None | Some(Value::Null) => return Ok(None),
|
||||
Some(Value::Array(a)) if (2..=MAX_GRADIENT_STOPS).contains(&a.len()) => a,
|
||||
Some(_) => return Err(bad()),
|
||||
};
|
||||
let mut stops = Vec::with_capacity(list.len());
|
||||
for v in list {
|
||||
let offset = opt_f32(v, "offset").map_err(|_| bad())?.ok_or_else(bad)?;
|
||||
if !(0.0..=1.0).contains(&offset) {
|
||||
return Err(EngineError::Param("a stop's 'offset' must be between 0 and 1".into()));
|
||||
}
|
||||
let color = opt_color(v, "color").map_err(|_| bad())?.ok_or_else(bad)?;
|
||||
stops.push(GradientStop { offset, color });
|
||||
}
|
||||
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
Ok(Some(stops))
|
||||
}
|
||||
|
||||
/// The kinds of fill `paint.set_fill` makes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum FillKind {
|
||||
Solid,
|
||||
Linear,
|
||||
Radial,
|
||||
Bitmap,
|
||||
}
|
||||
|
||||
fn fill_kind(p: &Paint) -> FillKind {
|
||||
match p {
|
||||
Paint::Solid(_) => FillKind::Solid,
|
||||
Paint::Linear { .. } => FillKind::Linear,
|
||||
Paint::Radial { .. } => FillKind::Radial,
|
||||
Paint::Bitmap { .. } => FillKind::Bitmap,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `paint.set_fill` asks for: a kind of fill and the parts given.
|
||||
struct FillSpec {
|
||||
kind: FillKind,
|
||||
color: Option<Rgba>,
|
||||
stops: Option<Vec<GradientStop>>,
|
||||
spread: Option<Spread>,
|
||||
linear_rgb: Option<bool>,
|
||||
focal: Option<f32>,
|
||||
bitmap: Option<BitmapId>,
|
||||
}
|
||||
|
||||
impl FillSpec {
|
||||
/// `base` with these changes. A fill of the same kind keeps its geometry; another kind
|
||||
/// comes out on the unit box (to be placed); a gradient keeps the colours and options of
|
||||
/// the gradient it replaces, else starts white to black. `None`: a bitmap fill with no
|
||||
/// bitmap given or held.
|
||||
fn apply(&self, base: &Paint) -> Option<Paint> {
|
||||
let mut p = match self.kind {
|
||||
FillKind::Solid => return Some(Paint::Solid(self.color.unwrap_or_else(|| base.primary_color()))),
|
||||
k if k == fill_kind(base) => base.clone(),
|
||||
FillKind::Linear | FillKind::Radial => {
|
||||
let stops = base.stops().map_or_else(default_stops, <[GradientStop]>::to_vec);
|
||||
let mut q = if self.kind == FillKind::Linear { Paint::linear(Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0), stops) } else { Paint::radial(Vec2::ZERO, 1.0, stops) };
|
||||
if let (Paint::Linear { spread: a, linear_rgb: b, .. } | Paint::Radial { spread: a, linear_rgb: b, .. }, Paint::Linear { spread, linear_rgb, .. } | Paint::Radial { spread, linear_rgb, .. }) = (&mut q, base) {
|
||||
*a = *spread;
|
||||
*b = *linear_rgb;
|
||||
}
|
||||
q
|
||||
}
|
||||
FillKind::Bitmap => Paint::Bitmap { bitmap: self.bitmap?, repeat: true, matrix: Affine::IDENTITY },
|
||||
};
|
||||
match &mut p {
|
||||
Paint::Linear { stops, spread, linear_rgb, .. } => self.set_common(stops, spread, linear_rgb),
|
||||
Paint::Radial { stops, spread, linear_rgb, focal, .. } => {
|
||||
self.set_common(stops, spread, linear_rgb);
|
||||
if let Some(f) = self.focal {
|
||||
*focal = f;
|
||||
}
|
||||
}
|
||||
Paint::Bitmap { bitmap, .. } => {
|
||||
if let Some(b) = self.bitmap {
|
||||
*bitmap = b;
|
||||
}
|
||||
}
|
||||
Paint::Solid(_) => {}
|
||||
}
|
||||
Some(p)
|
||||
}
|
||||
|
||||
fn set_common(&self, stops: &mut Vec<GradientStop>, spread: &mut Spread, linear_rgb: &mut bool) {
|
||||
if let Some(st) = &self.stops {
|
||||
stops.clone_from(st);
|
||||
}
|
||||
if let Some(sp) = self.spread {
|
||||
*spread = sp;
|
||||
}
|
||||
if let Some(l) = self.linear_rgb {
|
||||
*linear_rgb = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn hex_alpha(c: Rgba) -> String {
|
||||
let c = c.sanitized();
|
||||
if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) }
|
||||
}
|
||||
|
||||
/// A fill as `paint.set_fill` reports it (in its own params' terms).
|
||||
pub fn fill_json(p: &Paint) -> Value {
|
||||
let stops = |st: &[GradientStop]| -> Vec<Value> { st.iter().map(|s| json!({"offset": s.offset, "color": hex_alpha(s.color)})).collect() };
|
||||
match p {
|
||||
Paint::Solid(c) => json!({"type": "solid", "color": hex_alpha(*c)}),
|
||||
Paint::Linear { stops: st, spread, linear_rgb, .. } => json!({"type": "linear", "stops": stops(st), "spread": spread.key(), "linear_rgb": linear_rgb}),
|
||||
Paint::Radial { stops: st, spread, linear_rgb, focal, .. } => json!({"type": "radial", "stops": stops(st), "spread": spread.key(), "linear_rgb": linear_rgb, "focal": focal}),
|
||||
Paint::Bitmap { bitmap, repeat, .. } => json!({"type": "bitmap", "bitmap": bitmap.0, "repeat": repeat}),
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_focal(p: &Value) -> Result<Option<f32>> {
|
||||
let f = opt_f32(p, "focal")?;
|
||||
if f.is_some_and(|f| !(-MAX_FOCAL..=MAX_FOCAL).contains(&f)) {
|
||||
return Err(EngineError::Param(format!("param 'focal' must be between -{MAX_FOCAL} and {MAX_FOCAL}")));
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// `paint.set_fill`: the Colour panel's fill (type, stops, overflow, linear RGB, bitmap).
|
||||
fn set_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let swatch = s.style.fill_paint();
|
||||
let kind = match opt_str(p, "type")? {
|
||||
None => fill_kind(&swatch),
|
||||
Some("solid") => FillKind::Solid,
|
||||
Some("linear") => FillKind::Linear,
|
||||
Some("radial") => FillKind::Radial,
|
||||
Some("bitmap") => FillKind::Bitmap,
|
||||
Some(other) => return Err(EngineError::Param(format!("unknown fill type '{other}' (solid, linear, radial or bitmap)"))),
|
||||
};
|
||||
let spread = match opt_str(p, "spread")? {
|
||||
None => None,
|
||||
Some(k) => Some(Spread::from_key(k).ok_or_else(|| EngineError::Param(format!("unknown spread '{k}' (extend, reflect or repeat)")))?),
|
||||
};
|
||||
let bitmap = match opt_u64(p, "bitmap")? {
|
||||
None => None,
|
||||
Some(id) => Some(s.doc.bitmap(BitmapId(id)).ok_or_else(|| EngineError::Param(format!("there is no bitmap {id} in the Library")))?.id),
|
||||
};
|
||||
let spec = FillSpec { kind, color: opt_color(p, "color")?, stops: opt_stops(p)?, spread, linear_rgb: opt_bool(p, "linear_rgb")?, focal: opt_focal(p)?, bitmap };
|
||||
let new = spec.apply(&swatch).ok_or_else(|| EngineError::Param("a bitmap fill needs 'bitmap' (a Library bitmap's id)".into()))?;
|
||||
// The swatch keeps where its fill lies; a new kind lies across the stage.
|
||||
let stage = Rect::new(0.0, 0.0, s.doc.stage.width as f32, s.doc.stage.height as f32);
|
||||
let placed = if fill_kind(&swatch) == kind { new } else { new.fitted(&stage) };
|
||||
match &placed {
|
||||
Paint::Solid(c) => s.style.set_fill_color(*c),
|
||||
other => {
|
||||
s.style.fill = other.primary_color();
|
||||
s.style.fill_paint = Some(other.clone());
|
||||
}
|
||||
}
|
||||
s.style.use_fill = true;
|
||||
let changed = if opt_bool(p, "selection")?.unwrap_or(true) && !s.selection.is_empty() {
|
||||
// Counts from several layers are added up.
|
||||
s.each_layer(false, |s| set_selected_fills(s, &spec))?.get("changed").and_then(Value::as_u64).unwrap_or(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Ok(json!({"fill": fill_json(&placed), "changed": changed}))
|
||||
}
|
||||
|
||||
/// The selected shapes with a fill on the active layer get `spec`: the same kind of fill keeps
|
||||
/// where it lies, another kind is fitted to the shape.
|
||||
fn set_selected_fills(s: &mut Session, spec: &FillSpec) -> Result<Value> {
|
||||
let sel: std::collections::HashSet<ElementId> = s.selection.on(s.layer).into_iter().collect();
|
||||
if sel.is_empty() {
|
||||
return Ok(json!({"changed": 0}));
|
||||
}
|
||||
let mut changed = 0u64;
|
||||
let mut merged = Vec::new();
|
||||
for e in s.editable_keyframe()?.elements_mut_where(|id| sel.contains(&id)) {
|
||||
let id = e.id;
|
||||
let ElementKind::Shape(sh) = &mut e.kind else { continue };
|
||||
let Some(old) = &sh.fill else { continue };
|
||||
let Some(mut new) = spec.apply(old) else { continue };
|
||||
if fill_kind(old) != spec.kind {
|
||||
new = new.fitted(&sh.path.bounds());
|
||||
}
|
||||
if sh.fill.as_ref() != Some(&new) {
|
||||
sh.fill = Some(new);
|
||||
changed += 1;
|
||||
if sh.merge {
|
||||
merged.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A raw fill joins the fills of its new paint it touches (as the Paint Bucket's recolour).
|
||||
if !merged.is_empty() {
|
||||
crate::cmds_raw::remerge_in_place(s, &merged)?;
|
||||
}
|
||||
Ok(json!({"changed": changed}))
|
||||
}
|
||||
|
||||
/// The size of the image a bitmap fill shows (`None`: not a bitmap, or missing).
|
||||
pub fn image_size(doc: &anicraft_doc::Document, p: &Paint) -> Option<(f32, f32)> {
|
||||
match p {
|
||||
Paint::Bitmap { bitmap, .. } => doc.bitmap(*bitmap).map(|b| (b.width as f32, b.height as f32)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where element `e`'s gradient or bitmap fill lies: its frame (see [`Paint::frame`]) in the
|
||||
/// space being edited. `None` for anything else.
|
||||
pub fn fill_frame(doc: &anicraft_doc::Document, e: &Element) -> Option<Affine> {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return None };
|
||||
let f = sh.fill.as_ref()?;
|
||||
Some(e.transform.mul(&f.frame(image_size(doc, f))?))
|
||||
}
|
||||
|
||||
fn opt_vec2(p: &Value, key: &str) -> Result<Option<Vec2>> {
|
||||
let bad = || EngineError::Param(format!("param '{key}' must be [x, y] (finite numbers)"));
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Array(a)) if a.len() == 2 => {
|
||||
let v = |i: usize| a.get(i).and_then(Value::as_f64).filter(|x| x.is_finite() && x.abs() <= f64::from(crate::cmds_draw::MAX_EXTENT)).map(|x| x as f32);
|
||||
match (v(0), v(1)) {
|
||||
(Some(x), Some(y)) => Ok(Some(Vec2::new(x, y))),
|
||||
_ => Err(bad()),
|
||||
}
|
||||
}
|
||||
Some(_) => Err(bad()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame `paint.transform_fill`'s params ask for, from the current one `cur`.
|
||||
fn new_frame(cur: &Affine, p: &Value) -> Result<Affine> {
|
||||
if let Some(v) = p.get("frame").filter(|v| !v.is_null()) {
|
||||
let a = v.as_array().filter(|a| a.len() == 6).ok_or_else(|| EngineError::Param("param 'frame' must be [a, b, c, d, e, f]".into()))?;
|
||||
let mut m = [0.0f32; 6];
|
||||
for (slot, x) in m.iter_mut().zip(a) {
|
||||
*slot = x.as_f64().filter(|x| x.is_finite() && x.abs() <= 1e7).ok_or_else(|| EngineError::Param("param 'frame' must hold six finite numbers".into()))? as f32;
|
||||
}
|
||||
return Ok(Affine { m });
|
||||
}
|
||||
let scale = |k: &str| -> Result<f32> {
|
||||
match opt_f32(p, k)? {
|
||||
None => Ok(1.0),
|
||||
Some(v) if (1e-4..=1e4).contains(&v.abs()) => Ok(v),
|
||||
Some(_) => Err(EngineError::Param(format!("param '{k}' must be a scale between 0.0001 and 10000 (negative flips)"))),
|
||||
}
|
||||
};
|
||||
let both = scale("scale")?;
|
||||
let (sx, sy) = (scale("scale_x")? * both, scale("scale_y")? * both);
|
||||
let skew = |k: &str| -> Result<f32> {
|
||||
match opt_f32(p, k)? {
|
||||
None => Ok(0.0),
|
||||
Some(d) if d.abs() <= 85.0 => Ok(d.to_radians().tan()),
|
||||
Some(_) => Err(EngineError::Param(format!("param '{k}' must be between -85 and 85 degrees"))),
|
||||
}
|
||||
};
|
||||
let own = Affine::scale(sx, sy).mul(&Affine { m: [1.0, skew("skew_y")?, skew("skew_x")?, 1.0, 0.0, 0.0] });
|
||||
let mut f = cur.mul(&own);
|
||||
if let Some(deg) = opt_f32(p, "rotate")? {
|
||||
let c = f.apply(Vec2::ZERO);
|
||||
f = Affine::translate(c.x, c.y).mul(&Affine::rotate(deg.to_radians())).mul(&Affine::translate(-c.x, -c.y)).mul(&f);
|
||||
}
|
||||
if let Some(d) = opt_vec2(p, "move")? {
|
||||
f = Affine::translate(d.x, d.y).mul(&f);
|
||||
}
|
||||
if let Some(at) = opt_vec2(p, "center")? {
|
||||
let c = f.apply(Vec2::ZERO);
|
||||
f = Affine::translate(at.x - c.x, at.y - c.y).mul(&f);
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// `paint.transform_fill`: the Gradient Transform tool's edit.
|
||||
fn transform_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let focal = opt_focal(p)?;
|
||||
let only = opt_u64(p, "element")?.map(ElementId);
|
||||
let targets: std::collections::HashSet<ElementId> = match only {
|
||||
Some(id) => [id].into(),
|
||||
None => s.selection.on(s.layer).into_iter().collect(),
|
||||
};
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::State("select a shape with a gradient or bitmap fill".into()));
|
||||
}
|
||||
let doc = s.doc.clone();
|
||||
let mut frames = Vec::new();
|
||||
for e in s.editable_keyframe()?.elements_mut_where(|id| targets.contains(&id)) {
|
||||
let (Some(cur), Some(to_local)) = (fill_frame(&doc, e), e.transform.inverse()) else { continue };
|
||||
let f = new_frame(&cur, p)?;
|
||||
if !f.is_finite() || f.determinant().abs() < 1e-6 {
|
||||
return Err(EngineError::Param("that would flatten the fill to nothing".into()));
|
||||
}
|
||||
let ElementKind::Shape(sh) = &mut e.kind else { continue };
|
||||
let Some(fill) = &sh.fill else { continue };
|
||||
let mut new = fill.with_frame(&to_local.mul(&f), image_size(&doc, fill));
|
||||
if let (Paint::Radial { focal: slot, .. }, Some(v)) = (&mut new, focal) {
|
||||
*slot = v;
|
||||
}
|
||||
frames.push(json!(f.m));
|
||||
// Only where the fill lies changes, so a raw fill stays the shape it is (no re-merge:
|
||||
// its id holds through a drag, and a moved gradient matches no neighbour's anyway).
|
||||
sh.fill = Some(new);
|
||||
}
|
||||
if frames.is_empty() {
|
||||
return Err(EngineError::State(match only {
|
||||
Some(_) => "that shape has no gradient or bitmap fill on the active layer at this frame".into(),
|
||||
None => "none of the selected shapes has a gradient or bitmap fill".into(),
|
||||
}));
|
||||
}
|
||||
Ok(json!({"changed": frames.len(), "frames": frames}))
|
||||
}
|
||||
|
||||
/// `paint.lock_fill`.
|
||||
fn lock_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let on = opt_bool(p, "on")?.unwrap_or(!s.style.lock_fill);
|
||||
s.style.lock_fill = on;
|
||||
Ok(json!({"on": on}))
|
||||
}
|
||||
@@ -26,7 +26,7 @@ fn rect(s: &mut Session, x: f32, fill: &str) -> u64 {
|
||||
|
||||
/// A linear gradient across the shape's own width (local space: the shape is centred on 0).
|
||||
fn gradient() -> Paint {
|
||||
Paint::Linear { start: Vec2::new(-50.0, 0.0), end: Vec2::new(50.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }] }
|
||||
Paint::linear(Vec2::new(-50.0, 0.0), Vec2::new(50.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }])
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -119,7 +119,7 @@ pub(crate) fn movie() -> (Session, SymbolId, SymbolId, SymbolId) {
|
||||
k.script = Some(FrameScript::Source(Arc::new(SourceScript::new(Default::default(), "stop(); // say hello"))));
|
||||
}
|
||||
b.scene("Scene 1", vec![actions, art]);
|
||||
let r = b.rect(Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(10.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(RED) }, GradientStop { offset: 1.0, color: Rgba::WHITE }] }, None);
|
||||
let r = b.rect(Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(RED) }, GradientStop { offset: 1.0, color: Rgba::WHITE }]), None);
|
||||
let l = b.layer("Back", vec![(0, 1, "", vec![r])]);
|
||||
b.scene("Scene 2", vec![l]);
|
||||
(Session::new(b.doc), outer, inner, unused)
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
//! The fill swatch's gradients, Lock Fill and the Gradient Transform tool's command (ADR 0074).
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{ElementId, ElementKind, Paint, Rgba, Shape, Spread};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn shape(s: &Session, id: u64) -> (Shape, Affine) {
|
||||
s.visible_elements()
|
||||
.iter()
|
||||
.find(|e| e.id == ElementId(id))
|
||||
.and_then(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => Some((sh.clone(), e.transform)),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a shape")
|
||||
}
|
||||
|
||||
/// A 100 × 100 square at (x, 100), selected (drawing commands select what they draw).
|
||||
fn square(s: &mut Session, x: f32) -> u64 {
|
||||
run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}))["element"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// A 100 × 100 square at (x, 100) in the fill swatch.
|
||||
fn poured(s: &mut Session, x: f32) -> u64 {
|
||||
run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "stroke": null}))["element"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// Where a shape's fill lies on the stage.
|
||||
fn stage_frame(s: &Session, id: u64) -> Affine {
|
||||
let (sh, m) = shape(s, id);
|
||||
m.mul(&sh.fill.and_then(|f| f.frame(None)).expect("a gradient"))
|
||||
}
|
||||
|
||||
fn near(a: &Affine, b: &Affine) -> bool {
|
||||
a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() <= 1e-3 * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
|
||||
const RAMP: &str = r##"[{"offset": 0, "color": "#ff8800"}, {"offset": 0.5, "color": "#ffffff80"}, {"offset": 1, "color": "#0044ff"}]"##;
|
||||
|
||||
#[test]
|
||||
fn set_fill_makes_gradients_for_the_swatch_and_the_selection_in_one_step() {
|
||||
let mut s = Session::default();
|
||||
let a = square(&mut s, 100.0);
|
||||
let steps = s.history_len();
|
||||
let stops: Value = serde_json::from_str(RAMP).unwrap();
|
||||
let r = run(&mut s, "paint.set_fill", json!({"type": "linear", "stops": stops, "spread": "reflect", "linear_rgb": true}));
|
||||
assert_eq!(r["changed"], 1);
|
||||
assert_eq!(r["fill"]["type"], "linear");
|
||||
assert_eq!(r["fill"]["stops"][1]["color"], "#ffffff80", "alpha survives as #rrggbbaa");
|
||||
assert_eq!(s.history_len(), steps + 1, "one undo step");
|
||||
// The selected square's fill is fitted to it: across its width, through its middle.
|
||||
match shape(&s, a).0.fill {
|
||||
Some(Paint::Linear { start, end, stops, spread, linear_rgb }) => {
|
||||
assert_eq!((start, end), (Vec2::new(-50.0, 0.0), Vec2::new(50.0, 0.0)));
|
||||
assert_eq!((stops.len(), spread, linear_rgb), (3, Spread::Reflect, true));
|
||||
assert!((stops[1].color.a - 128.0 / 255.0).abs() < 1e-6);
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// The swatch holds it too (across the stage), so the next shape gets it, fitted.
|
||||
assert!(matches!(s.style.fill_paint, Some(Paint::Linear { .. })));
|
||||
assert_eq!(s.style.fill, Rgba::hex(0xff8800), "the swatch shows the first colour");
|
||||
let b = run(&mut s, "draw.rect", json!({"x": 300, "y": 300, "w": 200, "h": 40, "stroke": null}))["element"].as_u64().unwrap();
|
||||
assert!(near(&stage_frame(&s, b), &Affine { m: [100.0, 0.0, 0.0, 100.0, 400.0, 320.0] }), "{:?}", stage_frame(&s, b));
|
||||
// Undo puts the solid colour back.
|
||||
s.undo().unwrap();
|
||||
s.undo().unwrap();
|
||||
assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0xff0000))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_stops_keeps_where_a_gradient_lies() {
|
||||
let mut s = Session::default();
|
||||
let a = square(&mut s, 100.0);
|
||||
run(&mut s, "paint.set_fill", json!({"type": "radial"}));
|
||||
// A white-to-black ring round the square's centre, touching its sides.
|
||||
assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] }));
|
||||
run(&mut s, "paint.transform_fill", json!({"move": [10, 0], "scale_x": 2}));
|
||||
let moved = stage_frame(&s, a);
|
||||
// New stops, overflow and focal point: the ring stays put.
|
||||
let stops: Value = serde_json::from_str(RAMP).unwrap();
|
||||
run(&mut s, "paint.set_fill", json!({"stops": stops, "spread": "repeat", "focal": 0.5}));
|
||||
assert!(near(&stage_frame(&s, a), &moved));
|
||||
match shape(&s, a).0.fill {
|
||||
Some(Paint::Radial { stops, spread, focal, .. }) => assert_eq!((stops.len(), spread, focal), (3, Spread::Repeat, 0.5)),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// Changing kind fits it again; back to solid, and the swatch is solid too.
|
||||
run(&mut s, "paint.set_fill", json!({"type": "linear"}));
|
||||
assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] }));
|
||||
assert!(matches!(shape(&s, a).0.fill, Some(Paint::Linear { spread: Spread::Repeat, .. })), "the gradient keeps its colours and overflow");
|
||||
run(&mut s, "paint.set_fill", json!({"type": "solid", "color": "#00ff00"}));
|
||||
assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0x00ff00))));
|
||||
assert!(s.style.fill_paint.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_fill_checks_its_params() {
|
||||
let mut s = Session::default();
|
||||
square(&mut s, 100.0);
|
||||
for bad in [
|
||||
json!({"type": "conic"}),
|
||||
json!({"stops": [{"offset": 0, "color": "#ff0000"}]}),
|
||||
json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1.5, "color": "#ff0000"}]}),
|
||||
json!({"stops": [{"offset": 0, "color": "red"}, {"offset": 1, "color": "#ff0000"}]}),
|
||||
json!({"stops": (0..16).map(|i| json!({"offset": i as f32 / 15.0, "color": "#000000"})).collect::<Vec<_>>()}),
|
||||
json!({"spread": "mirror"}),
|
||||
json!({"focal": 1.0}),
|
||||
json!({"type": "bitmap"}),
|
||||
json!({"type": "bitmap", "bitmap": 999}),
|
||||
] {
|
||||
let before = s.doc.clone();
|
||||
assert!(s.execute("paint.set_fill", &bad).is_err(), "{bad}");
|
||||
assert!(s.doc == before, "{bad} changed nothing");
|
||||
}
|
||||
// Unselected: only the swatch.
|
||||
s.selection.clear();
|
||||
let r = run(&mut s, "paint.set_fill", json!({"type": "radial"}));
|
||||
assert_eq!(r["changed"], 0);
|
||||
assert!(matches!(s.style.fill_paint, Some(Paint::Radial { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_fill_moves_turns_scales_and_skews_analytically() {
|
||||
let mut s = Session::default();
|
||||
let a = square(&mut s, 100.0);
|
||||
run(&mut s, "paint.set_fill", json!({"type": "linear"}));
|
||||
let f0 = stage_frame(&s, a);
|
||||
// Scale along the gradient (its own x), then turn 90° about its centre, then move.
|
||||
run(&mut s, "paint.transform_fill", json!({"scale_x": 0.5, "rotate": 90, "move": [5, -5]}));
|
||||
let want = Affine::translate(5.0, -5.0).mul(&Affine::translate(150.0, 150.0)).mul(&Affine::rotate(std::f32::consts::FRAC_PI_2)).mul(&Affine::translate(-150.0, -150.0)).mul(&f0).mul(&Affine::scale(0.5, 1.0));
|
||||
let got = stage_frame(&s, a);
|
||||
// A linear gradient keeps only its axis: compare the ends.
|
||||
for x in [-1.0, 1.0] {
|
||||
assert!(got.apply(Vec2::new(x, 0.0)).distance(want.apply(Vec2::new(x, 0.0))) < 1e-3, "{got:?} vs {want:?}");
|
||||
}
|
||||
match shape(&s, a).0.fill {
|
||||
Some(Paint::Linear { start, end, .. }) => {
|
||||
assert!(start.distance(Vec2::new(5.0, -30.0)) < 1e-3 && end.distance(Vec2::new(5.0, 20.0)) < 1e-3, "{start:?} {end:?}");
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// A radial gradient takes any frame: skew and an absolute frame are kept exactly.
|
||||
run(&mut s, "paint.set_fill", json!({"type": "radial"}));
|
||||
let f1 = stage_frame(&s, a);
|
||||
run(&mut s, "paint.transform_fill", json!({"skew_x": 30, "focal": -0.25}));
|
||||
let want = f1.mul(&Affine { m: [1.0, 0.0, 30f32.to_radians().tan(), 1.0, 0.0, 0.0] });
|
||||
assert!(near(&stage_frame(&s, a), &want), "{:?}", stage_frame(&s, a));
|
||||
assert!(matches!(shape(&s, a).0.fill, Some(Paint::Radial { focal, .. }) if focal == -0.25));
|
||||
let frame = [40.0, 10.0, -5.0, 20.0, 160.0, 140.0];
|
||||
let r = run(&mut s, "paint.transform_fill", json!({"element": a, "frame": frame}));
|
||||
assert_eq!(r["changed"], 1);
|
||||
assert!(near(&stage_frame(&s, a), &Affine { m: frame }));
|
||||
// The result reports the frames, so a script can carry on from them.
|
||||
assert_eq!(r["frames"][0].as_array().map(Vec::len), Some(6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_fill_turns_bitmap_fills_and_refuses_what_it_cannot_do() {
|
||||
let mut s = Session::default();
|
||||
// A 4 × 2 bitmap from the library, poured into a square.
|
||||
let png = anicraft_render::encode_png(4, 2, &[255; 32]).unwrap();
|
||||
let id = s.doc.alloc_id();
|
||||
s.doc.bitmaps.push(std::sync::Arc::new(anicraft_doc::Bitmap::from_png(anicraft_doc::BitmapId(id), "tile.png", png).unwrap()));
|
||||
let a = square(&mut s, 100.0);
|
||||
run(&mut s, "paint.set_fill", json!({"type": "bitmap", "bitmap": id}));
|
||||
let (sh, m) = shape(&s, a);
|
||||
let fill = sh.fill.clone().unwrap();
|
||||
let frame = |s: &Session| {
|
||||
let (sh, m) = shape(s, a);
|
||||
let f = sh.fill.unwrap();
|
||||
m.mul(&f.frame(Some((4.0, 2.0))).unwrap())
|
||||
};
|
||||
// Tiled from the square's top-left at its own size.
|
||||
assert!(near(&m.mul(&fill.frame(Some((4.0, 2.0))).unwrap()), &Affine { m: [2.0, 0.0, 0.0, 1.0, 102.0, 101.0] }));
|
||||
let f0 = frame(&s);
|
||||
let steps = s.history_len();
|
||||
run(&mut s, "paint.transform_fill", json!({"scale": 3, "skew_y": 20, "rotate": -45}));
|
||||
assert_eq!(s.history_len(), steps + 1, "one step");
|
||||
let c = f0.apply(Vec2::ZERO);
|
||||
let want = Affine::translate(c.x, c.y).mul(&Affine::rotate(-std::f32::consts::FRAC_PI_4)).mul(&Affine::translate(-c.x, -c.y)).mul(&f0).mul(&Affine::scale(3.0, 3.0)).mul(&Affine { m: [1.0, 20f32.to_radians().tan(), 0.0, 1.0, 0.0, 0.0] });
|
||||
assert!(near(&frame(&s), &want), "{:?} vs {want:?}", frame(&s));
|
||||
// Nothing to flatten a fill to, nor a solid fill to transform.
|
||||
let before = s.doc.clone();
|
||||
assert!(s.execute("paint.transform_fill", &json!({"frame": [1, 0, 2, 0, 0, 0]})).is_err());
|
||||
assert!(s.execute("paint.transform_fill", &json!({"scale_x": 0})).is_err());
|
||||
assert!(s.execute("paint.transform_fill", &json!({"skew_x": 90})).is_err());
|
||||
assert!(s.doc == before);
|
||||
let b = square(&mut s, 300.0);
|
||||
assert!(s.execute("paint.transform_fill", &json!({"element": b, "move": [1, 1]})).is_err(), "a solid fill has no gradient to move");
|
||||
s.selection.clear();
|
||||
assert!(s.execute("paint.transform_fill", &json!({"move": [1, 1]})).is_err(), "nothing selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_fill_runs_one_gradient_across_shapes() {
|
||||
let mut s = Session::default();
|
||||
s.selection.clear();
|
||||
run(&mut s, "paint.set_fill", json!({"type": "linear"}));
|
||||
// The swatch spans the stage, left to right.
|
||||
let w = s.doc.stage.width as f32;
|
||||
match &s.style.fill_paint {
|
||||
Some(Paint::Linear { start, end, .. }) => assert_eq!((start.x, end.x), (0.0, w)),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// Unlocked (the default), each shape gets its own ramp.
|
||||
let a = poured(&mut s, 100.0);
|
||||
assert!(near(&stage_frame(&s, a), &Affine { m: [50.0, 0.0, 0.0, 50.0, 150.0, 150.0] }));
|
||||
// Locked, the swatch's ramp across the stage, in each shape's own space.
|
||||
let r = run(&mut s, "paint.lock_fill", json!({}));
|
||||
assert_eq!(r["on"], true);
|
||||
let b = poured(&mut s, 300.0);
|
||||
let f = stage_frame(&s, b);
|
||||
assert!(f.apply(Vec2::new(-1.0, 0.0)).x.abs() < 1e-3 && (f.apply(Vec2::new(1.0, 0.0)).x - w).abs() < 1e-3, "{f:?}");
|
||||
// The Paint Bucket follows it too: a click on the unlocked square locks its ramp to the stage.
|
||||
run(&mut s, "paint.bucket", json!({"x": 150, "y": 150}));
|
||||
let f = stage_frame(&s, a);
|
||||
assert!(f.apply(Vec2::new(-1.0, 0.0)).x.abs() < 1e-3, "{f:?}");
|
||||
assert_eq!(run(&mut s, "paint.lock_fill", json!({"on": false}))["on"], false);
|
||||
run(&mut s, "paint.bucket", json!({"x": 350, "y": 150}));
|
||||
assert!(near(&stage_frame(&s, b), &Affine { m: [50.0, 0.0, 0.0, 50.0, 350.0, 150.0] }));
|
||||
assert!(s.execute("paint.lock_fill", &json!({"on": "yes"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_raw_fill_keeps_its_id_through_a_drag_of_its_gradient() {
|
||||
// The editor draws raw (merge) shapes; the Gradient Transform tool addresses one by id
|
||||
// through every step of a drag, so moving where its fill lies never re-merges it.
|
||||
let mut s = Session::default();
|
||||
s.style.object_drawing = false;
|
||||
let a = square(&mut s, 100.0);
|
||||
run(&mut s, "paint.set_fill", json!({"type": "radial"}));
|
||||
let id = s.selection.id_list().first().copied().unwrap_or(a);
|
||||
for k in 1..=3 {
|
||||
let r = run(&mut s, "paint.transform_fill", json!({"element": id, "frame": [50.0 + 10.0 * k as f32, 0, 0, 50, 150, 150]}));
|
||||
assert_eq!(r["changed"], 1, "step {k}");
|
||||
}
|
||||
assert!(near(&stage_frame(&s, id), &Affine { m: [80.0, 0.0, 0.0, 50.0, 150.0, 150.0] }));
|
||||
}
|
||||
@@ -21,7 +21,7 @@ mod cmds_motion;
|
||||
mod cmds_hints;
|
||||
mod cmds_layer;
|
||||
pub mod cmds_library;
|
||||
mod cmds_paint;
|
||||
pub mod cmds_paint;
|
||||
mod cmds_path;
|
||||
pub mod cmds_raw;
|
||||
pub mod cmds_rawsub;
|
||||
@@ -215,9 +215,13 @@ pub(crate) fn pick_index(dl: &DisplayList, p: Vec2, slop: f32, ok: impl Fn(usize
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ToolStyle {
|
||||
pub fill: anicraft_doc::Rgba,
|
||||
/// The fill swatch holds a gradient or a bitmap (picked with the Eyedropper, ADR 0034), in
|
||||
/// stage space; `fill` is then its representative colour. `None`: the solid `fill`.
|
||||
/// The fill swatch holds a gradient or a bitmap (set in the Colour panel or picked with the
|
||||
/// Eyedropper, ADR 0034 and 0074), in stage space; `fill` is then its representative colour.
|
||||
/// `None`: the solid `fill`.
|
||||
pub fill_paint: Option<anicraft_doc::Paint>,
|
||||
/// Lock Fill (ADR 0074): a gradient or bitmap from the swatch is poured where it lies on the
|
||||
/// stage, so it runs on across shapes. Off, each shape gets it fitted to its own bounds.
|
||||
pub lock_fill: bool,
|
||||
pub stroke: anicraft_doc::Rgba,
|
||||
pub stroke_width: f32,
|
||||
pub use_fill: bool,
|
||||
@@ -239,7 +243,7 @@ pub struct ToolStyle {
|
||||
|
||||
impl Default for ToolStyle {
|
||||
fn default() -> Self {
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true }
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, lock_fill: false, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, line: anicraft_doc::StrokeStyle::default(), object_drawing: true, snap_objects: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +252,13 @@ impl ToolStyle {
|
||||
pub fn fill_paint(&self) -> anicraft_doc::Paint {
|
||||
self.fill_paint.clone().unwrap_or(anicraft_doc::Paint::Solid(self.fill))
|
||||
}
|
||||
/// The fill swatch's paint for a shape whose space is `to_local` from the stage and whose
|
||||
/// outline has the local `bounds`: with Lock Fill, the stage-space paint carried into the
|
||||
/// shape; without, a gradient or bitmap fitted to the bounds (as Animate pours them).
|
||||
pub fn fill_paint_for(&self, to_local: &anicraft_geom::Affine, bounds: &anicraft_geom::Rect) -> anicraft_doc::Paint {
|
||||
let paint = self.fill_paint();
|
||||
if self.lock_fill || matches!(paint, anicraft_doc::Paint::Solid(_)) { paint.transformed(to_local) } else { paint.fitted(bounds) }
|
||||
}
|
||||
/// Sets the fill swatch to a solid colour (dropping a picked gradient or bitmap).
|
||||
pub fn set_fill_color(&mut self, c: anicraft_doc::Rgba) {
|
||||
self.fill = c;
|
||||
@@ -1059,6 +1070,8 @@ mod erase_tests;
|
||||
#[cfg(test)]
|
||||
mod eyedropper_tests;
|
||||
#[cfg(test)]
|
||||
mod gradient_tests;
|
||||
#[cfg(test)]
|
||||
mod selection_tests;
|
||||
#[cfg(test)]
|
||||
mod scale_grid_tests;
|
||||
|
||||
@@ -245,13 +245,20 @@ fn fill_index(table: &mut Vec<(Paint, ColorEffect)>, v: (Paint, ColorEffect)) ->
|
||||
}
|
||||
|
||||
/// Whether two paints look the same (positions within a thousandth of a unit).
|
||||
pub(crate) fn same_paint(a: &Paint, b: &Paint) -> bool {
|
||||
pub(crate) fn same_paint(x: &Paint, y: &Paint) -> bool {
|
||||
const EPS: f32 = 1e-3;
|
||||
let near = |p: Vec2, q: Vec2| p.distance(q) <= EPS;
|
||||
match (a, b) {
|
||||
match (x, y) {
|
||||
(Paint::Solid(x), Paint::Solid(y)) => x == y,
|
||||
(Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => near(*s0, *s1) && near(*e0, *e1) && a == b,
|
||||
(Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => near(*c0, *c1) && (r0 - r1).abs() <= EPS && a == b,
|
||||
(Paint::Linear { start: s0, end: e0, stops: a, spread: p0, linear_rgb: l0 }, Paint::Linear { start: s1, end: e1, stops: b, spread: p1, linear_rgb: l1 }) => near(*s0, *s1) && near(*e0, *e1) && a == b && p0 == p1 && l0 == l1,
|
||||
(Paint::Radial { stops: a, spread: p0, linear_rgb: l0, focal: f0, .. }, Paint::Radial { stops: b, spread: p1, linear_rgb: l1, focal: f1, .. }) => {
|
||||
// The same ring: the frames agree (centre, axes and size).
|
||||
let same_frame = match (x.frame(None), y.frame(None)) {
|
||||
(Some(m0), Some(m1)) => m0.m.iter().zip(m1.m).all(|(u, v)| (u - v).abs() <= EPS * u.abs().max(v.abs()).max(1.0)),
|
||||
_ => false,
|
||||
};
|
||||
same_frame && a == b && p0 == p1 && l0 == l1 && (f0 - f1).abs() <= EPS
|
||||
}
|
||||
(Paint::Bitmap { bitmap: b0, repeat: r0, matrix: m0 }, Paint::Bitmap { bitmap: b1, repeat: r1, matrix: m1 }) => {
|
||||
b0 == b1 && r0 == r1 && m0.m.iter().zip(m1.m).all(|(x, y)| (x - y).abs() <= EPS * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
|
||||
@@ -291,13 +291,14 @@ fn a_pasted_raw_shape_cuts_what_it_lands_on() {
|
||||
}
|
||||
|
||||
fn linear() -> Paint {
|
||||
Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }] }
|
||||
Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_fills_take_part_in_the_merge() {
|
||||
let mut s = raw_session();
|
||||
s.style.fill_paint = Some(linear());
|
||||
s.style.lock_fill = true;
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null}));
|
||||
assert_eq!(fills(&s).len(), 1, "raw, not an object");
|
||||
// A line across cuts it in two; each half shows its part of the gradient where it was.
|
||||
@@ -383,6 +384,7 @@ fn subselection_timings() {
|
||||
fn the_eraser_takes_gradient_fills_too() {
|
||||
let mut s = raw_session();
|
||||
s.style.fill_paint = Some(linear());
|
||||
s.style.lock_fill = true;
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null}));
|
||||
let before: f32 = fills(&s).iter().map(|e| area(e)).sum();
|
||||
run(&mut s, "draw.erase", json!({"points": [[100, -20], [100, 120]], "size": 20}));
|
||||
|
||||
@@ -304,15 +304,17 @@ pub fn bin_with(scene: &Scene, width: u32, height: u32, gpu: Option<&crate::gpu_
|
||||
(_, Some((at, b))) => (IMAGE, [[u(at), u(b.width() as u32), u(b.height() as u32), 0.0], [u(b.x0 as u32), u(b.y0 as u32), 0.0, 0.0], [0.0; 4], [0.0; 4]]),
|
||||
(_, None) if f.layer.is_some() => (SOLID, [[0.0; 4]; 4]),
|
||||
(Shader::Solid(c), _) => (SOLID, [*c, [0.0; 4], [0.0; 4], [0.0; 4]]),
|
||||
(Shader::Linear { inv, start, dir, lut }, _) => {
|
||||
// A gradient's first vec4 holds what its colour slot doesn't need: the spread
|
||||
// (0 pad, 1 reflect, 2 repeat) and a radial gradient's focal point (ADR 0074).
|
||||
(Shader::Linear { inv, start, dir, spread, lut }, _) => {
|
||||
ramps.extend_from_slice(&lut[..]);
|
||||
let m = inv.m;
|
||||
(LINEAR, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]])
|
||||
(LINEAR, [[spread_code(*spread), 0.0, 0.0, 0.0], [m[0], m[1], m[2], m[3]], [m[4], m[5], start.x, start.y], [dir.x, dir.y, 0.0, 0.0]])
|
||||
}
|
||||
(Shader::Radial { inv, center, inv_radius, lut }, _) => {
|
||||
(Shader::Radial { inv, center, inv_radius, focal, spread, lut }, _) => {
|
||||
ramps.extend_from_slice(&lut[..]);
|
||||
let m = inv.m;
|
||||
(RADIAL, [[0.0; 4], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]])
|
||||
(RADIAL, [[spread_code(*spread), *focal, 0.0, 0.0], [m[0], m[1], m[2], m[3]], [m[4], m[5], center.x, center.y], [0.0, 0.0, *inv_radius, 0.0]])
|
||||
}
|
||||
// The oracle's sample of a bitmap (crates/render/src/paint.rs › sample).
|
||||
(Shader::Bitmap { inv, pixels, repeat, fx, smooth }, _) => {
|
||||
@@ -973,3 +975,12 @@ fn avg_clamp(u0: f32, u1: f32) -> f32 {
|
||||
pub(crate) fn solid_of(b: &Binned, op: usize) -> anicraft_render::paint::Premul {
|
||||
b.paints.get(PAINT_VEC4S * op).copied().unwrap_or([0.0; 4])
|
||||
}
|
||||
|
||||
/// How `fine.wgsl` reads a gradient's spread.
|
||||
fn spread_code(s: anicraft_doc::Spread) -> f32 {
|
||||
match s {
|
||||
anicraft_doc::Spread::Pad => 0.0,
|
||||
anicraft_doc::Spread::Reflect => 1.0,
|
||||
anicraft_doc::Spread::Repeat => 2.0,
|
||||
}
|
||||
}
|
||||
@@ -262,11 +262,36 @@ fn shade(op: u32, kind: u32, ramp: u32, p: vec2<f32>, x: u32, y: u32) -> vec4<f3
|
||||
let g = paints[base + 3u];
|
||||
// Pixel back to paint space: x' = a x + c y + e, y' = b x + d y + f.
|
||||
let q = vec2<f32>(m.x * p.x + m.z * p.y + n.x, m.y * p.x + m.w * p.y + n.y);
|
||||
// Spread and focal point (crates/render/src/paint.rs › Spread::apply, focal_t).
|
||||
let o = paints[base];
|
||||
var t: f32;
|
||||
if kind == 1u {
|
||||
t = dot(q - n.zw, g.xy);
|
||||
} else {
|
||||
t = length(q - n.zw) * g.z;
|
||||
let u = (q - n.zw) * g.z;
|
||||
let f = o.y;
|
||||
if f == 0.0 {
|
||||
t = length(u);
|
||||
} else {
|
||||
let d = vec2<f32>(u.x - f, u.y);
|
||||
let a = 1.0 - f * f;
|
||||
let fd = f * d.x;
|
||||
t = (fd + sqrt(max(fd * fd + a * dot(d, d), 0.0))) / a;
|
||||
}
|
||||
}
|
||||
let spread = u32(o.x + 0.5);
|
||||
if spread == 2u {
|
||||
t = t - floor(t);
|
||||
if t >= 1.0 {
|
||||
t = 0.0;
|
||||
}
|
||||
} else if spread == 1u {
|
||||
let m = t - 2.0 * floor(t * 0.5);
|
||||
if m > 1.0 {
|
||||
t = 2.0 - m;
|
||||
} else {
|
||||
t = m;
|
||||
}
|
||||
}
|
||||
t = clamp(t, 0.0, 1.0);
|
||||
let i = u32(t * 255.0 + 0.5) & 255u;
|
||||
|
||||
+34
-7
@@ -89,10 +89,30 @@ fn scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
star.fill_rule = FillRule::EvenOdd;
|
||||
out.push(("star", list(vec![star]), view(80, 80, Some(Rgba::WHITE))));
|
||||
// Gradients under rotation and scale.
|
||||
let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)]) });
|
||||
let mut lin = item(Path::rect(0.0, 0.0, 100.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), stops(&[(0.0, red), (0.5, Rgba::WHITE), (1.0, blue)])));
|
||||
lin.transform = Affine::translate(70.0, 10.0).mul(&Affine::rotate(0.4)).mul(&Affine::scale(1.2, 0.8));
|
||||
let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::Radial { center: Vec2::new(60.0, 90.0), radius: 50.0, stops: stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))]) });
|
||||
let rad = item(Path::ellipse(60.0, 90.0, 50.0, 30.0), Paint::radial(Vec2::new(60.0, 90.0), 50.0, stops(&[(0.0, Rgba::WHITE), (1.0, Rgba::new(0.0, 0.0, 0.0, 0.3))])));
|
||||
out.push(("gradients", list(vec![lin, rad]), view(180, 130, Some(Rgba::new(0.9, 0.9, 0.85, 1.0)))));
|
||||
// Gradient options (ADR 0074): reflect and repeat, linear light, a focal point on a turned
|
||||
// ellipse that repeats.
|
||||
let three = stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]);
|
||||
let mut refl = Paint::linear(Vec2::new(20.0, 0.0), Vec2::new(50.0, 0.0), three.clone());
|
||||
if let Paint::Linear { spread, linear_rgb, .. } = &mut refl {
|
||||
*spread = anicraft_doc::Spread::Reflect;
|
||||
*linear_rgb = true;
|
||||
}
|
||||
let mut rep = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(14.0, 9.0), three.clone());
|
||||
if let Paint::Linear { spread, .. } = &mut rep {
|
||||
*spread = anicraft_doc::Spread::Repeat;
|
||||
}
|
||||
let mut foc = Paint::radial(Vec2::ZERO, 1.0, three).with_frame(&Affine::translate(140.0, 60.0).mul(&Affine::rotate(0.6)).mul(&Affine::scale(40.0, 20.0)), None);
|
||||
if let Paint::Radial { focal, spread, .. } = &mut foc {
|
||||
*focal = 0.6;
|
||||
*spread = anicraft_doc::Spread::Repeat;
|
||||
}
|
||||
let mut rep_item = item(Path::rect(0.0, 60.0, 90.0, 50.0), rep);
|
||||
rep_item.transform = Affine::translate(5.0, 0.0);
|
||||
out.push(("gradient options", list(vec![item(Path::rect(0.0, 0.0, 90.0, 55.0), refl), rep_item, item(Path::ellipse(140.0, 60.0, 60.0, 50.0), foc)]), view(210, 120, Some(Rgba::WHITE))));
|
||||
// Strokes: wide, thin (sub-pixel, faded), on open and closed paths.
|
||||
let mut wide = item(Path::line(Vec2::new(10.0, 20.0), Vec2::new(150.0, 70.0)), Paint::Solid(red));
|
||||
wide.fill = None;
|
||||
@@ -166,7 +186,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let red = Rgba::new(0.9, 0.1, 0.1, 1.0);
|
||||
let blue = Rgba::new(0.1, 0.2, 0.9, 0.6);
|
||||
let green = Rgba::new(0.2, 0.7, 0.3, 0.8);
|
||||
let grad = || Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(120.0, 40.0), stops: stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]) };
|
||||
let grad = || Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(120.0, 40.0), stops(&[(0.0, red), (0.5, Rgba::new(1.0, 0.9, 0.3, 1.0)), (1.0, blue)]));
|
||||
let mut out = Vec::new();
|
||||
// A mask: a gradient seen through a circle, an unclipped shape over it, and one under it.
|
||||
let dl = DisplayList {
|
||||
@@ -256,7 +276,7 @@ fn composited_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
out.push(("malformed links", dl, view(50, 50, Some(Rgba::WHITE))));
|
||||
// Soft masks (ADR 0070): an alpha gradient fading a shape out, a luminance mask with a
|
||||
// stroke and overlapping faded art, and a soft mask inside a coverage one.
|
||||
let fade = Paint::Linear { start: Vec2::new(10.0, 0.0), end: Vec2::new(110.0, 0.0), stops: stops(&[(0.0, Rgba::new(1.0, 1.0, 1.0, 0.0)), (1.0, Rgba::new(0.2, 0.9, 0.4, 1.0))]) };
|
||||
let fade = Paint::linear(Vec2::new(10.0, 0.0), Vec2::new(110.0, 0.0), stops(&[(0.0, Rgba::new(1.0, 1.0, 1.0, 0.0)), (1.0, Rgba::new(0.2, 0.9, 0.4, 1.0))]));
|
||||
let soft_art = |path: Path, paint: Paint, clip: u32| {
|
||||
let mut m = item(path, paint);
|
||||
m.masks = Some(clip);
|
||||
@@ -347,7 +367,14 @@ fn emulate(b: &Binned, v: &View) -> Vec<Premul> {
|
||||
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let q = Vec2::new(m[0] * p.x + m[2] * p.y + nn[0], m[1] * p.x + m[3] * p.y + nn[1]);
|
||||
let d = q - Vec2::new(nn[2], nn[3]);
|
||||
let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { d.length() * g[2] };
|
||||
// As fine.wgsl: spread code and focal point in the first vec4.
|
||||
let o = b.paints[base];
|
||||
let t = if kind == 1 { d.x * g[0] + d.y * g[1] } else { anicraft_render::paint::focal_t(d * g[2], o[1]) };
|
||||
let t = match o[0] as u32 {
|
||||
1 => anicraft_doc::Spread::Reflect.apply(t),
|
||||
2 => anicraft_doc::Spread::Repeat.apply(t),
|
||||
_ => t,
|
||||
};
|
||||
let i = (t.clamp(0.0, 1.0) * 255.0 + 0.5) as usize & 255;
|
||||
b.paints[b.op_heads[hd + 2] as usize + i]
|
||||
}
|
||||
@@ -909,7 +936,7 @@ fn bitmap_scenes() -> Vec<(&'static str, DisplayList, View)> {
|
||||
let empty = Arc::new(anicraft_doc::Pixels { width: 0, height: 3, rgba: Vec::new() });
|
||||
out.push(("malformed bitmaps", list(vec![bitmap_item(Path::rect(0.0, 0.0, 30.0, 30.0), &short, false, Affine::scale(7.0, 7.0)), bitmap_item(Path::rect(10.0, 0.0, 10.0, 30.0), &empty, true, Affine::IDENTITY)]), view(32, 32, white)));
|
||||
// Inside a mask and a faded group, over a gradient.
|
||||
let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(80.0, 60.0), stops: stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))]) });
|
||||
let grad = item(Path::rect(0.0, 0.0, 80.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(80.0, 60.0), stops(&[(0.0, Rgba::BLACK), (1.0, Rgba::new(1.0, 0.8, 0.0, 1.0))])));
|
||||
let inside = in_group(clipped(bitmap_item(Path::rect(4.0, 4.0, 72.0, 52.0), &a, true, turned), 0), 0);
|
||||
let dl = DisplayList { clip_modes: Vec::new(), items: vec![grad, inside, mask(Path::ellipse(40.0, 30.0, 30.0, 22.0), 0)], clip_parents: vec![None], groups: vec![group(None, 0.7, BlendMode::Multiply)] };
|
||||
out.push(("bitmap masked and multiplied", dl, view(80, 60, white)));
|
||||
@@ -989,7 +1016,7 @@ fn symbol_items(g: u32) -> Vec<DisplayItem> {
|
||||
#[test]
|
||||
fn gpu_matches_the_oracle_on_every_filter() {
|
||||
let Some(g) = gpu() else { return };
|
||||
let backdrop = item(Path::rect(0.0, 0.0, 70.0, 60.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(70.0, 0.0), stops: stops(&[(0.0, Rgba::new(0.9, 0.9, 0.8, 1.0)), (1.0, Rgba::new(0.2, 0.4, 0.5, 1.0))]) });
|
||||
let backdrop = item(Path::rect(0.0, 0.0, 70.0, 60.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(70.0, 0.0), stops(&[(0.0, Rgba::new(0.9, 0.9, 0.8, 1.0)), (1.0, Rgba::new(0.2, 0.4, 0.5, 1.0))])));
|
||||
let mut worst: f64 = 0.0;
|
||||
for (name, f) in filters_to_test() {
|
||||
let mut items = vec![backdrop.clone()];
|
||||
|
||||
@@ -204,6 +204,55 @@ fn color(c: Rgba) -> Vec<Value> {
|
||||
[c.r, c.g, c.b, c.a].into_iter().map(|v| num(v, 10_000.0)).collect()
|
||||
}
|
||||
|
||||
/// A gradient's stops for a canvas, which only pads: with `Reflect` or `Repeat`, how many
|
||||
/// copies of the ramp lie each side of it, and the stops of them all laid end to end (the
|
||||
/// ramp is `2·copies + 1` times as long; `outward`, for a radial ramp, which has no inside of
|
||||
/// its centre: the ramp first, then all the copies). Linear-light mixing is sampled into stops.
|
||||
fn spread_stops(s: &[anicraft_doc::GradientStop], spread: anicraft_doc::Spread, linear_rgb: bool, outward: bool) -> (usize, Vec<anicraft_doc::GradientStop>) {
|
||||
use anicraft_doc::{GradientStop, Spread};
|
||||
let mut base: Vec<GradientStop> = s.iter().filter(|g| g.offset.is_finite()).copied().collect();
|
||||
base.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
if linear_rgb && base.len() >= 2 {
|
||||
// Sixteen samples per span, mixed in linear light as the renderer's ramp is.
|
||||
let lin = |c: f32| if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) };
|
||||
let enc = |c: f32| if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.max(0.0).powf(1.0 / 2.4) - 0.055 };
|
||||
let mut out = Vec::new();
|
||||
for w in base.windows(2) {
|
||||
if let [a, b] = w {
|
||||
let (ca, cb) = (a.color.sanitized(), b.color.sanitized());
|
||||
for k in 0..16 {
|
||||
let t = k as f32 / 16.0;
|
||||
let m = |x: f32, y: f32| enc(lin(x) + (lin(y) - lin(x)) * t);
|
||||
out.push(GradientStop { offset: a.offset + (b.offset - a.offset) * t, color: Rgba::new(m(ca.r, cb.r), m(ca.g, cb.g), m(ca.b, cb.b), ca.a + (cb.a - ca.a) * t) });
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(l) = base.last() {
|
||||
out.push(*l);
|
||||
}
|
||||
base = out;
|
||||
}
|
||||
if spread == Spread::Pad || base.is_empty() {
|
||||
return (0, base);
|
||||
}
|
||||
// Enough copies to cover a shape many times the ramp's length, within a bounded size.
|
||||
let copies = (240 / base.len()).saturating_sub(1) / 2;
|
||||
let copies = copies.clamp(0, 8);
|
||||
let n = 2 * copies + 1;
|
||||
let mut out = Vec::with_capacity(n * base.len());
|
||||
for k in 0..n {
|
||||
// Copy `k` runs forward unless it reflects (every other copy, counting from the ramp
|
||||
// itself: copy 0 outward, else the middle one).
|
||||
let from_ramp = if outward { k } else { k + copies };
|
||||
let backwards = spread == Spread::Reflect && from_ramp % 2 == 1;
|
||||
let ramp: Vec<GradientStop> = if backwards { base.iter().rev().map(|g| GradientStop { offset: 1.0 - g.offset, color: g.color }).collect() } else { base.clone() };
|
||||
for g in ramp {
|
||||
out.push(GradientStop { offset: (k as f32 + g.offset.clamp(0.0, 1.0)) / n as f32, color: g.color });
|
||||
}
|
||||
}
|
||||
(copies, out)
|
||||
}
|
||||
|
||||
/// `[a, b, c, d, e, f]`, the linear part finer than the offset; `None` for the identity.
|
||||
fn matrix(m: &Affine) -> Option<Value> {
|
||||
if *m == Affine::IDENTITY {
|
||||
@@ -392,8 +441,30 @@ impl<'a> Bake<'a> {
|
||||
};
|
||||
let v = match p {
|
||||
Paint::Solid(c) => json!({"s": color(*c)}),
|
||||
Paint::Linear { start, end, stops: s } => json!({"l": [coord(start.x), coord(start.y), coord(end.x), coord(end.y)], "st": stops(s)}),
|
||||
Paint::Radial { center, radius, stops: s } => json!({"r": [coord(center.x), coord(center.y), coord(radius.max(0.0))], "st": stops(s)}),
|
||||
Paint::Linear { start, end, stops: s, spread, linear_rgb } => {
|
||||
// Canvas gradients only pad: a reflecting or repeating one is drawn as its ramp
|
||||
// laid end to end, far enough to cover any shape it is on (ADR 0074).
|
||||
let (copies, s) = spread_stops(s, *spread, *linear_rgb, false);
|
||||
let d = *end - *start;
|
||||
let (a, b) = (*start - d * copies as f32, *end + d * copies as f32);
|
||||
json!({"l": [coord(a.x), coord(a.y), coord(b.x), coord(b.y)], "st": stops(&s)})
|
||||
}
|
||||
Paint::Radial { center, radius, stops: s, spread, linear_rgb, focal, matrix: own } => {
|
||||
// The ring as canvas draws it: a circle round the centre (an ellipse drawn
|
||||
// with its mean radius), the focal point on its own x axis.
|
||||
let (copies, s) = spread_stops(s, *spread, *linear_rgb, true);
|
||||
let c = own.apply(*center);
|
||||
let r = radius.max(0.0) * own.mean_scale();
|
||||
let axis = own.apply_vector(anicraft_geom::Vec2::new(1.0, 0.0));
|
||||
let axis = if axis.length() > 1e-9 { axis * (1.0 / axis.length()) } else { anicraft_geom::Vec2::new(1.0, 0.0) };
|
||||
let f = c + axis * (focal.clamp(-anicraft_doc::MAX_FOCAL, anicraft_doc::MAX_FOCAL) * r);
|
||||
let big = r * (1 + 2 * copies) as f32;
|
||||
let mut o = json!({"r": [coord(c.x), coord(c.y), coord(big)], "st": stops(&s)});
|
||||
if *focal != 0.0 && focal.is_finite() {
|
||||
o["f"] = json!([coord(f.x), coord(f.y)]);
|
||||
}
|
||||
o
|
||||
}
|
||||
Paint::Bitmap { bitmap, repeat, matrix: m } => match self.doc.bitmap(*bitmap) {
|
||||
Some(b) => {
|
||||
let n = self.images.len();
|
||||
|
||||
@@ -218,7 +218,7 @@
|
||||
if (!p) return null;
|
||||
if (p.s) return css(AniCraft.applyEffect(fx, p.s));
|
||||
if (p.l || p.r) {
|
||||
const gr = p.l ? g.createLinearGradient(p.l[0], p.l[1], p.l[2], p.l[3]) : g.createRadialGradient(p.r[0], p.r[1], 0, p.r[0], p.r[1], p.r[2]);
|
||||
const gr = p.l ? g.createLinearGradient(p.l[0], p.l[1], p.l[2], p.l[3]) : g.createRadialGradient(p.f ? p.f[0] : p.r[0], p.f ? p.f[1] : p.r[1], 0, p.r[0], p.r[1], p.r[2]);
|
||||
for (const s of p.st) gr.addColorStop(s[0], css(AniCraft.applyEffect(fx, [s[1], s[2], s[3], s[4]])));
|
||||
return gr;
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ fn fixture() -> Document {
|
||||
name: String::new(),
|
||||
transform: Affine::translate(20.0, 300.0),
|
||||
color: ColorEffect::Tint { color: Rgba::hex(0xff00ff), amount: 0.25 },
|
||||
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 100.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(100.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xffffff) }, GradientStop { offset: 1.0, color: Rgba::hex(0x000000) }] }).with_stroke(Rgba::hex(0xffff00), 2.0)),
|
||||
kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 100.0, 40.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::hex(0xffffff) }, GradientStop { offset: 1.0, color: Rgba::hex(0x000000) }])).with_stroke(Rgba::hex(0xffff00), 2.0)),
|
||||
});
|
||||
let mut mask = Layer::new(LayerId(6), "mask");
|
||||
mask.kind = LayerKind::Mask;
|
||||
@@ -714,7 +714,7 @@ fn button_sounds_start_in_the_page_as_in_the_player() {
|
||||
#[test]
|
||||
fn hostile_documents_export_without_panicking() {
|
||||
let mut doc = Document::default();
|
||||
let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect::Advanced(ColorTransform { mul: [f32::NAN, 2.0, -1.0, f32::INFINITY], add: [f32::NAN, 0.0, 0.0, 0.0] }), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::Radial { center: Vec2::ZERO, radius: -5.0, stops: vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }] })) };
|
||||
let bad = Element { id: ElementId(5), name: "x".into(), transform: Affine { m: [f32::NAN, 0.0, 0.0, 1.0, f32::INFINITY, 0.0] }, color: ColorEffect::Advanced(ColorTransform { mul: [f32::NAN, 2.0, -1.0, f32::INFINITY], add: [f32::NAN, 0.0, 0.0, 0.0] }), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, f32::NAN, 1.0), Paint::radial(Vec2::ZERO, -5.0, vec![GradientStop { offset: f32::NAN, color: Rgba::BLACK }]))) };
|
||||
let fine = Element { id: ElementId(6), transform: Affine::IDENTITY, ..bad.clone() };
|
||||
let missing = inst(7, 12345, "ghost", Affine::IDENTITY, vec![]);
|
||||
Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap().elements = vec![Arc::new(bad), Arc::new(fine), missing];
|
||||
@@ -1095,7 +1095,7 @@ fn filter_cases() -> Vec<Vec<anicraft_doc::Filter>> {
|
||||
/// small stage, with `filters`.
|
||||
fn filtered_doc(filters: &[anicraft_doc::Filter]) -> Document {
|
||||
let mut d = Document { stage: anicraft_doc::Stage { width: 64, height: 56, fps: 24.0, background: Rgba::WHITE }, ..Document::default() };
|
||||
let grad = Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(24.0, 18.0), stops: vec![stop(0.0, 0xff3300, 1.0), stop(1.0, 0x3366ff, 0.6)] };
|
||||
let grad = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(24.0, 18.0), vec![stop(0.0, 0xff3300, 1.0), stop(1.0, 0x3366ff, 0.6)]);
|
||||
let mut a = Shape::filled(Path::ellipse(12.0, 10.0, 11.0, 8.5), grad);
|
||||
a.stroke = Some(anicraft_doc::Stroke::new(Rgba::hex(0x112233), 1.5));
|
||||
let b = Shape::filled(Path::rect(16.3, 4.6, 9.2, 13.7), Paint::Solid(Rgba::hex(0x22aa44).with_alpha(0.5)));
|
||||
@@ -1200,7 +1200,7 @@ fn soft_masked_doc(mode: anicraft_doc::MaskMode, inside: bool) -> Document {
|
||||
Filter::Glow { blur_x: 6.0, blur_y: 6.0, strength: 1.5, quality: 2, color: Rgba::hex(0xffcc00), inner: false, knockout: false },
|
||||
];
|
||||
let mut d = filtered_doc(&filters);
|
||||
let ramp = Paint::Linear { start: Vec2::new(10.0, 0.0), end: Vec2::new(54.0, 0.0), stops: vec![stop(0.0, 0xffffff, 1.0), stop(0.5, 0x808080, 0.5), stop(1.0, 0x000000, 0.2)] };
|
||||
let ramp = Paint::linear(Vec2::new(10.0, 0.0), Vec2::new(54.0, 0.0), vec![stop(0.0, 0xffffff, 1.0), stop(0.5, 0x808080, 0.5), stop(1.0, 0x000000, 0.2)]);
|
||||
let art = Arc::new(Element { id: ElementId(320), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(10.0, 4.0, 44.0, 48.0), ramp)) });
|
||||
let mut mask = Layer::new(LayerId(321), "mask");
|
||||
mask.kind = LayerKind::Mask;
|
||||
@@ -1371,3 +1371,47 @@ fn the_pages_filters_survive_broken_data() {
|
||||
let out = js_json(&mut js, "(function () { var b = new Float32Array([0.5, 0, 0, 0.5, 1, 1, 1, 1]); AniCraftFilters.apply(b, 2, 1, [null, 3, {k: 'sparkle'}, {k: 'adjust', m: [1]}, {k: 'blur', x: 'wide', y: NaN, q: -4}, {k: 'shadow'}, {k: 'bevel', st: 'x'}, {k: 'gglow', st: [[0.5]]}], NaN); AniCraftFilters.apply(b, 3, 1, [{k: 'blur', x: 2, y: 2, q: 1}], 1); AniCraftFilters.blendImage(new Uint8ClampedArray(4), new Uint8ClampedArray(8), NaN, 'invert'); return [Array.from(b).every(isFinite), AniCraftFilters.region(new Uint8ClampedArray(16), 2, 2, 5)]; })()");
|
||||
assert_eq!(out, json!([true, null]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_options_are_drawn_the_nearest_way_canvas_can() {
|
||||
// ADR 0074: canvas gradients only pad, so reflect and repeat lay the ramp end to end.
|
||||
let two = vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }];
|
||||
let (copies, st) = spread_stops(&two, anicraft_doc::Spread::Pad, false, false);
|
||||
assert_eq!((copies, st.len()), (0, 2));
|
||||
let (copies, st) = spread_stops(&two, anicraft_doc::Spread::Repeat, false, false);
|
||||
let n = 2 * copies + 1;
|
||||
assert!(copies > 0 && st.len() == 2 * n && st.len() <= 255);
|
||||
// A linear ramp is the middle copy, forwards.
|
||||
assert_eq!((st[2 * copies].offset, st[2 * copies].color), (copies as f32 / n as f32, Rgba::BLACK));
|
||||
let (_, st) = spread_stops(&two, anicraft_doc::Spread::Reflect, false, false);
|
||||
assert_eq!(st[2 * copies + 2].color, Rgba::WHITE, "the copy after it runs backwards");
|
||||
// A radial one has no inside of its centre: the ramp comes first, then its copies.
|
||||
let (_, out) = spread_stops(&two, anicraft_doc::Spread::Reflect, false, true);
|
||||
assert_eq!((out[0].offset, out[0].color, out[2].color), (0.0, Rgba::BLACK, Rgba::WHITE));
|
||||
// Linear RGB is sampled into stops: the midpoint is the linear-light grey (≈ 0.735).
|
||||
let (_, lin) = spread_stops(&two, anicraft_doc::Spread::Pad, true, false);
|
||||
let mid = lin.iter().find(|s| (s.offset - 0.5).abs() < 1e-6).expect("a stop at the middle");
|
||||
assert!((mid.color.r - 0.735).abs() < 0.01, "{:?}", mid.color);
|
||||
// Through the export: the radial's focal point and the reflected linear's longer span.
|
||||
let mut lin_p = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), two.clone());
|
||||
if let Paint::Linear { spread, .. } = &mut lin_p {
|
||||
*spread = anicraft_doc::Spread::Reflect;
|
||||
}
|
||||
let mut rad = Paint::radial(Vec2::new(50.0, 50.0), 20.0, two);
|
||||
if let Paint::Radial { focal, .. } = &mut rad {
|
||||
*focal = 0.5;
|
||||
}
|
||||
let mut doc = Document::default();
|
||||
let shape = |id: u64, p: Paint| Arc::new(Element { id: ElementId(id), name: String::new(), transform: Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::Shape(Shape::filled(Path::rect(0.0, 0.0, 100.0, 100.0), p)) });
|
||||
{
|
||||
let k = Arc::make_mut(&mut doc.timeline_mut(0).layers[0]).keyframe_mut(0).unwrap();
|
||||
k.elements = vec![shape(80, lin_p), shape(81, rad)];
|
||||
}
|
||||
let m = movie(&doc, &HtmlOptions::default());
|
||||
let paints = m.json["paints"].as_array().cloned().unwrap_or_default();
|
||||
let l = paints.iter().find(|p| p.get("l").is_some()).expect("the linear gradient");
|
||||
assert!(l["l"][0].as_f64().unwrap() < -9.0 && l["l"][2].as_f64().unwrap() > 19.0, "{l}");
|
||||
let r = paints.iter().find(|p| p.get("r").is_some()).expect("the radial gradient");
|
||||
assert_eq!(r["f"], json!([60, 50]));
|
||||
assert_eq!(r["r"][2], json!(20));
|
||||
}
|
||||
@@ -1023,7 +1023,7 @@ mod tests {
|
||||
fn an_alpha_gradient_mask_fades_linearly() {
|
||||
// Transparent at x = 0 to opaque at x = 40: pixel x reveals (x + 0.5) / 40.
|
||||
let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: Rgba::new(1.0, 1.0, 1.0, 0.0) }, anicraft_doc::GradientStop { offset: 1.0, color: Rgba::WHITE }];
|
||||
let grad = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(40.0, 0.0), stops });
|
||||
let grad = item(Path::rect(0.0, 0.0, 40.0, 40.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(40.0, 0.0), stops));
|
||||
let pm = soft(MaskMode::Alpha, vec![grad.clone()]);
|
||||
for x in [0u32, 10, 20, 30, 39] {
|
||||
let a = pm.pixel(x, 20).unwrap()[3];
|
||||
@@ -1101,7 +1101,7 @@ mod tests {
|
||||
assert!(near(pm.pixel(2, 2).unwrap(), want(c)), "{:?} vs {:?}", pm.pixel(2, 2), want(c));
|
||||
// A two-stop gradient of one colour is that colour, through the transform.
|
||||
let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: c }, anicraft_doc::GradientStop { offset: 1.0, color: c }];
|
||||
let mut grad = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(4.0, 0.0), stops });
|
||||
let mut grad = item(Path::rect(0.0, 0.0, 4.0, 4.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), stops));
|
||||
grad.color = fx;
|
||||
let (pm, _) = render(&list(vec![grad]), &view(4, 4)).unwrap();
|
||||
assert!(near(pm.pixel(1, 2).unwrap(), want(c)));
|
||||
|
||||
+30
-12
@@ -302,18 +302,36 @@ fn sample(item: &DisplayItem, opacity: f32, masks: Vec<Bez>, report: &mut HashSe
|
||||
} else {
|
||||
let fill = match &item.fill {
|
||||
Some(Paint::Solid(c)) => Some(Fill::Solid { color: fx.apply(*c), rule: item.fill_rule }),
|
||||
Some(Paint::Linear { start, end, stops }) => Some(Fill::Gradient { radial: false, start: m.apply(*start), end: m.apply(*end), stops: stops.iter().map(|s| (s.offset, fx.apply(s.color))).collect(), rule: item.fill_rule }),
|
||||
Some(Paint::Radial { center, radius, stops }) => {
|
||||
// Lottie's radial gradients are circles: a stretched or skewed one is drawn
|
||||
// with its mean radius.
|
||||
let (ux, uy) = (m.apply_vector(Vec2::new(1.0, 0.0)), m.apply_vector(Vec2::new(0.0, 1.0)));
|
||||
let (lx, ly) = (ux.length(), uy.length());
|
||||
if (lx - ly).abs() > 0.01 * lx.max(ly) || ux.dot(uy).abs() > 0.01 * lx * ly {
|
||||
report.insert("stretched radial gradients (drawn as circles)");
|
||||
Some(p @ (Paint::Linear { .. } | Paint::Radial { .. })) => {
|
||||
// What Lottie's gradients can't show is drawn the nearest way, and said.
|
||||
if let Paint::Linear { spread, linear_rgb, .. } | Paint::Radial { spread, linear_rgb, .. } = p {
|
||||
if !spread.is_pad() {
|
||||
report.insert("reflected or repeated gradients (padded)");
|
||||
}
|
||||
if *linear_rgb {
|
||||
report.insert("linear-RGB gradients (blended in sRGB)");
|
||||
}
|
||||
}
|
||||
let stops = p.stops().unwrap_or(&[]).iter().map(|s| (s.offset, fx.apply(s.color))).collect();
|
||||
match p {
|
||||
Paint::Linear { start, end, .. } => Some(Fill::Gradient { radial: false, start: m.apply(*start), end: m.apply(*end), stops, rule: item.fill_rule }),
|
||||
_ => {
|
||||
if matches!(p, Paint::Radial { focal, .. } if *focal != 0.0) {
|
||||
report.insert("radial gradient focal points (drawn centred)");
|
||||
}
|
||||
// Lottie's radial gradients are circles: a stretched or skewed one is
|
||||
// drawn with its mean radius.
|
||||
let f = m.mul(&p.frame(None).unwrap_or(Affine::IDENTITY));
|
||||
let (ux, uy) = (f.apply_vector(Vec2::new(1.0, 0.0)), f.apply_vector(Vec2::new(0.0, 1.0)));
|
||||
let (lx, ly) = (ux.length(), uy.length());
|
||||
if (lx - ly).abs() > 0.01 * lx.max(ly) || ux.dot(uy).abs() > 0.01 * lx * ly {
|
||||
report.insert("stretched radial gradients (drawn as circles)");
|
||||
}
|
||||
let r = f.mean_scale();
|
||||
let c = f.apply(Vec2::ZERO);
|
||||
Some(Fill::Gradient { radial: true, start: c, end: c + Vec2::new(r, 0.0), stops, rule: item.fill_rule })
|
||||
}
|
||||
}
|
||||
let r = radius * m.mean_scale();
|
||||
let c = m.apply(*center);
|
||||
Some(Fill::Gradient { radial: true, start: c, end: c + Vec2::new(r, 0.0), stops: stops.iter().map(|s| (s.offset, fx.apply(s.color))).collect(), rule: item.fill_rule })
|
||||
}
|
||||
Some(Paint::Bitmap { .. }) => {
|
||||
report.insert("bitmap fills (not exported yet)");
|
||||
@@ -703,7 +721,7 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
let mut d = Document { scenes: vec![Arc::new(Scene::new("Scene 1"))], ..Document::default() };
|
||||
let stops = vec![GradientStop { offset: 0.0, color: Rgba::WHITE }, GradientStop { offset: 1.0, color: Rgba::new(1.0, 1.0, 1.0, 0.0) }];
|
||||
let art = Shape::filled(Path::rect(0.0, 0.0, 200.0, 200.0), Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops });
|
||||
let art = Shape::filled(Path::rect(0.0, 0.0, 200.0, 200.0), Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(200.0, 0.0), stops));
|
||||
let square = Shape::filled(Path::rect(20.0, 20.0, 160.0, 160.0), Paint::Solid(Rgba::new(1.0, 0.0, 0.0, 1.0)));
|
||||
for (id, kind, parent, shape) in [(1, LayerKind::Mask, None, art), (2, LayerKind::Normal, Some(LayerId(1)), square)] {
|
||||
let mut l = Layer::new(LayerId(id), format!("L{id}"));
|
||||
|
||||
+142
-22
@@ -1,6 +1,6 @@
|
||||
//! Paint shaders: solid colours and gradients evaluated per pixel through a 256-entry LUT.
|
||||
|
||||
use anicraft_doc::{ColorTransform, GradientStop, Paint, Pixels, Rgba};
|
||||
use anicraft_doc::{ColorTransform, GradientStop, MAX_FOCAL, Paint, Pixels, Rgba, Spread};
|
||||
use std::sync::Arc;
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
|
||||
@@ -16,8 +16,11 @@ const LUT: usize = 256;
|
||||
|
||||
pub enum Shader {
|
||||
Solid(Premul),
|
||||
Linear { inv: Affine, start: Vec2, dir: Vec2, lut: Box<[Premul; LUT]> },
|
||||
Radial { inv: Affine, center: Vec2, inv_radius: f32, lut: Box<[Premul; LUT]> },
|
||||
Linear { inv: Affine, start: Vec2, dir: Vec2, spread: Spread, lut: Box<[Premul; LUT]> },
|
||||
/// `inv` maps pixels into the gradient's own space (its matrix undone), where the ring is
|
||||
/// the circle of radius `1 / inv_radius` round `center` and the focal point sits `focal`
|
||||
/// of the radius along x.
|
||||
Radial { inv: Affine, center: Vec2, inv_radius: f32, focal: f32, spread: Spread, lut: Box<[Premul; LUT]> },
|
||||
/// Samples of a bitmap: `inv` maps pixels back to the bitmap's own pixel grid. Bilinear
|
||||
/// when `smooth` (Allow Smoothing, ADR 0050), else the nearest pixel.
|
||||
Bitmap { inv: Affine, pixels: Arc<Pixels>, repeat: bool, fx: ColorTransform, smooth: bool },
|
||||
@@ -42,17 +45,54 @@ fn sample_stops(stops: &[GradientStop], t: f32) -> Rgba {
|
||||
stops.last().map_or(first.color, |s| s.color)
|
||||
}
|
||||
|
||||
fn build_lut(stops: &[GradientStop], fx: &ColorTransform) -> Box<[Premul; LUT]> {
|
||||
let mut sorted: Vec<GradientStop> = stops.iter().copied().filter(|s| s.offset.is_finite()).collect();
|
||||
/// sRGB-encoded channel → linear light (IEC 61966-2-1).
|
||||
fn to_linear(c: f32) -> f32 {
|
||||
if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
|
||||
}
|
||||
|
||||
/// Linear light → sRGB-encoded channel.
|
||||
fn from_linear(c: f32) -> f32 {
|
||||
let c = c.clamp(0.0, 1.0);
|
||||
if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 }
|
||||
}
|
||||
|
||||
/// The ramp's 256 colours. With `linear_rgb` the stops mix in linear light (Animate's Linear
|
||||
/// RGB, SVG's `color-interpolation: linearRGB`); the colours at the stops are the same.
|
||||
fn build_lut(stops: &[GradientStop], fx: &ColorTransform, linear_rgb: bool) -> Box<[Premul; LUT]> {
|
||||
let mut sorted: Vec<GradientStop> = stops.iter().copied().filter(|s| s.offset.is_finite()).map(|s| GradientStop { color: s.color.sanitized(), ..s }).collect();
|
||||
sorted.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
if linear_rgb {
|
||||
for s in &mut sorted {
|
||||
s.color = Rgba::new(to_linear(s.color.r), to_linear(s.color.g), to_linear(s.color.b), s.color.a);
|
||||
}
|
||||
}
|
||||
let mut lut = Box::new([[0.0; 4]; LUT]);
|
||||
for (i, slot) in lut.iter_mut().enumerate() {
|
||||
let t = i as f32 / (LUT - 1) as f32;
|
||||
*slot = premultiply(fx.apply(sample_stops(&sorted, t)));
|
||||
let mut c = sample_stops(&sorted, t);
|
||||
if linear_rgb {
|
||||
c = Rgba::new(from_linear(c.r), from_linear(c.g), from_linear(c.b), c.a);
|
||||
}
|
||||
*slot = premultiply(fx.apply(c));
|
||||
}
|
||||
lut
|
||||
}
|
||||
|
||||
/// Where on a focal radial ramp the point `u` falls (in the gradient's unit space: the ring is
|
||||
/// the unit circle, the focal point at `(focal, 0)`): the `t` with `u = f + t·(q − f)` for `q`
|
||||
/// on the ring. With `focal = 0` it is `|u|`. Solves `(1 − f²)t² − 2(f·d)t − d·d = 0`, `d = u − f`.
|
||||
#[inline]
|
||||
pub fn focal_t(u: Vec2, focal: f32) -> f32 {
|
||||
if focal == 0.0 {
|
||||
return u.length();
|
||||
}
|
||||
let (dx, dy) = (u.x - focal, u.y);
|
||||
let a = 1.0 - focal * focal;
|
||||
let fd = focal * dx;
|
||||
let dd = dx * dx + dy * dy;
|
||||
(fd + (fd * fd + a * dd).max(0.0).sqrt()) / a
|
||||
}
|
||||
|
||||
impl Shader {
|
||||
/// `to_pixel` maps the paint's local space to pixels.
|
||||
/// `image` holds a [`Paint::Bitmap`]'s pixels (an image that can't be read shows grey).
|
||||
@@ -60,19 +100,22 @@ impl Shader {
|
||||
let inv = to_pixel.inverse();
|
||||
match (paint, inv) {
|
||||
(Paint::Solid(c), _) => Shader::Solid(premultiply(fx.apply(*c))),
|
||||
(Paint::Linear { start, end, stops }, Some(inv)) => {
|
||||
(Paint::Linear { start, end, stops, spread, linear_rgb }, Some(inv)) => {
|
||||
let d = *end - *start;
|
||||
let len2 = d.dot(d);
|
||||
if len2 < 1e-12 {
|
||||
return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color))));
|
||||
}
|
||||
Shader::Linear { inv, start: *start, dir: d * (1.0 / len2), lut: build_lut(stops, fx) }
|
||||
Shader::Linear { inv, start: *start, dir: d * (1.0 / len2), spread: *spread, lut: build_lut(stops, fx, *linear_rgb) }
|
||||
}
|
||||
(Paint::Radial { center, radius, stops }, Some(inv)) => {
|
||||
if !(radius.is_finite() && *radius > 1e-6) {
|
||||
return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color))));
|
||||
}
|
||||
Shader::Radial { inv, center: *center, inv_radius: 1.0 / radius, lut: build_lut(stops, fx) }
|
||||
(Paint::Radial { center, radius, stops, spread, linear_rgb, focal, matrix }, Some(_)) => {
|
||||
// Pixels → shape space → the gradient's own space.
|
||||
let inv = match to_pixel.mul(matrix).inverse() {
|
||||
Some(i) if radius.is_finite() && *radius > 1e-6 => i,
|
||||
_ => return Shader::Solid(premultiply(fx.apply(stops.last().map_or(Rgba::TRANSPARENT, |s| s.color)))),
|
||||
};
|
||||
let focal = if focal.is_finite() { focal.clamp(-MAX_FOCAL, MAX_FOCAL) } else { 0.0 };
|
||||
Shader::Radial { inv, center: *center, inv_radius: 1.0 / radius, focal, spread: *spread, lut: build_lut(stops, fx, *linear_rgb) }
|
||||
}
|
||||
(Paint::Bitmap { repeat, matrix, .. }, Some(inv)) => match (image, matrix.inverse()) {
|
||||
// Pixel → shape space → image pixels.
|
||||
@@ -105,14 +148,14 @@ impl Shader {
|
||||
#[inline]
|
||||
pub fn at(&self, x: i32, y: i32) -> Premul {
|
||||
let p = Vec2::new(x as f32 + 0.5, y as f32 + 0.5);
|
||||
let lookup = |lut: &[Premul; LUT], t: f32| {
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let lookup = |lut: &[Premul; LUT], spread: Spread, t: f32| {
|
||||
let t = spread.apply(t);
|
||||
lut[(t * (LUT - 1) as f32 + 0.5) as usize & (LUT - 1)]
|
||||
};
|
||||
match self {
|
||||
Shader::Solid(c) => *c,
|
||||
Shader::Linear { inv, start, dir, lut } => lookup(lut, (inv.apply(p) - *start).dot(*dir)),
|
||||
Shader::Radial { inv, center, inv_radius, lut } => lookup(lut, (inv.apply(p) - *center).length() * inv_radius),
|
||||
Shader::Linear { inv, start, dir, spread, lut } => lookup(lut, *spread, (inv.apply(p) - *start).dot(*dir)),
|
||||
Shader::Radial { inv, center, inv_radius, focal, spread, lut } => lookup(lut, *spread, focal_t((inv.apply(p) - *center) * *inv_radius, *focal)),
|
||||
Shader::Bitmap { inv, pixels, repeat, fx, smooth } => sample(pixels, inv.apply(p), *repeat, *smooth, fx),
|
||||
Shader::Image { data, x0, y0, w } => {
|
||||
let (dx, dy) = (x - x0, y - y0);
|
||||
@@ -168,11 +211,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn linear_gradient_endpoints() {
|
||||
let paint = Paint::Linear {
|
||||
start: Vec2::new(0.0, 0.0),
|
||||
end: Vec2::new(100.0, 0.0),
|
||||
stops: vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }],
|
||||
};
|
||||
let paint = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }]);
|
||||
let s = Shader::new(&paint, &Affine::IDENTITY, &ColorTransform::default(), None);
|
||||
assert!(s.at(0, 0)[0] < 0.02);
|
||||
assert!(s.at(99, 0)[0] > 0.98);
|
||||
@@ -182,6 +221,87 @@ mod tests {
|
||||
assert!((s2.at(99, 0)[0] - 0.5).abs() < 0.02);
|
||||
}
|
||||
|
||||
fn bw() -> Vec<GradientStop> {
|
||||
vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }]
|
||||
}
|
||||
|
||||
fn shade(p: &Paint, x: i32, y: i32) -> f32 {
|
||||
Shader::new(p, &Affine::IDENTITY, &ColorTransform::default(), None).at(x, y)[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_reflects_and_repeats_past_the_ends() {
|
||||
// A ramp over x = 0..100 (pixel centres at x + 0.5).
|
||||
let mut p = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0), bw());
|
||||
let set = |p: &mut Paint, s: Spread| {
|
||||
if let Paint::Linear { spread, .. } = p {
|
||||
*spread = s;
|
||||
}
|
||||
};
|
||||
assert!(shade(&p, 149, 0) > 0.99, "pad keeps the end colour");
|
||||
assert!(shade(&p, -50, 0) < 0.01);
|
||||
set(&mut p, Spread::Reflect);
|
||||
assert!((shade(&p, 149, 0) - 0.505).abs() < 0.01, "reflect: halfway back at 1.5");
|
||||
assert!((shade(&p, -51, 0) - 0.505).abs() < 0.01, "and mirrored before the start");
|
||||
assert!(shade(&p, 199, 0) < 0.01, "back at the start colour at 2");
|
||||
set(&mut p, Spread::Repeat);
|
||||
assert!((shade(&p, 149, 0) - 0.495).abs() < 0.01, "repeat: starts again");
|
||||
assert!((shade(&p, 125, 0) - 0.255).abs() < 0.01);
|
||||
assert!((shade(&p, -75, 0) - 0.255).abs() < 0.01, "and before the start");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focal_point_moves_where_the_ramp_starts() {
|
||||
// Analytic: in unit space with the focal point at (f, 0), t = 0 there, 1 on the ring,
|
||||
// and on the axis between them t grows linearly from the focal point.
|
||||
for f in [0.0, 0.5, -0.7] {
|
||||
assert!(focal_t(Vec2::new(f, 0.0), f).abs() < 1e-6);
|
||||
for a in [0.0f32, 1.0, 2.0, 3.0, 4.5] {
|
||||
assert!((focal_t(Vec2::new(a.cos(), a.sin()), f) - 1.0).abs() < 1e-5, "ring at {a} with focal {f}");
|
||||
}
|
||||
// Towards +x the ring is 1 − f away: halfway is t = 0.5.
|
||||
assert!((focal_t(Vec2::new(f + (1.0 - f) * 0.5, 0.0), f) - 0.5).abs() < 1e-5);
|
||||
}
|
||||
// Rendered: radius 100 round (100, 100), focal point at 0.5 → (150, 100) is black.
|
||||
let mut p = Paint::radial(Vec2::new(100.0, 100.0), 100.0, bw());
|
||||
if let Paint::Radial { focal, .. } = &mut p {
|
||||
*focal = 0.5;
|
||||
}
|
||||
let at = |x: f32, y: f32| shade(&p, (x - 0.5) as i32, (y - 0.5) as i32);
|
||||
assert!(at(150.5, 100.5) < 0.02);
|
||||
assert!((at(175.5, 100.5) - 0.5).abs() < 0.02, "halfway from the focal point to the ring on its side");
|
||||
assert!((at(75.5, 100.5) - 0.5).abs() < 0.02, "and on the far side (75 of 150)");
|
||||
assert!(at(100.5, 100.5) > 0.3, "the centre is no longer the start");
|
||||
// Out of range values are held inside the ring.
|
||||
if let Paint::Radial { focal, .. } = &mut p {
|
||||
*focal = 5.0;
|
||||
}
|
||||
assert!(Shader::new(&p, &Affine::IDENTITY, &ColorTransform::default(), None).at(10, 10)[0].is_finite());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn elliptical_radial_gradients_follow_their_matrix() {
|
||||
// Twice as wide as tall: the ring reaches x = ±100 but y = ±50.
|
||||
let p = Paint::radial(Vec2::ZERO, 1.0, bw()).with_frame(&Affine { m: [100.0, 0.0, 0.0, 50.0, 200.0, 200.0] }, None);
|
||||
let at = |x: i32, y: i32| shade(&p, x, y);
|
||||
assert!((at(249, 199) - 0.5).abs() < 0.02, "half way along x");
|
||||
assert!((at(199, 224) - 0.5).abs() < 0.02, "half way along y is half as far");
|
||||
assert!(at(199, 260) > 0.99);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_rgb_mixes_in_linear_light() {
|
||||
// Black to white: the sRGB midpoint is 0.5; mixed in linear light, the half-intensity
|
||||
// grey encodes as ≈ 0.735.
|
||||
let mut p = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(255.0, 0.0), bw());
|
||||
assert!((shade(&p, 127, 0) - 0.5).abs() < 0.01);
|
||||
if let Paint::Linear { linear_rgb, .. } = &mut p {
|
||||
*linear_rgb = true;
|
||||
}
|
||||
assert!((shade(&p, 127, 0) - 0.735).abs() < 0.01, "{}", shade(&p, 127, 0));
|
||||
assert!(shade(&p, -5, 0) < 1e-3 && shade(&p, 300, 0) > 0.999, "the stops keep their colours");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_without_smoothing_keep_hard_pixel_edges() {
|
||||
// A 2×1 image, black then white, drawn 10× larger: smoothed, the middle is a ramp;
|
||||
|
||||
@@ -461,14 +461,37 @@ fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorTransform, defs: &mut String
|
||||
sorted.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
let id = format!("g{n}");
|
||||
*n += 1;
|
||||
let m = xf.m;
|
||||
let gt = format!(" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"matrix({} {} {} {} {} {})\"", num(m[0]), num(m[1]), num(m[2]), num(m[3]), num(m[4]), num(m[5]));
|
||||
// A radial gradient's own matrix (an ellipse) goes into the gradient transform; its focal
|
||||
// point lies on its own x axis (ADR 0074).
|
||||
let own = match paint {
|
||||
Paint::Radial { matrix, .. } => xf.mul(matrix),
|
||||
_ => *xf,
|
||||
};
|
||||
let m = own.m;
|
||||
let mut gt = format!(" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"matrix({} {} {} {} {} {})\"", num(m[0]), num(m[1]), num(m[2]), num(m[3]), num(m[4]), num(m[5]));
|
||||
let (spread, linear_rgb) = match paint {
|
||||
Paint::Linear { spread, linear_rgb, .. } | Paint::Radial { spread, linear_rgb, .. } => (*spread, *linear_rgb),
|
||||
_ => (anicraft_doc::Spread::Pad, false),
|
||||
};
|
||||
match spread {
|
||||
anicraft_doc::Spread::Pad => {}
|
||||
anicraft_doc::Spread::Reflect => gt.push_str(" spreadMethod=\"reflect\""),
|
||||
anicraft_doc::Spread::Repeat => gt.push_str(" spreadMethod=\"repeat\""),
|
||||
}
|
||||
if linear_rgb {
|
||||
gt.push_str(" color-interpolation=\"linearRGB\"");
|
||||
}
|
||||
match paint {
|
||||
Paint::Linear { start, end, .. } => {
|
||||
let _ = write!(defs, "<linearGradient id=\"{id}\"{gt} x1=\"{}\" y1=\"{}\" x2=\"{}\" y2=\"{}\">", num(start.x), num(start.y), num(end.x), num(end.y));
|
||||
}
|
||||
Paint::Radial { center, radius, .. } => {
|
||||
let _ = write!(defs, "<radialGradient id=\"{id}\"{gt} cx=\"{}\" cy=\"{}\" r=\"{}\">", num(center.x), num(center.y), num(radius.max(0.0)));
|
||||
Paint::Radial { center, radius, focal, .. } => {
|
||||
let r = radius.max(0.0);
|
||||
let _ = write!(defs, "<radialGradient id=\"{id}\"{gt} cx=\"{}\" cy=\"{}\" r=\"{}\"", num(center.x), num(center.y), num(r));
|
||||
if *focal != 0.0 && focal.is_finite() {
|
||||
let _ = write!(defs, " fx=\"{}\" fy=\"{}\"", num(center.x + focal.clamp(-anicraft_doc::MAX_FOCAL, anicraft_doc::MAX_FOCAL) * r), num(center.y));
|
||||
}
|
||||
defs.push('>');
|
||||
}
|
||||
Paint::Solid(_) | Paint::Bitmap { .. } => return None,
|
||||
}
|
||||
@@ -515,6 +538,28 @@ mod tests {
|
||||
Stage { width: 100, height: 50, fps: 24.0, background: Rgba::WHITE }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_options_are_written_exactly() {
|
||||
// ADR 0074: spread, linear RGB, the focal point and the ellipse's matrix.
|
||||
let two = vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE }];
|
||||
let mut rad = Paint::radial(Vec2::ZERO, 1.0, two.clone()).with_frame(&Affine { m: [20.0, 0.0, 0.0, 10.0, 30.0, 30.0] }, None);
|
||||
if let Paint::Radial { focal, spread, linear_rgb, .. } = &mut rad {
|
||||
*focal = 0.5;
|
||||
*spread = anicraft_doc::Spread::Repeat;
|
||||
*linear_rgb = true;
|
||||
}
|
||||
let mut lin = Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), two);
|
||||
if let Paint::Linear { spread, .. } = &mut lin {
|
||||
*spread = anicraft_doc::Spread::Reflect;
|
||||
}
|
||||
let items = vec![item(Path::rect(0.0, 0.0, 60.0, 60.0), Some(rad)), item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(lin))];
|
||||
let svg = to_svg(&DisplayList { clip_modes: Vec::new(), items, clip_parents: vec![], groups: Vec::new() }, &stage());
|
||||
assert!(svg.contains("spreadMethod=\"repeat\"") && svg.contains("spreadMethod=\"reflect\""), "{svg}");
|
||||
assert!(svg.contains("color-interpolation=\"linearRGB\""), "{svg}");
|
||||
assert!(svg.contains("fx=\"40\" fy=\"30\""), "focal point half way along the ring's x axis: {svg}");
|
||||
assert!(svg.contains("matrix(1 0 0 0.5 0 15)"), "the ellipse in the gradient transform: {svg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitmaps_take_colour_effects_as_a_colour_matrix() {
|
||||
// ADR 0056: alpha alone is fill-opacity; anything more is an feColorMatrix on the image.
|
||||
@@ -582,7 +627,7 @@ mod tests {
|
||||
#[test]
|
||||
fn gradients_keep_local_geometry_and_masks_become_clip_paths() {
|
||||
let stops = vec![GradientStop { offset: 0.0, color: Rgba::BLACK }, GradientStop { offset: 1.0, color: Rgba::WHITE.with_alpha(0.25) }];
|
||||
let mut g = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(10.0, 0.0), stops }));
|
||||
let mut g = item(Path::rect(0.0, 0.0, 10.0, 10.0), Some(Paint::linear(Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), stops)));
|
||||
g.transform = Affine::translate(20.0, 0.0);
|
||||
g.clip = Some(1);
|
||||
let mut outer = item(Path::rect(0.0, 0.0, 50.0, 50.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
@@ -638,7 +683,7 @@ mod tests {
|
||||
// A broken transform, an empty gradient, an invisible fill and a malformed clip link.
|
||||
let mut bad = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
bad.transform = Affine::scale(f32::NAN, 1.0);
|
||||
let empty = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Radial { center: Vec2::new(0.0, 0.0), radius: f32::INFINITY, stops: vec![] }));
|
||||
let empty = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::radial(Vec2::new(0.0, 0.0), f32::INFINITY, vec![])));
|
||||
let clear = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::TRANSPARENT)));
|
||||
let mut lost = item(Path::rect(0.0, 0.0, 1.0, 1.0), Some(Paint::Solid(Rgba::BLACK)));
|
||||
lost.clip = Some(7);
|
||||
|
||||
+14
-13
@@ -26,7 +26,7 @@
|
||||
//! skewed gradient transforms (approximated).
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
use anicraft_doc::{Cap, Dash, ElementKind, GradientStop, Join, Paint, Rgba, Shape, Stroke, StrokeStyle};
|
||||
use anicraft_doc::{Cap, Dash, ElementKind, GradientStop, Join, Paint, Rgba, Shape, Spread, Stroke, StrokeStyle, MAX_FOCAL};
|
||||
use anicraft_geom::svg::parse_path_data;
|
||||
use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2};
|
||||
use anicraft_text::{FaceMatch, Fonts};
|
||||
@@ -1008,11 +1008,9 @@ impl<'a> Builder<'a> {
|
||||
None => if user { default * reference } else { default },
|
||||
}
|
||||
};
|
||||
if matches!(attr("spreadMethod"), Some("reflect" | "repeat")) {
|
||||
self.report.skip("reflected or repeated gradients (padded)");
|
||||
}
|
||||
let [a, b, c, d, _, _] = g.m;
|
||||
let similar = (a - d).abs() < 1e-3 * (a.abs() + d.abs() + 1e-6) && (b + c).abs() < 1e-3 * (b.abs() + c.abs() + 1e-6);
|
||||
// What shows past the ends and how the stops mix carry over (ADR 0074).
|
||||
let spread = attr("spreadMethod").and_then(|s| Spread::from_key(s.trim())).unwrap_or_default();
|
||||
let linear_rgb = attr("color-interpolation").is_some_and(|s| s.trim() == "linearRGB");
|
||||
let diag = ((vw * vw + vh * vh) / 2.0).sqrt();
|
||||
Some(match local(&first.name) {
|
||||
"linearGradient" => {
|
||||
@@ -1023,18 +1021,21 @@ impl<'a> Builder<'a> {
|
||||
if dir.dot(band).abs() > 1e-3 * dir.length() * band.length() {
|
||||
self.report.skip("stretched or skewed gradients (approximated)");
|
||||
}
|
||||
Paint::Linear { start: g.apply(p0), end: g.apply(p1), stops }
|
||||
Paint::Linear { start: g.apply(p0), end: g.apply(p1), stops, spread, linear_rgb }
|
||||
}
|
||||
_ => {
|
||||
if !similar {
|
||||
self.report.skip("stretched or skewed gradients (approximated)");
|
||||
}
|
||||
// Exact: the ring is carried by the gradient transform (any ellipse), turned so
|
||||
// its own x axis runs through the focal point.
|
||||
let (cx, cy) = (coord("cx", 0.5, vw), coord("cy", 0.5, vh));
|
||||
let (fx, fy) = (coord("fx", cx, vw), coord("fy", cy, vh));
|
||||
if (fx - cx).abs() > 1e-4 || (fy - cy).abs() > 1e-4 {
|
||||
self.report.skip("off-centre radial gradients (centred)");
|
||||
let r = coord("r", 0.5, diag);
|
||||
if !(r.is_finite() && r > 0.0) {
|
||||
return stops.last().map(|s| Paint::Solid(s.color));
|
||||
}
|
||||
Paint::Radial { center: g.apply(Vec2::new(cx, cy)), radius: coord("r", 0.5, diag) * g.mean_scale(), stops }
|
||||
let off = Vec2::new(fx - cx, fy - cy);
|
||||
let (focal, turn) = if off.length() > 1e-6 * r { ((off.length() / r).min(MAX_FOCAL), off.y.atan2(off.x)) } else { (0.0, 0.0) };
|
||||
let frame = g.mul(&Affine::translate(cx, cy)).mul(&Affine::rotate(turn)).mul(&Affine::scale(r, r));
|
||||
Paint::Radial { center: Vec2::ZERO, radius: 1.0, stops, spread, linear_rgb, focal, matrix: Affine::IDENTITY }.with_frame(&frame, None)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ fn gradients_in_both_unit_systems_with_inherited_stops() {
|
||||
</svg>"##);
|
||||
let i = Flat { shapes: i.shapes[1..].to_vec(), ..i };
|
||||
match &i.shapes[0].shape.fill {
|
||||
Some(Paint::Linear { start, end, stops }) => {
|
||||
Some(Paint::Linear { start, end, stops, .. }) => {
|
||||
assert_eq!((*start, *end), (Vec2::new(20.0, 10.0), Vec2::new(60.0, 10.0)), "bounding-box units map onto the shape");
|
||||
assert_eq!(stops.len(), 2);
|
||||
assert_eq!(stops[1].color, Rgba::WHITE.with_alpha(0.5));
|
||||
@@ -120,7 +120,7 @@ fn gradients_in_both_unit_systems_with_inherited_stops() {
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
match &i.shapes[1].shape.fill {
|
||||
Some(Paint::Radial { center, radius, stops }) => {
|
||||
Some(Paint::Radial { center, radius, stops, .. }) => {
|
||||
assert_eq!((*center, *radius), (Vec2::new(50.0, 50.0), 25.0));
|
||||
assert_eq!(stops[0].color.a, 0.5, "fill-opacity folds into the stops");
|
||||
}
|
||||
|
||||
+16
-23
@@ -23,7 +23,7 @@ use crate::edges::{self, Edge};
|
||||
use crate::xml::{self, Element as X};
|
||||
use anicraft_doc::{
|
||||
Cap, Dash, Join, StrokeStyle, Bitmap, BitmapId, BlendMode, ColorEffect, ColorTransform, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId,
|
||||
Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript,
|
||||
Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, FrameScript, FrameSound, Language, Linkage, ScaleGrid, SoundSync, SourceScript, Spread, MAX_FOCAL,
|
||||
};
|
||||
use anicraft_geom::{Affine, FillRule, Path, Vec2};
|
||||
use anicraft_text::{FaceMatch, Fonts};
|
||||
@@ -188,31 +188,24 @@ fn paint(def: &X, bitmaps: &HashMap<String, BitmapId>, report: &mut Report) -> O
|
||||
if stops.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// What AniCraft's gradients can't draw yet is drawn the nearest way, and said.
|
||||
if def.attr("spreadMethod").is_some_and(|s| s.trim() != "pad") {
|
||||
report.skip("repeating and reflecting gradients (drawn padded)");
|
||||
}
|
||||
if def.attr("interpolationMethod").is_some_and(|s| s.trim() == "linearRGB") {
|
||||
report.skip("linear-RGB gradients (blended in sRGB)");
|
||||
}
|
||||
if def.name == "RadialGradient" {
|
||||
if def.f32("focalPointRatio").is_some_and(|f| f != 0.0) {
|
||||
report.skip("radial gradient focal points (drawn centred)");
|
||||
// Overflow, interpolation and the focal point carry over as they are (ADR 0074).
|
||||
let spread = def.attr("spreadMethod").and_then(|s| Spread::from_key(s.trim())).unwrap_or_default();
|
||||
let linear_rgb = def.attr("interpolationMethod").is_some_and(|s| s.trim() == "linearRGB");
|
||||
let frame = m.mul(&Affine::scale(GRADIENT_HALF, GRADIENT_HALF));
|
||||
let mut p = if def.name == "LinearGradient" { Paint::linear(Vec2::new(-1.0, 0.0), Vec2::new(1.0, 0.0), stops) } else { Paint::radial(Vec2::ZERO, 1.0, stops) };
|
||||
match &mut p {
|
||||
Paint::Linear { spread: s, linear_rgb: l, .. } => {
|
||||
*s = spread;
|
||||
*l = linear_rgb;
|
||||
}
|
||||
let (x, y) = (m.apply_vector(Vec2::new(1.0, 0.0)), m.apply_vector(Vec2::new(0.0, 1.0)));
|
||||
let (lx, ly) = (x.length(), y.length());
|
||||
// Columns of different lengths, or not at right angles: an ellipse.
|
||||
if (lx - ly).abs() > 0.01 * lx.max(ly) || x.dot(y).abs() > 0.01 * lx * ly {
|
||||
report.skip("elliptical radial gradients (drawn round)");
|
||||
Paint::Radial { spread: s, linear_rgb: l, focal, .. } => {
|
||||
*s = spread;
|
||||
*l = linear_rgb;
|
||||
*focal = def.f32("focalPointRatio").filter(|f| f.is_finite()).unwrap_or(0.0).clamp(-MAX_FOCAL, MAX_FOCAL);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(if def.name == "LinearGradient" {
|
||||
Paint::Linear { start: m.apply(Vec2::new(-GRADIENT_HALF, 0.0)), end: m.apply(Vec2::new(GRADIENT_HALF, 0.0)), stops }
|
||||
} else {
|
||||
let c = m.apply(Vec2::ZERO);
|
||||
let r = (m.apply_vector(Vec2::new(GRADIENT_HALF, 0.0)).length() + m.apply_vector(Vec2::new(0.0, GRADIENT_HALF)).length()) * 0.5;
|
||||
Paint::Radial { center: c, radius: r, stops }
|
||||
})
|
||||
Some(p.with_frame(&frame, None))
|
||||
}
|
||||
"BitmapFill" => {
|
||||
let Some(&bitmap) = def.attr("bitmapPath").and_then(|n| bitmaps.get(n)) else {
|
||||
|
||||
@@ -57,16 +57,7 @@ const REPORTS: &[(&str, &[(&str, usize)])] = &[
|
||||
("bitmaps", &[("instances of missing bitmaps", 1), ("missing bitmap files", 1)]),
|
||||
("colour", &[]),
|
||||
("filters", &[("unknown filters", 1)]),
|
||||
(
|
||||
"gradients",
|
||||
&[
|
||||
("elliptical radial gradients (drawn round)", 1),
|
||||
("gradient and bitmap strokes (drawn in one colour)", 1),
|
||||
("linear-RGB gradients (blended in sRGB)", 1),
|
||||
("radial gradient focal points (drawn centred)", 1),
|
||||
("repeating and reflecting gradients (drawn padded)", 2),
|
||||
],
|
||||
),
|
||||
("gradients", &[("gradient and bitmap strokes (drawn in one colour)", 1)]),
|
||||
("guides", &[]),
|
||||
("interactive", &[]),
|
||||
("masks", &[]),
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,120 @@
|
||||
# ADR 0074: Gradient editor, the Gradient Transform tool and Lock Fill
|
||||
|
||||
* Status: accepted (2026-11-12)
|
||||
* Relates to: ADR 0002 (render pipeline), ADR 0019 / 0029 (GPU stage), ADR 0034 (Eyedropper),
|
||||
ADR 0040 (interface languages), ADR 0064 (accessibility), user issues #208 and #203, roadmap M1
|
||||
|
||||
## Context
|
||||
|
||||
The renderer, the file format, the importers and exporters and the Eyedropper already handled
|
||||
linear and radial gradients and bitmap fills, but an artist couldn't make or change one: there
|
||||
was no gradient editor and no way to move, turn or stretch where a fill lies. Animate's
|
||||
everyday workflow is the Color panel's fill type and colour stops, the Gradient Transform tool
|
||||
(**F**) and Lock Fill on the Paint Bucket and Brush. Animate's gradients also carry what our
|
||||
model lacked: overflow (Extend, Reflect, Repeat), Linear RGB, a focal point and elliptical,
|
||||
turned radial gradients. XFL import reported all four as approximations.
|
||||
|
||||
## Decision
|
||||
|
||||
### Model (`crates/doc`)
|
||||
|
||||
1. **Options on the existing variants, not a new paint type.** `Paint::Linear` gains `spread`
|
||||
and `linear_rgb`; `Paint::Radial` gains those plus `focal` (Animate's focal point ratio, along
|
||||
the gradient's own x axis, held to ±0.98 of the radius) and `matrix` (gradient space → shape
|
||||
space, so any ellipse at any angle). Each is `#[serde(default)]` and skipped when unset, so
|
||||
older files open unchanged and plain gradients are written byte-for-byte as before.
|
||||
2. **A radial gradient is stored as a circle when it is one**, else as a circle with a matrix
|
||||
about its centre (`Paint::with_frame` canonicalises). `Paint::transformed` composes the
|
||||
matrix, so a radial fill is now exact under any transform (it used the mean scale before).
|
||||
A linear gradient keeps `start`/`end`: its handles only move, turn and stretch it along its
|
||||
axis, as Animate's do.
|
||||
3. **Fill frames.** `Paint::frame` maps the box −1..1 onto a fill (a linear ramp's span, a radial
|
||||
ring, one copy of a bitmap; Animate's gradient square), and `with_frame` sets it. The tool,
|
||||
the command and fitting all work on frames, one representation for three kinds of fill.
|
||||
4. **`Spread::apply`** is the one definition of pad, reflect and repeat; the GPU shader, its
|
||||
emulator and the HTML exporter follow it.
|
||||
|
||||
### Rendering and interchange
|
||||
|
||||
5. **CPU oracle**: spread on the ramp position; the focal point by solving
|
||||
`(1 − f²)t² − 2(f·d)t − d·d = 0` in the ring's unit space (the cone of SVG's and canvas's
|
||||
two-circle gradient with the inner circle at the focal point, radius 0); Linear RGB by mixing
|
||||
the stops in linear light when the 256-entry table is built (so the GPU gets it for free).
|
||||
Analytic tests cover each.
|
||||
6. **GPU stage**: a gradient's paint record had a free vec4 (its colour slot); it now holds the
|
||||
spread code and the focal ratio, and `fine.wgsl` evaluates both. The radial `inv` already
|
||||
included the matrix. Parity scene: reflect + linear RGB, repeat, a repeating focal gradient
|
||||
on a turned ellipse.
|
||||
7. **SVG export** writes `spreadMethod`, `color-interpolation="linearRGB"`, `fx`/`fy` and the
|
||||
matrix in `gradientTransform`: exact. **HTML canvas** has only padded gradients, so reflect
|
||||
and repeat are drawn as the ramp laid end to end (bounded copies), Linear RGB as sampled
|
||||
stops, the focal point with the two-circle gradient; an ellipse uses its mean radius.
|
||||
**Lottie** reports spread, Linear RGB and focal points (it has none of them).
|
||||
8. **Import**: XFL's `spreadMethod`, `interpolationMethod`, `focalPointRatio` and elliptical
|
||||
matrices and SVG's `spreadMethod`, `color-interpolation`, `fx`/`fy` and skewed radial
|
||||
transforms come in exactly. The XFL corpus's gradients golden was regenerated: it now shows
|
||||
what the file asks for.
|
||||
|
||||
### Commands (`crates/engine/src/cmds_paint.rs`)
|
||||
|
||||
9. **`paint.set_fill`** sets the fill swatch and, by default, the selected shapes' fills in one
|
||||
step: `type`, `color`, `stops` (2 to 15, `#rrggbbaa` for opacity), `spread`, `linear_rgb`,
|
||||
`focal`, `bitmap`. A shape keeping its kind of fill keeps where it lies (editing stops never
|
||||
moves a gradient); a shape changing kind gets the new fill fitted to its bounds. A new
|
||||
gradient keeps the colours of the gradient it replaces, else starts white to black
|
||||
(Animate's default).
|
||||
10. **`paint.transform_fill`** sets a fill's frame (absolute, `frame`) or changes it (scale, skew,
|
||||
rotate about its centre, move, centre, focal), in the space being edited. The tool sends
|
||||
absolute frames worked out from the frame at the press, so a drag inside one gesture is one
|
||||
undo step and never drifts. Flattening a fill to nothing is refused.
|
||||
11. **Lock Fill** is tool state (`ToolStyle::lock_fill`, `paint.lock_fill`). Off (the default, as
|
||||
in Animate): the Paint Bucket, the Brush and the shape tools fit a gradient or bitmap to
|
||||
each shape (`Paint::fitted`: linear across the width, radial centred touching the longer
|
||||
side, bitmap tiled from the top-left). On: the swatch's stage-space fill is carried into each
|
||||
shape, so one ramp runs across many. **The Eyedropper turns Lock Fill on** when it picks a
|
||||
gradient or bitmap, which keeps ADR 0034's behaviour (a picked gradient stays where it was)
|
||||
and is what Animate does.
|
||||
12. The new commands are in the `paint` namespace, which plug-ins may already call; the
|
||||
`panic_hunt_every_command` fuzz covers them.
|
||||
|
||||
### Shell
|
||||
|
||||
13. **One colour picker, as Animate has one Color panel.** The colour picker (`src/colour.rs`:
|
||||
web-safe swatches, the mixer, hex, alpha) is where colours are chosen everywhere. A *fill's*
|
||||
picker (`src/colour_panel.rs`), opened from the Tools panel's Fill square or any Fill swatch
|
||||
in Properties (the selection's, or a tool's swatch), adds the fill's type on top, as
|
||||
Animate's Color Type menu: **None, Solid, Linear, Radial, Bitmap**. Solid shows the colour
|
||||
picker as it is; a gradient shows its stop bar, overflow, Linear RGB and focal point above
|
||||
the same colour picker, which then edits the picked stop's colour and opacity; a bitmap
|
||||
shows its Library image. The fill's No Colour is its type None; the Stroke square's picker
|
||||
keeps No Colour (strokes have no type). A gradient's swatch in Properties shows its ramp.
|
||||
The popup reports what was asked (`FillEdit`) and its caller applies it: solid colours and
|
||||
None exactly as each place did before (the Tools square recolours the selection with
|
||||
`element.set_fill`, a tool's swatch sets the tool style), everything else as
|
||||
`paint.set_fill` (from a tool's options with `selection: false`). An earlier draft of this
|
||||
PR had a separate Colour section in Properties; two places to choose a fill colour is what
|
||||
this decision avoids.
|
||||
14. **The stop bar** is keyboard-operable (ADR 0064): the bar is a button that adds a stop in the
|
||||
widest gap; each stop is a focusable, named control; arrow keys move it (Shift: 10 %),
|
||||
Delete removes it; dragging a stop off the bar removes it, as in Animate.
|
||||
15. **The Gradient Transform tool (F)** draws Animate's handles on the fill's frame: linear (edges,
|
||||
centre, width square, rotate knob), radial (ring, centre, focal triangle, width square, size
|
||||
circle, rotate knob) and bitmap (tile box, centre, width and height squares, skew diamonds,
|
||||
size circle, rotate knob). The plain selection box is hidden while it shows. In Animate it
|
||||
shares a flyout with Free Transform; AniCraft has no flyouts yet, so it has its own button.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Gradients round-trip exactly through `.anicraft`, SVG and XFL; files without the new options
|
||||
are unchanged. Radial fills on skewed shapes are now drawn exactly.
|
||||
* Scripts can build and place any gradient headless (`paint.set_fill`, `paint.transform_fill`).
|
||||
* The colour picker popups are named dialogs for screen readers, and the swatch grid is a named
|
||||
control (the accessibility audit now covers the solid and gradient pickers).
|
||||
|
||||
## Not in this slice
|
||||
|
||||
* Gradient and bitmap **strokes** (strokes have one colour).
|
||||
* Saved gradient swatches; the Brush's Lock Fill only for its fill colour mode.
|
||||
* Overflow on HTML canvas beyond the bounded copies; elliptical radial gradients in Lottie and
|
||||
canvas (mean radius).
|
||||
* Skewing a linear gradient's bands (its frame keeps only its axis).
|
||||
@@ -28,7 +28,7 @@ Animator and Designer, plus your own saved workspaces and Reset.
|
||||
| Output | The Output panel inside Test Movie, and **Window › Output**, which keeps the last run's lines. |
|
||||
| Align | The Align panel on the right, and **Modify › Align**. |
|
||||
| History | The History panel on the right. |
|
||||
| Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. |
|
||||
| Color and Swatches | **Window › Colour** (stroke and fill, Swap, Black and White). Click the Fill or Stroke squares in the Tools panel, the Colour panel, or any colour swatch in Properties: web-safe swatches, a mixer and a hex field. The fill's picker also sets its type (None, Solid, Linear, Radial, Bitmap) and a gradient's stops, overflow and Linear RGB, like the Color panel (no saved swatches yet). |
|
||||
| Transform and Info | Position, scale and rotation rows in Properties, and the Free Transform tool. |
|
||||
| Scene | The scene menu at the top left of the stage, **Insert › Scene** and **Modify › Scene**. |
|
||||
| Find and Replace | **Edit › Find and Replace** (**Ctrl+F**). |
|
||||
@@ -46,6 +46,7 @@ Each tool has the key you already know.
|
||||
| Selection | **V** | Selects raw strokes and fills with the dot pattern; drag an edge to bend it. |
|
||||
| Subselection | **A** | Points and handles, on raw drawings and drawing objects. |
|
||||
| Free Transform | **Q** | Scale, rotate and move; Shift and Alt as you'd expect. |
|
||||
| Gradient Transform | **F** | Its own button (no flyouts yet). Gradient and bitmap fills, with Lock Fill. |
|
||||
| Width | **U** | Variable-width strokes, with profiles in Properties. |
|
||||
| Bone | **M** | Joins symbol instances into an armature, or draws bones inside a shape. |
|
||||
| Bind | **Shift+M** | Chooses which points of a shape follow which bone. |
|
||||
@@ -66,7 +67,7 @@ Each tool has the key you already know.
|
||||
| Zoom | **Z** | |
|
||||
| Object Drawing | **J** | Toggles between merge drawing and drawing objects. |
|
||||
|
||||
Not in AniCraft yet: the Lasso, Polygon and Magic Wand tools, Gradient Transform, the 3D tools,
|
||||
Not in AniCraft yet: the Lasso, Polygon and Magic Wand tools, the 3D tools,
|
||||
Asset Warp, the Paint Brush and Fluid Brush, Deco and the Spray Brush. More on the tools in
|
||||
[Drawing](drawing.md).
|
||||
|
||||
|
||||
+50
-10
@@ -19,6 +19,7 @@ your hand.
|
||||
| Selection | **V** | Select, move and bend artwork |
|
||||
| Subselection | **A** | Edit points and curve handles |
|
||||
| Free Transform | **Q** | Scale, rotate and move |
|
||||
| Gradient Transform | **F** | Move, turn and stretch a gradient or bitmap fill |
|
||||
| Width | **U** | Vary a line's thickness along it |
|
||||
| Bone | **M** | Join symbol instances into a poseable armature |
|
||||
| Pen | **P** | Draw precise curves point by point |
|
||||
@@ -177,9 +178,11 @@ Click any colour swatch to open the colour picker. **Swatches**, the default, sh
|
||||
web-safe colours with greys and primaries beside them; a shade or highlight of a colour is
|
||||
usually one cell away. The colours you mix or type are kept in the row below for this session.
|
||||
**Mixer** sets any colour by hue, saturation and brightness (and alpha where the colour has
|
||||
one). The hex field shows the colour as `#rrggbb` and takes one you type. In the Tools panel's
|
||||
picker, **No colour** draws without a fill or a stroke, and with shapes selected, the colour
|
||||
you pick goes onto them too.
|
||||
one). The hex field shows the colour as `#rrggbb` and takes one you type. A fill's picker
|
||||
starts with the fill's type: **None** (no fill), **Solid**, **Linear**, **Radial** or
|
||||
**Bitmap** (see [Gradients and bitmap fills](#gradients-and-bitmap-fills)); the stroke's picker
|
||||
has **No colour** instead. In the Tools panel's picker, with shapes selected, the colour you
|
||||
pick goes onto them too.
|
||||
|
||||
To recolour existing artwork, select it and change **Fill** and **Stroke** in Properties.
|
||||
For transparency, use the colour effect's **Alpha** (see
|
||||
@@ -194,11 +197,48 @@ corner can get before it's bevelled.
|
||||
|
||||
### Gradients and bitmap fills
|
||||
|
||||
AniCraft draws linear and radial gradients and bitmap fills, and keeps them from Animate
|
||||
files and SVG drawings you import. There isn't a gradient editor for fills yet, so you can't
|
||||
make a new gradient from scratch in AniCraft. You can reuse one, though: pick it up with the
|
||||
Eyedropper and pour it with the Paint Bucket. A picked gradient stays where it was on the
|
||||
stage, so it carries on across every shape you pour it into.
|
||||
Choose **Linear**, **Radial** or **Bitmap** at the top of a fill's colour picker: the Tools
|
||||
panel's Fill square, or the **Fill** swatch in Properties. With a shape selected it changes
|
||||
that shape's fill; with a drawing tool in your hand, the Fill swatch in its options sets what
|
||||
new shapes, the Paint Bucket and the Brush pour. A gradient's swatch shows its ramp.
|
||||
|
||||
A gradient shows as a bar with its colour stops under it:
|
||||
|
||||
* **Click the bar** to add a stop there. **Drag a stop** to move it, or drag it down off the
|
||||
bar to remove it. A gradient has 2 to 15 stops.
|
||||
* Click a stop to pick it. Its **position** and **Remove** show under the bar, and the colour
|
||||
picker below them (Swatches, Mixer, the **hex** field and **alpha**) sets its colour and
|
||||
opacity. Type `#rrggbbaa` for a colour with opacity.
|
||||
* From the keyboard, **Tab** to a stop, move it with the **arrow keys** (**Shift** for bigger
|
||||
steps) and press **Delete** to remove it. The bar itself adds a stop in the widest gap.
|
||||
* **Overflow** sets what shows past the ends: **Extend** (the end colours carry on),
|
||||
**Reflect** (the ramp mirrors back and forth) or **Repeat**.
|
||||
* **Linear RGB** mixes the colours in linear light, for brighter, more even blends.
|
||||
* A radial gradient has a **Focal point**: where its ramp starts, from the centre.
|
||||
|
||||
Editing the stops never moves a gradient. A shape that gets a new kind of fill gets it fitted
|
||||
to its own bounds: a linear gradient runs across its width, a radial one is centred and
|
||||
touches its longer side, and a bitmap tiles from its top-left corner.
|
||||
|
||||
The **Gradient Transform** tool (**F**) changes where a gradient or bitmap fill lies. Click a
|
||||
shape with one to show its handles:
|
||||
|
||||
| Handle | Linear | Radial | Bitmap | What a drag does |
|
||||
|---|---|---|---|---|
|
||||
| Round dot in the middle | ✓ | ✓ | ✓ | Moves the fill |
|
||||
| Square | ✓ | ✓ | ✓ (left and bottom) | Changes its width (bitmap: width or height) |
|
||||
| Circle with a dot | | ✓ | ✓ (corner) | Changes its size |
|
||||
| Knob | ✓ | ✓ | ✓ | Turns it (**Shift**: 15° steps) |
|
||||
| Triangle | | ✓ | | Moves the focal point along its axis |
|
||||
| Diamonds | | | ✓ (top and right) | Skews it |
|
||||
|
||||
Each drag is one undo step. Gradients and bitmap fills from Animate files and SVG drawings
|
||||
keep their overflow, Linear RGB, focal point and shape.
|
||||
|
||||
**Lock Fill** (in the Paint Bucket's and the Brush's options) pours the fill where it lies on
|
||||
the stage instead of fitting it to each shape, so one gradient runs on across many shapes.
|
||||
When you pick up a gradient or bitmap with the Eyedropper, Lock Fill turns on, so it stays
|
||||
where it was.
|
||||
|
||||
### Paint Bucket, Ink Bottle and Eyedropper
|
||||
|
||||
@@ -339,8 +379,8 @@ on its symbol (see [Symbols and the Library](symbols-and-library.md#9-slice-scal
|
||||
|
||||
## Not there yet
|
||||
|
||||
Not in AniCraft yet: rulers, a grid and guides; Envelope and **Delete Envelope**; a gradient editor, the
|
||||
Gradient Transform tool and a Swatches panel (saved custom swatches); entering a drawing object
|
||||
Not in AniCraft yet: rulers, a grid and guides; Envelope and **Delete Envelope**; gradient and bitmap
|
||||
strokes, and a Swatches panel (saved custom colours and gradients); entering a drawing object
|
||||
with a double-click; PolyStar's Polygon option; the Paint Selection and Paint Inside
|
||||
brush modes, brush libraries and tilt; erasing inside symbols; and Animate's ragged, stipple
|
||||
and hatched line styles (drawn solid when you open an Animate file).
|
||||
@@ -91,7 +91,8 @@ exactly; the status bar names them after the export:
|
||||
* bitmaps and bitmap fills, and sound;
|
||||
* masks inside masks (the innermost is kept);
|
||||
* symbols fading as one (each shape fades on its own);
|
||||
* stretched round gradients (drawn as circles).
|
||||
* stretched round gradients (drawn as circles), gradient focal points (drawn centred),
|
||||
reflected or repeated gradients (drawn extended) and linear-RGB gradients.
|
||||
|
||||
### HTML canvas
|
||||
|
||||
|
||||
@@ -72,7 +72,8 @@ SVG files from illustration tools come in as artwork you can keep editing, not a
|
||||
limits and dashes.
|
||||
* Groups, reused parts (`use` and symbols), transforms and the drawing's view box.
|
||||
* Inline and attribute styles, and opacity.
|
||||
* Linear and radial gradients.
|
||||
* Linear and radial gradients, with their spread (reflect, repeat), linear-RGB blending, focal
|
||||
point and transform.
|
||||
* **Clip paths and masks.** A drawing with clipping comes in as a layer folder named after the
|
||||
file. Each clipped group sits on a masked layer under a mask layer that holds the clip's shape,
|
||||
so you can move or reshape the mask afterwards. Clips that cut nothing, like the frame clip
|
||||
@@ -89,7 +90,7 @@ SVG files from illustration tools come in as artwork you can keep editing, not a
|
||||
AniCraft lists these in the status bar after the import, instead of guessing:
|
||||
|
||||
* images embedded in the SVG, filters, style sheets (inline styles are read) and pattern fills;
|
||||
* gradient strokes (drawn in one colour), and repeated or reflected gradients (drawn padded).
|
||||
* gradient strokes (drawn in one colour).
|
||||
|
||||
### An SVG as a symbol
|
||||
|
||||
|
||||
@@ -83,8 +83,6 @@ each) and any fonts that are missing.
|
||||
|
||||
These come across, but look a little different from Animate, and the report counts them:
|
||||
|
||||
* repeating and reflecting gradients (drawn padded), radial gradient focal points (drawn
|
||||
centred), elliptical radial gradients (drawn round) and linear-RGB gradients;
|
||||
* gradient and bitmap strokes (drawn in one colour);
|
||||
* ragged, stipple and hatched strokes (drawn solid);
|
||||
* reverse loop modes (played forward) and extra spins on classic tweens (turned the shortest
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Command reference
|
||||
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 271 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
Everything you can do in AniCraft is a command: the menus, the shortcuts, the command palette (**Ctrl+K**, macOS **⌘K**), `anicraft-cli` and AI assistants over MCP all run the same 274 commands, listed here by menu. The id is what scripts and [working headless](../working-headless.md) use; the parameters are what a command takes as JSON. Commands that change the document are one undo step each. Your own shortcuts (**F1**) replace the defaults shown here; see the [shortcut reference](shortcuts.md).
|
||||
|
||||
This page is generated from the command registry, so it always matches the version of AniCraft it came with.
|
||||
|
||||
@@ -515,6 +515,12 @@ These commands have no menu item: the panels, the stage and the timeline use the
|
||||
Parameters: `{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings`
|
||||
- **Apply Style** `paint.apply_style` · changes the document
|
||||
Parameters: `{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)`
|
||||
- **Fill** `paint.set_fill` · changes the document
|
||||
Parameters: ``{type?: solid|linear|radial|bitmap (default: the swatch's), color? (solid), stops?: [{offset: 0..1, color: "#rrggbb" | "#rrggbbaa"}, ..] (2 to 15), spread?: extend|reflect|repeat, linear_rgb?: bool, focal?: -0.98..0.98 (radial), bitmap?: id, selection?: bool (default true)} sets the fill swatch (what new shapes, the Paint Bucket and the Brush pour) and, unless `selection` is false, the fills of the selected shapes. A shape keeping its kind of fill keeps where its gradient or bitmap lies; one changing kind gets it fitted to its bounds. A new gradient starts white to black → {fill: {type, ..}, changed}``
|
||||
- **Gradient Transform** `paint.transform_fill` · changes the document
|
||||
Parameters: `{element?: id (default: the selected shapes with a gradient or bitmap fill), frame?: [a, b, c, d, e, f] (the fill's frame in the space being edited: the box -1..1 onto a linear gradient's span, a radial gradient's ring or one copy of a bitmap), or changes made in this order: scale_x?, scale_y?, scale? (along the frame's own axes), skew_x?, skew_y? (degrees, along its axes), rotate? (degrees, about its centre), move?: [dx, dy], center?: [x, y]; focal?: -0.98..0.98 (radial)} moves, turns, scales or skews where a gradient or bitmap fill lies, as the Gradient Transform tool (F) does → {changed, frames: [[a, b, c, d, e, f], ..]}`
|
||||
- **Lock Fill** `paint.lock_fill`
|
||||
Parameters: `{on?: bool (default: toggle)} Lock Fill: a gradient or bitmap from the fill swatch is poured where it lies on the stage, running on across shapes; off, each shape gets it fitted to its bounds → {on}`
|
||||
- **New Text** `text.create` · changes the document
|
||||
Parameters: `{text (may be empty for an input field), type?: static|dynamic|input, x?, y? (top-left; default: centred), font?, size?, bold?, italic?, color?, align?, letter_spacing?, line_spacing?, width?}`
|
||||
- **Edit Text** `text.edit` · changes the document
|
||||
|
||||
@@ -21,6 +21,7 @@ This page is generated from the editor's shortcut map, so it always matches the
|
||||
| Selection | V | V |
|
||||
| Subselection | A | A |
|
||||
| Free Transform | Q | Q |
|
||||
| Gradient Transform | F | F |
|
||||
| Width | U | U |
|
||||
| Bone | M | M |
|
||||
| Bind | Shift+M | ⇧M |
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Dimension | Status |
|
||||
|---|---|
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`<mask>` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 ms, the 50k-shape 4K stage 75 → 37 ms (Direct3D 12 keeps CPU binning: slower therLine truncated
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients (with reflect/repeat, focal points, elliptical radials and linear RGB, ADR 0074), round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Soft masks** (ADR 0070): a mask layer's mask type is Shape (coverage), Alpha (its artwork's opacity as drawn: gradients, faded shapes, strokes, bitmaps) or Luminance (brightness × opacity, SVG's coefficients), in the CPU oracle (analytic tests), the GPU stage (parity: mean 0.00006, worst 1 step of 255), SVG export (`<mask>` with `mask-type`), Lottie (alpha and luma track mattes) and the HTML canvas; Layer Properties › Mask type. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). **Fourth slice** (ADR 0048): **tile binning on the GPU** for heavy frames without masks or groups (count, prefix sum, scatter and tile-list passes, no atomics, no readback; the CPU binning stays the reference and does the rest; one tile format for both: an integer backdrop per tile and steps on the tiles' left edges): on Vulkan, 10k shapes at 4K in one texture 21.7 → 4.7 ms, 50k shapes 122 → 22.5 msLine truncated
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, icon buttons and right-click menu) act on the whole selection; with no frame selection F5 extends every layer with frames at or after the playhead, and F5/F6/F7 move the playhead on as in Animate (F6/F7 on a keyframe key the next frame; `all_layers`/`advance` headless); drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), **timeline polish** (ADR 0061): a per-layer **onion skin toggle** column (Alt-click solos; left-out layers aren't onion-skinned; Edit Multiple Frames unaffected), the colour square toggles **View as Outlines** in the layer colour **on the stage only** (exports, Test Movie and the player draw the artwork as it is), the **colour chip** opens the layer colour (swatches, hex, More…), **onion frames of the parent timeline** dimmed around a symbol edited in place, **Layer Height** 100/200/300 %, **Layer Properties** (double-click the layer icon; name, show/lock, type, outline colour, outlines, onion, height; one undo step), **Frame View** (Tiny/Small/Normal/Medium/Large, Short rows) with the frame zoom in the timeline's bottom bar (the header fits at the default window size, tested); headless `layer.set_onion/set_color/set_height/set_properties/properties`; XFL `heightMultiplier`. Not yet: folder onion toggles, onion of deeper parent timelines, multi-layer Layer Properties and layer transparency, frame thumbnails (Preview). Keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, looping playback. **Onion skin and Edit Multiple Frames** (ADR 0047): onion markers on the frame ruler (drag the start and end brackets; Always Show Markers, Anchor Markers, Onion 2 / Onion 5 / Onion All, also on a right-click on the ruler), frames before and after the playhead tinted in their own colours (theme blue and green, changeable in the onion menu, Reset) and fading with distance, Outlines, Keyframes Only, locked layers left out as in Animate, each layer's onion frames under its own artwork and over the layers below; options saved in the preferences; the stage's frame cache keys every look apart. **Edit Multiple Frames** shows every keyframe within the markers at full strength and selects (click, Shift-click, marquee, Select All) and moves (drag, arrow keys) artwork across them, one undo step, motion tween paths moving with their objects. Headless: `frames.artwork`, `frames.edit_multiple`. **Edit Multiple Frames, complete** (ADR 0051): Cut, Copy, Paste (current frame), Paste in Place (back keyframe by keyframe, or a one-frame copy onto every keyframe between the markers), Clear, Align (Ctrl+Alt+1…6, To Stage), Rotate 90° and Flip, and **Free Transform** of the selection on every keyframe about one shared pivot (one box, one undo step per drag); raw shapes moved, transformed or pasted merge again on their own keyframe; **onion skin and Edit Multiple Frames inside a symbol edited in place**, on its own timeline and markLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge; **across layers**, ADR 0044: a selection holds artwork on several visible, unlocked layers, the timeline marks them, Properties shows mixed values), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Stroke styles** (ADR 0046): Properties › Style (Solid, Dashed with dash and gap, Dotted with spacing), Cap (None, Round, Square), Join (Miter, Round, Bevel) and Miter limit, also in the drawing tools' options for new strokes; drawn exactly by the oracle (butt and square caps, miters bevelled past the limit, dashes by arc length restarting per subpath, round dots, dashes keeping a width profile's widths; sub-pixel patterns solid and faded) and so by the GPU stage; the Ink Bottle carries the style and the Eyedropper picks it; merge drawing keeps it on cut pieces; shape tweens blend miter limits and dash lengths; SVG, HTML canvas and Lottie export write it. Headless: `stroke.set_style`, and `cap`, `join`, `miter`, `style`, `dash`, `dash_offset`, `dot_spacing` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: Animate's ragged, stipple and hatched styles, multi-dash patterns in Properties (kept and editable by command), stroke scale modes and hairlines. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click Line truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
@@ -34,7 +34,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| M | Theme | Exit criteria |
|
||||
|---|---|---|
|
||||
| **M0** | Foundations *(this version)* | Workspace + layering; document model; timeline evaluation with classic tweens and easing; CPU oracle renderer; command registry with undo; `.anicraft`; CLI render + JSON-lines; egui shell with stage, tools, timeline, properties, library; `--screenshot`. |
|
||||
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073). |
|
||||
| **M1** | Authoring core ✅ *(v0.1.0)* | ~~Free transform tool with handles~~ ✅; ~~subselection and Bézier point editing~~ ✅; ~~Pen and Pencil~~ ✅; ~~Paint bucket / Ink bottle~~ ✅; ~~copy/paste~~ ✅, ~~duplicate, arrange~~ ✅, ~~align~~ ✅ (commands and menus; and the dock's Align panel ✅); ~~onion skin~~ ✅ (markers, tint, fade, outlines, keyframes only, Edit Multiple Frames: ADR 0047; its delete, copy/paste, Free Transform, align and re-merge, and both inside symbols: ADR 0051); ~~frame selection ranges in the timeline (multi-frame insert/remove/move keyframes by drag)~~ ✅ (including between layers); ~~PNG sequence + animated GIF export~~ ✅; ~~keyboard shortcut map editor~~ ✅; ~~groups, Combine Objects, Selection-tool modifiers~~ ✅ first slice (ADR 0073); ~~gradient editor, Gradient Transform tool and Lock Fill~~ ✅ (ADR 0074: the colour picker sets a fill's type, with a keyboard-operable stop bar, overflow, Linear RGB, focal point and bitmap fills; the Gradient Transform tool (F). |
|
||||
| **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅, ~~shape hints~~ ✅ (ADR 0023); ~~motion tween + Motion Editor curves~~ ✅ first slice (ADR 0016); ~~motion paths on the stage with orient to path~~ ✅ first slice (ADR 0030), ~~path point add/delete/convert and moving the whole path~~ ✅ (ADR 0038), ~~anchors pinned to frames~~ ✅ (ADR 0049; 3D and XFL import later); ~~library management~~ ✅ first slice (ADR 0050: folders, rename, duplicate, Swap Symbol, use counts and unused items, sort, search, preview, Allow Smoothing), ~~Library and Properties polish~~ ✅ (ADR 0053: drag onto the stage, Swap Bitmap, Convert to Symbol folders, mixed on every Properties row), ~~9-slice scaling~~ ✅ first slice (ADR 0055); ~~colour effects, complete~~ ✅ (ADR 0056: Properties' Style menu with None, Brightness, Tint, Advanced and Alpha, one exact colour transform in the CPU oracle, the GPU stage, SVG `feColorMatrix`, HTML canvas and Lottie, XFL `Color` import with a corpus package, classic tweens across styles, motion tween tint colour, brightness and Advanced tracks; not yet: camera colour effects beyond tint, a colour picker for the Motion Editor's tint colour); ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). |
|
||||
| **M3** | GPU stage *(in progress; the default stage renderer since ADR 0032)* | ~~wgpu renderer behind a feature flag~~ ✅ first slice (ADR 0019: the oracle's fills, CPU tile binning with backdrops, compute coverage; gradient tables in a storage buffer); ~~per-pixel parity tests vs the CPU oracle~~ ✅ (max 1/255, mean < 0.0001/255); ~~4K at 60 fps for 1,000 shapes~~ ✅ (8.8–9.0 ms); ~~no-readback textures, masks/groups/blend modes on the GPU~~ ✅ second slice (ADR 0029: window's device, 4K 10k shapes in 10.2 ms as tiles); ~~GPU binning~~ ✅ fourth slice (ADR 0048: heavy frames without masks or groups binned on the GPU, 50k shapes at 4K 122 → 22.5 ms in one texture; outline mode's hairlines as fast as tinted onion skin); ~~bitmaps and filters on the GPU~~ ✅ third slice (ADR 0032: bitmaps byte-identical, filters max 1/255; 4K filtered sample 3.9 ms, 200 bitmaps 4.4 ms); ~~hardware breadth~~ ✅ Vulkan and DX12 (FXC), software adapters refused, oracle-checked self-test; ~~GPU as the default stage renderer~~ ✅ (`gpu-stage` on by default for the app, automatic CPU fallback); next: GPU binning inside masks and groups, shared filtered layers across tiles, an image atlas, GPU exports. |
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~larger self-authored corpus with golden render tests~~ ✅ (ADR 0035: twelve packages covering every mapped feature, exact report expectations, hostile variants, CPU-oracle goldens); ~~`.fla` variants of the corpus and a hardened zip reader~~ ✅ (ADR 0054: nine zip layouts imported identically to the folder, ZIP64, CP437 names, a 9,664-archive hostile fuzz; a 54.6 MB `.fla` imports in 0.31 s); not yet: sound and video items, self-extracting and top-folder `.fla` archives; ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅; ~~animated PNG and WebP~~ ✅ (ADR 0063; lossless WebP; lossy WebP not yet). |
|
||||
|
||||
+1
-1
@@ -388,7 +388,7 @@ mod tests {
|
||||
for tool in [Tool::Bone, Tool::Bind, Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "shapebones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "motionedit", "motionpins", "motionpinsspan", "rawsub", "camera", "cameraview", "bones", "shapebones", "sound", "envelope", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames", "actions", "script", "scriptproblems", "testscript", "onion", "onionmenu", "editmultiple", "library", "librarymenu", "edittransform", "onionsymbol", "layerprops", "frameview", "layercolour", "timelinepolish", "convert", "mixed", "bitmap", "nineslice", "nineslicedit", "find", "explorer", "publish", "publishreport", "publishanim", "start", "drop", "droplibrary", "testmovie", "testmovieinside", "templates", "savetemplate", "droptimeline", "textfields", "testtext", "softmask", "pathtext", "gradient", "gradientbucket", "swatches", "brushlibrary", "brushcurve", "paintbrush"] {
|
||||
found.extend(check(panel, |a, _| a.open_panel(Some(panel))));
|
||||
}
|
||||
// Every panel in front where it docks, and floating (ADR 0075); the other workspaces.
|
||||
|
||||
+34
-2
@@ -15,6 +15,7 @@ pub enum Tool {
|
||||
Select,
|
||||
Subselect,
|
||||
Transform,
|
||||
GradientTransform,
|
||||
Width,
|
||||
Bone,
|
||||
Bind,
|
||||
@@ -68,13 +69,14 @@ impl GapSize {
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
pub const ALL: [Tool; 22] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Width, Tool::Bone, Tool::Bind, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom];
|
||||
pub const ALL: [Tool; 23] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::GradientTransform, Tool::Width, Tool::Bone, Tool::Bind, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBrush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Tool::Select => tr_noop!("Selection"),
|
||||
Tool::Subselect => tr_noop!("Subselection"),
|
||||
Tool::Transform => tr_noop!("Free Transform"),
|
||||
Tool::GradientTransform => tr_noop!("Gradient Transform"),
|
||||
Tool::Width => tr_noop!("Width"),
|
||||
Tool::Bone => tr_noop!("Bone"),
|
||||
Tool::Bind => tr_noop!("Bind"),
|
||||
@@ -102,6 +104,7 @@ impl Tool {
|
||||
Tool::Select => Some("V"),
|
||||
Tool::Subselect => Some("A"),
|
||||
Tool::Transform => Some("Q"),
|
||||
Tool::GradientTransform => Some("F"),
|
||||
Tool::Width => Some("U"),
|
||||
Tool::Bone => Some("M"),
|
||||
Tool::Bind => Some("Shift+M"),
|
||||
@@ -137,6 +140,7 @@ impl Tool {
|
||||
Tool::Width => tr_noop!("Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it."),
|
||||
Tool::Bone => tr_noop!("Drag from one symbol instance to another to join them with a bone (they move to an armature layer), or drag inside a shape to draw a bone in it (the shape bends with its bones); start on a bone's end to continue the chain. Click a bone to select it. Pose the armature by dragging bones or instances with the Selection tool."),
|
||||
Tool::Bind => tr_noop!("Shows the points of shapes with bones: a square follows one bone, a triangle several. Click a bone to see the points it moves (filled). Click a point, or drag a box around points, to make them follow only that bone; Shift shares the bone with the ones they follow, Ctrl takes them from it."),
|
||||
Tool::GradientTransform => tr_noop!("Click a shape with a gradient or bitmap fill to show its handles. Drag the centre to move the fill, the square to change its width, the circle to change its size, the knob to rotate it (Shift: 15° steps) and, on a radial gradient, the triangle to move its focal point. A bitmap fill also has a square for its height and diamonds to skew it. Each drag is one undo step."),
|
||||
Tool::Transform => tr_noop!("Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move."),
|
||||
Tool::Rect => tr_noop!("Drag to draw a rectangle. Shift draws a square."),
|
||||
Tool::Oval => tr_noop!("Drag to draw an oval. Shift draws a circle."),
|
||||
@@ -218,6 +222,9 @@ pub enum Drag {
|
||||
/// `sub`; `start` is its left and right width when the drag began.
|
||||
/// `index` is the grabbed width point (None: one the drag adds at `t`).
|
||||
Width { id: anicraft_engine::doc::ElementId, sub: usize, index: Option<usize>, t: f32, grip: crate::widthtool::Grip, start: (f32, f32) },
|
||||
/// Gradient Transform tool (ADR 0074): dragging `grip` of shape `id`'s fill, whose frame was
|
||||
/// `frame` when the drag began at stage point `press`.
|
||||
Gradient { id: anicraft_engine::doc::ElementId, grip: crate::gradient_tool::Grip, frame: anicraft_engine::geom::Affine, press: egui::Pos2 },
|
||||
/// Free transform: `applied` is the transform already sent to the engine this gesture.
|
||||
Transform { kind: XfKind, start: egui::Pos2, bounds: [f32; 4], applied: anicraft_engine::geom::Affine },
|
||||
/// Dragging shape hint `index` on the side the frame shows (ADR 0023).
|
||||
@@ -1379,7 +1386,7 @@ impl App {
|
||||
}
|
||||
let mask = self.run("layer.new", json!({"name": "Soft mask"})).and_then(|v| v["layer"].as_u64());
|
||||
let stops = vec![anicraft_engine::doc::GradientStop { offset: 0.0, color: anicraft_engine::doc::Rgba::WHITE }, anicraft_engine::doc::GradientStop { offset: 1.0, color: anicraft_engine::doc::Rgba::WHITE.with_alpha(0.0) }];
|
||||
let swatch = self.s.style.fill_paint.replace(anicraft_engine::doc::Paint::Radial { center: anicraft_engine::geom::Vec2::new(320.0, 200.0), radius: 190.0, stops });
|
||||
let swatch = self.s.style.fill_paint.replace(anicraft_engine::doc::Paint::radial(anicraft_engine::geom::Vec2::new(320.0, 200.0), 190.0, stops));
|
||||
self.run("draw.ellipse", json!({"x": 130, "y": 10, "w": 380, "h": 380, "stroke": null}));
|
||||
self.s.style.fill_paint = swatch;
|
||||
self.run("layer.toggle_mask", json!({}));
|
||||
@@ -1916,6 +1923,31 @@ impl App {
|
||||
}
|
||||
self.tool = Tool::Width;
|
||||
}
|
||||
Some(which @ ("gradient" | "gradientbucket")) => {
|
||||
// The gradient tools (ADR 0074): a reflecting linear gradient turned on a panel,
|
||||
// and an oval with a stretched radial gradient and its focal point off centre,
|
||||
// selected with the Gradient Transform tool (its handles show) while the colour
|
||||
// picker edits its stops.
|
||||
self.perform("file.new", json!({"width": 640, "height": 400}));
|
||||
self.run("draw.rect", json!({"x": 0, "y": 0, "w": 640, "h": 400, "fill": "#14213d", "stroke": null}));
|
||||
self.run("draw.rect", json!({"x": 40, "y": 60, "w": 200, "h": 280, "stroke": null}));
|
||||
self.run("paint.set_fill", json!({"type": "linear", "stops": [{"offset": 0, "color": "#e76f51"}, {"offset": 1, "color": "#f4a261"}], "spread": "reflect"}));
|
||||
self.run("paint.transform_fill", json!({"scale_x": 0.3, "rotate": 30}));
|
||||
self.run("draw.ellipse", json!({"x": 280, "y": 50, "w": 320, "h": 300, "stroke": null}));
|
||||
self.run("paint.set_fill", json!({"type": "radial", "stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.45, "color": "#8ecae6"}, {"offset": 1, "color": "#023047"}], "focal": 0.55}));
|
||||
self.run("paint.transform_fill", json!({"scale_x": 1.1, "scale_y": 0.8, "rotate": -35}));
|
||||
self.tool = Tool::GradientTransform;
|
||||
if which == "gradient" {
|
||||
// The colour picker open on it, in gradient mode: the stop bar, overflow and
|
||||
// the picked stop's colour.
|
||||
self.open_fill_swatch = true;
|
||||
}
|
||||
if which == "gradientbucket" {
|
||||
// The Paint Bucket in hand, nothing selected: the swatch's gradient and Lock Fill.
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.tool = Tool::PaintBucket;
|
||||
}
|
||||
}
|
||||
Some(which @ ("motion" | "motionspan")) => {
|
||||
// The Star layer's span as a motion tween: it moves, turns and fades out, with
|
||||
// an eased X and a custom Bezier on Y, shown in the Motion Editor.
|
||||
|
||||
+16
-4
@@ -117,7 +117,7 @@ fn remember(ctx: &egui::Context, popup: Id, c: [u8; 3]) {
|
||||
}
|
||||
|
||||
/// A new popup opening adds its first change as a new recent colour.
|
||||
fn new_session(ctx: &egui::Context) {
|
||||
pub(crate) fn new_session(ctx: &egui::Context) {
|
||||
ctx.data_mut(|d| d.get_temp_mut_or_default::<Recent>(recent_id()).from = None);
|
||||
}
|
||||
|
||||
@@ -161,14 +161,25 @@ pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, c: &mut [u8; 4], a
|
||||
new_session(ui.ctx());
|
||||
}
|
||||
let mut changed = false;
|
||||
egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
let shown = egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
changed = picker(ui, popup, c, alpha, none);
|
||||
});
|
||||
if let Some(r) = shown {
|
||||
name_popup(&r.response, tr!("Colour picker"));
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Names a picker popup for screen readers: a dialog holding the picker's controls.
|
||||
pub(crate) fn name_popup(r: &Response, name: &str) {
|
||||
r.ctx.accesskit_node_builder(r.id, |node| {
|
||||
node.set_role(egui::accesskit::Role::Dialog);
|
||||
node.set_label(name);
|
||||
});
|
||||
}
|
||||
|
||||
/// The picker itself: swatches or mixer, then the colour, its hex and its alpha.
|
||||
fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, none: Option<&mut bool>) -> bool {
|
||||
pub(crate) fn picker(ui: &mut egui::Ui, popup: Id, c: &mut [u8; 4], alpha: bool, none: Option<&mut bool>) -> bool {
|
||||
let view_id = Id::new("anicraft.colour.view");
|
||||
let mut view: View = ui.data(|d| d.get_temp(view_id)).unwrap_or_default();
|
||||
let mut changed = false;
|
||||
@@ -299,7 +310,8 @@ fn swatches(ui: &mut egui::Ui, current: [u8; 3]) -> Option<[u8; 3]> {
|
||||
painter.rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, T.selection), StrokeKind::Middle);
|
||||
resp.clone().on_hover_text(text(Type::Data, to_hex([c[0], c[1], c[2], 255], false)));
|
||||
}
|
||||
resp.clone().named(tr!("Colour swatches"));
|
||||
// One control for the whole grid (a click picks the cell under the pointer).
|
||||
crate::a11y::control(ui, &resp, egui::WidgetType::Button, tr!("Colour swatches"), None);
|
||||
if resp.clicked() { resp.interact_pointer_pos().and_then(hit).map(|(_, c)| c) } else { None }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,579 @@
|
||||
//! The fill side of the colour picker (ADR 0074): one picker, as Animate has one Color panel.
|
||||
//!
|
||||
//! The Tools panel's Fill square and every Fill swatch in Properties open the same popup. Its
|
||||
//! top row is the fill's type (None, Solid, Linear, Radial, Bitmap). A solid fill shows the
|
||||
//! colour picker (`crate::colour`: web-safe swatches, the mixer, hex). A gradient shows its stop
|
||||
//! bar, overflow, Linear RGB and focal point above that same picker, which then edits the picked
|
||||
//! stop's colour and opacity. A bitmap fill shows the Library image it uses. The Stroke square
|
||||
//! opens the colour picker alone (strokes are one colour).
|
||||
//!
|
||||
//! The popup says what was asked ([`FillEdit`]); its caller applies it: a solid colour or None
|
||||
//! the way that place always has, anything else as `paint.set_fill`, which sets the fill swatch
|
||||
//! and the selected fills in one step, so agents and the CLI work the same way.
|
||||
|
||||
use crate::a11y::{self, Named};
|
||||
use crate::app::App;
|
||||
use crate::theme::{T, Type, text, to_color32, with_type};
|
||||
use anicraft_engine::doc::{ElementKind, GradientStop, MAX_FOCAL, MAX_GRADIENT_STOPS, Paint, Rgba, Spread, ramp_at};
|
||||
use egui::{Id, Key, Rect, Response, Sense, Stroke, StrokeKind, WidgetType, pos2, vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// How far (screen points) a stop dragged off the bar must go to be removed.
|
||||
const TEAR_OFF: f32 = 26.0;
|
||||
/// The stop bar's width: the colour picker's swatch grid under it.
|
||||
const BAR_WIDTH: f32 = 270.0;
|
||||
|
||||
/// What the fill picker asks for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum FillEdit {
|
||||
/// A solid colour (opaque).
|
||||
Solid([u8; 3]),
|
||||
/// No fill (true), or a fill again (false).
|
||||
None(bool),
|
||||
/// `paint.set_fill` params, with its undo label; `live` while a drag or typing goes on (one
|
||||
/// undo step for all of it).
|
||||
Set { label: &'static str, live: bool, params: Value },
|
||||
}
|
||||
|
||||
/// The fill the pickers show: the first selected shape's on the active layer, else the swatch.
|
||||
/// True when it is the selection's.
|
||||
pub fn current(app: &App) -> (Paint, bool) {
|
||||
let selected = app.s.selected_elements().into_iter().filter(|(l, _)| *l == app.s.layer).find_map(|(_, e)| match &e.kind {
|
||||
ElementKind::Shape(sh) => sh.fill.clone(),
|
||||
_ => None,
|
||||
});
|
||||
match selected {
|
||||
Some(p) => (p, true),
|
||||
None => (app.s.style.fill_paint(), false),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Library's bitmaps, for a bitmap fill: `(id, name)`.
|
||||
pub fn bitmaps(app: &App) -> Vec<(u64, String)> {
|
||||
app.s.doc.bitmaps.iter().map(|b| (b.id.0, b.name.clone())).collect()
|
||||
}
|
||||
|
||||
/// Applies `edit` as `paint.set_fill` (`selection`: also to the selected fills). Solid and None
|
||||
/// edits are the caller's (each place keeps its own rule for those).
|
||||
pub fn apply_set(app: &mut App, edit: &FillEdit, selection: bool) {
|
||||
if let FillEdit::Set { label, live, params } = edit {
|
||||
let mut p = params.clone();
|
||||
if !selection && let Some(o) = p.as_object_mut() {
|
||||
o.insert("selection".into(), json!(false));
|
||||
}
|
||||
if *live {
|
||||
crate::panels::live(app, label, "paint.set_fill", p);
|
||||
} else {
|
||||
app.run("paint.set_fill", p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
|
||||
fn hex(c: Rgba) -> String {
|
||||
let c = c.sanitized();
|
||||
if c.a >= 1.0 { c.to_hex() } else { format!("{}{:02x}", c.to_hex(), (c.a * 255.0).round() as u8) }
|
||||
}
|
||||
|
||||
fn stops_json(stops: &[GradientStop]) -> Value {
|
||||
json!(stops.iter().map(|s| json!({"offset": s.offset.clamp(0.0, 1.0), "color": hex(s.color)})).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn bytes(c: Rgba) -> [u8; 4] {
|
||||
let c = c.sanitized();
|
||||
let b = |v: f32| (v * 255.0).round() as u8;
|
||||
[b(c.r), b(c.g), b(c.b), b(c.a)]
|
||||
}
|
||||
|
||||
fn from_bytes(c: [u8; 4]) -> Rgba {
|
||||
Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, f32::from(c[3]) / 255.0)
|
||||
}
|
||||
|
||||
/// Paints `paint` into `r`: a colour, a gradient's ramp, a bitmap's mark, or the empty field
|
||||
/// with a slash for no fill.
|
||||
fn paint_preview(p: &egui::Painter, r: Rect, paint: Option<&Paint>) {
|
||||
match paint {
|
||||
None => {
|
||||
p.rect_filled(r, 0.0, T.field);
|
||||
p.line_segment([r.left_bottom(), r.right_top()], Stroke::new(1.5, T.danger));
|
||||
}
|
||||
Some(Paint::Solid(c)) => egui::color_picker::show_color_at(p, to_color32(*c), r),
|
||||
Some(Paint::Bitmap { .. }) => {
|
||||
p.rect_filled(r, 0.0, T.text_faint);
|
||||
crate::icons::paint(p, r.shrink(2.0), crate::icons::Icon::Image, T.panel);
|
||||
}
|
||||
Some(g) => {
|
||||
let stops = g.stops().unwrap_or(&[]);
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let steps = 24u32;
|
||||
for i in 0..=steps {
|
||||
let t = i as f32 / steps as f32;
|
||||
let c = to_color32(ramp_at(stops, t));
|
||||
let x = r.left() + t * r.width();
|
||||
mesh.colored_vertex(pos2(x, r.top()), c);
|
||||
mesh.colored_vertex(pos2(x, r.bottom()), c);
|
||||
if i > 0 {
|
||||
let k = 2 * i;
|
||||
mesh.add_triangle(k - 2, k - 1, k);
|
||||
mesh.add_triangle(k - 1, k, k + 1);
|
||||
}
|
||||
}
|
||||
p.add(mesh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fill swatch for Properties: shows the fill (a gradient as its ramp) and opens the fill
|
||||
/// picker. Name it with `Named::named`.
|
||||
pub fn swatch(ui: &mut egui::Ui, paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> (Response, Option<FillEdit>) {
|
||||
let size = ui.spacing().interact_size;
|
||||
let (rect, mut resp) = ui.allocate_exact_size(size, Sense::click());
|
||||
resp.widget_info(|| egui::WidgetInfo::new(WidgetType::ColorButton));
|
||||
let popup = resp.id.with("colour_popup");
|
||||
let open = egui::Popup::is_id_open(ui.ctx(), popup);
|
||||
if ui.is_rect_visible(rect) {
|
||||
paint_preview(ui.painter(), rect.shrink(1.0), paint);
|
||||
ui.painter().rect_stroke(rect, T.rc(), Stroke::new(1.0, if open || resp.hovered() { T.selection } else { T.border }), StrokeKind::Inside);
|
||||
}
|
||||
let edit = popup_for(ui, &resp, popup, paint, bitmaps);
|
||||
if edit.is_some() {
|
||||
resp.mark_changed();
|
||||
}
|
||||
(resp, edit)
|
||||
}
|
||||
|
||||
/// Opens the fill picker under `anchor` when it is clicked, and shows it while open. `paint`
|
||||
/// is the fill (`None`: no fill).
|
||||
pub fn popup_for(ui: &egui::Ui, anchor: &Response, popup: Id, paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> Option<FillEdit> {
|
||||
if anchor.clicked() {
|
||||
crate::colour::new_session(ui.ctx());
|
||||
}
|
||||
let mut edit = None;
|
||||
let shown = egui::Popup::menu(anchor).id(popup).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
edit = fill_picker(ui, popup, paint, bitmaps);
|
||||
});
|
||||
if let Some(r) = shown {
|
||||
crate::colour::name_popup(&r.response, tr!("Fill colour picker"));
|
||||
}
|
||||
edit
|
||||
}
|
||||
|
||||
/// The kinds of fill on the type row, as Animate's Color Type menu: key, label, what it is.
|
||||
fn kinds() -> [(&'static str, &'static str, &'static str); 5] {
|
||||
[
|
||||
("none", tr!("None"), tr!("No fill")),
|
||||
("solid", tr!("Solid"), tr!("Solid colour")),
|
||||
("linear", tr!("Linear"), tr!("Linear gradient: colours along a line")),
|
||||
("radial", tr!("Radial"), tr!("Radial gradient: colours out from a centre")),
|
||||
("bitmap", tr!("Bitmap"), tr!("Bitmap fill: a Library image, tiled")),
|
||||
]
|
||||
}
|
||||
|
||||
/// The picker's body: the type row, then what that type has.
|
||||
pub fn fill_picker(ui: &mut egui::Ui, popup: Id, paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> Option<FillEdit> {
|
||||
let now = match paint {
|
||||
None => "none",
|
||||
Some(Paint::Solid(_)) => "solid",
|
||||
Some(Paint::Linear { .. }) => "linear",
|
||||
Some(Paint::Radial { .. }) => "radial",
|
||||
Some(Paint::Bitmap { .. }) => "bitmap",
|
||||
};
|
||||
let mut pick = now;
|
||||
ui.horizontal(|ui| {
|
||||
for (key, label, tip) in kinds() {
|
||||
let usable = key != "bitmap" || !bitmaps.is_empty();
|
||||
let r = ui.add_enabled(usable, egui::Button::selectable(pick == key, label)).named(&tr!("Fill type: {kind}", kind = tip));
|
||||
let r = if usable { r.on_hover_text(tip) } else { r.on_disabled_hover_text(tr!("Import an image into the Library first (File › Import › Import to Library), then fill with it.")) };
|
||||
if r.clicked() {
|
||||
pick = key;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
if pick != now {
|
||||
return Some(match pick {
|
||||
"none" => FillEdit::None(true),
|
||||
"solid" => match paint {
|
||||
// A fill again: the colour it shows.
|
||||
None => FillEdit::None(false),
|
||||
Some(p) => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "solid", "color": hex(p.primary_color().with_alpha(1.0))}) },
|
||||
},
|
||||
"bitmap" => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "bitmap", "bitmap": bitmaps.first().map_or(0, |b| b.0)}) },
|
||||
other => FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": other}) },
|
||||
});
|
||||
}
|
||||
match paint {
|
||||
None => {
|
||||
ui.label(text(Type::Caption, tr!("No fill. Choose a type above to fill again.")));
|
||||
None
|
||||
}
|
||||
Some(Paint::Solid(c)) => {
|
||||
let mut px = bytes(*c);
|
||||
crate::colour::picker(ui, popup, &mut px, false, None).then_some(FillEdit::Solid([px[0], px[1], px[2]]))
|
||||
}
|
||||
Some(Paint::Linear { stops, spread, linear_rgb, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, None),
|
||||
Some(Paint::Radial { stops, spread, linear_rgb, focal, .. }) => gradient(ui, popup, stops, *spread, *linear_rgb, Some(*focal)),
|
||||
Some(Paint::Bitmap { bitmap, .. }) => {
|
||||
let current = bitmap.0;
|
||||
let mut want = current;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr!("Bitmap"));
|
||||
egui::ComboBox::from_id_salt(popup.with("fill_bitmap"))
|
||||
.width(180.0)
|
||||
.selected_text(bitmaps.iter().find(|c| c.0 == current).map_or_else(|| tr!("missing bitmap").to_string(), |c| c.1.clone()))
|
||||
.show_ui(ui, |ui| {
|
||||
for (id, name) in bitmaps {
|
||||
ui.selectable_value(&mut want, *id, name.as_str());
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name(tr!("Fill bitmap"));
|
||||
});
|
||||
ui.label(text(Type::Caption, tr!("Scale, turn and skew it with the Gradient Transform tool (F).")));
|
||||
(want != current).then(|| FillEdit::Set { label: tr_noop!("Fill"), live: false, params: json!({"type": "bitmap", "bitmap": want}) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient: overflow, Linear RGB and the focal point, the stop bar, the picked stop's
|
||||
/// position, and the colour picker for its colour.
|
||||
fn gradient(ui: &mut egui::Ui, popup: Id, stops: &[GradientStop], spread: Spread, linear_rgb: bool, focal: Option<f32>) -> Option<FillEdit> {
|
||||
let set = |label: &'static str, live: bool, params: Value| Some(FillEdit::Set { label, live, params });
|
||||
let mut out = None;
|
||||
let mut sp = spread;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr!("Overflow"));
|
||||
for (s, label, tip) in [
|
||||
(Spread::Pad, tr!("Extend"), tr!("Past its ends the gradient keeps its end colours")),
|
||||
(Spread::Reflect, tr!("Reflect"), tr!("Past its ends the gradient mirrors back and forth")),
|
||||
(Spread::Repeat, tr!("Repeat"), tr!("Past its ends the gradient starts again")),
|
||||
] {
|
||||
ui.selectable_value(&mut sp, s, label).on_hover_text(tip);
|
||||
}
|
||||
});
|
||||
if sp != spread {
|
||||
out = set(tr_noop!("Overflow"), false, json!({"spread": sp.key()}));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let mut lin = linear_rgb;
|
||||
if crate::theme::checkbox(ui, &mut lin, tr!("Linear RGB")).on_hover_text(tr!("Mix the colours in linear light: brighter, more even blends")).changed() {
|
||||
out = set(tr_noop!("Linear RGB"), false, json!({"linear_rgb": lin}));
|
||||
}
|
||||
if let Some(f) = focal {
|
||||
ui.add_space(8.0);
|
||||
ui.label(tr!("Focal point"));
|
||||
let mut pct = f * 100.0;
|
||||
let lim = MAX_FOCAL * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(-lim..=lim).max_decimals(0)));
|
||||
if r.named(tr!("Focal point")).on_hover_text(tr!("Where the ramp starts, from the centre along the gradient's axis (drag the triangle with the Gradient Transform tool)")).changed() {
|
||||
out = set(tr_noop!("Focal point"), true, json!({"focal": (pct / 100.0).clamp(-MAX_FOCAL, MAX_FOCAL)}));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mut edited = stops.to_vec();
|
||||
if let Some((label, live)) = stop_bar(ui, popup, &mut edited) {
|
||||
out = set(label, live, json!({"stops": stops_json(&edited)}));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where stop `i` may move: between its neighbours, so the order (and the pick) stays.
|
||||
fn room(stops: &[GradientStop], i: usize) -> (f32, f32) {
|
||||
let lo = i.checked_sub(1).and_then(|j| stops.get(j)).map_or(0.0, |s| s.offset);
|
||||
let hi = stops.get(i + 1).map_or(1.0, |s| s.offset);
|
||||
(lo.min(hi), hi.max(lo))
|
||||
}
|
||||
|
||||
/// Moves stop `i` to `offset`, held between its neighbours.
|
||||
fn move_stop(stops: &mut [GradientStop], i: usize, offset: f32) {
|
||||
let (lo, hi) = room(stops, i);
|
||||
if let Some(s) = stops.get_mut(i) {
|
||||
s.offset = if offset.is_finite() { offset.clamp(lo, hi) } else { s.offset };
|
||||
}
|
||||
}
|
||||
|
||||
/// The middle of the widest gap between stops: where the keyboard adds one.
|
||||
fn widest_gap(stops: &[GradientStop]) -> f32 {
|
||||
stops.windows(2).filter_map(|w| if let [a, b] = w { Some((b.offset - a.offset, (a.offset + b.offset) / 2.0)) } else { None }).max_by(|a, b| a.0.total_cmp(&b.0)).map_or(0.5, |g| g.1)
|
||||
}
|
||||
|
||||
/// Adds a stop at `t` in the colour the ramp has there; its index, or `None` when the gradient
|
||||
/// is full.
|
||||
fn add_stop(stops: &mut Vec<GradientStop>, t: f32) -> Option<usize> {
|
||||
if stops.len() >= MAX_GRADIENT_STOPS {
|
||||
return None;
|
||||
}
|
||||
let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.5 };
|
||||
let i = stops.iter().position(|s| s.offset > t).unwrap_or(stops.len());
|
||||
let color = ramp_at(stops, t);
|
||||
stops.insert(i, GradientStop { offset: t, color });
|
||||
Some(i)
|
||||
}
|
||||
|
||||
/// Removes stop `i` unless only two are left. True when it went.
|
||||
fn remove_stop(stops: &mut Vec<GradientStop>, i: usize) -> bool {
|
||||
if stops.len() <= 2 || i >= stops.len() {
|
||||
return false;
|
||||
}
|
||||
stops.remove(i);
|
||||
true
|
||||
}
|
||||
|
||||
/// The bar of colour stops, the picked stop's position and its colour (the colour picker,
|
||||
/// with opacity). What changed (its undo label), and whether it is live (a drag or typing).
|
||||
fn stop_bar(ui: &mut egui::Ui, popup: Id, stops: &mut Vec<GradientStop>) -> Option<(&'static str, bool)> {
|
||||
let sel_id = popup.with("fill_stop");
|
||||
let tear_id = popup.with("fill_stop_tear");
|
||||
let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0).min(stops.len().saturating_sub(1));
|
||||
let mut changed = None;
|
||||
let can_remove = stops.len() > 2;
|
||||
let w = BAR_WIDTH;
|
||||
let (strip, resp) = ui.allocate_exact_size(vec2(w, 18.0), Sense::click());
|
||||
a11y::control(ui, &resp, WidgetType::Button, tr!("Gradient: add a colour stop"), None);
|
||||
let resp = resp.on_hover_text(tr!("Click to add a colour stop. Drag a stop to move it, or off the bar to remove it. With a stop focused, the arrow keys move it and Delete removes it."));
|
||||
let p = ui.painter();
|
||||
// A checkerboard under the ramp shows its opacity.
|
||||
let cell = 4.0;
|
||||
let (cols, rows) = ((strip.width() / cell).ceil() as usize, (strip.height() / cell).ceil() as usize);
|
||||
p.rect_filled(strip, 0.0, T.header);
|
||||
for (cx, cy) in (0..cols).flat_map(|x| (0..rows).map(move |y| (x, y))).filter(|(x, y)| (x + y) % 2 == 0) {
|
||||
let r = Rect::from_min_size(pos2(strip.left() + cx as f32 * cell, strip.top() + cy as f32 * cell), vec2(cell, cell)).intersect(strip);
|
||||
p.rect_filled(r, 0.0, T.text_faint);
|
||||
}
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let steps = 64u32;
|
||||
for i in 0..=steps {
|
||||
let t = i as f32 / steps as f32;
|
||||
let c = to_color32(ramp_at(stops, t));
|
||||
let x = strip.left() + t * strip.width();
|
||||
mesh.colored_vertex(pos2(x, strip.top()), c);
|
||||
mesh.colored_vertex(pos2(x, strip.bottom()), c);
|
||||
if i > 0 {
|
||||
let k = 2 * i;
|
||||
mesh.add_triangle(k - 2, k - 1, k);
|
||||
mesh.add_triangle(k - 1, k, k + 1);
|
||||
}
|
||||
}
|
||||
p.add(mesh);
|
||||
p.rect_stroke(strip, 0.0, Stroke::new(1.0, T.border), StrokeKind::Outside);
|
||||
// A marker under the bar per stop: click to pick it, drag to move it, drag off to remove it.
|
||||
let (track, _) = ui.allocate_exact_size(vec2(w, 14.0), Sense::hover());
|
||||
let mut remove: Option<usize> = None;
|
||||
let mut tearing: Option<usize> = ui.data(|d| d.get_temp(tear_id));
|
||||
let count = stops.len();
|
||||
for i in 0..count {
|
||||
let Some(off) = stops.get(i).map(|s| s.offset) else { continue };
|
||||
let x = strip.left() + off.clamp(0.0, 1.0) * strip.width();
|
||||
let hit = Rect::from_center_size(pos2(x, track.center().y), vec2(12.0, 14.0));
|
||||
let r = ui.interact(hit, popup.with(("fill_stop_marker", i)), Sense::click_and_drag());
|
||||
let at = format!("{:.0}", off * 100.0);
|
||||
a11y::control(ui, &r, WidgetType::Button, &tr!("Colour stop {stop} of {count} at {at}%", stop = i + 1, count = count, at = at), Some(i == sel));
|
||||
if r.clicked() || r.drag_started() || r.gained_focus() {
|
||||
sel = i;
|
||||
}
|
||||
if r.dragged()
|
||||
&& let Some(pt) = r.interact_pointer_pos()
|
||||
{
|
||||
sel = i;
|
||||
// Far enough above or below the bar: the stop comes off when let go.
|
||||
let off_bar = can_remove && (pt.y - track.center().y).abs() > TEAR_OFF && (pt.y - strip.center().y).abs() > TEAR_OFF;
|
||||
tearing = off_bar.then_some(i);
|
||||
if !off_bar {
|
||||
move_stop(stops, i, (pt.x - strip.left()) / strip.width());
|
||||
changed = Some((tr_noop!("Move colour stop"), true));
|
||||
}
|
||||
}
|
||||
if r.drag_stopped() && tearing == Some(i) {
|
||||
remove = Some(i);
|
||||
tearing = None;
|
||||
}
|
||||
// The keyboard: arrows move the focused stop (Shift: by 10 %), Delete removes it.
|
||||
if r.has_focus() {
|
||||
let (left, right, shift, del) = ui.input(|inp| (inp.key_pressed(Key::ArrowLeft), inp.key_pressed(Key::ArrowRight), inp.modifiers.shift, inp.key_pressed(Key::Delete) || inp.key_pressed(Key::Backspace)));
|
||||
let step = if shift { 0.1 } else { 0.01 };
|
||||
let d = if right { step } else if left { -step } else { 0.0 };
|
||||
if d != 0.0 {
|
||||
move_stop(stops, i, off + d);
|
||||
changed = Some((tr_noop!("Move colour stop"), true));
|
||||
}
|
||||
if del && can_remove {
|
||||
remove = Some(i);
|
||||
}
|
||||
// Arrow keys stay on the stop rather than moving focus.
|
||||
ui.memory_mut(|m| m.set_focus_lock_filter(r.id, egui::EventFilter { horizontal_arrows: true, ..Default::default() }));
|
||||
}
|
||||
let Some(st) = stops.get(i) else { continue };
|
||||
let torn = tearing == Some(i);
|
||||
let tip = pos2(x, track.top());
|
||||
let body = [tip, pos2(x + 6.0, track.top() + 6.0), pos2(x + 6.0, track.bottom()), pos2(x - 6.0, track.bottom()), pos2(x - 6.0, track.top() + 6.0)];
|
||||
let edge = if i == sel { T.accent } else if r.hovered() { T.text } else { T.control_edge };
|
||||
let fill = to_color32(st.color.with_alpha(if torn { 0.3 } else { 1.0 }));
|
||||
ui.painter().add(egui::Shape::convex_polygon(body.to_vec(), fill, Stroke::new(if i == sel { 2.0 } else { 1.0 }, edge)));
|
||||
}
|
||||
ui.data_mut(|d| match tearing {
|
||||
Some(t) => {
|
||||
d.insert_temp(tear_id, t);
|
||||
}
|
||||
None => d.remove::<usize>(tear_id),
|
||||
});
|
||||
if resp.clicked() {
|
||||
// Where the pointer clicked; from the keyboard or a screen reader, the middle of the
|
||||
// widest gap.
|
||||
let t = resp.interact_pointer_pos().map_or_else(|| widest_gap(stops), |at| (at.x - strip.left()) / strip.width());
|
||||
if let Some(i) = add_stop(stops, t) {
|
||||
sel = i;
|
||||
changed = Some((tr_noop!("Add colour stop"), false));
|
||||
}
|
||||
}
|
||||
if let Some(i) = remove.take()
|
||||
&& remove_stop(stops, i)
|
||||
{
|
||||
sel = sel.min(stops.len().saturating_sub(1));
|
||||
changed = Some((tr_noop!("Remove colour stop"), false));
|
||||
}
|
||||
// The picked stop: its position, then its colour in the colour picker.
|
||||
let n = stops.len();
|
||||
if let Some(st) = stops.get_mut(sel) {
|
||||
ui.add_space(2.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr!("Stop {stop} at", stop = sel + 1));
|
||||
let mut pct = st.offset * 100.0;
|
||||
let r = with_type(ui, Type::Data, |ui| ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)));
|
||||
if r.named(tr!("Colour stop position")).changed() {
|
||||
st.offset = (pct / 100.0).clamp(0.0, 1.0);
|
||||
changed = Some((tr_noop!("Move colour stop"), true));
|
||||
}
|
||||
if ui.add_enabled(n > 2, egui::Button::new(tr!("Remove")).small()).named(tr!("Remove colour stop")).on_hover_text(tr!("Remove this colour stop (or drag it off the bar)")).clicked() {
|
||||
remove = Some(sel);
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mut px = bytes(st.color);
|
||||
if crate::colour::picker(ui, popup.with(("stop", sel)), &mut px, true, None) {
|
||||
st.color = from_bytes(px);
|
||||
changed = Some((tr_noop!("Colour stop"), true));
|
||||
}
|
||||
}
|
||||
if let Some(i) = remove
|
||||
&& remove_stop(stops, i)
|
||||
{
|
||||
sel = sel.min(stops.len().saturating_sub(1));
|
||||
changed = Some((tr_noop!("Remove colour stop"), false));
|
||||
}
|
||||
// Typed positions may pass a neighbour: keep the stops in order (the pick follows its stop).
|
||||
if let Some(picked) = stops.get(sel).copied() {
|
||||
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
sel = stops.iter().position(|s| *s == picked).unwrap_or(sel);
|
||||
}
|
||||
ui.data_mut(|d| d.insert_temp(sel_id, sel));
|
||||
changed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::Tool;
|
||||
use anicraft_engine::geom::Vec2;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn stop(offset: f32, c: u32) -> GradientStop {
|
||||
GradientStop { offset, color: Rgba::hex(c) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stops_are_added_moved_and_removed_in_order() {
|
||||
let mut st = vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)];
|
||||
// Added where asked, in the ramp's colour there, in order.
|
||||
assert_eq!(add_stop(&mut st, 0.25), Some(1));
|
||||
assert!((st[1].color.r - 0.25).abs() < 1e-6);
|
||||
assert_eq!(widest_gap(&st), 0.625);
|
||||
assert_eq!(add_stop(&mut st, f32::NAN), Some(2), "a bad position lands in the middle");
|
||||
// A stop moves only between its neighbours.
|
||||
move_stop(&mut st, 1, 0.9);
|
||||
assert_eq!(st[1].offset, 0.5);
|
||||
move_stop(&mut st, 1, -1.0);
|
||||
assert_eq!(st[1].offset, 0.0);
|
||||
move_stop(&mut st, 9, 0.5);
|
||||
// Full at 15 stops; never fewer than 2.
|
||||
while add_stop(&mut st, 0.7).is_some() {}
|
||||
assert_eq!(st.len(), MAX_GRADIENT_STOPS);
|
||||
while remove_stop(&mut st, 0) {}
|
||||
assert_eq!(st.len(), 2);
|
||||
assert!(!remove_stop(&mut st, 5));
|
||||
assert_eq!(hex(Rgba::new(1.0, 0.0, 0.0, 0.5)), "#ff000080");
|
||||
assert_eq!(hex(Rgba::hex(0x00ff00)), "#00ff00");
|
||||
}
|
||||
|
||||
/// Draws a few frames of the whole window.
|
||||
fn frames(ctx: &egui::Context, app: &mut App) {
|
||||
let screen = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1400.0))), ..Default::default() };
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(screen.clone(), |ui| app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill picker drawn alone for `paint`: what it asked for with no input.
|
||||
fn picker_once(paint: Option<&Paint>, bitmaps: &[(u64, String)]) -> Option<FillEdit> {
|
||||
let ctx = egui::Context::default();
|
||||
let mut edit = Some(FillEdit::None(false));
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| edit = fill_picker(ui, Id::new("test_fill"), paint, bitmaps));
|
||||
out.textures_delta.clear();
|
||||
edit
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_picker_shows_every_kind_of_fill_without_changing_it() {
|
||||
let two = vec![stop(0.0, 0x000000), stop(1.0, 0xffffff)];
|
||||
let bitmaps = vec![(7u64, "tile.png".to_string())];
|
||||
let mut radial = Paint::radial(Vec2::ZERO, 10.0, two.clone());
|
||||
if let Paint::Radial { focal, .. } = &mut radial {
|
||||
*focal = 0.4;
|
||||
}
|
||||
for p in [None, Some(Paint::Solid(Rgba::hex(0x3d8bfd))), Some(Paint::linear(Vec2::ZERO, Vec2::new(10.0, 0.0), two)), Some(radial), Some(Paint::Bitmap { bitmap: anicraft_engine::doc::BitmapId(7), repeat: true, matrix: anicraft_engine::geom::Affine::IDENTITY })] {
|
||||
assert_eq!(picker_once(p.as_ref(), &bitmaps), None, "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edits_from_the_picker_reach_the_swatch_and_the_selection() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(PathBuf::from("unused.png")));
|
||||
app.run("draw.rect", json!({"x": 10, "y": 10, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null}));
|
||||
app.tool = Tool::Select;
|
||||
assert!(matches!(current(&app), (Paint::Solid(_), true)));
|
||||
// A type change is one step on the selection and the swatch.
|
||||
let steps = app.s.history_len();
|
||||
apply_set(&mut app, &FillEdit::Set { label: "Fill", live: false, params: json!({"type": "radial"}) }, true);
|
||||
assert_eq!(app.s.history_len(), steps + 1);
|
||||
assert!(matches!(current(&app).0, Paint::Radial { .. }) && matches!(app.s.style.fill_paint, Some(Paint::Radial { .. })));
|
||||
// A drag of a stop's colour is one step however many frames it takes.
|
||||
let steps = app.s.history_len();
|
||||
for c in ["#112233", "#445566", "#778899"] {
|
||||
let stops = json!([{"offset": 0, "color": c}, {"offset": 1, "color": "#000000"}]);
|
||||
apply_set(&mut app, &FillEdit::Set { label: "Colour stop", live: true, params: json!({"stops": stops}) }, true);
|
||||
}
|
||||
app.s.end_gesture();
|
||||
assert_eq!(app.s.history_len(), steps + 1);
|
||||
// From the tool options: the swatch only.
|
||||
apply_set(&mut app, &FillEdit::Set { label: "Fill", live: false, params: json!({"type": "linear"}) }, false);
|
||||
assert!(matches!(current(&app).0, Paint::Radial { .. }), "the selection keeps its fill");
|
||||
assert!(matches!(app.s.style.fill_paint, Some(Paint::Linear { .. })));
|
||||
// Solid and None are the caller's: apply_set leaves them alone.
|
||||
let before = app.s.doc.clone();
|
||||
apply_set(&mut app, &FillEdit::Solid([1, 2, 3]), true);
|
||||
apply_set(&mut app, &FillEdit::None(true), true);
|
||||
assert!(app.s.doc == before);
|
||||
// The whole window draws with the Tools square's picker open on the selection's gradient,
|
||||
// and on the swatch with a fill tool in hand.
|
||||
app.open_fill_swatch = true;
|
||||
frames(&ctx, &mut app);
|
||||
app.run("edit.deselect", json!({}));
|
||||
app.tool = Tool::PaintBucket;
|
||||
frames(&ctx, &mut app);
|
||||
assert!(!current(&app).1);
|
||||
assert_eq!(stops_json(&[stop(0.0, 0xff0000)])[0]["color"], "#ff0000");
|
||||
assert_eq!(from_bytes(bytes(Rgba::new(1.0, 0.0, 0.0, 0.5))).a, 128.0 / 255.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
//! Gradient Transform tool (F): where a gradient or bitmap fill lies (ADR 0074).
|
||||
//!
|
||||
//! Click a shape with a gradient or bitmap fill to show its handles, drawn as Animate draws
|
||||
//! them on the fill's frame (the box −1..1 mapped onto the fill, `Paint::frame`):
|
||||
//!
|
||||
//! * linear: the two edges of the ramp, the centre (move), a square on the right edge (width
|
||||
//! along the ramp) and a knob on its corner (rotate);
|
||||
//! * radial: the ring, the centre (move), the focal point (a triangle that slides along the
|
||||
//! gradient's axis), a square on the ring (width: an ellipse), a circle below it (size) and a
|
||||
//! knob below that (rotate);
|
||||
//! * bitmap: the box of one copy of the image, the centre, squares for width and height,
|
||||
//! diamonds to skew each way, a circle to scale and a knob to rotate.
|
||||
//!
|
||||
//! Each drag is one undo step: `paint.transform_fill` with the frame worked out from the frame
|
||||
//! the drag started on, so agents and the CLI move fills exactly the same way.
|
||||
|
||||
use crate::app::{App, Drag, Tool};
|
||||
use crate::pathtools::Xf;
|
||||
use crate::theme::T;
|
||||
use anicraft_engine::doc::{Element, ElementId, ElementKind, MAX_FOCAL, Paint};
|
||||
use anicraft_engine::geom::{Affine, Vec2};
|
||||
use egui::{Color32, CursorIcon, Pos2, Stroke as Line, StrokeKind, pos2, vec2};
|
||||
use serde_json::json;
|
||||
|
||||
/// Pick radius for handles, in screen points.
|
||||
const PICK: f32 = 7.0;
|
||||
/// How far round the ring (radians, clockwise on screen) the size and rotate handles sit from
|
||||
/// the width handle on a radial gradient.
|
||||
const SIZE_AT: f32 = 0.45;
|
||||
const TURN_AT: f32 = 0.9;
|
||||
|
||||
/// What a handle does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Grip {
|
||||
Move,
|
||||
Focal,
|
||||
Width,
|
||||
Height,
|
||||
Size,
|
||||
Rotate,
|
||||
SkewX,
|
||||
SkewY,
|
||||
}
|
||||
|
||||
/// The kind of fill the handles are for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
Linear,
|
||||
Radial,
|
||||
Bitmap,
|
||||
}
|
||||
|
||||
/// The fill being edited: a shape on the active layer with a gradient or bitmap fill.
|
||||
struct Target {
|
||||
id: ElementId,
|
||||
kind: Kind,
|
||||
/// The fill's frame in the space being edited.
|
||||
frame: Affine,
|
||||
focal: f32,
|
||||
}
|
||||
|
||||
fn target_of(app: &App, e: &Element) -> Option<Target> {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return None };
|
||||
let (kind, focal) = match sh.fill.as_ref()? {
|
||||
Paint::Linear { .. } => (Kind::Linear, 0.0),
|
||||
Paint::Radial { focal, .. } => (Kind::Radial, *focal),
|
||||
Paint::Bitmap { .. } => (Kind::Bitmap, 0.0),
|
||||
Paint::Solid(_) => return None,
|
||||
};
|
||||
let frame = anicraft_engine::cmds_paint::fill_frame(&app.s.doc, e)?;
|
||||
frame.inverse()?;
|
||||
Some(Target { id: e.id, kind, frame, focal })
|
||||
}
|
||||
|
||||
/// The selected shape whose fill the tool edits (the topmost with a gradient or bitmap).
|
||||
fn target(app: &App) -> Option<Target> {
|
||||
app.s.selected_elements().into_iter().filter(|(l, _)| *l == app.s.layer).rev().find_map(|(_, e)| target_of(app, &e))
|
||||
}
|
||||
|
||||
fn target_by_id(app: &App, id: ElementId) -> Option<Target> {
|
||||
app.s.visible_elements().into_iter().find(|e| e.id == id).and_then(|e| target_of(app, &e))
|
||||
}
|
||||
|
||||
/// Where each handle sits, in the frame's own space.
|
||||
fn handles(t: &Target) -> Vec<(Grip, Vec2)> {
|
||||
let ring = |a: f32| Vec2::new(a.cos(), a.sin());
|
||||
match t.kind {
|
||||
Kind::Linear => vec![(Grip::Move, Vec2::ZERO), (Grip::Width, Vec2::new(1.0, 0.0)), (Grip::Rotate, Vec2::new(1.0, -1.0))],
|
||||
Kind::Radial => vec![(Grip::Move, Vec2::ZERO), (Grip::Focal, Vec2::new(t.focal, 0.0)), (Grip::Width, Vec2::new(1.0, 0.0)), (Grip::Size, ring(SIZE_AT)), (Grip::Rotate, ring(TURN_AT))],
|
||||
Kind::Bitmap => vec![
|
||||
(Grip::Move, Vec2::ZERO),
|
||||
(Grip::Width, Vec2::new(-1.0, 0.0)),
|
||||
(Grip::Height, Vec2::new(0.0, 1.0)),
|
||||
(Grip::SkewX, Vec2::new(0.0, -1.0)),
|
||||
(Grip::SkewY, Vec2::new(1.0, 0.0)),
|
||||
(Grip::Size, Vec2::new(1.0, 1.0)),
|
||||
(Grip::Rotate, Vec2::new(1.0, -1.0)),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle under screen point `at` (the focal point and centre last, so a handle on top of
|
||||
/// them wins only where it is drawn).
|
||||
fn hit(t: &Target, at: Pos2, xf: Xf) -> Option<Grip> {
|
||||
let hs = handles(t);
|
||||
let near = |g: Grip| hs.iter().find(|(h, _)| *h == g).map(|(_, u)| xf.to_screen(t.frame.apply(*u)).distance(at));
|
||||
// The rest before the centre and focal point, which may sit under them.
|
||||
let order = [Grip::Width, Grip::Height, Grip::Size, Grip::Rotate, Grip::SkewX, Grip::SkewY, Grip::Focal, Grip::Move];
|
||||
order.into_iter().filter_map(|g| near(g).map(|d| (g, d))).filter(|(_, d)| *d <= PICK).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(g, _)| g)
|
||||
}
|
||||
|
||||
/// Press with the tool: grab a handle of the selected fill, else select the filled shape under
|
||||
/// the pointer (its handles show), else deselect.
|
||||
pub fn drag_start(app: &mut App, press: Pos2, xf: Xf) -> Drag {
|
||||
if let Some(t) = target(app)
|
||||
&& let Some(grip) = hit(&t, press, xf)
|
||||
{
|
||||
// Undo labels stay English in the history and are translated where they show.
|
||||
app.s.begin_gesture(tr_noop!("Gradient Transform"));
|
||||
let at = xf.to_stage(press);
|
||||
return Drag::Gradient { id: t.id, grip, frame: t.frame, press: pos2(at.x, at.y) };
|
||||
}
|
||||
pick(app, press, xf);
|
||||
Drag::None
|
||||
}
|
||||
|
||||
/// Click (or a press that grabbed nothing): select the filled shape under the pointer.
|
||||
pub fn pick(app: &mut App, at: Pos2, xf: Xf) {
|
||||
let p = xf.to_stage(at);
|
||||
if app.s.hit_test(p, 3.0 * xf.unit()).is_none() {
|
||||
app.run("edit.deselect", json!({}));
|
||||
return;
|
||||
}
|
||||
app.run("element.pick", json!({"x": p.x, "y": p.y}));
|
||||
if target(app).is_none() && !app.s.selection.is_empty() {
|
||||
app.status_ok(tr!("That fill is a solid colour. Click its Fill swatch and choose Linear, Radial or Bitmap to give it a gradient."));
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame a drag of `grip` from frame `f0` (pressed at stage point `p0`) asks for with the
|
||||
/// pointer at stage point `p` (`snap`: Shift, rotation in 15° steps); for the focal point of a
|
||||
/// `radial` gradient, the new focal ratio instead. `None`: nothing to do.
|
||||
pub fn dragged_frame(radial: bool, grip: Grip, f0: &Affine, p0: Vec2, p: Vec2, snap: bool) -> Option<(Affine, Option<f32>)> {
|
||||
let inv = f0.inverse()?;
|
||||
let u = inv.apply(p);
|
||||
let c = f0.apply(Vec2::ZERO);
|
||||
// A scale factor held clear of zero (the frame never collapses), keeping its sign.
|
||||
let factor = |v: f32, h: f32| {
|
||||
let k = if h.abs() > 1e-6 { v / h } else { 1.0 };
|
||||
if k.abs() < 0.02 { 0.02f32.copysign(if k == 0.0 { 1.0 } else { k }) } else { k.clamp(-1e4, 1e4) }
|
||||
};
|
||||
let f = match grip {
|
||||
Grip::Move => Affine::translate(p.x - p0.x, p.y - p0.y).mul(f0),
|
||||
Grip::Focal => return radial.then(|| (*f0, Some(u.x.clamp(-MAX_FOCAL, MAX_FOCAL)))),
|
||||
// Width: along the frame's own x (the linear ramp's length, a radial ring's width; on a
|
||||
// bitmap the handle is on the left).
|
||||
Grip::Width => {
|
||||
let h = inv.apply(p0).x.signum();
|
||||
let h = if h == 0.0 { 1.0 } else { h };
|
||||
f0.mul(&Affine::scale(factor(u.x, h), 1.0))
|
||||
}
|
||||
Grip::Height => f0.mul(&Affine::scale(1.0, factor(u.y, 1.0))),
|
||||
Grip::Size => {
|
||||
let u0 = inv.apply(p0);
|
||||
let k = factor(u.length(), u0.length().max(1e-3)).abs();
|
||||
f0.mul(&Affine::scale(k, k))
|
||||
}
|
||||
Grip::Rotate => {
|
||||
let (a, b) = (p0 - c, p - c);
|
||||
let mut turn = a.cross(b).atan2(a.dot(b));
|
||||
if snap {
|
||||
let step = 15f32.to_radians();
|
||||
turn = (turn / step).round() * step;
|
||||
}
|
||||
Affine::translate(c.x, c.y).mul(&Affine::rotate(turn)).mul(&Affine::translate(-c.x, -c.y)).mul(f0)
|
||||
}
|
||||
// Skew: the top edge slides along x, the right edge along y (in the frame's own axes).
|
||||
Grip::SkewX => f0.mul(&Affine { m: [1.0, 0.0, (-u.x).clamp(-10.0, 10.0), 1.0, 0.0, 0.0] }),
|
||||
Grip::SkewY => f0.mul(&Affine { m: [1.0, u.y.clamp(-10.0, 10.0), 0.0, 1.0, 0.0, 0.0] }),
|
||||
};
|
||||
(f.is_finite() && f.determinant().abs() > 1e-6).then_some((f, None))
|
||||
}
|
||||
|
||||
/// Pointer at stage point `at` while dragging: the fill follows, inside the drag's gesture.
|
||||
pub fn drag_to(app: &mut App, d: Drag, at: Vec2, shift: bool) {
|
||||
let Drag::Gradient { id, grip, frame, press } = d else { return };
|
||||
let Some(t) = target_by_id(app, id) else { return };
|
||||
let Some((f, focal)) = dragged_frame(t.kind == Kind::Radial, grip, &frame, Vec2::new(press.x, press.y), at, shift) else { return };
|
||||
let p = match focal {
|
||||
Some(v) => json!({"element": id.0, "focal": v}),
|
||||
None => json!({"element": id.0, "frame": f.m}),
|
||||
};
|
||||
let _ = app.s.execute("paint.transform_fill", &p);
|
||||
}
|
||||
|
||||
pub fn drag_end(app: &mut App) {
|
||||
app.s.end_gesture();
|
||||
app.status_ok(tr!("Transformed the fill. {undo} to undo.", undo = app.undo_key()));
|
||||
}
|
||||
|
||||
/// The cursor while hovering.
|
||||
pub fn cursor(app: &App, at: Option<Pos2>, xf: Xf) -> CursorIcon {
|
||||
let grip = match app.drag {
|
||||
Drag::Gradient { grip, .. } => Some(grip),
|
||||
_ => at.and_then(|p| target(app).and_then(|t| hit(&t, p, xf))),
|
||||
};
|
||||
match grip {
|
||||
Some(Grip::Move | Grip::Focal) => CursorIcon::Move,
|
||||
Some(Grip::Rotate) => CursorIcon::Alias,
|
||||
Some(Grip::Width | Grip::SkewY) => CursorIcon::ResizeHorizontal,
|
||||
Some(Grip::Height | Grip::SkewX) => CursorIcon::ResizeVertical,
|
||||
Some(Grip::Size) => CursorIcon::ResizeNwSe,
|
||||
None => CursorIcon::Default,
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool's overlay: the selected fill's frame and handles, the hovered one highlighted.
|
||||
pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Pos2>) {
|
||||
if app.tool != Tool::GradientTransform {
|
||||
return;
|
||||
}
|
||||
let t = match app.drag {
|
||||
Drag::Gradient { id, .. } => target_by_id(app, id),
|
||||
_ => target(app),
|
||||
};
|
||||
let Some(t) = t else { return };
|
||||
let to_px = |u: Vec2| xf.to_screen(t.frame.apply(u));
|
||||
let line = Line::new(1.0, T.selection);
|
||||
let faint = Line::new(1.0, T.selection.gamma_multiply(0.7));
|
||||
match t.kind {
|
||||
Kind::Linear => {
|
||||
// The two edges of the ramp, across the shape.
|
||||
for x in [-1.0, 1.0] {
|
||||
painter.line_segment([to_px(Vec2::new(x, -1.0)), to_px(Vec2::new(x, 1.0))], line);
|
||||
}
|
||||
painter.add(egui::Shape::dashed_line(&[to_px(Vec2::new(-1.0, 0.0)), to_px(Vec2::new(1.0, 0.0))], faint, 4.0, 3.0));
|
||||
}
|
||||
Kind::Radial => {
|
||||
let ring: Vec<Pos2> = (0..96).map(|k| to_px(Vec2::new((k as f32 / 96.0 * std::f32::consts::TAU).cos(), (k as f32 / 96.0 * std::f32::consts::TAU).sin()))).collect();
|
||||
painter.add(egui::Shape::closed_line(ring, line));
|
||||
painter.add(egui::Shape::dashed_line(&[to_px(Vec2::ZERO), to_px(Vec2::new(1.0, 0.0))], faint, 4.0, 3.0));
|
||||
}
|
||||
Kind::Bitmap => {
|
||||
let corners = [Vec2::new(-1.0, -1.0), Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, 1.0), Vec2::new(-1.0, -1.0)].map(to_px);
|
||||
painter.add(egui::Shape::dashed_line(&corners, line, 5.0, 3.0));
|
||||
}
|
||||
}
|
||||
let hot = match app.drag {
|
||||
Drag::Gradient { grip, .. } => Some(grip),
|
||||
_ => hover.and_then(|p| hit(&t, p, xf)),
|
||||
};
|
||||
for (g, u) in handles(&t) {
|
||||
let c = to_px(u);
|
||||
let fill = if hot == Some(g) { T.selection } else { Color32::WHITE };
|
||||
let edge = Line::new(1.0, T.selection);
|
||||
match g {
|
||||
Grip::Move => {
|
||||
painter.circle(c, 4.5, fill, edge);
|
||||
}
|
||||
Grip::Focal => {
|
||||
// An inverted triangle, as Animate marks the focal point.
|
||||
let pts = vec![c + vec2(-5.0, -4.0), c + vec2(5.0, -4.0), c + vec2(0.0, 4.5)];
|
||||
painter.add(egui::Shape::convex_polygon(pts, fill, edge));
|
||||
}
|
||||
Grip::Width | Grip::Height => {
|
||||
painter.rect(egui::Rect::from_center_size(c, vec2(8.0, 8.0)), 0.0, fill, edge, StrokeKind::Middle);
|
||||
}
|
||||
Grip::SkewX | Grip::SkewY => {
|
||||
let pts = vec![c + vec2(0.0, -5.0), c + vec2(5.0, 0.0), c + vec2(0.0, 5.0), c + vec2(-5.0, 0.0)];
|
||||
painter.add(egui::Shape::convex_polygon(pts, fill, edge));
|
||||
}
|
||||
Grip::Size => {
|
||||
painter.circle(c, 4.5, fill, edge);
|
||||
painter.circle_stroke(c, 1.5, edge);
|
||||
}
|
||||
Grip::Rotate => {
|
||||
// A knob joined to where it turns from.
|
||||
painter.circle(c, 5.0, fill, edge);
|
||||
painter.circle_filled(c, 1.5, T.selection);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn near(a: &Affine, b: &Affine) -> bool {
|
||||
a.m.iter().zip(b.m).all(|(x, y)| (x - y).abs() < 1e-3)
|
||||
}
|
||||
|
||||
fn frames(ctx: &egui::Context, app: &mut App) {
|
||||
let screen = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 1000.0))), ..Default::default() };
|
||||
for _ in 0..2 {
|
||||
let mut out = ctx.run_ui(screen.clone(), |ui| app.frame(ui));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_drag_on_a_handle_is_one_undo_step_on_every_kind_of_fill() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = App::with_context(&ctx, anicraft_engine::Session::default(), Some(std::path::PathBuf::from("unused.png")));
|
||||
let xf = Xf { origin: pos2(0.0, 0.0), zoom: 1.0 };
|
||||
app.tool = Tool::GradientTransform;
|
||||
// A solid fill has no handles: picking it says how to get a gradient.
|
||||
app.run("draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
pick(&mut app, pos2(150.0, 150.0), xf);
|
||||
assert!(target(&app).is_none());
|
||||
let png = anicraft_engine::render::encode_png(4, 2, &[200; 32]).unwrap_or_default();
|
||||
let id = app.s.doc.alloc_id();
|
||||
app.s.doc.bitmaps.push(std::sync::Arc::new(anicraft_engine::doc::Bitmap::from_png(anicraft_engine::doc::BitmapId(id), "tile.png", png).unwrap()));
|
||||
for (kind, extra) in [("linear", json!({})), ("radial", json!({"focal": 0.3})), ("bitmap", json!({"bitmap": id}))] {
|
||||
let mut p = json!({"type": kind});
|
||||
if let (Some(o), Some(e)) = (p.as_object_mut(), extra.as_object()) {
|
||||
o.extend(e.clone());
|
||||
}
|
||||
app.run("paint.set_fill", p);
|
||||
frames(&ctx, &mut app);
|
||||
let t = target(&app).expect("a gradient or bitmap to transform");
|
||||
// Every handle shows, with a cursor that says what it does.
|
||||
for (g, u) in handles(&t) {
|
||||
let at = xf.to_screen(t.frame.apply(u));
|
||||
assert_eq!(hit(&t, at, xf), Some(g), "{kind} {g:?}");
|
||||
assert_ne!(cursor(&app, Some(at), xf), CursorIcon::Default);
|
||||
}
|
||||
// Grab the width handle and pull it out: the fill widens, in one step.
|
||||
let (_, w) = handles(&t).into_iter().find(|(g, _)| *g == Grip::Width).expect("a width handle");
|
||||
let press = xf.to_screen(t.frame.apply(w));
|
||||
let steps = app.s.history_len();
|
||||
let d = drag_start(&mut app, press, xf);
|
||||
assert!(matches!(d, Drag::Gradient { grip: Grip::Width, .. }), "{kind}: {d:?}");
|
||||
app.drag = d;
|
||||
frames(&ctx, &mut app);
|
||||
for k in 1..=3 {
|
||||
let to = t.frame.apply(w * (1.0 + 0.2 * k as f32));
|
||||
drag_to(&mut app, d, to, false);
|
||||
}
|
||||
assert_eq!(cursor(&app, None, xf), CursorIcon::ResizeHorizontal);
|
||||
app.drag = Drag::None;
|
||||
drag_end(&mut app);
|
||||
assert_eq!(app.s.history_len(), steps + 1, "{kind}: one step");
|
||||
let after = target(&app).expect("still a fill");
|
||||
let len = |f: &Affine| Vec2::new(f.m[0], f.m[1]).length();
|
||||
assert!((len(&after.frame) / len(&t.frame) - 1.6).abs() < 1e-3, "{kind}: {:?}", after.frame);
|
||||
}
|
||||
// The focal point slides along the radial gradient's axis.
|
||||
app.run("paint.set_fill", json!({"type": "radial", "focal": 0.0}));
|
||||
let t = target(&app).expect("radial");
|
||||
let press = xf.to_screen(t.frame.apply(Vec2::ZERO));
|
||||
let d = Drag::Gradient { id: t.id, grip: Grip::Focal, frame: t.frame, press: pos2(press.x, press.y) };
|
||||
drag_to(&mut app, d, t.frame.apply(Vec2::new(0.5, 0.4)), false);
|
||||
assert!((target(&app).expect("radial").focal - 0.5).abs() < 1e-4);
|
||||
// A press away from any handle selects what is under it; on nothing, deselects.
|
||||
assert_eq!(drag_start(&mut app, pos2(5.0, 5.0), xf), Drag::None);
|
||||
assert!(app.s.selection.is_empty());
|
||||
frames(&ctx, &mut app);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_drags_make_the_frames_animate_does() {
|
||||
// A ring of radius 50 round (100, 100).
|
||||
let f0 = Affine { m: [50.0, 0.0, 0.0, 50.0, 100.0, 100.0] };
|
||||
let at = |x: f32, y: f32| Vec2::new(x, y);
|
||||
// Move: by the pointer's travel.
|
||||
let (f, _) = dragged_frame(true, Grip::Move, &f0, at(100.0, 100.0), at(130.0, 90.0), false).unwrap();
|
||||
assert!(near(&f, &Affine { m: [50.0, 0.0, 0.0, 50.0, 130.0, 90.0] }));
|
||||
// Width: the ring's x radius follows the pointer, its height stays.
|
||||
let (f, _) = dragged_frame(true, Grip::Width, &f0, at(150.0, 100.0), at(200.0, 100.0), false).unwrap();
|
||||
assert!(near(&f, &Affine { m: [100.0, 0.0, 0.0, 50.0, 100.0, 100.0] }));
|
||||
// Size: both, by the distance from the centre.
|
||||
let (f, _) = dragged_frame(true, Grip::Size, &f0, at(150.0, 100.0), at(125.0, 100.0), false).unwrap();
|
||||
assert!(near(&f, &Affine { m: [25.0, 0.0, 0.0, 25.0, 100.0, 100.0] }));
|
||||
// Rotate: a quarter turn about the centre (Shift snaps 80° to 75°).
|
||||
let (f, _) = dragged_frame(true, Grip::Rotate, &f0, at(150.0, 100.0), at(100.0, 150.0), false).unwrap();
|
||||
assert!(near(&f, &Affine { m: [0.0, 50.0, -50.0, 0.0, 100.0, 100.0] }), "{f:?}");
|
||||
let a = 80f32.to_radians();
|
||||
let (f, _) = dragged_frame(true, Grip::Rotate, &f0, at(150.0, 100.0), at(100.0 + 50.0 * a.cos(), 100.0 + 50.0 * a.sin()), true).unwrap();
|
||||
assert!((f.m[1].atan2(f.m[0]).to_degrees() - 75.0).abs() < 1e-3);
|
||||
// Focal point: along the axis only, held inside the ring.
|
||||
let (f, focal) = dragged_frame(true, Grip::Focal, &f0, at(100.0, 100.0), at(125.0, 140.0), false).unwrap();
|
||||
assert!(near(&f, &f0));
|
||||
assert_eq!(focal, Some(0.5));
|
||||
assert_eq!(dragged_frame(true, Grip::Focal, &f0, at(100.0, 100.0), at(400.0, 100.0), false).unwrap().1, Some(MAX_FOCAL));
|
||||
assert!(dragged_frame(false, Grip::Focal, &f0, at(100.0, 100.0), at(120.0, 100.0), false).is_none(), "no focal point on a linear gradient");
|
||||
// Skews slide the top edge along x and the right edge along y.
|
||||
let (f, _) = dragged_frame(false, Grip::SkewX, &f0, at(100.0, 50.0), at(125.0, 50.0), false).unwrap();
|
||||
assert!(f.apply(Vec2::new(0.0, -1.0)).distance(at(125.0, 50.0)) < 1e-3);
|
||||
let (f, _) = dragged_frame(false, Grip::SkewY, &f0, at(150.0, 100.0), at(150.0, 80.0), false).unwrap();
|
||||
assert!(f.apply(Vec2::new(1.0, 0.0)).distance(at(150.0, 80.0)) < 1e-3);
|
||||
// Dragging a width handle onto the centre never collapses the frame.
|
||||
let (f, _) = dragged_frame(true, Grip::Width, &f0, at(150.0, 100.0), at(100.0, 100.0), false).unwrap();
|
||||
assert!(f.determinant().abs() > 1e-6);
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -63,6 +63,7 @@ pub enum Icon {
|
||||
Image,
|
||||
Type,
|
||||
Width,
|
||||
GradientTransform,
|
||||
Sound,
|
||||
SoundOff,
|
||||
Camera,
|
||||
@@ -79,7 +80,7 @@ pub enum Icon {
|
||||
|
||||
impl Icon {
|
||||
#[cfg(test)]
|
||||
pub const ALL: [Icon; 61] = [
|
||||
pub const ALL: [Icon; 62] = [
|
||||
Icon::ClipStage,
|
||||
Icon::InsertFrame,
|
||||
Icon::InsertKeyframe,
|
||||
@@ -92,6 +93,7 @@ impl Icon {
|
||||
Icon::SoundOff,
|
||||
Icon::Camera,
|
||||
Icon::Width,
|
||||
Icon::GradientTransform,
|
||||
Icon::Sound,
|
||||
Icon::Guide,
|
||||
Icon::Image,
|
||||
@@ -158,6 +160,8 @@ impl Icon {
|
||||
Icon::Transform => ("scaling", false),
|
||||
// A stroke swelling and tapering, with a width point across it (AniCraft original).
|
||||
Icon::Width => ("anicraft-width", false),
|
||||
// A box of gradient bands with a turning knob on its corner (AniCraft original).
|
||||
Icon::GradientTransform => ("anicraft-gradient-transform", false),
|
||||
Icon::Pen => ("pen-tool", false),
|
||||
Icon::Pencil => ("pencil", false),
|
||||
// A round brush: handle, ferrule and a painted tip (AniCraft original, on Lucide's grid).
|
||||
@@ -284,6 +288,7 @@ static FILES: &[(&str, &str)] = &[
|
||||
("anicraft-distribute-v", include_str!("../assets/icons/anicraft-distribute-v.svg")),
|
||||
("anicraft-mask", include_str!("../assets/icons/anicraft-mask.svg")),
|
||||
("anicraft-width", include_str!("../assets/icons/anicraft-width.svg")),
|
||||
("anicraft-gradient-transform", include_str!("../assets/icons/anicraft-gradient-transform.svg")),
|
||||
("anicraft-brush", include_str!("../assets/icons/anicraft-brush.svg")),
|
||||
("anicraft-eraser", include_str!("../assets/icons/anicraft-eraser.svg")),
|
||||
("anicraft-paint-brush", include_str!("../assets/icons/anicraft-paint-brush.svg")),
|
||||
|
||||
@@ -48,6 +48,7 @@ pub fn tool_id(t: Tool) -> &'static str {
|
||||
Tool::Select => "tool.selection",
|
||||
Tool::Subselect => "tool.subselection",
|
||||
Tool::Transform => "tool.free_transform",
|
||||
Tool::GradientTransform => "tool.gradient_transform",
|
||||
Tool::Width => "tool.width",
|
||||
Tool::Pen => "tool.pen",
|
||||
Tool::Text => "tool.text",
|
||||
|
||||
+3
-1
@@ -28,6 +28,7 @@ mod autosave;
|
||||
mod brush_panel;
|
||||
mod brushtool;
|
||||
mod colour;
|
||||
mod colour_panel;
|
||||
mod envelope;
|
||||
mod find_panel;
|
||||
mod publish_panel;
|
||||
@@ -42,6 +43,7 @@ mod dock;
|
||||
mod dock_ui;
|
||||
mod drop;
|
||||
mod gpu_stage;
|
||||
mod gradient_tool;
|
||||
mod icons;
|
||||
mod keymap;
|
||||
mod library;
|
||||
@@ -247,7 +249,7 @@ fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
|
||||
/// `--help` (the console's text, in English).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
// i18n-exempt: the --help console text
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme dark|light|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer]\n\
|
||||
const HELP: &str = "anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png [--shot-width <px>]] [--renderer gl|wgpu|vulkan|dx12|metal] [--theme dark|light|high-contrast] [--scale <percent>] [--lang <code>|auto|pseudo] [--open palette|shortcuts|lastscene|start|drop|droplibrary|select|selectzoom|about|files|confirm|transform|points|merge|rawparts|rawedit|rawsub|rawpoints|rawsnap|symboledit|groups|combine|nineslice|nineslicedit|brush|brushing|brushlibrary|brushcurve|paintbrush|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|motionedit|motionpins|motionpinsspan|hints|hintsend|camera|cameraview|filters|strokes|prefs|licenses|zoom|recovery|plugins|actions|script|scriptproblems|testmovie|testmovieinside|testscript|textfields|testtext|softmask|pathtext|button|testhits|exporthtml|publish|publishreport|publishanim|sound|envelope|library|librarymenu|colour|layerprops|frameview|layercolour|timelinepolish|dock|animator|designer|gradient|gradientbucket]\n\
|
||||
--renderer the window's graphics (also ANICRAFT_RENDERER); default automatic, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
--shot-width scales the screenshot down to this width (the user guide's pictures)\n\
|
||||
|
||||
+83
-21
@@ -16,6 +16,7 @@ fn tool_icon(tool: Tool) -> Icon {
|
||||
Tool::Select => Icon::Select,
|
||||
Tool::Subselect => Icon::Subselect,
|
||||
Tool::Transform => Icon::Transform,
|
||||
Tool::GradientTransform => Icon::GradientTransform,
|
||||
Tool::Width => Icon::Width,
|
||||
Tool::Pen => Icon::Pen,
|
||||
Tool::Text => Icon::Type,
|
||||
@@ -139,7 +140,32 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) {
|
||||
if fill && std::mem::take(&mut app.open_fill_swatch) {
|
||||
egui::Popup::open_id(ui.ctx(), resp.id.with("colour_popup"));
|
||||
}
|
||||
if crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, false, Some(&mut none)) {
|
||||
// The fill opens the one colour picker with the fill's type on top (ADR 0074): what the
|
||||
// selection is filled with, else the swatch. Solid colours and None go on as below.
|
||||
let picked = if fill {
|
||||
let (paint, selected) = crate::colour_panel::current(app);
|
||||
let shown = (selected || st.use_fill).then_some(paint);
|
||||
match crate::colour_panel::popup_for(ui, &resp, resp.id.with("colour_popup"), shown.as_ref(), &crate::colour_panel::bitmaps(app)) {
|
||||
Some(crate::colour_panel::FillEdit::Solid(p)) => {
|
||||
c = [p[0], p[1], p[2], 255];
|
||||
none = false;
|
||||
true
|
||||
}
|
||||
Some(crate::colour_panel::FillEdit::None(n)) => {
|
||||
none = n;
|
||||
true
|
||||
}
|
||||
Some(edit) => {
|
||||
app.s.style.use_fill = true;
|
||||
crate::colour_panel::apply_set(app, &edit, true);
|
||||
false
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
} else {
|
||||
crate::colour::popup_for(ui, &resp, resp.id.with("colour_popup"), &mut c, false, Some(&mut none))
|
||||
};
|
||||
if picked {
|
||||
// No Colour toggled says which; a colour picked turns the colour back on.
|
||||
let none = none != was && none;
|
||||
let pick = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0);
|
||||
@@ -166,6 +192,16 @@ fn tool_swatches(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a gradient or bitmap fill is, for the caption beside its swatch (nothing for a colour).
|
||||
fn fill_kind_label(p: Option<&Paint>) -> Option<&'static str> {
|
||||
match p? {
|
||||
Paint::Linear { .. } => Some(tr!("Linear gradient")),
|
||||
Paint::Radial { .. } => Some(tr!("Radial gradient")),
|
||||
Paint::Bitmap { .. } => Some(tr!("Bitmap fill")),
|
||||
Paint::Solid(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rgba(c: Rgba) -> [u8; 4] {
|
||||
let [r, g, b] = rgb(c);
|
||||
[r, g, b, 255]
|
||||
@@ -866,18 +902,27 @@ fn selection_props(app: &mut App, ui: &mut egui::Ui, e: &anicraft_engine::doc::E
|
||||
if let ElementKind::Shape(sh) = &e.kind {
|
||||
ui.add_space(4.0);
|
||||
let fill = sh.fill.as_ref().map(Paint::primary_color);
|
||||
let bitmaps = crate::colour_panel::bitmaps(app);
|
||||
row(ui, tr!("Fill"), |ui| {
|
||||
let is_grad = matches!(sh.fill, Some(Paint::Linear { .. } | Paint::Radial { .. }));
|
||||
let mut c = rgb(fill.unwrap_or(Rgba::WHITE));
|
||||
if crate::colour::button(ui, &mut c).named(tr!("Fill colour")).changed() {
|
||||
live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(c)}));
|
||||
let c = rgb(fill.unwrap_or(Rgba::WHITE));
|
||||
// The one colour picker, with the fill's type (ADR 0074): a gradient shows as its
|
||||
// ramp here and is edited in the picker.
|
||||
let (r, edit) = crate::colour_panel::swatch(ui, sh.fill.as_ref(), &bitmaps);
|
||||
r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill"));
|
||||
match edit {
|
||||
Some(crate::colour_panel::FillEdit::Solid(p)) => live(app, tr_noop!("Fill colour"), "element.set_fill", json!({"color": hex(p)})),
|
||||
Some(crate::colour_panel::FillEdit::None(n)) => {
|
||||
app.run("element.set_fill", if n { json!({"color": null}) } else { json!({"color": hex(c)}) });
|
||||
}
|
||||
Some(edit) => crate::colour_panel::apply_set(app, &edit, true),
|
||||
None => {}
|
||||
}
|
||||
let mut on = fill.is_some();
|
||||
if crate::theme::checkbox(ui, &mut on, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off")).changed() {
|
||||
app.run("element.set_fill", if on { json!({"color": hex(c)}) } else { json!({"color": null}) });
|
||||
}
|
||||
if is_grad {
|
||||
ui.label(text(Type::Caption, tr!("gradient")));
|
||||
if let Some(what) = fill_kind_label(sh.fill.as_ref()) {
|
||||
ui.label(text(Type::Caption, what));
|
||||
}
|
||||
mixed(ui, m.fill);
|
||||
});
|
||||
@@ -1295,7 +1340,7 @@ fn side_rows(ui: &mut egui::Ui, fname: &str, side: &mut anicraft_engine::doc::Fi
|
||||
}
|
||||
|
||||
/// A colour swatch with opacity (Animate's bevel colours carry alpha). True when changed.
|
||||
fn alpha_swatch(ui: &mut egui::Ui, c: &mut Rgba, name: &str) -> bool {
|
||||
pub(crate) fn alpha_swatch(ui: &mut egui::Ui, c: &mut Rgba, name: &str) -> bool {
|
||||
let s = c.sanitized();
|
||||
let b = |v: f32| (v * 255.0).round() as u8;
|
||||
let mut px = [b(s.r), b(s.g), b(s.b), b(s.a)];
|
||||
@@ -1970,26 +2015,36 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
let (fills, ink) = (matches!(app.tool, Tool::PaintBucket | Tool::Brush), stroke_only(app.tool));
|
||||
let brush_line = app.tool == Tool::PaintBrush;
|
||||
if !ink {
|
||||
let bitmaps = crate::colour_panel::bitmaps(app);
|
||||
let mut set = None;
|
||||
row(ui, tr!("Fill"), |ui| {
|
||||
let mut c = rgb(st.fill);
|
||||
if crate::colour::button(ui, &mut c).named(tr!("Fill colour")).changed() {
|
||||
st.set_fill_color(Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0));
|
||||
// The fill swatch: what new shapes, the Paint Bucket and the Brush pour, in the one
|
||||
// colour picker with the fill's type (ADR 0074).
|
||||
let paint = st.fill_paint();
|
||||
let (r, edit) = crate::colour_panel::swatch(ui, (st.use_fill || fills).then_some(&paint), &bitmaps);
|
||||
r.named(tr!("Fill colour")).on_hover_text(tr!("Fill: click for its colour, or a gradient or bitmap fill"));
|
||||
match edit {
|
||||
Some(crate::colour_panel::FillEdit::Solid(p)) => {
|
||||
st.set_fill_color(Rgba::new(f32::from(p[0]) / 255.0, f32::from(p[1]) / 255.0, f32::from(p[2]) / 255.0, 1.0));
|
||||
st.use_fill = true;
|
||||
}
|
||||
Some(crate::colour_panel::FillEdit::None(n)) => st.use_fill = !n || fills,
|
||||
other => set = other,
|
||||
}
|
||||
// A gradient or bitmap picked with the Eyedropper (ADR 0034): the swatch shows its
|
||||
// first colour, and says what it holds.
|
||||
if let Some(p) = &st.fill_paint {
|
||||
let what = match p {
|
||||
Paint::Linear { .. } => tr!("Linear gradient"),
|
||||
Paint::Radial { .. } => tr!("Radial gradient"),
|
||||
Paint::Bitmap { .. } => tr!("Bitmap fill"),
|
||||
Paint::Solid(_) => tr!("Solid"),
|
||||
};
|
||||
ui.label(text(Type::Caption, what)).on_hover_text(tr!("Picked with the Eyedropper. It stays where it was on the stage (lock fill). Pick a colour to fill with a solid colour again."));
|
||||
if let Some(what) = fill_kind_label(st.fill_paint.as_ref()) {
|
||||
ui.label(text(Type::Caption, what)).on_hover_text(tr!("Set in the colour picker or picked with the Eyedropper. Choose Solid in the picker to fill with a colour again."));
|
||||
}
|
||||
if !fills {
|
||||
crate::theme::checkbox(ui, &mut st.use_fill, "").named(tr!("Fill")).on_hover_text(tr!("Fill on/off"));
|
||||
}
|
||||
});
|
||||
// A type, stops or bitmap: the swatch through the command (the rest of the options go
|
||||
// on from what it set).
|
||||
if let Some(edit) = set {
|
||||
app.s.style = st;
|
||||
crate::colour_panel::apply_set(app, &edit, false);
|
||||
st = app.s.style.clone();
|
||||
}
|
||||
}
|
||||
if !fills {
|
||||
row(ui, tr!("Stroke"), |ui| {
|
||||
@@ -2018,6 +2073,13 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
st.line = line;
|
||||
}
|
||||
}
|
||||
// Lock Fill (ADR 0074): a gradient or bitmap runs on across shapes instead of being fitted
|
||||
// to each one. The Eyedropper turns it on for what it picks, as in Animate.
|
||||
if matches!(app.tool, Tool::PaintBucket | Tool::Brush) {
|
||||
row_prose(ui, tr!("Lock fill"), |ui| {
|
||||
crate::theme::checkbox(ui, &mut st.lock_fill, "").named(tr!("Lock fill")).on_hover_text(tr!("On: a gradient or bitmap is poured where it lies on the stage, so it runs on across shapes. Off: each shape gets it fitted to its own bounds."));
|
||||
});
|
||||
}
|
||||
// Merge drawing (ADR 0031) or drawing objects, for the tools that draw shapes.
|
||||
if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::PaintBrush) {
|
||||
let key = anicraft_engine::find_command("draw.object_drawing").and_then(|c| c.shortcut).map(crate::platform::shortcut_label).unwrap_or_default();
|
||||
|
||||
+12
-2
@@ -359,6 +359,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
_ if mp_hot.is_some() => CursorIcon::Grab,
|
||||
_ if pen_hot.is_some() => CursorIcon::Copy,
|
||||
Tool::Width => crate::widthtool::cursor(app, pointer, xf),
|
||||
Tool::GradientTransform => crate::gradient_tool::cursor(app, pointer, xf),
|
||||
Tool::Transform => {
|
||||
let zone = match app.drag {
|
||||
Drag::Transform { kind, .. } | Drag::MultiTransform { kind, .. } => Some(kind),
|
||||
@@ -453,6 +454,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Tool::Bone => crate::bone_tool::drag_start(app, xf, press),
|
||||
Tool::Bind => crate::bind_tool::drag_start(app, xf, press),
|
||||
Tool::Width => crate::widthtool::drag_start(app, press, xf),
|
||||
Tool::GradientTransform => crate::gradient_tool::drag_start(app, press, xf),
|
||||
Tool::Pencil => {
|
||||
app.pencil = vec![to_v(sp)];
|
||||
Drag::Pencil
|
||||
@@ -594,6 +596,10 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
let d = *d;
|
||||
crate::widthtool::drag_to(app, d, to_v(c), alt, zoom);
|
||||
}
|
||||
(d @ Drag::Gradient { .. }, Some(c)) => {
|
||||
let d = *d;
|
||||
crate::gradient_tool::drag_to(app, d, to_v(c), shift);
|
||||
}
|
||||
(Drag::Pencil, Some(c)) => crate::pathtools::pencil_sample(app, to_v(c), xf),
|
||||
(Drag::Brush, Some(c)) => crate::brushtool::sample(app, to_v(c), pressure, xf, now),
|
||||
(Drag::Eraser, Some(c)) => crate::brushtool::sample(app, to_v(c), None, xf, now),
|
||||
@@ -613,6 +619,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Drag::Transform { .. } | Drag::SliceGuide { .. } | Drag::Points { .. } | Drag::Hint { .. } | Drag::MotionMove { .. } | Drag::CameraPan { .. } | Drag::CameraRotate { .. } | Drag::BonePose { .. } | Drag::ArmatureMove { .. } => app.s.end_gesture(),
|
||||
Drag::Bone { from, head, cur } => crate::bone_tool::drag_end(app, xf, from, head, cur),
|
||||
Drag::Width { .. } => crate::widthtool::drag_end(app),
|
||||
Drag::Gradient { .. } => crate::gradient_tool::drag_end(app),
|
||||
Drag::MotionPath { .. } => crate::motion_path::drag_end(app),
|
||||
Drag::PointMarquee { start, cur } => crate::pathtools::marquee_points(app, start, cur, shift),
|
||||
Drag::BindMarquee { start, cur } => crate::bind_tool::drag_end(app, start, cur, shift, command),
|
||||
@@ -656,6 +663,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
Tool::Width if !panning => crate::widthtool::click(app, p, xf),
|
||||
Tool::GradientTransform if !panning => crate::gradient_tool::pick(app, p, xf),
|
||||
Tool::PaintBucket if !panning => {
|
||||
// The gap size is set in screen points, so it feels the same at any zoom.
|
||||
let gap = app.bucket_gap.screen_px() / zoom.max(1e-3);
|
||||
@@ -1032,8 +1040,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
continue;
|
||||
}
|
||||
let r = Rect::from_min_max(to_screen(b.min), to_screen(b.max)).expand(1.0);
|
||||
if matches!(app.tool, Tool::Subselect | Tool::Width) {
|
||||
// Subselection and Width show outlines and points instead (below).
|
||||
if matches!(app.tool, Tool::Subselect | Tool::Width | Tool::GradientTransform) {
|
||||
// Subselection and Width show outlines and points instead (below); Gradient
|
||||
// Transform shows the fill's handles (ADR 0074).
|
||||
continue;
|
||||
}
|
||||
if app.tool == Tool::Select && raw.contains(&(layer, id)) {
|
||||
@@ -1080,6 +1089,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
crate::pathtools::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));
|
||||
crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));
|
||||
crate::gradient_tool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning));
|
||||
crate::brushtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused));
|
||||
crate::erasertool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused));
|
||||
// After this frame's edits, so a drag on the path shows where it is now.
|
||||
|
||||
Reference in new issue
Block a user