Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Shapes: rounded corners on live triangles, polygons and stars (TOOL-214-12)

bazmarth8744820a279f
diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs
index f36df185a..6ccac6074 100644
--- a/crates/doc/src/vector.rs
+++ b/crates/doc/src/vector.rs
@@ -302,10 +302,14 @@ pub enum LiveShape {
rect: [f64; 4],
},
/// Regular polygon or star inscribed in `rect`; `star_ratio` = inner/outer radius (1 = polygon).
+ /// `corner_radius` rounds every vertex (0 = sharp), each within what its edges allow; the
+ /// Triangle tool draws a 3-sided one.
Polygon {
rect: [f64; 4],
sides: u32,
star_ratio: f64,
+ #[serde(default)]
+ corner_radius: f64,
},
/// Line from `from` to `to` drawn as a filled bar `weight` px thick.
Line {
@@ -352,6 +356,15 @@ mod tests {
assert_eq!(t.control_bounds(), Some((2.0, 3.0, 6.0, 10.0)));
}
+ #[test]
+ fn a_polygon_saved_before_corner_radii_loads_sharp() {
+ let old = r#"{"kind":"polygon","rect":[0.0,0.0,10.0,10.0],"sides":3,"star_ratio":1.0}"#;
+ let back: LiveShape = serde_json::from_str(old).unwrap();
+ assert_eq!(back, LiveShape::Polygon { rect: [0.0, 0.0, 10.0, 10.0], sides: 3, star_ratio: 1.0, corner_radius: 0.0 });
+ let round = LiveShape::Polygon { rect: [0.0; 4], sides: 6, star_ratio: 1.0, corner_radius: 4.5 };
+ assert_eq!(serde_json::from_str::<LiveShape>(&serde_json::to_string(&round).unwrap()).unwrap(), round);
+ }
+
#[test]
fn serde_roundtrip() {
let p = Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (3.0, 4.0)]).with_op(PathOp::Exclude)]);
diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rs
index 14579e595..77849f737 100644
--- a/crates/engine/src/vector_cmds.rs
+++ b/crates/engine/src/vector_cmds.rs
@@ -412,13 +412,19 @@ fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&LiveShape>)
}
"ellipse" => LiveShape::Ellipse { rect: rect()? },
"polygon" | "star" => {
- let (ps, pr) = match prev {
- Some(LiveShape::Polygon { sides, star_ratio, .. }) => (*sides, *star_ratio),
- _ => (5, if kind == "star" { 0.5 } else { 1.0 }),
+ let (ps, pr, pc) = match prev {
+ Some(LiveShape::Polygon { sides, star_ratio, corner_radius, .. }) => (*sides, *star_ratio, *corner_radius),
+ _ => (5, if kind == "star" { 0.5 } else { 1.0 }, 0.0),
};
+ let corner_radius = f64p(p, "cornerRadius").map_or(pc, |v| if v.is_finite() { v.clamp(0.0, 1.0e6) } else { pc });
let sides = f64p(p, "sides").map_or(ps, |v| v.round().clamp(3.0, 100.0) as u32);
let ratio = f64p(p, "starRatio").map_or(if kind == "star" && pr >= 1.0 { 0.5 } else { pr }, |v| v.clamp(0.01, 1.0));
- LiveShape::Polygon { rect: rect()?, sides, star_ratio: if kind == "polygon" && f64p(p, "starRatio").is_none() { 1.0 } else { ratio } }
+ LiveShape::Polygon {
+ rect: rect()?,
+ sides,
+ star_ratio: if kind == "polygon" && f64p(p, "starRatio").is_none() { 1.0 } else { ratio },
+ corner_radius,
+ }
}
"line" => {
let (pf, pto, pw) = match prev {
@@ -510,7 +516,9 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
LiveShape::Rect { rect: r(rect), radii: radii.map(|v| v * k) }
}
LiveShape::Ellipse { rect } => LiveShape::Ellipse { rect: r(rect) },
- LiveShape::Polygon { rect, sides, star_ratio } => LiveShape::Polygon { rect: r(rect), sides, star_ratio },
+ LiveShape::Polygon { rect, sides, star_ratio, corner_radius } => {
+ LiveShape::Polygon { rect: r(rect), sides, star_ratio, corner_radius: corner_radius * m0.min(m3) }
+ }
LiveShape::Line { from, to, weight } => {
// Live-shape edits regenerate the line's filled bar from its parameters.
// Keep the weight in sync with a positive scale of the path, or an
@@ -704,7 +712,7 @@ fn shape_edit(s: &mut Session, p: &Value) -> Result<Value> {
sh.live = None;
sh.psd_raw = None;
}
- let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "from", "to", "weight"];
+ let geom_keys = ["kind", "rect", "radii", "radius", "sides", "starRatio", "cornerRadius", "from", "to", "weight"];
if geom_keys.iter().any(|k| p.get(*k).is_some()) {
let kind = p.get("kind").and_then(Value::as_str).map(str::to_string).or_else(|| sh.live.as_ref().map(|l| live_kind(l).to_string()));
let kind = kind.ok_or_else(|| bad(CMD, "this shape has no live-shape parameters; pass `kind` or `path`"))?;
@@ -1683,7 +1691,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Shape Layer",
["Layer", "New"],
leak(format!(
- r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
+ r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
)),
has_doc,
shape_create
@@ -1693,7 +1701,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Shape",
[],
leak(format!(
- r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
+ r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
)),
has_layer,
shape_edit
diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/vector_cmds/tests.rs
index 7e1c871df..8f619c9ad 100644
--- a/crates/engine/src/vector_cmds/tests.rs
+++ b/crates/engine/src/vector_cmds/tests.rs
@@ -948,3 +948,35 @@ fn combine_shapes_fails_gracefully() {
assert!(s.execute("layer.combineShapes.unite", json!({})).is_err());
assert_eq!(*doc(&s), before);
}
+
+#[test]
+fn triangles_and_polygons_take_a_corner_radius_kept_through_edits_and_scaling() {
+ let mut s = session(200, 200, 8);
+ let r = s.execute("shape.create", json!({"kind": "polygon", "rect": [20, 20, 120, 120], "sides": 3, "cornerRadius": 12})).unwrap();
+ let id = r["layer"].as_u64().unwrap();
+ let live = |s: &Session| match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content {
+ LayerContent::Shape(sh) => sh.live.clone(),
+ _ => None,
+ };
+ let path_len = |s: &Session| match &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content {
+ LayerContent::Shape(sh) => sh.path.subpaths[0].knots.len(),
+ _ => 0,
+ };
+ assert!(matches!(live(&s), Some(LiveShape::Polygon { sides: 3, corner_radius, .. }) if corner_radius == 12.0));
+ assert_eq!(path_len(&s), 6, "every vertex rounded");
+ // Other edits keep the radius; a radius edit regenerates the path; 0 makes it sharp again.
+ s.execute("shape.edit", json!({"layer": id, "sides": 6})).unwrap();
+ assert!(matches!(live(&s), Some(LiveShape::Polygon { sides: 6, corner_radius, .. }) if corner_radius == 12.0));
+ assert_eq!(path_len(&s), 12);
+ s.execute("shape.edit", json!({"layer": id, "cornerRadius": 0})).unwrap();
+ assert_eq!(path_len(&s), 6);
+ // Hostile values never panic: negative and non-finite radii are clamped or ignored.
+ for bad in [json!(-5), json!(1e300), json!("x")] {
+ let _ = s.execute("shape.edit", json!({"layer": id, "cornerRadius": bad}));
+ }
+ assert!(matches!(live(&s), Some(LiveShape::Polygon { corner_radius, .. }) if corner_radius.is_finite() && corner_radius >= 0.0));
+ // Scaling the layer by half halves the radius, as for a rectangle's radii.
+ s.execute("shape.edit", json!({"layer": id, "cornerRadius": 10})).unwrap();
+ s.execute("shape.edit", json!({"layer": id, "transform": [0.5, 0, 0, 0.5, 0, 0]})).unwrap();
+ assert!(matches!(live(&s), Some(LiveShape::Polygon { corner_radius, .. }) if (corner_radius - 5.0).abs() < 1e-9));
+}
diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rs
index 3bd127445..bb830dbd6 100644
--- a/crates/io/src/vector_map.rs
+++ b/crates/io/src/vector_map.rs
@@ -671,7 +671,7 @@ mod tests {
let b = vogk_bytes(&s, 72.0).unwrap();
assert_eq!(live_from_vogk(&b), Some(s));
}
- assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0 }, 72.0).is_none());
+ assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0, corner_radius: 0.0 }, 72.0).is_none());
}
#[test]
@@ -699,7 +699,7 @@ mod tests {
// Edit: path changes → vmsk regenerated, live dropped when polygon.
let mut edited = sh.clone();
edited.path.subpaths.pop();
- edited.live = Some(LiveShape::Polygon { rect: [0.0; 4], sides: 3, star_ratio: 1.0 });
+ edited.live = Some(LiveShape::Polygon { rect: [0.0; 4], sides: 3, star_ratio: 1.0, corner_radius: 0.0 });
shape_blocks(&edited, &mut raw, 64, 64, 72.0);
assert!(!raw.iter().any(|(k, _)| k == b"vogk"));
let (p, _) = path_from_vmsk(&raw[0].1, 64, 64).unwrap();
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 7a9592b69..b41f4f02d 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -5005,8 +5005,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
}
// Move tool: ⇧ locks the axis, ⌥ duplicates (move_mods.rs).
let ev = crate::move_mods::filter_event(app, ev, mods);
- // A live rectangle's corner radius widgets (Path Selection, Rectangle tool).
- if crate::corner_radius::pointer(app, ev, mods) {
+ // A live shape's corner radius widgets (Path Selection, the shape tools, Move with its
+ // transform controls). Unsnapped, as Free Transform's handles: snapping would pull the press
+ // off a widget onto a nearby vertex or guide, and the shape tool would draw a new shape.
+ if crate::corner_radius::pointer(app, raw, mods) {
return;
}
// Direct Selection, and the Pen's ⌘ (Direct Selection) and ⌥ (Convert Point) modes (#790).
diff --git a/crates/ui-egui/src/corner_radius.rs b/crates/ui-egui/src/corner_radius.rs
index b02e4d0ee..388ad60a9 100644
--- a/crates/ui-egui/src/corner_radius.rs
+++ b/crates/ui-egui/src/corner_radius.rs
@@ -1,14 +1,17 @@
-//! On-canvas corner radius widgets for live rectangles (TOOL-214-12), as in Photoshop: with Path
-//! Selection, the Rectangle tool, or the Move tool showing its transform controls, every selected
-//! shape layer that is a live rectangle shows a round widget inside each corner, at the centre of
-//! its arc. Dragging one rounds every corner of every selected rectangle to the same radius;
-//! ⌥/Alt changes that corner only, on each of them. The drag previews the new outlines and
-//! commits one `shape.edit` with `radii` per changed layer on release, as one history step; a
-//! click without movement changes nothing.
+//! On-canvas corner radius widgets for live shapes (TOOL-214-12), as in Photoshop: with Path
+//! Selection, a shape tool (Rectangle, Triangle, Polygon), or the Move tool showing its transform
+//! controls, every selected shape layer that is a live rectangle, triangle, polygon or star shows
+//! a round widget inside each corner, at the centre of its arc. Dragging one rounds every corner
+//! of every selected shape to the same radius; ⌥/Alt changes that corner only on rectangles
+//! (a triangle or polygon has one radius for all its corners, as in Photoshop). The drag previews
+//! the new outlines and commits one `shape.edit` per changed layer on release (`radii` for a
+//! rectangle, `cornerRadius` for a polygon), as one history step; a click without movement
+//! changes nothing.
use egui::{Color32, Modifiers, Pos2, Stroke};
use photocraft_doc::LayerContent;
use photocraft_doc::vector::LiveShape;
+use photocraft_vector::shapes;
use crate::PhotocraftApp;
use crate::canvas::ToolEvent;
@@ -18,24 +21,124 @@ use crate::state::Tool;
/// can still be grabbed.
const MIN_INSET: f64 = 10.0;
-/// A selected live rectangle: its layer, `[x, y, w, h]` with a positive size, and its radii.
-#[derive(Clone, Copy, Debug, PartialEq)]
+/// The live shape a target's corners belong to.
+#[derive(Clone, Debug, PartialEq)]
+enum Geom {
+ /// `[x, y, w, h]` with a positive size.
+ Rect([f64; 4]),
+ /// The polygon's parameters and its sharp vertices, in path order.
+ Polygon { rect: [f64; 4], sides: u32, star_ratio: f64, vertices: Vec<[f64; 2]> },
+}
+
+/// A selected live shape with corners: its layer, its geometry, and its radii (a rectangle's four
+/// `[tl, tr, br, bl]`; a polygon's one radius, repeated).
+#[derive(Clone, Debug, PartialEq)]
pub struct Target {
layer: u64,
- rect: [f64; 4],
+ geom: Geom,
radii: [f64; 4],
}
+/// One corner: its vertex, and how far its arc's centre moves per unit of radius (the centre is
+/// `vertex + step * r`: `(±1, ±1)` for a rectangle, `bisector / sin(half the angle)` for a
+/// polygon vertex).
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct Corner {
+ vertex: [f64; 2],
+ step: [f64; 2],
+}
+
+impl Target {
+ fn corners(&self) -> usize {
+ match &self.geom {
+ Geom::Rect(_) => 4,
+ Geom::Polygon { vertices, .. } => vertices.len(),
+ }
+ }
+
+ fn is_rect(&self) -> bool {
+ matches!(self.geom, Geom::Rect(_))
+ }
+
+ /// Corner `i`, `None` when it is degenerate.
+ fn corner(&self, i: usize) -> Option<Corner> {
+ match &self.geom {
+ Geom::Rect([x, y, w, h]) => {
+ let (vertex, d) = match i {
+ 0 => ([*x, *y], [1.0, 1.0]),
+ 1 => ([x + w, *y], [-1.0, 1.0]),
+ 2 => ([x + w, y + h], [-1.0, -1.0]),
+ _ => ([*x, y + h], [1.0, -1.0]),
+ };
+ Some(Corner { vertex, step: d })
+ }
+ Geom::Polygon { vertices, .. } => {
+ let f = self.fillet(i, 1.0)?;
+ let sin = f.half_angle.sin();
+ (sin > 1e-9).then(|| Corner { vertex: vertices.get(i).copied().unwrap_or(f.centre), step: [f.bisector[0] / sin, f.bisector[1] / sin] })
+ }
+ }
+ }
+
+ /// A polygon vertex's rounding with radius `r`.
+ fn fillet(&self, i: usize, r: f64) -> Option<shapes::Fillet> {
+ let Geom::Polygon { vertices, .. } = &self.geom else { return None };
+ let n = vertices.len();
+ let at = |k: usize| vertices.get(k % n).copied();
+ shapes::fillet(at(i + n - 1)?, at(i)?, at(i + 1)?, r)
+ }
+
+ /// The largest radius every corner of the shape can take.
+ fn max_radius(&self) -> f64 {
+ match &self.geom {
+ Geom::Rect(r) => r[2].min(r[3]) / 2.0,
+ Geom::Polygon { vertices, .. } => (0..vertices.len()).filter_map(|i| self.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min),
+ }
+ }
+
+ /// The radius corner `i` is drawn with for `radii`: capped at what the shape allows there.
+ fn radius_at(&self, radii: [f64; 4], i: usize) -> f64 {
+ match &self.geom {
+ Geom::Rect(_) => radii.get(i).copied().unwrap_or(0.0).clamp(0.0, self.max_radius()),
+ Geom::Polygon { .. } => self.fillet(i, radii[0]).map_or(0.0, |f| f.radius),
+ }
+ }
+
+ /// Where corner `i`'s widget is drawn for `radii`: the centre of its arc, or a few screen
+ /// points inside a sharper corner.
+ fn widget(&self, radii: [f64; 4], i: usize, zoom: f64) -> Option<[f64; 2]> {
+ let c = self.corner(i)?;
+ let most = match &self.geom {
+ Geom::Rect(_) => self.max_radius(),
+ Geom::Polygon { .. } => self.fillet(i, 1.0e12).map_or(0.0, |f| f.radius),
+ };
+ // The inset is measured like a rectangle's: 10 points along each axis of a right angle.
+ let len = c.step[0].hypot(c.step[1]).max(1e-9);
+ let inset = MIN_INSET / zoom * std::f64::consts::SQRT_2 / len;
+ let r = self.radius_at(radii, i).max(inset).min(most);
+ Some([c.vertex[0] + c.step[0] * r, c.vertex[1] + c.step[1] * r])
+ }
+
+ /// The outline for `radii`.
+ fn path(&self, radii: [f64; 4]) -> photocraft_doc::Path {
+ match &self.geom {
+ Geom::Rect([x, y, w, h]) => shapes::rounded_rect(*x, *y, *w, *h, radii),
+ Geom::Polygon { rect, sides, star_ratio, .. } => {
+ shapes::live_path(&LiveShape::Polygon { rect: *rect, sides: *sides, star_ratio: *star_ratio, corner_radius: radii[0] })
+ }
+ }
+ }
+}
+
/// A corner radius drag in progress.
#[derive(Clone, Debug, PartialEq)]
pub struct Drag {
- /// Every selected live rectangle, as at the press.
+ /// Every selected live shape with corners, as at the press.
targets: Vec<Target>,
- /// The rectangle whose widget was pressed (an index into `targets`) and its corner,
- /// `[tl, tr, br, bl]` order.
+ /// The shape whose widget was pressed (an index into `targets`) and its corner.
grabbed: usize,
corner: usize,
- /// Every corner (no ⌥) or the dragged one only.
+ /// Every corner (no ⌥) or the dragged one only (rectangles).
all: bool,
/// Where the press was.
start: [f64; 2],
@@ -47,13 +150,39 @@ pub struct Drag {
fn shows(app: &PhotocraftApp) -> bool {
app.ui.transform.is_none()
&& match app.ui.tool {
- Tool::PathSelection | Tool::Rectangle => true,
+ Tool::PathSelection | Tool::Rectangle | Tool::Triangle | Tool::Polygon => true,
Tool::Move => app.ui.tool_options.move_show_transform,
_ => false,
}
}
-/// The selected layers that are live rectangles, front first.
+/// A shape layer's live shape as a target, if it has corners.
+fn target(layer: u64, live: &LiveShape) -> Option<Target> {
+ let finite = |v: &[f64]| v.iter().all(|v| v.is_finite());
+ let positive = |[x, y, w, h]: [f64; 4]| {
+ let (x, w) = if w < 0.0 { (x + w, -w) } else { (x, w) };
+ let (y, h) = if h < 0.0 { (y + h, -h) } else { (y, h) };
+ (w > 0.0 && h > 0.0 && finite(&[x, y, w, h])).then_some([x, y, w, h])
+ };
+ match *live {
+ LiveShape::Rect { rect, radii } => {
+ let rect = positive(rect)?;
+ finite(&radii).then_some(Target { layer, geom: Geom::Rect(rect), radii })
+ }
+ LiveShape::Polygon { rect, sides, star_ratio, corner_radius } => {
+ positive(rect)?;
+ if !finite(&[star_ratio, corner_radius]) {
+ return None;
+ }
+ let sharp = shapes::polygon(rect[0], rect[1], rect[2], rect[3], sides, star_ratio);
+ let vertices = sharp.subpaths.first()?.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect();
+ Some(Target { layer, geom: Geom::Polygon { rect, sides, star_ratio, vertices }, radii: [corner_radius.max(0.0); 4] })
+ }
+ LiveShape::Ellipse { .. } | LiveShape::Line { .. } => None,
+ }
+}
+
+/// The selected layers that are live shapes with corners, front first.
fn targets(app: &PhotocraftApp) -> Vec<Target> {
if !shows(app) {
return Vec::new();
@@ -65,10 +194,7 @@ fn targets(app: &PhotocraftApp) -> Vec<Target> {
.filter_map(|id| {
let l = st.doc.layer(id)?;
let LayerContent::Shape(sh) = &l.content else { return None };
- let Some(LiveShape::Rect { rect: [x, y, w, h], radii }) = sh.live else { return None };
- let (x, w) = if w < 0.0 { (x + w, -w) } else { (x, w) };
- let (y, h) = if h < 0.0 { (y + h, -h) } else { (y, h) };
- (w > 0.0 && h > 0.0 && [x, y, w, h].iter().chain(&radii).all(|v| v.is_finite())).then_some(Target { layer: l.id.0, rect: [x, y, w, h], radii })
+ target(l.id.0, sh.live.as_ref()?)
})
.collect();
// `selected_layers` lists bottom to top; the topmost widget wins a press.
@@ -76,58 +202,19 @@ fn targets(app: &PhotocraftApp) -> Vec<Target> {
out
}
-/// The largest radius a corner of `rect` takes.
-fn max_radius(rect: [f64; 4]) -> f64 {
- rect[2].min(rect[3]) / 2.0
-}
-
-/// Corner `i` of `rect` and the unit-step direction pointing inside from it.
-fn corner(rect: [f64; 4], i: usize) -> ([f64; 2], [f64; 2]) {
- let [x, y, w, h] = rect;
- match i {
- 0 => ([x, y], [1.0, 1.0]),
- 1 => ([x + w, y], [-1.0, 1.0]),
- 2 => ([x + w, y + h], [-1.0, -1.0]),
- _ => ([x, y + h], [1.0, -1.0]),
- }
-}
-
-/// Where corner `i`'s widget is drawn: the centre of its arc, or a few screen points inside a
-/// sharper corner.
-fn widget(rect: [f64; 4], radii: [f64; 4], i: usize, zoom: f64) -> [f64; 2] {
- let (c, d) = corner(rect, i);
- let r = radii.get(i).copied().unwrap_or(0.0).max(MIN_INSET / zoom).min(max_radius(rect));
- [c[0] + d[0] * r, c[1] + d[1] * r]
-}
-
-/// The radius the pressed corner `i` asks for when the pointer has moved from `start` to `p`: its
-/// radius at the press plus the move projected onto the corner's diagonal (inward rounds more),
-/// at least 0. Relative, so a click on a sharp corner's inset widget changes nothing. Each
-/// rectangle then caps it at half its own shorter side.
-fn radius_after(rect: [f64; 4], i: usize, from: f64, start: [f64; 2], p: [f64; 2]) -> f64 {
- let (_, d) = corner(rect, i);
- let r = from + ((p[0] - start[0]) * d[0] + (p[1] - start[1]) * d[1]) / 2.0;
- if r.is_finite() { r.max(0.0) } else { from }
-}
-
fn zoom(app: &PhotocraftApp) -> f64 {
f64::from(app.point_zoom().max(0.01))
}
-/// The widget of `targets` within grabbing distance of document point `p`: the rectangle (an
-/// index into `targets`) and its corner, the nearest when several are close.
+/// The widget of `targets` within grabbing distance of document point `p`: the shape (an index
+/// into `targets`) and its corner, the nearest when several are close.
fn hit(app: &PhotocraftApp, targets: &[Target], p: [f64; 2]) -> Option<(usize, usize)> {
let z = zoom(app);
let tol = 7.0 / z;
targets
.iter()
.enumerate()
- .flat_map(|(t, g)| {
- (0..4).map(move |i| {
- let w = widget(g.rect, g.radii, i, z);
- (t, i, (w[0] - p[0]).hypot(w[1] - p[1]))
- })
- })
+ .flat_map(|(t, g)| (0..g.corners()).filter_map(move |i| g.widget(g.radii, i, z).map(|w| (t, i, (w[0] - p[0]).hypot(w[1] - p[1])))))
.filter(|(.., d)| *d <= tol)
.min_by(|a, b| a.2.total_cmp(&b.2))
.map(|(t, i, _)| (t, i))
@@ -159,12 +246,18 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool
ToolEvent::Move { x, y, .. } => {
let Some(d) = app.ui.corner_radius.as_mut() else { return false };
let Some(g) = d.targets.get(d.grabbed) else { return true };
- let from = g.radii.get(d.corner).copied().unwrap_or(0.0).clamp(0.0, max_radius(g.rect));
- let r = radius_after(g.rect, d.corner, from, d.start, [x, y]);
- // Every selected rectangle takes the same radius, within its own size.
+ let Some(c) = g.corner(d.corner) else { return true };
+ // The radius at the press plus the move projected onto the corner's step (the way its
+ // arc's centre moves as the radius grows). Relative, so a click on a sharp corner's
+ // inset widget changes nothing.
+ let from = g.radius_at(g.radii, d.corner);
+ let len2 = c.step[0] * c.step[0] + c.step[1] * c.step[1];
+ let r = from + ((x - d.start[0]) * c.step[0] + (y - d.start[1]) * c.step[1]) / len2.max(1e-12);
+ let r = if r.is_finite() { r.max(0.0) } else { from };
+ // Every selected shape takes the same radius, within its own size.
for (t, now) in d.targets.iter().zip(d.now.iter_mut()) {
- let r = r.min(max_radius(t.rect));
- if d.all {
+ let r = r.min(t.max_radius());
+ if d.all || !t.is_rect() {
*now = [r; 4];
} else {
*now = t.radii;
@@ -184,9 +277,15 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool
// One history step for every layer changed.
let key = format!("corner-radius-{}", app.ui.alloc_id());
for (t, now) in d.targets.iter().zip(&d.now) {
- if *now != t.radii
- && let Err(e) = app.run("shape.edit", serde_json::json!({"layer": t.layer, "radii": now, "coalesce": key}))
- {
+ if *now == t.radii {
+ continue;
+ }
+ let params = if t.is_rect() {
+ serde_json::json!({"layer": t.layer, "radii": now, "coalesce": key})
+ } else {
+ serde_json::json!({"layer": t.layer, "cornerRadius": now[0], "coalesce": key})
+ };
+ if let Err(e) = app.run("shape.edit", params) {
app.ui.status = e;
app.ui.status_error = true;
break;
@@ -199,11 +298,13 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool
/// The radius the dragged corner shows in the readout.
fn dragged_radius(d: &Drag) -> Option<f64> {
- d.now.get(d.grabbed).and_then(|r| r.get(d.corner)).copied()
+ let g = d.targets.get(d.grabbed)?;
+ let now = d.now.get(d.grabbed)?;
+ if g.is_rect() { now.get(d.corner).copied() } else { Some(g.radius_at(*now, d.corner)) }
}
-/// The widgets of every selected live rectangle; while one is dragged, the new outlines and the
-/// radius beside the pointer (`R: 25.0 px`), as in Photoshop.
+/// The widgets of every selected live shape with corners; while one is dragged, the new outlines
+/// and the radius beside the pointer (`R: 25.0 px`), as in Photoshop.
pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32) {
let drag = app.ui.corner_radius.as_ref();
if let Some(r) = drag.and_then(dragged_radius)
@@ -216,13 +317,14 @@ pub fn draw(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64;
let now = drag.and_then(|d| d.targets.iter().position(|g| g.layer == t.layer).and_then(|i| d.now.get(i)));
let radii = now.copied().unwrap_or(t.radii);
if now.is_some() {
- let path = photocraft_vector::shapes::rounded_rect(t.rect[0], t.rect[1], t.rect[2], t.rect[3], radii);
- crate::vector_ui::draw_outline(painter, &path, to_scr, accent);
+ crate::vector_ui::draw_outline(painter, &t.path(radii), to_scr, accent);
}
- for i in 0..4 {
- let p = to_scr(widget(t.rect, radii, i, z));
- painter.circle(p, 5.0, Color32::WHITE, Stroke::new(1.5, accent));
- painter.circle_filled(p, 2.5, accent);
+ for i in 0..t.corners() {
+ if let Some(w) = t.widget(radii, i, z) {
+ let p = to_scr(w);
+ painter.circle(p, 5.0, Color32::WHITE, Stroke::new(1.5, accent));
+ painter.circle_filled(p, 2.5, accent);
+ }
}
}
}
diff --git a/crates/ui-egui/src/corner_radius_tests.rs b/crates/ui-egui/src/corner_radius_tests.rs
index b0b47c45b..252e9ce58 100644
--- a/crates/ui-egui/src/corner_radius_tests.rs
+++ b/crates/ui-egui/src/corner_radius_tests.rs
@@ -184,3 +184,86 @@ fn the_cursor_and_readout_follow_the_widgets() {
tool_event(&mut app, ToolEvent::Up { x: 62.0, y: 62.0 }, Modifiers::NONE);
assert!(!super::hovers(&app, [100.0, 80.0]));
}
+
+/// The live polygon of layer `id`: its corner radius.
+fn corner_radius_of(app: &PhotocraftApp, id: photocraft_doc::LayerId) -> f64 {
+ match &app.session.active().unwrap().doc.layer(id).unwrap().content {
+ LayerContent::Shape(sh) => match sh.live {
+ Some(LiveShape::Polygon { corner_radius, .. }) => corner_radius,
+ _ => panic!("live polygon"),
+ },
+ _ => panic!("shape"),
+ }
+}
+
+/// A live triangle (a 3-sided polygon) in (40, 40) 120 × 120, as the Triangle tool draws it.
+fn triangle(tool: Tool, radius: f64) -> (PhotocraftApp, photocraft_doc::LayerId) {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
+ app.sync_views();
+ app.run("shape.create", json!({"kind": "polygon", "rect": [40, 40, 120, 120], "sides": 3, "cornerRadius": radius})).unwrap();
+ app.ui.tool = tool;
+ let id = app.session.active().unwrap().active_layer.unwrap();
+ (app, id)
+}
+
+/// Where the widget of corner `i` of the first target is, and the way its arc's centre moves.
+fn widget_of(app: &PhotocraftApp, i: usize) -> ([f64; 2], [f64; 2]) {
+ let t = &super::targets(app)[0];
+ let z = f64::from(app.point_zoom());
+ (t.widget(t.radii, i, z).unwrap(), t.corner(i).unwrap().step)
+}
+
+#[test]
+fn a_triangle_rounds_all_its_corners_from_any_widget_in_one_step() {
+ for tool in [Tool::Triangle, Tool::Polygon, Tool::PathSelection] {
+ let (mut app, id) = triangle(tool, 6.0);
+ assert_eq!(super::targets(&app)[0].corners(), 3, "{tool:?}");
+ let n = steps(&app);
+ // Drag the bottom-right widget inwards by 4 radius units along its step: 6 + 4 = 10.
+ let (w, step) = widget_of(&app, 1);
+ let to = [w[0] + step[0] * 4.0, w[1] + step[1] * 4.0];
+ drag(&mut app, w, to, Modifiers::NONE);
+ assert!((corner_radius_of(&app, id) - 10.0).abs() < 1e-9, "{tool:?}: {}", corner_radius_of(&app, id));
+ assert_eq!(steps(&app), n + 1, "one history step");
+ // ⌥ makes no difference: a triangle has one radius for all its corners.
+ let (w, step) = widget_of(&app, 0);
+ drag(&mut app, w, [w[0] + step[0] * 2.0, w[1] + step[1] * 2.0], Modifiers::ALT);
+ assert!((corner_radius_of(&app, id) - 12.0).abs() < 1e-9);
+ assert!(app.session.undo());
+ assert!((corner_radius_of(&app, id) - 10.0).abs() < 1e-9);
+ }
+}
+
+#[test]
+fn a_triangle_radius_is_capped_and_a_click_on_a_sharp_corner_changes_nothing() {
+ let (mut app, id) = triangle(Tool::PathSelection, 0.0);
+ let n = steps(&app);
+ let (w, step) = widget_of(&app, 2);
+ drag(&mut app, w, w, Modifiers::NONE);
+ assert_eq!((corner_radius_of(&app, id), steps(&app)), (0.0, n), "a click commits nothing");
+ // Dragged far in: the radius stops where the arcs meet halfway along the edges.
+ drag(&mut app, w, [w[0] + step[0] * 1000.0, w[1] + step[1] * 1000.0], Modifiers::NONE);
+ let max = super::targets(&app)[0].max_radius();
+ assert!(max > 0.0 && (corner_radius_of(&app, id) - max).abs() < 1e-9, "{} vs {max}", corner_radius_of(&app, id));
+}
+
+#[test]
+fn rectangles_and_triangles_selected_together_take_the_same_radius() {
+ let (mut app, tri) = triangle(Tool::PathSelection, 0.0);
+ app.run("shape.create", json!({"kind": "rect", "rect": [10, 170, 100, 20], "radii": 0})).unwrap();
+ let rect = app.session.active().unwrap().active_layer.unwrap();
+ app.run("layer.select", json!({"layer": tri.0, "mode": "add"})).unwrap();
+ // The rectangle's top-left widget (10 px inside, at (20, 180)), 4 px in each direction: 4.
+ drag(&mut app, [20.0, 180.0], [24.0, 184.0], Modifiers::NONE);
+ assert_eq!(radii(&app), None, "the active layer is the triangle");
+ let rr = match &app.session.active().unwrap().doc.layer(rect).unwrap().content {
+ LayerContent::Shape(sh) => match sh.live {
+ Some(LiveShape::Rect { radii, .. }) => radii,
+ _ => panic!(),
+ },
+ _ => panic!(),
+ };
+ assert_eq!(rr, [4.0; 4]);
+ assert!((corner_radius_of(&app, tri) - 4.0).abs() < 1e-9);
+}
diff --git a/crates/ui-egui/src/shape_dialog_tests.rs b/crates/ui-egui/src/shape_dialog_tests.rs
index a0b5c6159..d5dc01ebf 100644
--- a/crates/ui-egui/src/shape_dialog_tests.rs
+++ b/crates/ui-egui/src/shape_dialog_tests.rs
@@ -76,7 +76,7 @@ fn from_center_and_the_other_tools() {
let id = only_dialog(&app);
set(&mut app, id, json!({"width": 50, "height": 60, "sides": 7, "starRatio": 50}));
crate::dialogs::confirm(&mut app, id).unwrap();
- assert_eq!(live(&app), LiveShape::Polygon { rect: [10.0, 10.0, 50.0, 60.0], sides: 7, star_ratio: 0.5 });
+ assert_eq!(live(&app), LiveShape::Polygon { rect: [10.0, 10.0, 50.0, 60.0], sides: 7, star_ratio: 0.5, corner_radius: 0.0 });
press(&mut app, Tool::Triangle, [5.0, 6.0], [5.0, 6.0]);
let id = only_dialog(&app);
diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs
index fe6db7407..86b10dd92 100644
--- a/crates/ui-egui/src/vector_ui.rs
+++ b/crates/ui-egui/src/vector_ui.rs
@@ -1555,7 +1555,14 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
});
}
}
- photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, .. } => {
+ photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, corner_radius, .. } => {
+ // One radius rounds every vertex of a triangle, polygon or star, as in Photoshop.
+ ui.horizontal(|ui| {
+ let mut r = *corner_radius as f32;
+ if num(ui, tl!("Corner radius"), &mut r, 0.0..=100000.0, "px") {
+ edit = Some(json!({"cornerRadius": r, "coalesce": key("corner-radius")}));
+ }
+ });
ui.horizontal(|ui| {
let mut n = *sides as f32;
if num(ui, tl!("Sides"), &mut n, 3.0..=100.0, "") {
diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs
index b154a4732..dfeae26e8 100644
--- a/crates/vector/src/shapes.rs
+++ b/crates/vector/src/shapes.rs
@@ -111,6 +111,101 @@ pub fn polygon(x: f64, y: f64, w: f64, h: f64, sides: u32, star_ratio: f64) -> P
Path::new(vec![Subpath::polygon(&pts)])
}
+/// A rounded vertex: see [`fillet`].
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Fillet {
+ /// The arc's centre and its tangent points on the edge to the previous and the next vertex.
+ pub centre: [f64; 2],
+ pub from: [f64; 2],
+ pub to: [f64; 2],
+ /// The radius used (the one asked for, capped at what the edges allow).
+ pub radius: f64,
+ /// Unit direction from the vertex towards the arc's centre, and half the vertex's angle.
+ pub bisector: [f64; 2],
+ pub half_angle: f64,
+}
+
+/// Where a vertex's rounding sits: the vertex `v` between neighbours `prev` and `next`, rounded
+/// with radius `r`, capped so its tangent points stay within half of each edge (two neighbouring
+/// roundings never overlap). `None` for `r <= 0` or a degenerate vertex (a zero-length edge, or
+/// a straight or folded angle).
+pub fn fillet(prev: [f64; 2], v: [f64; 2], next: [f64; 2], r: f64) -> Option<Fillet> {
+ let unit = |a: [f64; 2], b: [f64; 2]| {
+ let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
+ let l = dx.hypot(dy);
+ (l > 1e-9).then(|| ([dx / l, dy / l], l))
+ };
+ if r.is_nan() || r <= 0.0 {
+ return None;
+ }
+ let (u1, l1) = unit(v, prev)?;
+ let (u2, l2) = unit(v, next)?;
+ let cos = (u1[0] * u2[0] + u1[1] * u2[1]).clamp(-1.0, 1.0);
+ let half = cos.acos() / 2.0;
+ if half < 1e-6 || half > std::f64::consts::FRAC_PI_2 - 1e-6 {
+ return None;
+ }
+ let r = r.min(l1.min(l2) / 2.0 * half.tan());
+ let t = r / half.tan();
+ let (bx, by) = (u1[0] + u2[0], u1[1] + u2[1]);
+ let bl = bx.hypot(by);
+ if bl < 1e-9 {
+ return None;
+ }
+ let bisector = [bx / bl, by / bl];
+ let c = r / half.sin();
+ Some(Fillet {
+ centre: [v[0] + bisector[0] * c, v[1] + bisector[1] * c],
+ from: [v[0] + u1[0] * t, v[1] + u1[1] * t],
+ to: [v[0] + u2[0] * t, v[1] + u2[1] * t],
+ radius: r,
+ bisector,
+ half_angle: half,
+ })
+}
+
+/// `path` (closed subpaths of corner knots, as [`polygon`] makes) with every vertex rounded by a
+/// circular arc of radius `r` tangent to both its edges, each capped as [`fillet`] does, like
+/// Photoshop's rounded triangles and polygons. `r <= 0` leaves it sharp.
+pub fn round_corners(path: Path, r: f64) -> Path {
+ if r.is_nan() || r <= 0.0 {
+ return path;
+ }
+ let subpaths = path
+ .subpaths
+ .into_iter()
+ .map(|sp| {
+ let n = sp.knots.len();
+ if n < 3 || !sp.closed {
+ return sp;
+ }
+ let pt = |i: usize| sp.knots.get(i % n).map_or([0.0; 2], |k| [k.anchor.x, k.anchor.y]);
+ let mut knots = Vec::with_capacity(n * 2);
+ for i in 0..n {
+ let (prev, v, next) = (pt(i + n - 1), pt(i), pt(i + 1));
+ let Some(f) = fillet(prev, v, next, r) else {
+ knots.push(Knot::corner(v[0], v[1]));
+ continue;
+ };
+ // The arc as one cubic: handles 4/3 tan(sweep/4) r long, along the tangents
+ // towards the vertex; the sweep is pi minus the vertex's angle.
+ let sweep = std::f64::consts::PI - 2.0 * f.half_angle;
+ let h = 4.0 / 3.0 * (sweep / 4.0).tan() * f.radius;
+ let toward = |a: [f64; 2]| {
+ let (dx, dy) = (v[0] - a[0], v[1] - a[1]);
+ let l = dx.hypot(dy).max(1e-12);
+ Point::new(a[0] + dx / l * h, a[1] + dy / l * h)
+ };
+ let (from, to) = (Point::new(f.from[0], f.from[1]), Point::new(f.to[0], f.to[1]));
+ knots.push(Knot { anchor: from, in_ctrl: from, out_ctrl: toward(f.from), smooth: false });
+ knots.push(Knot { anchor: to, in_ctrl: toward(f.to), out_ctrl: to, smooth: false });
+ }
+ Subpath { knots, ..sp }
+ })
+ .collect();
+ Path { subpaths, ..path }
+}
+
/// A line drawn as a filled bar of `weight` px from `a` to `b`.
pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
@@ -125,7 +220,9 @@ pub fn live_path(s: &LiveShape) -> Path {
match s {
LiveShape::Rect { rect: [x, y, w, h], radii } => rounded_rect(*x, *y, *w, *h, *radii),
LiveShape::Ellipse { rect: [x, y, w, h] } => ellipse(*x, *y, *w, *h),
- LiveShape::Polygon { rect: [x, y, w, h], sides, star_ratio } => polygon(*x, *y, *w, *h, *sides, *star_ratio),
+ LiveShape::Polygon { rect: [x, y, w, h], sides, star_ratio, corner_radius } => {
+ round_corners(polygon(*x, *y, *w, *h, *sides, *star_ratio), *corner_radius)
+ }
LiveShape::Line { from, to, weight } => line((from[0], from[1]), (to[0], to[1]), *weight),
}
}
@@ -134,6 +231,59 @@ pub fn live_path(s: &LiveShape) -> Path {
mod tests {
use super::*;
+ /// The point at `t` of the cubic leaving `a` towards `b`.
+ fn at(a: &Knot, b: &Knot, t: f64) -> [f64; 2] {
+ let u = 1.0 - t;
+ let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t];
+ let p = [a.anchor, a.out_ctrl, b.in_ctrl, b.anchor];
+ [p.iter().zip(w).map(|(p, w)| p.x * w).sum(), p.iter().zip(w).map(|(p, w)| p.y * w).sum()]
+ }
+
+ #[test]
+ fn a_rounded_triangle_has_one_arc_per_vertex_on_a_true_circle() {
+ let sharp = polygon(0.0, 0.0, 300.0, 300.0, 3, 1.0);
+ assert_eq!(sharp.subpaths[0].knots.len(), 3);
+ let p = round_corners(sharp.clone(), 20.0);
+ let k = &p.subpaths[0].knots;
+ assert_eq!(k.len(), 6, "two knots per rounded vertex");
+ // Each arc stays 20 px from its centre along its length (one cubic, within 0.1 px).
+ let verts: Vec<[f64; 2]> = sharp.subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect();
+ for i in 0..3 {
+ let f = fillet(verts[(i + 2) % 3], verts[i], verts[(i + 1) % 3], 20.0).unwrap();
+ assert!((f.radius - 20.0).abs() < 1e-9);
+ assert_eq!([k[2 * i].anchor.x, k[2 * i].anchor.y], f.from);
+ for t in [0.25, 0.5, 0.75] {
+ let q = at(&k[2 * i], &k[2 * i + 1], t);
+ let d = (q[0] - f.centre[0]).hypot(q[1] - f.centre[1]);
+ assert!((d - 20.0).abs() < 0.1, "vertex {i} t {t}: {d}");
+ }
+ }
+ // The edges between the arcs stay straight.
+ assert_eq!((k[1].out_ctrl, k[2].in_ctrl), (k[1].anchor, k[2].anchor));
+ }
+
+ #[test]
+ fn huge_radii_are_capped_and_zero_stays_sharp() {
+ let sharp = polygon(0.0, 0.0, 100.0, 100.0, 6, 1.0);
+ assert_eq!(round_corners(sharp.clone(), 0.0), sharp);
+ assert_eq!(round_corners(sharp.clone(), f64::NAN), sharp);
+ let p = round_corners(sharp, 1.0e9);
+ // Capped: the tangent points of neighbouring vertices meet halfway along each edge.
+ let k = &p.subpaths[0].knots;
+ assert_eq!(k.len(), 12);
+ for w in k.windows(2).skip(1).step_by(2) {
+ let d = (w[0].anchor.x - w[1].anchor.x).hypot(w[0].anchor.y - w[1].anchor.y);
+ assert!(d < 1e-6, "no straight left between arcs: {d}");
+ }
+ assert!(k.iter().all(|k| k.anchor.x.is_finite() && k.anchor.y.is_finite()));
+ }
+
+ #[test]
+ fn a_star_rounds_its_inner_vertices_too() {
+ let p = live_path(&LiveShape::Polygon { rect: [0.0, 0.0, 200.0, 200.0], sides: 5, star_ratio: 0.5, corner_radius: 6.0 });
+ assert_eq!(p.subpaths[0].knots.len(), 20);
+ }
+
#[test]
fn rounded_rect_knots() {
let p = rounded_rect(0.0, 0.0, 100.0, 50.0, [10.0; 4]);
diff --git a/docs/scorecard.md b/docs/scorecard.md
index fe9c144ba..174ecf810 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -156,7 +156,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| TOOL-214-9 | Crop: W x H x Resolution with units, saved crop presets, Straighten in the options bar | done | [#214](https://github.com/storytold/photocraft/issues/214) | Ratio dropdown and fields, Straighten (TOOL-214-21); W x H x Resolution with units, built-in size presets and Front Image (crop_size.rs, image.crop targetWidth/targetHeight/resolution, #2443); New / Delete Crop Preset save and delete crop tool presets (crop_presets.rs, tool.presets.* with tool crop, persisted with the preferences) |
| TOOL-214-10 | Pen: Alt breaks a handle, Shift 45 deg, Ctrl direct-selects, Backspace, close-drag handle | done | [#214](https://github.com/storytold/photocraft/issues/214) | Ctrl/Cmd = Direct Selection and Alt = Convert Point on existing paths (direct_select.rs, #790); Backspace/Delete retracts the last point while drawing (#1466); Alt during a drag breaks the handle pair, Alt-drag turns the last anchor's outgoing handle alone, and dragging on the first anchor closes with that anchor's handles (vector_ui.rs, #3306); Shift-click puts the next anchor on the nearest 45 deg ray from the previous one and Shift-drag turns the handles to 45 deg steps, live (vector_ui.rs pen_shift_click_puts_the_next_anchor_on_a_45_degree_ray, pen_shift_drag_turns_handles_to_45_degrees_live, #3751) |
| TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) |
-| TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle with Path Selection, the Rectangle tool and Move + Show Transform Controls: drag rounds every corner of every selected rectangle alike, Alt that corner on each, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather |
+| TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | partial | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle, triangle, polygon and star (LiveShape::Polygon corner_radius, shape.create/edit cornerRadius, vector shapes::round_corners) with Path Selection, the Rectangle/Triangle/Polygon tools and Move + Show Transform Controls: drag rounds every corner of every selected shape alike, Alt one corner of a rectangle, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather |
| TOOL-214-13 | Mask Properties: Density and Feather controls | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Vector-mask density/feather in the engine (vector_cmds.rs:948); no UI controls |
| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing |
| TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog |
diff --git a/docs/ui-parity.md b/docs/ui-parity.md
index 7fbe8932c..23ef1452d 100644
--- a/docs/ui-parity.md
+++ b/docs/ui-parity.md
@@ -1,6 +1,6 @@
# UI parity: tools, handles, modifiers and feel
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (rounded triangle, polygon and star corners; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
@@ -123,7 +123,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Pen Auto Add/Delete: click a segment of the active path to add, an anchor to delete; ⇧ suspends it | done | #4144 |
| Curvature Pen edits the active path with no modifier: drag an anchor (the curve reflows), click a segment to add an anchor, double-click smooth ↔ corner; cursor badge + on segments, four arrows on anchors | done: `direct_select.rs` (`curvature_press`, `curvature_hover`), `path.moveAnchors`/`path.convertPoint` with `curvature`, `direct_select_tests.rs` | |
| Path operations in the options bar (combine, subtract, intersect, exclude) | partial | `layer.combineShapes.*`; Pen options #1397 |
-| On-canvas corner-radius handles on live shapes | done: every selected live rectangle shows a widget at each arc centre with Path Selection, the Rectangle tool and Move with Show Transform Controls; a drag rounds every corner of every selected rectangle to the same radius, ⌥ that corner on each, with the corner radius cursor and an `R:` readout, previewed and committed as one history step (`corner_radius.rs`, `corner_radius_tests.rs`) | TOOL-214-12 |
+| On-canvas corner-radius handles on live shapes | done: every selected live rectangle, triangle, polygon and star shows a widget at each arc centre with Path Selection, the Rectangle, Triangle and Polygon tools and Move with Show Transform Controls; a drag rounds every corner of every selected shape to the same radius, ⌥ one corner of a rectangle (a triangle or polygon has one radius), with the corner radius cursor and an `R:` readout, previewed and committed as one history step (`corner_radius.rs`, `corner_radius_tests.rs`) | TOOL-214-12 |
| Shape stroke controls (dash, caps, joins, align) | done | TOOL-1053-1, [`shape-strokes.md`](shape-strokes.md) |
| Rotated shape selection hints correct | partial | #2512 |
| Curved shape bounds exact | partial | one pixel too wide (#2537) |
@@ -253,3 +253,4 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) |
| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit |
| 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) |
+| 2026-10-14 | minor | Rounded corners on live triangles, polygons and stars: Properties field and on-canvas widgets (TOOL-214-12) |
diff --git a/scorecard/tools.toml b/scorecard/tools.toml
index 51f6b1cf3..9ed74a2fc 100644
--- a/scorecard/tools.toml
+++ b/scorecard/tools.toml
@@ -192,7 +192,7 @@ id = "TOOL-214-12"
target = "Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance"
status = "partial"
issue = 214
-note = "On-canvas corner radius widgets on every selected live rectangle with Path Selection, the Rectangle tool and Move + Show Transform Controls: drag rounds every corner of every selected rectangle alike, Alt that corner on each, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather"
+note = "On-canvas corner radius widgets on every selected live rectangle, triangle, polygon and star (LiveShape::Polygon corner_radius, shape.create/edit cornerRadius, vector shapes::round_corners) with Path Selection, the Rectangle/Triangle/Polygon tools and Move + Show Transform Controls: drag rounds every corner of every selected shape alike, Alt one corner of a rectangle, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256). Missing: shape feather"
[[item]]
id = "TOOL-214-13"