Compare commits

..
7 changed files with 401 additions and 189 deletions

No files matched your search

@@ -3023,7 +3023,7 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
let angular_resolution = number_widget(
ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context),
NumberInput::default().min(1.).max(180.).unit("°"),
NumberInput::default().min(0.).max(180.).range_min(Some(1.)).unit("°"),
);
widgets.push(LayoutGroup::row(angular_resolution));
@@ -14,7 +14,7 @@ use glam::DVec2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::FallibleVec2Operations;
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::algorithms::shapes::SpiralCurve;
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
use std::f64::consts::TAU;
@@ -41,13 +41,12 @@ pub struct SpiralTurns {
pub handle_state: SpiralTurnsState,
initial_turns: f64,
initial_outer_radius: f64,
initial_inner_radius: f64,
initial_growth_factor: f64,
initial_spiral: SpiralCurve,
/// In degrees, as stored in the node.
initial_start_angle: f64,
previous_mouse_position: DVec2,
total_angle_delta: f64,
gizmo_type: GizmoType,
spiral_type: SpiralType,
}
impl SpiralTurns {
@@ -84,12 +83,10 @@ impl SpiralTurns {
) {
self.layer = Some(layer);
self.initial_turns = turns;
self.initial_growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
self.initial_inner_radius = inner_radius;
self.initial_outer_radius = outer_radius;
self.initial_spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
self.initial_start_angle = start_angle;
self.previous_mouse_position = mouse_position;
self.spiral_type = spiral_type;
self.gizmo_type = gizmo_type;
self.update_state(SpiralTurnsState::Hover);
}
@@ -100,9 +97,9 @@ impl SpiralTurns {
match &self.handle_state {
SpiralTurnsState::Inactive => {
if let Some((spiral_type, start_angle, inner_radius, outer_radius, turns, _)) = extract_spiral_parameters(layer, document) {
let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
let end_point = viewport.transform_point2(spiral_point(turns * TAU + start_angle.to_radians(), inner_radius, growth_factor, spiral_type));
let start_point = viewport.transform_point2(spiral_point(0. + start_angle.to_radians(), inner_radius, growth_factor, spiral_type));
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
let end_point = viewport.transform_point2(spiral.point(turns * TAU));
let start_point = viewport.transform_point2(spiral.point(0.));
if mouse_position.distance(end_point) < SPIRAL_END_HOVER_RADIUS {
self.store_initial_parameters(layer, inner_radius, outer_radius, turns, start_angle, mouse_position, GizmoType::End, spiral_type);
@@ -144,17 +141,27 @@ impl SpiralTurns {
/// How much the outer radius grows as the spiral gains a number of turns, keeping its growth and tightness the same.
fn outer_radius_change(&self, turns_gained: f64) -> f64 {
match self.spiral_type {
SpiralType::Archimedean => turns_gained * self.initial_growth_factor * TAU,
SpiralType::Logarithmic => self.initial_outer_radius * ((self.initial_growth_factor * TAU * turns_gained).exp() - 1.),
let growth_factor = self.initial_spiral.growth_factor;
match self.initial_spiral.spiral_type {
SpiralType::Archimedean => turns_gained * growth_factor * TAU,
SpiralType::Logarithmic => self.initial_outer_radius * ((growth_factor * TAU * turns_gained).exp() - 1.),
}
}
/// The start angle in degrees, the turns, and the outer radius that dragging the start writes for a number of turns, which turns the start along as turns come off.
/// The start angle in degrees, the turns, and the inner radius that dragging the start writes for a number of turns.
/// The start moves along the spiral as turns come off or are added, leaving the rest of the spiral where it was.
fn start_dragged_to(&self, turns: f64) -> (f64, f64, f64) {
let spiral = self.initial_spiral;
let mut turns = turns.max(0.5);
// An Archimedean spiral gains turns at its start only until its radius there shrinks to the center
if spiral.spiral_type == SpiralType::Archimedean && spiral.growth_factor > 0. {
turns = turns.min(self.initial_turns + spiral.inner_radius / (spiral.growth_factor * TAU));
}
let turns_taken_off = self.initial_turns - turns;
let outer_radius = (self.initial_outer_radius + self.outer_radius_change(-turns_taken_off)).max(0.1);
(self.initial_start_angle + turns_taken_off * 360., turns.max(0.5), outer_radius)
let inner_radius = spiral.radius(turns_taken_off * TAU).max(0.);
(self.initial_start_angle + turns_taken_off * 360., turns, inner_radius)
}
/// Snaps a number of turns to whole and half turns, judged by how far the pointer travels around the center on screen.
@@ -171,17 +178,17 @@ impl SpiralTurns {
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
let on_screen_per_turn = TAU * pointer_travel_per_radian(layer_to_viewport, view.input.mouse.position);
let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
let viewport_to_document = document.metadata().document_to_viewport.inverse();
let position_of = |turns_landed_on: f64| {
let (angle, growth_factor) = match self.gizmo_type {
let point = match self.gizmo_type {
GizmoType::Start => {
let (start_angle, turns, outer_radius) = self.start_dragged_to(turns_landed_on);
(start_angle.to_radians(), calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type))
let (start_angle, turns, inner_radius) = self.start_dragged_to(turns_landed_on);
SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians()).point(0.)
}
_ => (turns_landed_on * TAU + start_angle.to_radians(), growth_factor),
_ => spiral.point(turns_landed_on * TAU),
};
viewport_to_document.transform_point2(layer_to_viewport.transform_point2(spiral_point(angle, inner_radius, growth_factor, spiral_type)))
viewport_to_document.transform_point2(layer_to_viewport.transform_point2(point))
};
// The whole and half turns around the asked-for number, counted in half turns
@@ -223,9 +230,8 @@ impl SpiralTurns {
return;
}
// Increase the number of turns and outer radius in unison such that growth and tightness remain same
// The total angle dragged around the center, in degrees, as a number of full turns
let total_delta = self.total_angle_delta + angle_delta;
// Convert the total angle (in degrees) to number of full turns
let turns_delta = total_delta / 360.;
// Dragging the start takes turns away rather than adding them
@@ -238,21 +244,16 @@ impl SpiralTurns {
let snap_correction = (self.snap_turns(view, snap_session, layer, free_turns) - free_turns) * direction;
let turns_delta = turns_delta + snap_correction;
// Calculate the new outer radius based on spiral type and turn change
let outer_radius_change = self.outer_radius_change(turns_delta);
// Skip if outer_radius calculation produced invalid values
if !outer_radius_change.is_finite() {
return;
}
let Some(node_id) = graph_modification_utils::get_spiral_id(layer, &document.network_interface) else {
return;
};
match self.gizmo_type {
GizmoType::Start => {
let (new_start_angle, new_turns, new_outer_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
let (new_start_angle, new_turns, new_inner_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
if !new_inner_radius.is_finite() {
return;
}
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, StartAngleInput),
@@ -263,12 +264,17 @@ impl SpiralTurns {
input: NodeInput::value(TaggedValue::Number(new_turns), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, OuterRadiusInput),
input: NodeInput::value(TaggedValue::Number(new_outer_radius), false),
input_connector: InputConnector::node(node_id, InnerRadiusInput),
input: NodeInput::value(TaggedValue::Number(new_inner_radius), false),
});
}
GizmoType::End => {
// The outer radius grows by the turns actually gained, so the spiral keeps its growth and tightness
let new_turns = (self.initial_turns + turns_delta).max(0.5);
let outer_radius_change = self.outer_radius_change(new_turns - self.initial_turns);
if !outer_radius_change.is_finite() {
return;
}
let new_outer_radius = (self.initial_outer_radius + outer_radius_change).max(0.1);
responses.add(NodeGraphMessage::SetInput {
@@ -14,7 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::algorithms::shapes::SpiralCurve;
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
@@ -83,11 +83,10 @@ impl ShapeGizmoHandler for SpiralGizmoHandler {
/// Calculates the position of a spiral endpoint at a given angle offset (0 = start, TAU = end).
pub fn calculate_spiral_endpoints(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport: DAffine2, theta: f64) -> Option<DVec2> {
let (spiral_type, start_angle, a, outer_radius, turns, _) = extract_spiral_parameters(layer, document)?;
let b = calculate_growth_factor(a, turns, outer_radius, spiral_type);
let theta = turns * theta + start_angle.to_radians();
let (spiral_type, start_angle, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document)?;
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
Some(viewport.transform_point2(spiral_point(theta, a, b, spiral_type)))
Some(viewport.transform_point2(spiral.point(turns * theta)))
}
#[derive(Default)]
@@ -1654,7 +1654,7 @@ mod test_shape_tool {
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, heart_bezpath};
use graphene_std::vector::algorithms::shapes::{SpiralCurve, heart_bezpath};
use graphene_std::vector::generator_nodes::arc;
use graphene_std::vector::misc::{SpiralType, point_to_dvec2};
use kurbo::{Affine, CubicBez, ParamCurve, PathEl, PathSeg};
@@ -2213,12 +2213,17 @@ mod test_shape_tool {
let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await;
let turns_and_growth_factor_of = |document: &DocumentMessageHandler| {
let (spiral_type, _, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document).expect("the spiral should have its parameters");
(turns, calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type))
let (spiral_type, start_angle, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document).expect("the spiral should have its parameters");
(turns, SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians()).growth_factor)
};
let end_of = |document: &DocumentMessageHandler| {
let to_viewport = document.metadata().transform_to_viewport(layer);
calculate_spiral_endpoints(layer, document, to_viewport, TAU).expect("the spiral should have an end")
};
let (turns, growth_factor) = turns_and_growth_factor_of(editor.active_document());
let end = end_of(editor.active_document());
// The start lands on a whole turn fewer, and the outer radius shrinks so the spiral keeps winding as it did
// The start lands on a whole turn fewer, and the inner radius grows so the rest of the spiral stays where it was
let whole = turns.ceil() - 1.;
let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await;
@@ -2229,6 +2234,9 @@ mod test_shape_tool {
"the growth factor is {dragged_growth_factor} rather than {growth_factor}"
);
let dragged_end = end_of(editor.active_document());
assert!(dragged_end.distance(end) < 1e-6, "the far end moved from {end} to {dragged_end}");
editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await;
}
@@ -423,7 +423,11 @@ fn compute_circular_subpath_details(left: DVec2, arc_point: DVec2, right: DVec2,
let center_to_arc_point = arc_point - center;
// Based on https://pomax.github.io/bezierinfo/#circles_cubic
let handle_offset_factor = if let Some(angle) = angle { 4. / 3. * (angle / 4.).tan() } else { 0.551784777779014 };
let handle_offset_factor = if let Some(angle) = angle {
4. / 3. * (angle / 4.).tan()
} else {
super::shapes::HANDLE_OFFSET_FACTOR
};
let p1 = dvec2_to_point(left - (left - center).perp() * handle_offset_factor);
let p2 = dvec2_to_point(arc_point + center_to_arc_point.perp() * handle_offset_factor);
@@ -5,19 +5,27 @@
mod heart;
use crate::vector::misc::{ArcType, SpiralType, bezpath_from_anchors_and_handles};
use glam::DVec2;
use glam::{DMat2, DVec2};
pub use heart::{HEART_SIZE, HeartProportions, heart_bezpath};
use kurbo::BezPath;
use std::f64::consts::TAU;
use std::f64::consts::{PI, SQRT_2, TAU};
/// Constant from <https://pomax.github.io/bezierinfo/#circles_cubic>
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
/// Handle length of a quarter circle's cubic relative to its radius, 4(√2 − 1)/3, which puts each quarter's midpoint on the circle.
/// Other vector editors draw circles with it, so it's kept for interop over the 0.551915 that slightly lowers the largest error.
pub(crate) const HANDLE_OFFSET_FACTOR: f64 = 4. * (SQRT_2 - 1.) / 3.;
/// Relative growth per radian below which spiral arc lengths use a circle, since the closed forms divide by the growth.
const SPIRAL_CIRCLE_GROWTH: f64 = 1e-6;
/// The most anchors a polygon or star can have before allocating them overflows the address space.
const MAX_POLYGON_ANCHORS: u64 = (isize::MAX as usize / size_of::<Anchor>()) as u64;
/// The smallest radius of a logarithmic spiral, standing in for zero since such a spiral never reaches its center.
const LOGARITHMIC_SPIRAL_MIN_RADIUS: f64 = 1e-10;
/// Cubic parameters where the error peaks for the best fit to any smooth curve with the cubic's ends and end tangents on it.
/// To leading order that error is proportional to t²(1 − t)²((t − ½)² − q), with q = 0.0264731 equalizing its three peaks.
const SPIRAL_RIPPLE_PARAMETERS: [f64; 3] = [0.18222320647320767, 0.5, 0.8177767935267923];
/// The most anchors a generated shape can have before allocating them overflows the address space.
const MAX_SHAPE_ANCHORS: u64 = (isize::MAX as usize / size_of::<Anchor>()) as u64;
/// The failure of [`regular_polygon_bezpath`] and [`star_polygon_bezpath`].
#[derive(Debug, thiserror::Error)]
@@ -177,7 +185,7 @@ pub fn arc_bezpath(radius: f64, start_angle: f64, sweep_angle: f64, arc_type: Ar
/// Constructs a regular polygon (ngon). Based on `sides` and `radius`, which is the distance from the center to any vertex.
/// Fails when it has more sides than can be allocated.
pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> Result<BezPath, PolygonError> {
if sides > MAX_POLYGON_ANCHORS {
if sides > MAX_SHAPE_ANCHORS {
return Err(PolygonError::TooManySides(sides));
}
@@ -194,7 +202,7 @@ pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> Result
/// Constructs a star polygon (n-star). See [`regular_polygon_bezpath`], but with interspersed vertices at an `inner_radius`.
pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> Result<BezPath, PolygonError> {
// Each side has an outer and an inner anchor
if sides > MAX_POLYGON_ANCHORS / 2 {
if sides > MAX_SHAPE_ANCHORS / 2 {
return Err(PolygonError::TooManySides(sides));
}
@@ -250,151 +258,239 @@ pub fn arrow_bezpath(start: DVec2, end: DVec2, shaft_width: f64, head_width: f64
/// The failure of [`spiral_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum SpiralError {
#[error("The angular resolution must be greater than 0")]
AngularResolutionNotPositive,
#[error("The number of turns must be finite")]
TurnsNotFinite,
#[error("The start angle is too large to step through at this angular resolution")]
AngleTooLarge,
#[error("A spiral with this many turns at this angular resolution is too large to fit in memory")]
TooManySegments,
}
/// Constructs a spiral winding from an inner radius `a` out to `outer_radius`, sampled every `delta_theta` radians.
pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> Result<BezPath, SpiralError> {
if delta_theta.is_nan() || delta_theta <= 0. {
return Err(SpiralError::AngularResolutionNotPositive);
}
if turns == f64::INFINITY {
return Err(SpiralError::TurnsNotFinite);
/// Constructs a spiral winding `turns` times from `inner_radius` out to `outer_radius`, rotated to start at `start_angle`, with a cubic every `angular_resolution` (both in radians).
pub fn spiral_bezpath(inner_radius: f64, outer_radius: f64, turns: f64, start_angle: f64, angular_resolution: f64, spiral_type: SpiralType) -> Result<BezPath, SpiralError> {
let sweep = turns * TAU;
if sweep.is_nan() || sweep <= 0. {
return Ok(BezPath::new());
}
let mut anchors = Vec::new();
let mut prev_in_handle = None;
let theta_end = turns * TAU + start_angle;
let a = if spiral_type == SpiralType::Logarithmic { a.max(1e-10) } else { a };
let b = calculate_growth_factor(a, turns, outer_radius, spiral_type);
let mut theta = start_angle;
while theta < theta_end {
let theta_next = f64::min(theta + delta_theta, theta_end);
// A step lost to the angle's float precision would never reach the end
if theta_next == theta {
return Err(SpiralError::AngleTooLarge);
}
let p0 = spiral_point(theta, a, b, spiral_type);
let p3 = spiral_point(theta_next, a, b, spiral_type);
let t0 = spiral_tangent(theta, a, b, spiral_type);
let t1 = spiral_tangent(theta_next, a, b, spiral_type);
let arc_length = spiral_arc_length(theta, theta_next, a, b, spiral_type);
let handle_distance = arc_length / 3.;
let p1 = p0 + handle_distance * t0;
let p2 = p3 - handle_distance * t1;
anchors.push(Anchor::new(p0, prev_in_handle, Some(p1)));
prev_in_handle = Some(p2);
// If final segment, end with anchor at theta_end
if (theta_next - theta_end).abs() < f64::EPSILON {
anchors.push(Anchor::new(p3, prev_in_handle, None));
break;
}
theta = theta_next;
// Slightly under a whole number of segments counts as that number, so float error in the division adds no sliver segment at the end
let segment_count = (sweep / angular_resolution - 1e-9).ceil().max(1.);
if segment_count >= MAX_SHAPE_ANCHORS as f64 {
return Err(SpiralError::TooManySegments);
}
let segment_count = segment_count as usize;
// Segment ends are multiples of the resolution rather than running sums, which would accumulate float error
let segment_end = |index: usize| if index == segment_count { sweep } else { index as f64 * angular_resolution };
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle);
let mut anchors = Vec::with_capacity(segment_count + 1);
let mut in_handle = None;
for index in 0..segment_count {
let [start, start_handle, end_handle, _] = spiral.segment(segment_end(index), segment_end(index + 1));
anchors.push(Anchor::new(start, in_handle, Some(start_handle)));
in_handle = Some(end_handle);
}
anchors.push(Anchor::new(spiral.point(sweep), in_handle, None));
Ok(bezpath_from_anchors(&anchors, false))
}
pub fn calculate_growth_factor(a: f64, turns: f64, outer_radius: f64, spiral_type: SpiralType) -> f64 {
match spiral_type {
SpiralType::Archimedean => {
let total_theta = turns * TAU;
(outer_radius - a) / total_theta
}
SpiralType::Logarithmic => {
let total_theta = turns * TAU;
((outer_radius.abs() / a).ln()) / total_theta
/// A spiral starting at its inner radius in the direction of its start angle, its radius changing with the angle it sweeps from there.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SpiralCurve {
pub spiral_type: SpiralType,
/// The radius at the start.
pub inner_radius: f64,
/// The change per radian swept, added to the radius of an Archimedean spiral or to the natural log of the radius of a logarithmic one.
pub growth_factor: f64,
/// The direction of the start in radians, which rotates the spiral without changing its shape.
pub start_angle: f64,
}
impl SpiralCurve {
/// The spiral winding `turns` times from `inner_radius` to `outer_radius`, rotated to start at `start_angle` radians.
pub fn new(spiral_type: SpiralType, inner_radius: f64, outer_radius: f64, turns: f64, start_angle: f64) -> Self {
let (inner_radius, total_growth) = match spiral_type {
SpiralType::Archimedean => (inner_radius, outer_radius - inner_radius),
SpiralType::Logarithmic => {
let inner_radius = inner_radius.max(LOGARITHMIC_SPIRAL_MIN_RADIUS);
let outer_radius = outer_radius.abs().max(LOGARITHMIC_SPIRAL_MIN_RADIUS);
(inner_radius, outer_radius.ln() - inner_radius.ln())
}
};
// With no turns to grow over, the spiral stays at its inner radius
let growth_factor = total_growth / (turns * TAU);
let growth_factor = if growth_factor.is_finite() { growth_factor } else { 0. };
Self {
spiral_type,
inner_radius,
growth_factor,
start_angle,
}
}
}
/// Returns a point on the given spiral type at angle `theta`.
pub fn spiral_point(theta: f64, a: f64, b: f64, spiral_type: SpiralType) -> DVec2 {
match spiral_type {
SpiralType::Archimedean => archimedean_spiral_point(theta, a, b),
SpiralType::Logarithmic => log_spiral_point(theta, a, b),
/// The radius at `angle` radians swept from the start.
pub fn radius(&self, angle: f64) -> f64 {
match self.spiral_type {
SpiralType::Archimedean => self.inner_radius + self.growth_factor * angle,
SpiralType::Logarithmic => self.inner_radius * (self.growth_factor * angle).exp(),
}
}
/// The point at `angle` radians swept from the start.
pub fn point(&self, angle: f64) -> DVec2 {
self.radius(angle) * self.outward(angle)
}
/// The unit direction from the center to the point at `angle` radians swept from the start, which turns counterclockwise with +Y pointing down.
fn outward(&self, angle: f64) -> DVec2 {
let (sin, cos) = (self.start_angle + angle).sin_cos();
DVec2::new(cos, -sin)
}
/// The point at `angle` radians swept from the start, and its first and second derivatives with respect to that angle.
fn derivatives(&self, angle: f64) -> [DVec2; 3] {
let radius = self.radius(angle);
let (radius_rate, radius_acceleration) = match self.spiral_type {
SpiralType::Archimedean => (self.growth_factor, 0.),
SpiralType::Logarithmic => (self.growth_factor * radius, self.growth_factor * self.growth_factor * radius),
};
// The outward direction turns toward `around` as the angle grows, and `around` toward the inward direction
let outward = self.outward(angle);
let around = DVec2::new(outward.y, -outward.x);
[
radius * outward,
radius_rate * outward + radius * around,
(radius_acceleration - radius) * outward + 2. * radius_rate * around,
]
}
/// The length along the spiral from `start` to `end` radians swept.
fn arc_length(&self, start: f64, end: f64) -> f64 {
let growth_factor = self.growth_factor;
match self.spiral_type {
SpiralType::Archimedean => {
let middle_radius = self.radius((start + end) / 2.);
if growth_factor.abs() <= middle_radius.abs() * SPIRAL_CIRCLE_GROWTH {
return middle_radius.abs() * (end - start);
}
// An antiderivative of the arc length, in terms of the radius
let antiderivative = |radius: f64| {
let hypotenuse = (radius * radius + growth_factor * growth_factor).sqrt();
(radius * hypotenuse + growth_factor * growth_factor * (radius + hypotenuse).ln()) / (2. * growth_factor)
};
antiderivative(self.radius(end)) - antiderivative(self.radius(start))
}
SpiralType::Logarithmic => {
let factor = (1. + growth_factor * growth_factor).sqrt();
if growth_factor.abs() < SPIRAL_CIRCLE_GROWTH {
return self.radius((start + end) / 2.) * factor * (end - start);
}
(self.radius(end) - self.radius(start)) * factor / growth_factor
}
}
}
/// The control points of the cubic closest to the spiral from `start` to `end` radians swept, its ends and end tangents on the spiral.
/// Its two handle lengths are solved so its largest distance from the spiral, which shrinks as the sixth power of the span, is as small as possible.
fn segment(&self, start: f64, end: f64) -> [DVec2; 4] {
let span = end - start;
let [start_point, start_velocity, _] = self.derivatives(start);
let [end_point, end_velocity, _] = self.derivatives(end);
let (start_tangent, end_tangent) = (start_velocity.normalize_or(DVec2::X), end_velocity.normalize_or(DVec2::X));
let cubic = |lengths: DVec2| [start_point, start_point + lengths.x * start_tangent, end_point - lengths.y * end_tangent, end_point];
// Both handles at a third of the arc length is the fallback where the fit fails, and past a half turn where it finds spurious solutions
let arc_third = DVec2::splat(self.arc_length(start, end) / 3.);
if span > PI * (1. + 1e-9) {
return cubic(arc_third);
}
// Coarse samples of the spiral seed each search for the spiral angle nearest a point on the cubic
let samples: [(f64, DVec2); 9] = std::array::from_fn(|index| {
let angle = start + span * index as f64 / 8.;
(angle, self.point(angle))
});
// The signed distance from the cubic at `t` to the spiral, and its slope in each handle length. `nearest` carries the angle found to the next search.
let error_and_slope = |lengths: DVec2, t: f64, nearest: &mut Option<f64>| {
let s = 1. - t;
let (start_weight, end_weight) = (3. * s * s * t, 3. * s * t * t);
let point = (s * s * s + start_weight) * start_point + start_weight * lengths.x * start_tangent + (t * t * t + end_weight) * end_point - end_weight * lengths.y * end_tangent;
let guess = nearest.unwrap_or_else(|| {
let closest = samples.iter().min_by(|(_, a), (_, b)| a.distance_squared(point).total_cmp(&b.distance_squared(point)));
closest.map_or(start, |&(angle, _)| angle)
});
let angle = self.nearest_angle(point, guess, start, end);
*nearest = Some(angle);
let [position, velocity, _] = self.derivatives(angle);
let normal = velocity.normalize_or(DVec2::X).perp();
let slope = DVec2::new(start_weight * normal.dot(start_tangent), -end_weight * normal.dot(end_tangent));
(normal.dot(point - position), slope)
};
// Errors this small are float noise with nothing left to improve
let noise_floor = 1e-13 * (start_point.length() + end_point.length());
// Newton's method on the handle lengths, first from the fallback (which finds the better of two solutions on steep spirals), then from a circle's lengths
let circle_factor = 4. / 3. * (span / 4.).tan();
let initial_guesses = [arc_third, circle_factor * DVec2::new(start_velocity.length(), end_velocity.length())];
'guesses: for mut lengths in initial_guesses {
let mut nearest = [None; 3];
for _ in 0..8 {
let [(error_a, slope_a), (error_middle, slope_middle), (error_b, slope_b)] =
std::array::from_fn(|index| error_and_slope(lengths, SPIRAL_RIPPLE_PARAMETERS[index], &mut nearest[index]));
// The largest error is smallest when its three peaks alternate in sign with equal size
let residual = DVec2::new(error_a + error_middle, error_middle + error_b);
let step = if residual.abs().element_sum() <= noise_floor {
DVec2::ZERO
} else {
DMat2::from_cols(slope_a + slope_middle, slope_middle + slope_b).transpose().inverse() * residual
};
if !step.is_finite() {
continue 'guesses;
}
// Neither handle changes by more than half its length in one step, which keeps both positive
let step = step * (0.5 * lengths / step.abs()).min_element().min(1.);
lengths -= step;
if step.abs().element_sum() <= 1e-9 * lengths.element_sum() {
return cubic(lengths);
}
}
}
cubic(arc_third)
}
/// The angle within `start..end` radians swept where the spiral comes nearest to `point`, searched from `guess`.
fn nearest_angle(&self, point: DVec2, guess: f64, start: f64, end: f64) -> f64 {
let max_step = (end - start) / 4.;
let mut angle = guess;
for _ in 0..6 {
let [position, velocity, acceleration] = self.derivatives(angle);
let offset = position - point;
// Newton's method on the squared distance, or Gauss-Newton where that distance isn't convex
let speed_squared = velocity.length_squared();
let second_derivative = speed_squared + offset.dot(acceleration);
let step = offset.dot(velocity) / if second_derivative > 0.25 * speed_squared { second_derivative } else { speed_squared };
if !step.is_finite() {
break;
}
angle = (angle - step.clamp(-max_step, max_step)).clamp(start, end);
}
angle
}
}
/// Returns the tangent direction at angle `theta` for the given spiral type.
fn spiral_tangent(theta: f64, a: f64, b: f64, spiral_type: SpiralType) -> DVec2 {
match spiral_type {
SpiralType::Archimedean => archimedean_spiral_tangent(theta, a, b),
SpiralType::Logarithmic => log_spiral_tangent(theta, a, b),
}
}
/// Computes arc length between two angles for the given spiral type.
fn spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64, spiral_type: SpiralType) -> f64 {
match spiral_type {
SpiralType::Archimedean => archimedean_spiral_arc_length(theta_start, theta_end, a, b),
SpiralType::Logarithmic => log_spiral_arc_length(theta_start, theta_end, a, b),
}
}
/// Returns a point on a logarithmic spiral at angle `theta`.
fn log_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a * (b * theta).exp(); // a * e^(bθ)
DVec2::new(r * theta.cos(), -r * theta.sin())
}
/// Computes arc length along a logarithmic spiral between two angles.
fn log_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let factor = (1. + b * b).sqrt();
if b.abs() < SPIRAL_CIRCLE_GROWTH {
return a * (b * (theta_start + theta_end) / 2.).exp() * factor * (theta_end - theta_start);
}
(a / b) * factor * ((b * theta_end).exp() - (b * theta_start).exp())
}
/// Returns the tangent direction of a logarithmic spiral at angle `theta`.
fn log_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a * (b * theta).exp();
let dx = r * (b * theta.cos() - theta.sin());
let dy = r * (b * theta.sin() + theta.cos());
DVec2::new(dx, -dy).normalize_or(DVec2::X)
}
/// Returns a point on an Archimedean spiral at angle `theta`.
fn archimedean_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a + b * theta;
DVec2::new(r * theta.cos(), -r * theta.sin())
}
/// Returns the tangent direction of an Archimedean spiral at angle `theta`.
fn archimedean_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a + b * theta;
let dx = b * theta.cos() - r * theta.sin();
let dy = b * theta.sin() + r * theta.cos();
DVec2::new(dx, -dy).normalize_or(DVec2::X)
}
/// Computes arc length along an Archimedean spiral between two angles.
fn archimedean_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let middle_radius = a + b * (theta_start + theta_end) / 2.;
if b.abs() <= middle_radius.abs() * SPIRAL_CIRCLE_GROWTH {
return middle_radius.abs() * (theta_end - theta_start);
}
archimedean_spiral_arc_length_origin(theta_end, a, b) - archimedean_spiral_arc_length_origin(theta_start, a, b)
}
/// Computes arc length from origin to a point on Archimedean spiral at angle `theta`.
fn archimedean_spiral_arc_length_origin(theta: f64, a: f64, b: f64) -> f64 {
let r = a + b * theta;
let sqrt_term = (r * r + b * b).sqrt();
(r * sqrt_term + b * b * ((r + sqrt_term).ln())) / (2. * b)
}
+100 -1
View File
@@ -56,17 +56,23 @@ fn spiral(
_: impl Ctx,
_primary: (),
spiral_type: Item<SpiralType>,
#[default(5.)] turns: Item<f64>,
#[hard(0..)]
#[default(5.)]
turns: Item<f64>,
#[unit("°")]
#[default(0.)]
start_angle: Item<f64>,
#[unit(" px")]
#[hard(0..)]
#[default(0.)]
inner_radius: Item<f64>,
#[unit(" px")]
#[default(25)]
outer_radius: Item<f64>,
// Past a half turn no cubic follows the spiral closely
#[unit("°")]
#[hard(0..180)]
#[soft(1..)]
#[default(90.)]
angular_resolution: Item<f64>,
) -> Result<Item<Vector>, SpiralError> {
@@ -547,6 +553,7 @@ mod tests {
use super::*;
use core_types::list::{ATTR_DEPTH, ATTR_DISTANCE, ATTR_HEADING, ATTR_KIND, ATTR_SMOOTH, ATTR_STEP, ATTR_UV, ATTR_WIDTH};
use kurbo::ParamCurve;
use std::f64::consts::{PI, TAU};
use vector_types::vector::misc::point_to_dvec2;
use vector_types::vector::shared_paths_from_item_attributes;
@@ -790,6 +797,98 @@ mod tests {
}
}
/// Every control point of a spiral's cubics, in order.
fn spiral_control_points(inner_radius: f64, outer_radius: f64, turns: f64, start_angle: f64, angular_resolution: f64, spiral_type: SpiralType) -> Vec<DVec2> {
let bezpath = shapes::spiral_bezpath(inner_radius, outer_radius, turns, start_angle, angular_resolution, spiral_type).unwrap();
bezpath
.segments()
.flat_map(|segment| {
let cubic = segment.to_cubic();
[cubic.p0, cubic.p1, cubic.p2, cubic.p3]
})
.map(point_to_dvec2)
.collect()
}
// Between quarter-turn anchors, the best cubics stay within 0.02% of the spiral's radius
#[test]
fn spiral_cubics_stay_on_the_spiral_between_anchors() {
let (turns, angular_resolution) = (5., 90_f64.to_radians());
for (inner_radius, outer_radius, spiral_type) in [
(25., 25., SpiralType::Archimedean),
(20., 25., SpiralType::Archimedean),
(25., 25., SpiralType::Logarithmic),
(1., 100., SpiralType::Logarithmic),
] {
let bezpath = shapes::spiral_bezpath(inner_radius, outer_radius, turns, 0., angular_resolution, spiral_type).unwrap();
let spiral = shapes::SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, 0.);
// Each point's distance from the spiral at the same angle, unwrapped to the turn its segment winds through, relative to the spiral's radius there
let largest_error = bezpath
.segments()
.enumerate()
.flat_map(|(index, segment)| {
let middle = (index as f64 + 0.5) * angular_resolution;
(0..=64).map(move |step| {
let point = point_to_dvec2(segment.eval(step as f64 / 64.));
let angle = middle + (f64::atan2(-point.y, point.x) - middle + PI).rem_euclid(TAU) - PI;
let radius = spiral.radius(angle);
((point.length() - radius) / radius).abs()
})
})
.fold(0., f64::max);
assert!(largest_error < 2.5e-4, "{spiral_type:?} from {inner_radius} to {outer_radius} strays {largest_error} of its radius");
}
}
// Each segment's end is a multiple of the resolution, so a whole number of steps lands exactly on the end without a sliver segment after it
#[test]
fn spiral_has_one_segment_per_resolution_step() {
for (turns, degrees, segment_count) in [
(5., 30., 60),
(5., 60., 30),
(5., 22.5, 80),
(10., 45., 80),
(1., 60., 6),
(5., 1., 1800),
(5., 90., 20),
(1.25, 100., 5),
] {
let control_points = spiral_control_points(0., 25., turns, 0., f64::to_radians(degrees), SpiralType::Archimedean);
assert_eq!(control_points.len(), segment_count * 4, "{turns} turns at {degrees}°");
}
}
// The start angle rotates the spiral, which still winds from its inner radius to its outer radius
#[test]
fn spiral_start_angle_only_rotates_it() {
for spiral_type in [SpiralType::Archimedean, SpiralType::Logarithmic] {
let unrotated = spiral_control_points(5., 25., 2.5, 0., 45_f64.to_radians(), spiral_type);
let rotated = spiral_control_points(5., 25., 2.5, 90_f64.to_radians(), 45_f64.to_radians(), spiral_type);
// A quarter turn counterclockwise on screen, where +Y points down
let quarter_turn = DVec2::from_angle(-90_f64.to_radians());
assert!(unrotated.iter().zip(&rotated).all(|(unrotated, rotated)| quarter_turn.rotate(*unrotated).distance(*rotated) < 1e-9));
let (first, last) = (rotated.first().unwrap(), rotated.last().unwrap());
assert!((first.length() - 5.).abs() < 1e-9 && (last.length() - 25.).abs() < 1e-9, "{spiral_type:?} runs from {first} to {last}");
}
}
#[test]
fn logarithmic_spiral_to_a_zero_outer_radius_stays_finite() {
let control_points = spiral_control_points(10., 0., 2., 0., 90_f64.to_radians(), SpiralType::Logarithmic);
assert!(!control_points.is_empty() && control_points.iter().all(|point| point.is_finite()));
}
#[test]
fn spirals_report_more_segments_than_can_be_allocated() {
let endless = spiral((), (), item(SpiralType::Archimedean), item(f64::INFINITY), item(0.), item(0.), item(25.), item(90.));
assert!(matches!(endless, Err(SpiralError::TooManySegments)));
}
fn turtle(commands: &str) -> Item<Vector> {
turtle_varied(commands, 0., 0)
}