Compare commits

..
Author SHA1 Message Date
Keavon Chambers 517477e391 Improve the 'Spiral' node's curve accuracy and make Start Angle only rotate it 2026-12-05 17:26:00 -08:00
Dennis Kobert 436c943196 Hash vector modifications deterministically instead of with a random ID (#5082) 2026-12-05 12:33:12 +01:00
Keavon Chambers 5add0191f4 Make middle-clicking a node toggle its visibility in the node graph, Inspector, and Layers panels (#5080) 2026-12-04 16:22:27 -08:00
Timon c7e9aaa016 Fix value nodes leaking source map rows on every graph compile (#5078)
* Fix value nodes leaking source map rows on every graph compile

* Update the flatten test for value nodes without a document path
2026-12-04 19:22:18 +00:00
24 changed files with 718 additions and 332 deletions

No files matched your search

@@ -1,11 +1,11 @@
use crate::application::Environment;
use crate::consts::{
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
};
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
@@ -34,6 +34,8 @@ pub struct NavigationMessageHandler {
abortable_pan_start: Option<f64>,
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
artwork_behind_graph: bool,
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
graph_middle_click_start: Option<ViewportPosition>,
}
#[message_handler_data]
@@ -99,6 +101,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
return;
};
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
}
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
@@ -341,6 +347,13 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
responses.add(ToolMessage::UpdateCursor);
responses.add(ToolMessage::UpdateHints);
responses.add(NavigateToolMessage::End);
// Not a pan after all, but a middle click in the graph
let middle_click_start = self.graph_middle_click_start.take();
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
responses.add(NodeGraphMessage::MiddleClick);
}
}
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
self.finish_operation_with_click = false;
@@ -417,6 +430,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
}
}
NavigationMessage::PointerMove { snap } => {
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
self.graph_middle_click_start = None;
}
match self.navigation_operation {
NavigationOperation::None => {}
NavigationOperation::Pan { .. } => {
@@ -170,6 +170,8 @@ pub enum NodeGraphMessage {
PointerOutsideViewport {
shift: Key,
},
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
MiddleClick,
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
WireHoverTick,
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
@@ -437,6 +439,7 @@ impl NodeGraphMessage {
| Self::PointerMove { .. }
| Self::PointerUp
| Self::PointerOutsideViewport { .. }
| Self::MiddleClick
| Self::WireHoverTick
| Self::SendGlide
| Self::GlideTick
@@ -1752,6 +1752,20 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.auto_panning.stop(&messages, responses);
}
}
// Middle-clicking a node toggles its visibility
NodeGraphMessage::MiddleClick => {
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
return;
}
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
return;
};
responses.add(NodeGraphMessage::ToggleVisibility {
node_id,
network_path: breadcrumb_network_path.to_vec(),
});
}
NodeGraphMessage::WireHoverTick => {
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
}
@@ -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));
@@ -3399,6 +3399,63 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
);
}
#[tokio::test]
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
let graph_pan = |editor: &EditorTestUtils| {
editor
.active_document()
.network_interface
.network_metadata(&[])
.unwrap()
.persistent_metadata
.navigation_metadata
.node_graph_ptz
.pan
};
let layer_in_viewport = |editor: &EditorTestUtils| {
let network_interface = &editor.active_document().network_interface;
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
(0..=(max.x - min.x) as i32)
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
.expect("the layer should be pressable")
};
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
editor_position: position,
mouse_keys,
..Default::default()
};
// Pressed and released with a wobble too small to count as a drag
let start = layer_in_viewport(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
// Dragged away and back before the release
let start = layer_in_viewport(&editor);
let pan_before = graph_pan(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
editor.handle_message(DocumentMessage::Undo).await;
assert!(is_visible(&editor), "one undo should revert the middle click");
}
#[tokio::test]
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
let mut editor = EditorTestUtils::create();
@@ -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;
}
@@ -2,6 +2,8 @@
import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
import type { DragToggleListener } from "/src/managers/drag-toggle";
import { inspectorLayout } from "/src/stores/portfolio";
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -23,7 +25,15 @@
let lastDragClientY = 0;
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
// Everything one middle-button drag across the section headers paints is one history step
const dragToggleListener: DragToggleListener = {
groups: ["inspector-section-visibility"],
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
};
onMount(() => {
createDragToggleManager(dragToggleListener);
addEventListener("pointermove", draggingPointerMove);
addEventListener("pointerup", draggingPointerUp);
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
@@ -36,6 +46,8 @@
});
onDestroy(() => {
destroyDragToggleManager(dragToggleListener);
removeEventListener("pointermove", draggingPointerMove);
removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointercancel", abortDrag);
@@ -331,6 +331,7 @@
}
const dragToggleListener: DragToggleListener = {
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
activeGroupChanged: (group) => {
activeDragToggleGroup = group;
},
@@ -342,6 +343,15 @@
editor.toggleNodeVisibilityLayerPanel(id);
}
// Middle-clicking one of the chain's node buttons toggles that node's visibility
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
if (e.button !== 1) return;
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
}
function toggleLayerLock(id: bigint) {
editor.toggleLayerLock(id);
}
@@ -1194,6 +1204,7 @@
on:pointerdown={(e) => layerPointerDown(e, listing)}
on:click={(e) => selectLayerWithModifiers(e, listing)}
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
on:pointerenter={() => hoverRow(index)}
on:pointerleave={() => (hoveredRowIndex = undefined)}
>
@@ -1343,6 +1354,8 @@
data-chain-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
/>
{/if}
{/if}
@@ -1359,12 +1372,17 @@
: entry.chainExpanded
? "Stop listing this layer's chain one node per row."
: "List this layer's chain one node per row, beneath the layer."}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
on:click={(e) => {
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
if (entry.chainNodes.length === 0) return;
e.stopPropagation();
editor.toggleLayerChainExpanded(listing.id);
}}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
}}
>
<IconLabel
icon={entry.iconName}
@@ -1395,10 +1413,15 @@
data-chain-row-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
on:pointerdown={(e) => {
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
}}
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
}}
on:dblclick={(e) => {
// Only the node's icon opens it in the graph
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
@@ -41,6 +41,12 @@
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
}
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
if (e.button !== 1 || widgetData.disabled) return;
editor.toggleNodeVisibilityInspector(widgetData.id);
}
</script>
<!-- TODO: Implement collapsable sections with the Inspector system -->
@@ -76,7 +82,16 @@
{/if}
{/each}
{:else}
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
<button
class="header"
class:expanded
class:expandable
data-inspector-reorder-handle={reorderable ? "" : undefined}
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
onclick={toggleExpandedWithModifiers}
onauxclick={toggleVisibilityWithMiddleClick}
>
<div
class="icon-slot"
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
+81 -25
View File
@@ -8,21 +8,30 @@
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
//
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
// rather than a click. Their gesture engages on the press, which toggles the source at once.
export type DragToggleListener = {
// The groups whose gestures this listener is told about
groups: string[];
// Given the group of the pressed button, and undefined once the press ends
activeGroupChanged?: (activeGroup: string | undefined) => void;
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
engagedChanged?: (engaged: boolean) => void;
};
const MIDDLE_BUTTON = 1;
const listeners = new Set<DragToggleListener>();
let activeGroup: string | undefined = undefined;
let middleButtonGesture = false;
let source: HTMLElement | undefined = undefined;
let startingState: string | undefined = undefined;
let visited = new WeakSet<Element>();
let engaged = false;
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
let suppressNextAuxClick = false;
export function createDragToggleManager(listener: DragToggleListener) {
listeners.add(listener);
@@ -38,12 +47,13 @@ export function createDragToggleManager(listener: DragToggleListener) {
window.addEventListener("blur", onPointerUp);
// Capture phase on click suppresses the natural source-click before the button's handler runs
window.addEventListener("click", onClickCapture, true);
window.addEventListener("auxclick", onAuxClickCapture, true);
}
}
export function destroyDragToggleManager(listener: DragToggleListener) {
// A consumer leaving mid-gesture still hears it end
if (engaged) listener.engagedChanged?.(false);
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
listeners.delete(listener);
// Uninstall the window event listeners only once the last consumer leaves
@@ -54,83 +64,120 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
window.removeEventListener("pointercancel", onPointerUp);
window.removeEventListener("blur", onPointerUp);
window.removeEventListener("click", onClickCapture, true);
window.removeEventListener("auxclick", onAuxClickCapture, true);
activeGroup = undefined;
middleButtonGesture = false;
source = undefined;
startingState = undefined;
visited = new WeakSet();
engaged = false;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
}
}
function notifyActiveGroupChange(group: string | undefined) {
activeGroup = group;
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
function listenersOfGroup(group: string): DragToggleListener[] {
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
}
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
function notifyActiveGroupChange(group: string | undefined) {
const previousGroup = activeGroup;
activeGroup = group;
const notifiedGroup = group || previousGroup;
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
}
function groupAttribute(middleButton: boolean): string {
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
}
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
if (!(target instanceof Element)) return undefined;
const found = target.closest("[data-drag-toggle-group]");
const found = target.closest(`[${groupAttribute(middleButton)}]`);
return found instanceof HTMLElement ? found : undefined;
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0) return;
suppressNextClickFromSource = undefined;
function memberState(member: HTMLElement): string | undefined {
return member.getAttribute("data-drag-toggle-state") || undefined;
}
const found = findMember(e.target || undefined);
function toggle(member: HTMLElement) {
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
else member.click();
}
function engage() {
if (!activeGroup || !source) return;
engaged = true;
visited.add(source);
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
if (memberState(source) === startingState) toggle(source);
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
const middleButton = e.button === MIDDLE_BUTTON;
const found = findMember(e.target || undefined, middleButton);
if (!found) return;
// Stop the event so sibling drag/select handlers on ancestors don't also engage
e.stopPropagation();
middleButtonGesture = middleButton;
source = found;
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
startingState = memberState(found);
visited = new WeakSet();
engaged = false;
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
if (middleButton) engage();
}
function onPointerMove(e: PointerEvent) {
if (!activeGroup || !source) return;
const member = findMember(e.target || undefined);
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
const member = findMember(e.target || undefined, middleButtonGesture);
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
if (member === source || visited.has(member)) return;
// First crossing engages the drag and toggles the source as part of the operation
if (!engaged) {
engaged = true;
visited.add(source);
listeners.forEach((listener) => listener.engagedChanged?.(true));
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
}
if (!engaged) engage();
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
if (memberState(member) !== startingState) return;
visited.add(member);
member.click();
toggle(member);
}
function onPointerUp(e: Event) {
if (!activeGroup) return;
const endedGroup = activeGroup;
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
// An engaged drag already toggled the source, so its release's click won't toggle it again
if (engaged && source && e.type === "pointerup") {
if (middleButtonGesture) suppressNextAuxClick = true;
else suppressNextClickFromSource = source;
}
const wasEngaged = engaged;
middleButtonGesture = false;
source = undefined;
startingState = undefined;
visited = new WeakSet();
engaged = false;
notifyActiveGroupChange(undefined);
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
}
function onClickCapture(e: Event) {
@@ -141,6 +188,15 @@ function onClickCapture(e: Event) {
suppressNextClickFromSource = undefined;
}
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
function onAuxClickCapture(e: MouseEvent) {
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
suppressNextAuxClick = false;
e.stopPropagation();
e.preventDefault();
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => {
const carried = Array.from(listeners);
@@ -360,15 +360,11 @@ impl NodeNetwork {
};
let value_node_id = gen_id();
let merged_node_id = map_ids(id, value_node_id);
let mut original_location = OriginalLocation {
path: Some(path.to_vec()),
let original_location = OriginalLocation {
dependants: vec![vec![id]],
..Default::default()
};
if let Some(path) = &mut original_location.path {
path.push(value_node_id);
}
collection.insert(
merged_node_id,
DocumentNode {
@@ -63,7 +63,6 @@ fn flatten_add_expected() -> NodeNetwork {
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(4)]),
dependants: vec![vec![NodeId(10)]],
..Default::default()
},
@@ -155,24 +155,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
)
};
}
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
// which the new compiler selects by signature
macro_rules! also_under_own_identifier {
($module:ident, $row:expr) => {{
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
[row, own]
}};
}
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
macro_rules! input_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
]
.concat();
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
];
entries
}};
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
@@ -264,7 +254,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$(
entries.extend(input_adapter_node!(element: $element));
entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
entries.push(item_to_list_node!(element: $element));
)*
entries
}};
@@ -369,10 +359,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
$(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
]
.concat();
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
];
entries
}};
}
@@ -405,8 +394,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
($($element:ty),* $(,)?) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$(
entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
entries.push(bundle_node!(element: $element));
entries.push(unbundle_node!(element: $element));
)*
entries
}};
@@ -466,11 +455,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
macro_rules! embed_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
]
.concat();
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element),
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element),
];
entries
}};
}
@@ -487,11 +475,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
macro_rules! convert_adapter_node {
(from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
]
.concat();
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
];
entries
}};
}
@@ -513,19 +500,13 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
macro_rules! attribute_value_node {
(Item<$element:ty>) => {
also_under_own_identifier!(
item_to_attribute_value,
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
)
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
};
(List<$element:ty>) => {
also_under_own_identifier!(
list_to_attribute_value,
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
)
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
};
}
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
attribute_value_node!(Item<f64>),
attribute_value_node!(Item<i64>),
attribute_value_node!(Item<bool>),
@@ -550,8 +531,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(List<Raster<GPU>>),
attribute_value_node!(List<Graphic>),
attribute_value_node!(List<Artboard>),
]
.concat();
];
node_types.extend(attribute_value_rows);
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
macro_rules! transform_list_node {
@@ -29,17 +29,6 @@ pub struct NodeFlags {
pub forwards_input: bool,
pub inject_scope: bool,
pub asynchronous: bool,
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
pub adapter: Option<AdapterKind>,
}
/// How an adapter node changes the wire it is inserted on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdapterKind {
/// Converts the wire's element into another element type.
Conversion,
/// Changes the wire's rank, like raising an `Item` onto a `List`.
Rank,
}
// Translation struct between macro and definition
@@ -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)
}
@@ -3,7 +3,6 @@ use crate::vector::flatten::WorkingVector;
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
use crate::vector::path::{CurveType, Path, curve_types_of};
use core_types::list::{ATTR_ID, List};
use core_types::uuid::generate_uuid;
use dyn_any::DynAny;
use glam::DVec2;
use rustc_hash::{FxHashMap, FxHashSet};
@@ -1086,16 +1085,49 @@ impl VectorModification {
}
}
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order,
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present.
// This will not actually lead to a cache invalidation in most cases due to the
// graph inputs being wrapped in a `MemoHash` wrapper.
// Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
impl graphene_hash::CacheHash for PointModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.add.cache_hash(state);
sorted_set(&self.remove).cache_hash(state);
sorted_map(&self.delta).cache_hash(state);
}
}
impl graphene_hash::CacheHash for SegmentModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.add.cache_hash(state);
sorted_set(&self.remove).cache_hash(state);
sorted_map(&self.start_point).cache_hash(state);
sorted_map(&self.end_point).cache_hash(state);
sorted_map(&self.handle_primary).cache_hash(state);
sorted_map(&self.handle_end).cache_hash(state);
}
}
impl graphene_hash::CacheHash for VectorModification {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&generate_uuid(), state);
self.points.cache_hash(state);
self.segments.cache_hash(state);
sorted_set(&self.add_g1_continuous).cache_hash(state);
sorted_set(&self.remove_g1_continuous).cache_hash(state);
sorted_set(&self.path_breaks).cache_hash(state);
sorted_set(&self.turned_on_load).cache_hash(state);
}
}
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
let mut items: Vec<_> = set.iter().collect();
items.sort_unstable();
items
}
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_unstable_by_key(|&(key, _)| key);
entries
}
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
// TODO: Eventually remove this document upgrade code
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
@@ -1263,6 +1295,23 @@ mod tests {
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
}
fn cache_hash(modification: &VectorModification) -> u64 {
let mut hasher = std::hash::DefaultHasher::new();
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
std::hash::Hasher::finish(&hasher)
}
#[test]
fn equal_modifications_hash_equally() {
let (vector, paths) = mixed_geometry();
let first = VectorModification::create_from_vector(&vector, &paths);
let second = VectorModification::create_from_vector(&vector, &paths);
assert_eq!(cache_hash(&first), cache_hash(&first));
assert_eq!(cache_hash(&first), cache_hash(&second));
}
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
fn mixed_geometry() -> (Vector, List<Path>) {
let mut bezpath = BezPath::new();
-7
View File
@@ -838,14 +838,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
footprint_invariant,
forwards_input,
inject_scope,
adapter,
..
} = attributes.flags;
let adapter = match adapter {
Some(AdapterKind::Conversion) => quote!(Some(gcore::registry::AdapterKind::Conversion)),
Some(AdapterKind::Rank) => quote!(Some(gcore::registry::AdapterKind::Rank)),
None => quote!(None),
};
let asynchronous = parsed.is_async;
let version = attributes.version.unwrap_or(1);
// A node returning a `Destructure` struct records its fields as output connectors
@@ -1059,7 +1053,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
forwards_input: #forwards_input,
inject_scope: #inject_scope,
asynchronous: #asynchronous,
adapter: #adapter,
},
version: #version,
output_fields: #output_fields,
+1 -29
View File
@@ -54,15 +54,6 @@ pub(crate) struct NodeFlags {
pub(crate) no_partial: bool,
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
pub(crate) destructure_extractor: bool,
/// Whether type resolution may insert this node on an edge, and how it changes the wire.
pub(crate) adapter: Option<AdapterKind>,
}
/// Mirrors `core_types::registry::AdapterKind`, which this proc-macro crate cannot depend on.
#[derive(Debug, Clone, Copy)]
pub(crate) enum AdapterKind {
Conversion,
Rank,
}
#[derive(Debug, Default, Clone)]
@@ -566,25 +557,6 @@ impl Parse for NodeFnAttributes {
// Example usage:
// #[node_macro::node(..., forwards_input, ...)]
"forwards_input" => set_flag(&mut flags.forwards_input, meta, "forwards_input")?,
// Marks the node as an adapter that type resolution may insert on an edge, either converting the wire's element type or changing its rank.
//
// Example usage:
// #[node_macro::node(..., adapter(conversion), ...)]
// #[node_macro::node(..., adapter(rank), ...)]
"adapter" => {
let meta = meta.require_list()?;
if flags.adapter.is_some() {
return Err(Error::new_spanned(meta, "Multiple 'adapter' attributes are not allowed"));
}
let kind: Ident = meta
.parse_args()
.map_err(|_| Error::new_spanned(meta, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)"))?;
flags.adapter = Some(match kind.to_string().as_str() {
"conversion" => AdapterKind::Conversion,
"rank" => AdapterKind::Rank,
_ => return Err(Error::new_spanned(kind, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)")),
});
}
// Instructs the preprocessor to make this node available as a scope.
// Other nodes can then access it with `#[scope(node::IDENTIFIER)]`.
//
@@ -632,7 +604,7 @@ impl Parse for NodeFnAttributes {
indoc!(
r#"
Unsupported attribute in `node`.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'adapter', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'.
Example usage:
#[node_macro::node(..., name("Test Node"), ...)]
"#
+12 -12
View File
@@ -13,19 +13,19 @@ fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
}
/// Shifts a whole wire value onto a connector's type through the std `Into` trait, serving the whole-`List` erasure onto `ListDyn` under the input adapter identifier.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
value.into()
}
/// Raises an `Item` wire onto a `List` connector as its one-element list.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn item_to_list<'i, T: 'i + Send>(_: impl Ctx, value: Item<T>) -> List<T> {
value.into()
}
/// Boxes a ranked wire's element into a type-erased attribute value, carrying the cell's attributes through the wire.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
_: impl Ctx,
value: Item<T>,
@@ -36,7 +36,7 @@ fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
}
/// Boxes a whole `List` wire as one type-erased attribute value, for attributes whose per-item value is itself a collection.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
_: impl Ctx,
value: T,
@@ -46,27 +46,27 @@ fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
}
/// Wraps a whole `List` onto the wire as one rank-0 `Item<Bundle<T>>` so an entire collection can feed a connector that carries it as one opaque cell.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn bundle<'i, T: 'i + Send>(_: impl Ctx, value: List<T>) -> Item<Bundle<T>> {
Item::new_from_element(Bundle(value))
}
/// Unwraps a `Bundle` wire back into the whole `List` it carries, restoring the collection after it passed through a connector as one opaque cell.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn unbundle<'i, T: 'i + Send>(_: impl Ctx, value: Item<Bundle<T>>) -> List<T> {
value.into_element().0
}
/// Converts an `Item` wire's element to a different element type it can produce through the std `Into` trait,
/// letting a convertible wire feed an `Item` connector whose element type it does not match by identity.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn into_item<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
let (value, attributes) = value.into_parts();
Item::from_parts(value.into(), attributes)
}
/// The `List` counterpart of `into_item`, converting every element to a different element type it can produce.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
value
.into_iter()
@@ -79,19 +79,19 @@ fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, valu
/// Moves a whole `Item` wire inside an element type like `Graphic` that embeds ranked values as its variants.
/// The attributes describe the element they arrived with, so they travel inside it and the fresh envelope starts empty.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn embed_item<'i, T: 'i + Send, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
Item::new_from_element(value.into())
}
/// The `List` counterpart of `embed_item`, each item moving whole inside its own embedding element.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn embed_list<'i, T: 'i + Send + Clone, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
value.into_iter().map(|item| Item::new_from_element(E::from(item))).collect()
}
/// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
let (value, attributes) = value.into_parts();
@@ -100,7 +100,7 @@ fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx +
}
/// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type.
#[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
#[node_macro::node(category("_Adapters"), skip_impl)]
fn convert_list<'i, T: 'i + Send + Clone + Convert<E, ()>, E: 'i + Send + Clone>(ctx: impl Ctx + ExtractFootprint, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
+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)
}
-1
View File
@@ -206,7 +206,6 @@ impl Preprocessor {
forwards_input,
inject_scope,
asynchronous,
adapter: _,
},
output_fields,
context_features,