mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-24 17:27:03 +00:00
M4: a rounded vector point reaches along the whole of a segment whose other end is sharp (#2334)
This commit is contained in:
@@ -1350,6 +1350,8 @@ mod proto_overlay_anchor_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod vector_radius_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_regions_tests;
|
||||
#[cfg(test)]
|
||||
mod width_sides_tests;
|
||||
|
||||
+49
-11
@@ -145,6 +145,25 @@ struct Corner {
|
||||
cut2: f64,
|
||||
}
|
||||
|
||||
/// Where point `v` turns between its two segments, for rounding it: `r` its radius, `s1`/`s2` the
|
||||
/// segments (`a1`/`a2` whether `v` is their `a` end), `c1`/`c2` them as curves running away from
|
||||
/// `v`, `u1`/`u2` the directions they leave in, `angle` between those, and `l1`/`l2` their lengths.
|
||||
struct Turn {
|
||||
v: usize,
|
||||
r: f64,
|
||||
s1: usize,
|
||||
a1: bool,
|
||||
s2: usize,
|
||||
a2: bool,
|
||||
c1: CubicBez,
|
||||
c2: CubicBez,
|
||||
u1: Vec2,
|
||||
u2: Vec2,
|
||||
angle: f64,
|
||||
l1: f64,
|
||||
l2: f64,
|
||||
}
|
||||
|
||||
/// One curve of a rounded point: its handles at its start (`ta`) and its end (`tb`), relative to
|
||||
/// those ends, and the point it ends at.
|
||||
struct CornerCurve {
|
||||
@@ -391,10 +410,11 @@ impl VectorNetwork {
|
||||
}
|
||||
|
||||
/// The network with its rounded points drawn in: each sharp point with a corner radius becomes
|
||||
/// an arc between its two segments (the radius shrinks so the arc fits in half of each
|
||||
/// segment, like a polygon's corners). A curved segment is cut where the arc meets it and keeps
|
||||
/// the rest of its curve, the arc leaving along its direction there. `None` when no point is
|
||||
/// rounded.
|
||||
/// an arc between its two segments. The radius shrinks so the arc fits: a segment whose other
|
||||
/// end is rounded too is shared, half for each end, as a polygon's sides are, and one whose
|
||||
/// other end stays sharp can be used whole (as in Figma, #2334). A curved segment is cut where
|
||||
/// the arc meets it and keeps the rest of its curve, the arc leaving along its direction there.
|
||||
/// `None` when no point is rounded.
|
||||
pub fn rounded(&self) -> Option<VectorNetwork> {
|
||||
self.rounded_smoothed(0.0)
|
||||
}
|
||||
@@ -424,7 +444,9 @@ impl VectorNetwork {
|
||||
*x = true;
|
||||
}
|
||||
}
|
||||
let corners: Vec<Corner> = (0..self.vertices.len()).filter_map(|v| self.corner(v, incident.get(v)?, smoothing, &on_loop)).collect();
|
||||
let turns: Vec<Option<Turn>> = (0..self.vertices.len()).map(|v| self.turn(v, incident.get(v)?)).collect();
|
||||
let rounds: Vec<bool> = turns.iter().map(Option::is_some).collect();
|
||||
let corners: Vec<Corner> = turns.iter().flatten().filter_map(|t| self.corner(t, smoothing, &on_loop, &rounds)).collect();
|
||||
let mut out = self.clone();
|
||||
for v in &mut out.vertices {
|
||||
v.radius = 0.0;
|
||||
@@ -558,10 +580,9 @@ impl VectorNetwork {
|
||||
joining.next().is_none().then_some(first)
|
||||
}
|
||||
|
||||
/// How point `v` (its `incident` segments) is rounded, if it is: not where the two segments
|
||||
/// run on smoothly or fold back. With `smoothing`, a point between two straight segments that
|
||||
/// are both `on_loop` gets a smoothed corner.
|
||||
fn corner(&self, v: usize, incident: &[(usize, bool)], smoothing: f64, on_loop: &[bool]) -> Option<Corner> {
|
||||
/// How point `v` (its `incident` segments) turns, if it is rounded: it has a radius and two
|
||||
/// segments that neither run on smoothly nor fold back there.
|
||||
fn turn(&self, v: usize, incident: &[(usize, bool)]) -> Option<Turn> {
|
||||
let r = self.vertices.get(v)?.radius;
|
||||
let [(s1, a1), (s2, a2)] = *incident else { return None };
|
||||
if !(r > 0.0 && r.is_finite()) || s1 == s2 {
|
||||
@@ -577,6 +598,23 @@ impl VectorNetwork {
|
||||
if !(l1 > 1e-9 && l2 > 1e-9) {
|
||||
return None;
|
||||
}
|
||||
Some(Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 })
|
||||
}
|
||||
|
||||
/// How far along segment `s` (`l` long) from its `a` end (`at_a`) or its `b` end the corner
|
||||
/// there may reach: all of it when the other end stays sharp, half when that end is rounded
|
||||
/// too (`rounds`, by point) and takes the other half.
|
||||
fn room(&self, s: usize, at_a: bool, l: f64, rounds: &[bool]) -> f64 {
|
||||
let far = self.segments.get(s).map(|x| if at_a { x.b } else { x.a });
|
||||
if far.and_then(|f| rounds.get(f)).copied().unwrap_or(false) { l / 2.0 } else { l }
|
||||
}
|
||||
|
||||
/// The corner of a rounded point (`p`, see [`Self::turn`]); it reaches along each segment as
|
||||
/// far as [`Self::room`] allows (`rounds`: which points are rounded). With `smoothing`, a point
|
||||
/// between two straight segments that are both `on_loop` gets a smoothed corner.
|
||||
fn corner(&self, p: &Turn, smoothing: f64, on_loop: &[bool], rounds: &[bool]) -> Option<Corner> {
|
||||
let &Turn { v, r, s1, a1, s2, a2, c1, c2, u1, u2, angle, l1, l2 } = p;
|
||||
let reach = self.room(s1, a1, l1, rounds).min(self.room(s2, a2, l2, rounds));
|
||||
let own = |at_a: bool, t: f64| if at_a { t } else { 1.0 - t };
|
||||
let closed = |s: usize| on_loop.get(s).copied().unwrap_or(false);
|
||||
if smoothing > 0.0
|
||||
@@ -584,7 +622,7 @@ impl VectorNetwork {
|
||||
&& is_line(&c2)
|
||||
&& closed(s1)
|
||||
&& closed(s2)
|
||||
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, l1.min(l2) / 2.0, r, smoothing)
|
||||
&& let Some(curves) = figcraft_geom::smoothed_corner(c1.p0, u1, u2, reach, r, smoothing)
|
||||
&& let (Some(first), Some(last)) = (curves.first(), curves.last())
|
||||
{
|
||||
let (a, b) = (first.p0, last.p3);
|
||||
@@ -595,7 +633,7 @@ impl VectorNetwork {
|
||||
let (cut1, cut2) = ((a - c1.p0).hypot() / l1, (b - c2.p0).hypot() / l2);
|
||||
return Some(Corner { v, s1, s1_at_a: a1, s2, s2_at_a: a2, a, chain, cut1: own(a1, cut1), cut2: own(a2, cut2) });
|
||||
}
|
||||
let t = (r / (angle / 2.0).tan()).min(l1.min(l2) / 2.0);
|
||||
let t = (r / (angle / 2.0).tan()).min(reach);
|
||||
let ((a, d1, k1), (b, d2, k2)) = (trim(&c1, t, l1), trim(&c2, t, l2));
|
||||
// A cubic arc: handles of 4/3·tan(φ/4)·ρ along each end's direction, φ the turn between
|
||||
// them and ρ the radius of the circle through both ends (the corner radius between lines).
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! How far a rounded point's arc may reach along its segments (#2334): the whole segment when the
|
||||
//! segment's other end stays sharp, half of it when that end is rounded too. Figma draws a single
|
||||
//! rounded point of a 100 × 100 square with radius 100 as an arc from one neighbour to the other.
|
||||
|
||||
use figcraft_geom::kurbo::{CubicBez, ParamCurve, PathSeg};
|
||||
use figcraft_geom::{BezPath, Point};
|
||||
|
||||
use crate::vector::VectorNetwork;
|
||||
|
||||
/// A 100 × 100 square's points: top left, top right, bottom right, bottom left.
|
||||
const SQUARE: [Point; 4] = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)];
|
||||
|
||||
/// A network through `pts` (closed or open) whose points have radii `radii`.
|
||||
fn network(pts: &[Point], closed: bool, radii: &[f64]) -> VectorNetwork {
|
||||
let mut n = VectorNetwork::from_points(pts, closed);
|
||||
for (v, r) in n.vertices.iter_mut().zip(radii) {
|
||||
v.radius = *r;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The cubic curves of `path` (the rounded points' arcs; every other segment is straight).
|
||||
fn curves(path: &BezPath) -> Vec<CubicBez> {
|
||||
path.segments()
|
||||
.filter_map(|s| match s {
|
||||
PathSeg::Cubic(c) => Some(c),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are the same point to within rounding.
|
||||
fn near(a: Point, b: Point) -> bool {
|
||||
(a - b).hypot() < 1e-9
|
||||
}
|
||||
|
||||
/// Checks that `path` draws, for each `(corner, prev, next, t)` of `want`, a circular arc
|
||||
/// between the points `t` from `corner` toward `prev` and toward `next` (a right angle, so the
|
||||
/// circle's radius is `t`), and no other curve.
|
||||
fn assert_arcs(path: &BezPath, want: &[(Point, Point, Point, f64)], why: &str) {
|
||||
let got = curves(path);
|
||||
assert_eq!(got.len(), want.len(), "{why}: {got:?}");
|
||||
for &(corner, prev, next, t) in want {
|
||||
let toward = |p: Point| corner + (p - corner) / (p - corner).hypot() * t;
|
||||
let (a, b) = (toward(prev), toward(next));
|
||||
let center = a + (b - corner);
|
||||
let mid = center + (corner - center) / (corner - center).hypot() * t;
|
||||
let arc = got.iter().find(|c| (near(c.p0, a) && near(c.p3, b)) || (near(c.p0, b) && near(c.p3, a)));
|
||||
let Some(arc) = arc else { panic!("{why}: no arc from {a:?} to {b:?} in {got:?}") };
|
||||
assert!(near(arc.eval(0.5), mid), "{why}: the arc at {corner:?} passes {:?}, not {mid:?}", arc.eval(0.5));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rounded_points_arc_reaches_as_far_as_its_segments_other_ends_allow() {
|
||||
let [tl, tr, br, bl] = SQUARE;
|
||||
// (radii of [top left, top right, bottom right, bottom left], each arc as (point, its
|
||||
// neighbours, how far it reaches along both), derivation)
|
||||
#[allow(clippy::type_complexity)]
|
||||
let rows: Vec<([f64; 4], Vec<(Point, Point, Point, f64)>, &str)> = vec![
|
||||
([0.0, 0.0, 100.0, 0.0], vec![(br, tr, bl, 100.0)], "the issue's square: the arc runs from one sharp neighbour to the other"),
|
||||
([0.0, 0.0, 500.0, 0.0], vec![(br, tr, bl, 100.0)], "a larger radius stops at the sharp neighbours"),
|
||||
([0.0, 0.0, 75.0, 0.0], vec![(br, tr, bl, 75.0)], "a radius past half the segments is drawn whole"),
|
||||
([0.0, 0.0, 40.0, 0.0], vec![(br, tr, bl, 40.0)], "a radius that fits half the segments is unchanged"),
|
||||
(
|
||||
[0.0, 10.0, 100.0, 0.0],
|
||||
vec![(tr, tl, br, 10.0), (br, tr, bl, 50.0)],
|
||||
"the segment to the rounded top right is shared, half each, and the shorter room wins",
|
||||
),
|
||||
(
|
||||
[100.0, 0.0, 100.0, 0.0],
|
||||
vec![(tl, bl, tr, 100.0), (br, tr, bl, 100.0)],
|
||||
"opposite points share no segment: each reaches its sharp neighbours (a lens)",
|
||||
),
|
||||
(
|
||||
[100.0; 4],
|
||||
vec![(tl, bl, tr, 50.0), (tr, tl, br, 50.0), (br, tr, bl, 50.0), (bl, br, tl, 50.0)],
|
||||
"every point rounded: a circle, as before",
|
||||
),
|
||||
];
|
||||
for (radii, want, why) in rows {
|
||||
let net = network(&SQUARE, true, &radii);
|
||||
assert_arcs(&net.fill_path(), &want, why);
|
||||
assert_arcs(&net.stroke_path(), &want, why);
|
||||
// The stored radii stay as they were set.
|
||||
assert_eq!(net.vertices.iter().map(|p| p.radius).collect::<Vec<_>>(), radii.to_vec(), "{why}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_paths_ends_leave_its_rounded_point_the_whole_segments() {
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0)];
|
||||
// (radii, derivation): the ends don't turn, so a radius on them rounds nothing and takes no
|
||||
// room from the middle point.
|
||||
let rows: Vec<([f64; 3], &str)> =
|
||||
vec![([0.0, 100.0, 0.0], "sharp ends"), ([100.0, 100.0, 100.0], "ends with a radius of their own stay sharp and leave the room to it")];
|
||||
for (radii, why) in rows {
|
||||
let net = network(&pts, false, &radii);
|
||||
assert_arcs(&net.stroke_path(), &[(pts[1], pts[0], pts[2], 100.0)], why);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_smoothed_corner_takes_the_room_of_a_sharp_neighbour_before_losing_smoothing() {
|
||||
// Radius 40 with smoothing 0.6 eases in from 1.6 × 40 = 64 along each side. Half of a 100
|
||||
// side (50) would cut smoothing down; the whole side next to sharp points leaves all of it.
|
||||
let net = network(&SQUARE, true, &[0.0, 0.0, 40.0, 0.0]);
|
||||
let path = net.rounded_smoothed(0.6).unwrap().fill_path();
|
||||
let ends: Vec<Point> = curves(&path).iter().flat_map(|c| [c.p0, c.p3]).collect();
|
||||
for p in [Point::new(100.0, 36.0), Point::new(36.0, 100.0)] {
|
||||
assert!(ends.iter().any(|e| (*e - p).hypot() < 1e-6), "the smoothed corner starts at {p:?}: {ends:?}");
|
||||
}
|
||||
assert!(ends.iter().all(|e| e.x >= 36.0 - 1e-6 && e.y >= 36.0 - 1e-6), "and reaches no further: {ends:?}");
|
||||
}
|
||||
@@ -296,6 +296,8 @@ mod vector_keys_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_panel_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_point_radius_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_point_xy_tests;
|
||||
#[cfg(test)]
|
||||
mod vector_tail_ui_tests;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//! The vector edit panel's Corner radius for a point (#2334): a typed radius larger than half the
|
||||
//! point's segments is kept and shown as typed, and the point is drawn rounded across the whole of
|
||||
//! the segments whose other ends stay sharp, as Figma draws it.
|
||||
|
||||
use egui::Key;
|
||||
use figcraft_geom::Point;
|
||||
use figcraft_geom::kurbo::{ParamCurve, PathSeg};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::field_tests::{field, type_into};
|
||||
use crate::vector_point_xy_tests::setup;
|
||||
|
||||
#[test]
|
||||
fn a_typed_radius_is_kept_shown_and_drawn_across_the_sharp_neighbours_segments() {
|
||||
// The 100 × 60 rectangle in vector edit mode; point 2 is its bottom right corner.
|
||||
let (mut u, id) = setup();
|
||||
u.app.session.execute("vector.edit.select", &json!({"vertices": [2]})).unwrap();
|
||||
type_into(&mut u, "Corner radius", "100", Key::Enter);
|
||||
assert_eq!(field(&mut u, "Corner radius").1, "100", "the field shows the radius as typed");
|
||||
let doc = u.app.session.doc().unwrap();
|
||||
let net = figcraft_engine::vectoredit::network(doc, id).unwrap();
|
||||
assert_eq!(net.vertices.iter().map(|v| v.radius).collect::<Vec<_>>(), vec![0.0, 0.0, 100.0, 0.0], "only point 2 stores it, unclamped");
|
||||
assert_eq!(net.vertices[2].point(), Point::new(100.0, 60.0));
|
||||
// Both neighbours are sharp, so the arc reaches the whole 60 of the shorter side: from the top
|
||||
// right corner to 60 along the bottom, on a circle of radius 60 centred at (40, 0).
|
||||
let arcs: Vec<_> = net
|
||||
.fill_path()
|
||||
.segments()
|
||||
.filter_map(|s| match s {
|
||||
PathSeg::Cubic(c) => Some(c),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(arcs.len(), 1, "{arcs:?}");
|
||||
let ends = [arcs[0].p0, arcs[0].p3];
|
||||
let close = |a: Point, b: Point| (a - b).hypot() < 1e-9;
|
||||
assert!(ends.iter().any(|e| close(*e, Point::new(100.0, 0.0))) && ends.iter().any(|e| close(*e, Point::new(40.0, 60.0))), "{ends:?}");
|
||||
let h = 60.0 / 2f64.sqrt();
|
||||
assert!(close(arcs[0].eval(0.5), Point::new(40.0 + h, h)), "{:?}", arcs[0].eval(0.5));
|
||||
}
|
||||
@@ -9,7 +9,9 @@ use serde_json::json;
|
||||
use crate::field_tests::{field, scrub, type_into, undo_steps};
|
||||
use crate::layers_drag_tests::Ui;
|
||||
|
||||
fn setup() -> (Ui, NodeId) {
|
||||
/// A 100 × 60 rectangle at the origin, selected and in vector edit mode (points clockwise from
|
||||
/// the top left), and its id.
|
||||
pub(crate) fn setup() -> (Ui, NodeId) {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 60})).unwrap();
|
||||
let id = NodeId(r["id"].as_u64().unwrap());
|
||||
|
||||
+3
-2
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user