mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06285430f0 | ||
|
|
deaee8aa80 | ||
|
|
6a0f39e8ad |
No files matched your search
@@ -665,6 +665,18 @@ mod test {
|
||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||
}
|
||||
|
||||
#[cfg_attr(miri, ignore)]
|
||||
#[tokio::test]
|
||||
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
|
||||
let mut editor = create_editor_with_three_layers().await;
|
||||
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
|
||||
|
||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
|
||||
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
|
||||
}
|
||||
|
||||
/// - paste
|
||||
/// - assert that ellipse was copied
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::application::Environment;
|
||||
use crate::consts::{
|
||||
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,
|
||||
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::{MouseKeys, ViewportPosition};
|
||||
use crate::messages::input_mapper::utility_types::pointer::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,8 +34,6 @@ 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]
|
||||
@@ -101,10 +99,6 @@ 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 {
|
||||
@@ -347,13 +341,6 @@ 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;
|
||||
@@ -430,10 +417,6 @@ 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,8 +170,6 @@ 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.
|
||||
@@ -439,7 +437,6 @@ impl NodeGraphMessage {
|
||||
| Self::PointerMove { .. }
|
||||
| Self::PointerUp
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
|
||||
@@ -1752,20 +1752,6 @@ 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(0.).max(180.).range_min(Some(1.)).unit("°"),
|
||||
NumberInput::default().min(1.).max(180.).unit("°"),
|
||||
);
|
||||
|
||||
widgets.push(LayoutGroup::row(angular_resolution));
|
||||
|
||||
-57
@@ -3399,63 +3399,6 @@ 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();
|
||||
|
||||
@@ -997,7 +997,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
let result = self.executor.submit_document_export(document, export_config);
|
||||
|
||||
if let Err(description) = result {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
@@ -1124,18 +1124,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitClipboardSvg { id } => {
|
||||
let layers = self.active_document().map(|document| {
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|layer| selected.contains(layer))
|
||||
.map(|layer| layer.to_node())
|
||||
.collect::<Vec<_>>();
|
||||
layers.reverse();
|
||||
layers
|
||||
});
|
||||
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
|
||||
let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
|
||||
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||
return;
|
||||
};
|
||||
let selected = document.partition_selection().layers;
|
||||
let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
|
||||
layers.reverse();
|
||||
responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
|
||||
+35
-41
@@ -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::SpiralCurve;
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::misc::SpiralType;
|
||||
use std::collections::VecDeque;
|
||||
use std::f64::consts::TAU;
|
||||
@@ -41,12 +41,13 @@ pub struct SpiralTurns {
|
||||
pub handle_state: SpiralTurnsState,
|
||||
initial_turns: f64,
|
||||
initial_outer_radius: f64,
|
||||
initial_spiral: SpiralCurve,
|
||||
/// In degrees, as stored in the node.
|
||||
initial_inner_radius: f64,
|
||||
initial_growth_factor: f64,
|
||||
initial_start_angle: f64,
|
||||
previous_mouse_position: DVec2,
|
||||
total_angle_delta: f64,
|
||||
gizmo_type: GizmoType,
|
||||
spiral_type: SpiralType,
|
||||
}
|
||||
|
||||
impl SpiralTurns {
|
||||
@@ -83,10 +84,12 @@ 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);
|
||||
}
|
||||
@@ -97,9 +100,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 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.));
|
||||
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));
|
||||
|
||||
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);
|
||||
@@ -141,27 +144,17 @@ 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 {
|
||||
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.),
|
||||
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.),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// 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.
|
||||
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 inner_radius = spiral.radius(turns_taken_off * TAU).max(0.);
|
||||
(self.initial_start_angle + turns_taken_off * 360., turns, inner_radius)
|
||||
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)
|
||||
}
|
||||
|
||||
/// Snaps a number of turns to whole and half turns, judged by how far the pointer travels around the center on screen.
|
||||
@@ -178,17 +171,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 spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
|
||||
let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
|
||||
let viewport_to_document = document.metadata().document_to_viewport.inverse();
|
||||
let position_of = |turns_landed_on: f64| {
|
||||
let point = match self.gizmo_type {
|
||||
let (angle, growth_factor) = match self.gizmo_type {
|
||||
GizmoType::Start => {
|
||||
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.)
|
||||
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))
|
||||
}
|
||||
_ => spiral.point(turns_landed_on * TAU),
|
||||
_ => (turns_landed_on * TAU + start_angle.to_radians(), growth_factor),
|
||||
};
|
||||
viewport_to_document.transform_point2(layer_to_viewport.transform_point2(point))
|
||||
viewport_to_document.transform_point2(layer_to_viewport.transform_point2(spiral_point(angle, inner_radius, growth_factor, spiral_type)))
|
||||
};
|
||||
|
||||
// The whole and half turns around the asked-for number, counted in half turns
|
||||
@@ -230,8 +223,9 @@ impl SpiralTurns {
|
||||
return;
|
||||
}
|
||||
|
||||
// The total angle dragged around the center, in degrees, as a number of full turns
|
||||
// Increase the number of turns and outer radius in unison such that growth and tightness remain same
|
||||
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
|
||||
@@ -244,16 +238,21 @@ 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_inner_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
|
||||
if !new_inner_radius.is_finite() {
|
||||
return;
|
||||
}
|
||||
let (new_start_angle, new_turns, new_outer_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, StartAngleInput),
|
||||
@@ -264,17 +263,12 @@ impl SpiralTurns {
|
||||
input: NodeInput::value(TaggedValue::Number(new_turns), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, InnerRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_inner_radius), false),
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_outer_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::SpiralCurve;
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
|
||||
use graphene_std::vector::misc::SpiralType;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -83,10 +83,11 @@ 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, 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());
|
||||
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();
|
||||
|
||||
Some(viewport.transform_point2(spiral.point(turns * theta)))
|
||||
Some(viewport.transform_point2(spiral_point(theta, a, b, spiral_type)))
|
||||
}
|
||||
|
||||
#[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::{SpiralCurve, heart_bezpath};
|
||||
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, 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,17 +2213,12 @@ 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, 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 (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 (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 inner radius grows so the rest of the spiral stays where it was
|
||||
// The start lands on a whole turn fewer, and the outer radius shrinks so the spiral keeps winding as it did
|
||||
let whole = turns.ceil() - 1.;
|
||||
let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await;
|
||||
|
||||
@@ -2234,9 +2229,6 @@ 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::list;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
|
||||
use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
@@ -112,19 +116,24 @@ pub enum NodeGraphUpdate {
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
Export {
|
||||
id: u64,
|
||||
svg: Option<String>,
|
||||
result: Box<ExecutionResult>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NodeGraphExecutor {
|
||||
sender: Sender<GraphRuntimeRequest>,
|
||||
|
||||
receiver: Receiver<NodeGraphUpdate>,
|
||||
current_execution_id: u64,
|
||||
futures: VecDeque<(u64, ExecutionContext)>,
|
||||
pending: Option<(u64, ExecutionContext)>,
|
||||
|
||||
current_export_id: u64,
|
||||
exports: HashMap<u64, ExportTarget>,
|
||||
|
||||
node_graph_hash: u64,
|
||||
/// The document whose network the graph runtime was last sent.
|
||||
node_graph_document: Option<DocumentId>,
|
||||
@@ -146,9 +155,14 @@ pub struct NodeGraphExecutor {
|
||||
gradient_migration_attempted: HashSet<DocumentId>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ExportTarget {
|
||||
File(ExportConfig),
|
||||
Clipboard(u64),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ExecutionContext {
|
||||
export_config: Option<ExportConfig>,
|
||||
document_id: DocumentId,
|
||||
/// The view the render was asked for, which the footprints it reports back are measured in.
|
||||
document_to_viewport: DAffine2,
|
||||
@@ -183,6 +197,8 @@ impl NodeGraphExecutor {
|
||||
futures: Default::default(),
|
||||
pending: None,
|
||||
current_execution_id: 0,
|
||||
current_export_id: 0,
|
||||
exports: HashMap::new(),
|
||||
node_graph_hash: 0,
|
||||
node_graph_document: None,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
@@ -211,6 +227,22 @@ impl NodeGraphExecutor {
|
||||
execution_id
|
||||
}
|
||||
|
||||
fn queue_export(&mut self, document: &DocumentMessageHandler, network: NodeNetwork, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
|
||||
let id = self.current_export_id;
|
||||
self.current_export_id += 1;
|
||||
let resources = document.resources.registry.clone();
|
||||
let request = GraphRuntimeRequest::Export {
|
||||
id,
|
||||
render_config,
|
||||
network,
|
||||
resources,
|
||||
};
|
||||
self.sender.send(request).map_err(|e| e.to_string())?;
|
||||
self.exports.insert(id, target);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
|
||||
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
|
||||
log::error!("Failed to send the overlays: {error}");
|
||||
@@ -229,13 +261,27 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the context overrides");
|
||||
}
|
||||
|
||||
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
||||
if document_id.is_none() || self.node_graph_document != document_id {
|
||||
return ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
}
|
||||
pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
|
||||
let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
let Some((network, [min, max])) = copied_layers(document, layers) else { return no_svg };
|
||||
|
||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
||||
Message::NoOp
|
||||
let viewport = Footprint {
|
||||
resolution: (max - min).round().as_uvec2(),
|
||||
transform: DAffine2::from_translation(-min),
|
||||
..Default::default()
|
||||
};
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: 1.,
|
||||
export_format: ExportFormat::Svg,
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match self.queue_export(document, network, render_config, ExportTarget::Clipboard(id)) {
|
||||
Ok(()) => Message::NoOp,
|
||||
Err(_) => no_svg,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||
@@ -337,7 +383,6 @@ impl NodeGraphExecutor {
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
@@ -404,7 +449,6 @@ impl NodeGraphExecutor {
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
@@ -415,10 +459,8 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
/// Evaluates a node graph for export
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let resources = document.resources.registry.clone();
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
|
||||
let network = network_as_compiled(&document.network_interface);
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
graphene_std::application_io::ExportFormat::Svg
|
||||
@@ -452,34 +494,12 @@ impl NodeGraphExecutor {
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed,
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
},
|
||||
));
|
||||
|
||||
Ok(())
|
||||
self.queue_export(document, network, render_config, ExportTarget::File(export_config))
|
||||
}
|
||||
|
||||
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
|
||||
@@ -491,8 +511,8 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
let mut all_dropped_thumbnails = Vec::new();
|
||||
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
|
||||
for response in results.by_ref() {
|
||||
let results = self.receiver.try_iter().collect::<Vec<_>>();
|
||||
for response in results {
|
||||
match response {
|
||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||
let ExecutionResponse {
|
||||
@@ -516,7 +536,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
||||
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
|
||||
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
|
||||
if execution_context.measure_fill.is_none() {
|
||||
self.pending = Some((execution_id, execution_context.clone()));
|
||||
}
|
||||
execution_context
|
||||
@@ -571,7 +591,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
||||
if !matches!(result, ExecutionResult::Pending) {
|
||||
let errors = match &result {
|
||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||
let in_document = |path: &&[NodeId]| {
|
||||
@@ -644,11 +664,8 @@ impl NodeGraphExecutor {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
|
||||
if execution_context.export_config.is_some() {
|
||||
responses.add(export_failure_dialog(message));
|
||||
}
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -666,10 +683,8 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
document.network_interface.update_vector_modify(path_contents(&observations));
|
||||
|
||||
match (node_graph_output, execution_context.export_config) {
|
||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
|
||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
|
||||
(None, _) => {}
|
||||
if let Some(node_graph_output) = node_graph_output {
|
||||
self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
|
||||
}
|
||||
responses.add(DeferMessage::TriggerGraphRun {
|
||||
execution_id,
|
||||
@@ -724,7 +739,7 @@ impl NodeGraphExecutor {
|
||||
});
|
||||
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
Ok(result) => result,
|
||||
};
|
||||
@@ -756,33 +771,7 @@ impl NodeGraphExecutor {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
}
|
||||
}
|
||||
|
||||
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
|
||||
for response in results {
|
||||
match response {
|
||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||
let execution_context = self.execution_context(execution_response.execution_id);
|
||||
|
||||
if execution_context.is_some_and(|context| context.document_id == document_id) {
|
||||
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
|
||||
}
|
||||
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
|
||||
responses.add(export_failure_dialog(None));
|
||||
}
|
||||
|
||||
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
|
||||
}
|
||||
NodeGraphUpdate::Thumbnails {
|
||||
responses: thumbnails,
|
||||
document_id: thumbnails_document,
|
||||
} if thumbnails_document == document_id => {
|
||||
Self::receive_thumbnails(document, thumbnails, responses);
|
||||
}
|
||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
||||
_ => {}
|
||||
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -798,15 +787,6 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// What an execution was submitted for, while it's still queued or pending.
|
||||
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
|
||||
self.futures
|
||||
.iter()
|
||||
.chain(&self.pending)
|
||||
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
|
||||
.map(|(_, execution_context)| execution_context)
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
|
||||
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
|
||||
@@ -920,7 +900,6 @@ impl NodeGraphExecutor {
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: None,
|
||||
document_id,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: Some((network_path, fill_node_id, gradient)),
|
||||
@@ -1080,6 +1059,51 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
||||
}
|
||||
|
||||
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(target) = self.exports.remove(&export_id) else { return };
|
||||
|
||||
let failure = match (result, &target) {
|
||||
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
|
||||
return match target {
|
||||
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
|
||||
ExportTarget::Clipboard(id) => {
|
||||
let svg = match value {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => Some(svg),
|
||||
_ => None,
|
||||
};
|
||||
responses.add(ClipboardMessage::Rendered { id, svg });
|
||||
}
|
||||
};
|
||||
}
|
||||
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
|
||||
(ExecutionResult::Panic(payload), _) => {
|
||||
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
||||
Some(format!("Panicked: {}", message.unwrap_or("no message")))
|
||||
}
|
||||
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
|
||||
};
|
||||
if let Some(message) = &failure {
|
||||
log::error!("Node graph evaluation failed:\n{message}");
|
||||
}
|
||||
|
||||
match target {
|
||||
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||
}),
|
||||
ExportTarget::Clipboard(id) => {
|
||||
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||
if let Some(description) = failure {
|
||||
let title = "Unable to copy as SVG".to_string();
|
||||
responses.add(DialogMessage::DisplayDialogError { title, description });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let ExportConfig {
|
||||
file_type,
|
||||
@@ -1179,6 +1203,46 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
|
||||
}
|
||||
}
|
||||
|
||||
fn network_as_compiled(interface: &NodeNetworkInterface) -> NodeNetwork {
|
||||
let mut network = interface.document_network().clone();
|
||||
apply_previews(&mut network, &interface.previewed_nodes());
|
||||
write_layer_paths(&mut network, &interface.layer_paths());
|
||||
|
||||
network
|
||||
}
|
||||
|
||||
fn copied_layers(document: &DocumentMessageHandler, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
|
||||
let (interface, metadata) = (&document.network_interface, document.metadata());
|
||||
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
|
||||
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
|
||||
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
|
||||
artboards if artboards == layers.len() => list!(Artboard),
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let mut network = network_as_compiled(interface);
|
||||
let mut below = NodeInput::type_default(stack, true);
|
||||
let mut bounds = None;
|
||||
for &layer in layers {
|
||||
let mut node = network.nodes.get(&layer.to_node())?.clone();
|
||||
*node.inputs.first_mut()? = below;
|
||||
let copy = NodeId::new();
|
||||
network.nodes.insert(copy, node);
|
||||
below = NodeInput::node(copy, 0);
|
||||
|
||||
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
|
||||
true => metadata.downstream_transform_to_document(layer).inverse(),
|
||||
false => DAffine2::IDENTITY,
|
||||
};
|
||||
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
|
||||
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
|
||||
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
|
||||
}
|
||||
network.exports = vec![below];
|
||||
|
||||
Some((network, bounds?))
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
|
||||
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
||||
@@ -1200,14 +1264,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
None
|
||||
}
|
||||
|
||||
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
DialogMessage::DisplayDialogError {
|
||||
title: "Unable to export document".to_string(),
|
||||
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
editor.dispatch(Message::Wake);
|
||||
}
|
||||
|
||||
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
|
||||
/// for one more update, so a first update clears those of the graph before it.
|
||||
/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
|
||||
/// an update replaces for one more update, so a first update clears the nodes of the graph before it.
|
||||
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
|
||||
compile_and_run(editor).await;
|
||||
compile_and_run(editor).await;
|
||||
|
||||
@@ -43,25 +43,34 @@ pub struct NodeRuntime {
|
||||
pub(super) executor: DynamicExecutor,
|
||||
#[cfg(not(test))]
|
||||
executor: DynamicExecutor,
|
||||
output: OutputHandle,
|
||||
|
||||
receiver: Receiver<GraphRuntimeRequest>,
|
||||
sender: Sender<NodeGraphUpdate>,
|
||||
|
||||
editor_wake: Wake,
|
||||
dirty: Arc<AtomicBool>,
|
||||
|
||||
output: Option<OutputHandle>,
|
||||
previous: Option<OutputHandle>,
|
||||
|
||||
pending: Option<ExecutionRequest>,
|
||||
pending_export: Option<ExecutionRequest>,
|
||||
pending_eyedropper: Option<ExecutionRequest>,
|
||||
pending_thumbnails: Option<DocumentId>,
|
||||
|
||||
viewport_artwork: Option<ViewportArtwork>,
|
||||
|
||||
exports: Vec<(u64, RenderConfig, OutputHandle)>,
|
||||
|
||||
/// The network the executor last compiled successfully, with previews applied.
|
||||
old_graph: Option<NodeNetwork>,
|
||||
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
||||
compile_failed: bool,
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
|
||||
thumbnails: Thumbnails,
|
||||
observer: Observer<ObservationKey>,
|
||||
/// Whether an observation changed since its results were last sent.
|
||||
@@ -69,13 +78,9 @@ pub struct NodeRuntime {
|
||||
|
||||
preprocessor: preprocessor::Preprocessor,
|
||||
|
||||
/// Cached surface for Wasm viewport rendering (reused across frames)
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle,
|
||||
/// The viewport's latest artwork.
|
||||
viewport_artwork: Option<ViewportArtwork>,
|
||||
/// The layers from the render of the viewport's latest artwork.
|
||||
rendered_layers: RenderedLayers,
|
||||
|
||||
/// The latest overlays, rendered again over each new artwork.
|
||||
overlays: Option<OverlayContext>,
|
||||
/// Whether the overlays or the artwork changed since the overlays were last rendered.
|
||||
@@ -83,6 +88,10 @@ pub struct NodeRuntime {
|
||||
overlays_canvas: VelloCanvas,
|
||||
/// The latest rendered overlays.
|
||||
overlays_texture: Option<Texture>,
|
||||
|
||||
/// Cached surface for Wasm viewport rendering (reused across frames)
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle,
|
||||
}
|
||||
|
||||
/// What the viewport shows beneath its overlays.
|
||||
@@ -98,20 +107,21 @@ enum ViewportArtwork {
|
||||
pub enum GraphRuntimeRequest {
|
||||
GraphUpdate(GraphUpdate),
|
||||
ExecutionRequest(ExecutionRequest),
|
||||
Export {
|
||||
id: u64,
|
||||
render_config: RenderConfig,
|
||||
network: NodeNetwork,
|
||||
resources: ResourceRegistry,
|
||||
},
|
||||
ThumbnailsInView {
|
||||
layers: HashSet<NodeId>,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Starts, changes, or with `None` stops one observation without a graph update.
|
||||
RenderOverlays(OverlayContext),
|
||||
Observe {
|
||||
key: ObservationKey,
|
||||
observation: Option<Observation>,
|
||||
},
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
layers: Vec<NodeId>,
|
||||
},
|
||||
RenderOverlays(OverlayContext),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -149,20 +159,27 @@ impl NodeRuntime {
|
||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
|
||||
Self {
|
||||
executor: DynamicExecutor::default(),
|
||||
output: OutputHandle::default(),
|
||||
|
||||
receiver,
|
||||
sender,
|
||||
|
||||
editor_wake,
|
||||
dirty: Default::default(),
|
||||
|
||||
output: None,
|
||||
previous: None,
|
||||
|
||||
pending: None,
|
||||
pending_export: None,
|
||||
pending_eyedropper: None,
|
||||
pending_thumbnails: None,
|
||||
old_graph: None,
|
||||
compile_failed: false,
|
||||
resources: ResourceRegistry::default(),
|
||||
async_runtime: None,
|
||||
|
||||
viewport_artwork: None,
|
||||
|
||||
exports: Vec::new(),
|
||||
|
||||
old_graph: None,
|
||||
|
||||
async_runtime: None,
|
||||
editor_api: PlatformEditorApi {
|
||||
#[cfg(not(test))]
|
||||
application_io: None,
|
||||
@@ -171,61 +188,94 @@ impl NodeRuntime {
|
||||
application_io: Some(PlatformApplicationIo::default().into()),
|
||||
}
|
||||
.into(),
|
||||
resources: ResourceRegistry::default(),
|
||||
|
||||
node_graph_errors: Vec::new(),
|
||||
node_graph_warnings: Vec::new(),
|
||||
|
||||
thumbnails: Thumbnails::new(),
|
||||
observer: Observer::default(),
|
||||
observations_changed: false,
|
||||
|
||||
preprocessor: preprocessor::Preprocessor::new(),
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle::new(),
|
||||
viewport_artwork: None,
|
||||
rendered_layers: RenderedLayers::default(),
|
||||
|
||||
overlays: None,
|
||||
overlays_stale: false,
|
||||
overlays_canvas: VelloCanvas::default(),
|
||||
overlays_texture: None,
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self) {
|
||||
if self.pending_export.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut graph = None;
|
||||
for request in self.receiver.try_iter() {
|
||||
while let Ok(request) = self.receiver.try_recv() {
|
||||
match request {
|
||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
|
||||
self.pending_export = Some(request);
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
break;
|
||||
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
mut network,
|
||||
resources,
|
||||
previewed,
|
||||
layers,
|
||||
observations,
|
||||
}) => {
|
||||
apply_previews(&mut network, &previewed);
|
||||
write_layer_paths(&mut network, &layers);
|
||||
self.observer.replace_all(observations);
|
||||
self.resources = resources;
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
self.node_graph_warnings.clear();
|
||||
let result = self.update_network(network.clone());
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
self.old_graph = Some(network);
|
||||
}
|
||||
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
let node_graph_warnings = self.node_graph_warnings.clone();
|
||||
|
||||
self.sender
|
||||
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
|
||||
result,
|
||||
node_graph_errors,
|
||||
node_graph_warnings,
|
||||
}))
|
||||
.expect("Failed to send response");
|
||||
}
|
||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
|
||||
GraphRuntimeRequest::ExecutionRequest(request) => {
|
||||
self.pending = Some(request);
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
}
|
||||
GraphRuntimeRequest::Export {
|
||||
id,
|
||||
render_config,
|
||||
network,
|
||||
resources,
|
||||
} => {
|
||||
let mut scoped_network = wrap_network_with_render_node_in_scope(network, self.editor_api.clone(), self.async_runtime().handle());
|
||||
let preprocessed = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)).ok();
|
||||
let compiled = preprocessed.and_then(|_| Compiler {}.compile_single(scoped_network).ok());
|
||||
let inserted = compiled.and_then(|compiled| self.executor.update_without_freeing(compiled.network).ok());
|
||||
self.async_runtime().update_sources(self.executor.sources());
|
||||
match inserted {
|
||||
Some((output, _)) => {
|
||||
self.exports.push((id, render_config, output));
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
}
|
||||
None => self.send_export(id, ExecutionResult::Uncompiled),
|
||||
}
|
||||
}
|
||||
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => {
|
||||
self.thumbnails.set_in_view(layers);
|
||||
self.pending_thumbnails = Some(document_id);
|
||||
}
|
||||
// A graph update applied after this loop would otherwise replace this with what it observed before
|
||||
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
|
||||
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
|
||||
(Some(update), None) => _ = update.observations.remove(&key),
|
||||
(None, observation) => {
|
||||
self.observer.set(key, observation);
|
||||
self.observations_changed = true;
|
||||
}
|
||||
},
|
||||
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
|
||||
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
|
||||
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
||||
GraphRuntimeRequest::Observe { key, observation } => {
|
||||
self.observer.set(key, observation);
|
||||
self.observations_changed = true;
|
||||
}
|
||||
GraphRuntimeRequest::RenderOverlays(context) => {
|
||||
self.overlays = Some(context);
|
||||
@@ -233,82 +283,47 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(GraphUpdate {
|
||||
mut network,
|
||||
resources,
|
||||
previewed,
|
||||
layers,
|
||||
observations,
|
||||
}) = graph
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
apply_previews(&mut network, &previewed);
|
||||
write_layer_paths(&mut network, &layers);
|
||||
self.observer.replace_all(observations);
|
||||
self.resources = resources;
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
self.node_graph_warnings.clear();
|
||||
let result = self.update_network(network.clone());
|
||||
self.compile_failed = result.is_err();
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
self.old_graph = Some(network);
|
||||
}
|
||||
let node_graph_errors = self.node_graph_errors.clone();
|
||||
let node_graph_warnings = self.node_graph_warnings.clone();
|
||||
|
||||
self.sender
|
||||
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
|
||||
result,
|
||||
node_graph_errors,
|
||||
node_graph_warnings,
|
||||
}))
|
||||
.expect("Failed to send response");
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Option<Texture> {
|
||||
let dirty = self.dirty.swap(false, Ordering::Acquire);
|
||||
let mut texture = None;
|
||||
|
||||
if let Some(export) = self.pending_export {
|
||||
if dirty {
|
||||
self.run_export(export).await;
|
||||
if dirty {
|
||||
for (id, render_config, output) in std::mem::take(&mut self.exports) {
|
||||
self.run_export(id, render_config, output).await;
|
||||
}
|
||||
} else {
|
||||
let viewport = if dirty { self.pending } else { None };
|
||||
}
|
||||
|
||||
if let Some(document_id) = self.pending_thumbnails.take()
|
||||
&& viewport.is_none()
|
||||
&& !self.compile_failed
|
||||
{
|
||||
let mut responses = VecDeque::new();
|
||||
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
|
||||
if !responses.is_empty() {
|
||||
self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response");
|
||||
}
|
||||
}
|
||||
let viewport = if dirty { self.pending } else { None };
|
||||
|
||||
if std::mem::take(&mut self.observations_changed) && viewport.is_none() {
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response");
|
||||
if let Some(document_id) = self.pending_thumbnails.take()
|
||||
&& viewport.is_none()
|
||||
&& self.output.is_some()
|
||||
{
|
||||
let mut responses = VecDeque::new();
|
||||
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
|
||||
if !responses.is_empty() {
|
||||
self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response");
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(eyedropper) = self.pending_eyedropper.take() {
|
||||
self.run_eyedropper(eyedropper).await;
|
||||
}
|
||||
if std::mem::take(&mut self.observations_changed) && viewport.is_none() {
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response");
|
||||
}
|
||||
|
||||
if let Some(viewport) = viewport {
|
||||
self.run_viewport(viewport).await;
|
||||
}
|
||||
if let Some(eyedropper) = self.pending_eyedropper.take() {
|
||||
self.run_eyedropper(eyedropper).await;
|
||||
}
|
||||
|
||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||
if self.overlays_stale {
|
||||
texture = self.composite_viewport_frame();
|
||||
}
|
||||
if let Some(viewport) = viewport {
|
||||
self.run_viewport(viewport).await;
|
||||
}
|
||||
|
||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||
if self.overlays_stale {
|
||||
texture = self.composite_viewport_frame();
|
||||
}
|
||||
|
||||
(self.editor_wake)();
|
||||
@@ -318,7 +333,11 @@ impl NodeRuntime {
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let Some(mut result) = self.evaluate(request) else { return };
|
||||
let result = match self.output.clone() {
|
||||
Some(output) => self.evaluate(&output, request),
|
||||
None => Some(ExecutionResult::Uncompiled),
|
||||
};
|
||||
let Some(mut result) = result else { return };
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
||||
@@ -378,24 +397,20 @@ impl NodeRuntime {
|
||||
Some(frame)
|
||||
}
|
||||
|
||||
async fn run_export(&mut self, request: ExecutionRequest) {
|
||||
let result = self.evaluate(request);
|
||||
if matches!(result, Some(ExecutionResult::Pending)) {
|
||||
async fn run_export(&mut self, id: u64, render_config: RenderConfig, output: OutputHandle) {
|
||||
let mut result = self.execute(&output, render_config);
|
||||
if matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) {
|
||||
self.exports.push((id, render_config, output));
|
||||
return;
|
||||
}
|
||||
|
||||
self.pending_export = None;
|
||||
let Some(mut result) = result else { return };
|
||||
self.dirty.store(true, Ordering::Release);
|
||||
|
||||
if let Some(RenderOutput { data, .. }) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request, result, observations).await;
|
||||
self.send_export(id, result);
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
@@ -405,7 +420,8 @@ impl NodeRuntime {
|
||||
request.render_config.pointer = viewport.render_config.pointer;
|
||||
}
|
||||
|
||||
if let Some(mut result) = self.evaluate(request)
|
||||
if let Some(output) = self.output.clone()
|
||||
&& let Some(mut result) = self.evaluate(&output, request)
|
||||
&& let Some(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
@@ -416,11 +432,7 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate(&mut self, request: ExecutionRequest) -> Option<ExecutionResult> {
|
||||
if self.compile_failed {
|
||||
return Some(ExecutionResult::Uncompiled);
|
||||
}
|
||||
|
||||
fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option<ExecutionResult> {
|
||||
let ExecutionRequest { execution_id, mut render_config } = request;
|
||||
|
||||
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active
|
||||
@@ -428,40 +440,53 @@ impl NodeRuntime {
|
||||
render_config.export_format = ExportFormat::Svg;
|
||||
}
|
||||
|
||||
match self.execute(output, render_config) {
|
||||
ExecutionResult::Panic(payload) => {
|
||||
self.send_result(execution_id, ExecutionResult::Panic(payload));
|
||||
None
|
||||
}
|
||||
result => Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute(&mut self, output: &OutputHandle, render_config: RenderConfig) -> ExecutionResult {
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
|
||||
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(output, context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||
let (value, error) = *boxed;
|
||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
||||
ExecutionResult::Fallback(value, self.resolve_errors(output, &error))
|
||||
}
|
||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(output, &error)),
|
||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||
Err(payload) => {
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
result: ExecutionResult::Panic(payload),
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info: None,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
return None;
|
||||
}
|
||||
Err(payload) => ExecutionResult::Panic(payload),
|
||||
}
|
||||
}
|
||||
|
||||
fn send_result(&self, execution_id: u64, result: ExecutionResult) {
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
result,
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info: None,
|
||||
};
|
||||
Some(result)
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
|
||||
fn send_export(&self, id: u64, result: ExecutionResult) {
|
||||
self.sender.send(NodeGraphUpdate::Export { id, result: Box::new(result) }).expect("Failed to send response");
|
||||
}
|
||||
|
||||
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||
let dropped_thumbnails = if self.output.is_none() { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let mut result = result;
|
||||
@@ -507,6 +532,10 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
if let Some(output) = self.output.take() {
|
||||
self.previous = Some(output);
|
||||
}
|
||||
|
||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
@@ -530,7 +559,7 @@ impl NodeRuntime {
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
let updated = self.executor.update(proto_network).map(|(output, types)| {
|
||||
self.output = output;
|
||||
self.output = Some(output);
|
||||
types
|
||||
});
|
||||
let result = updated.map_err(|(types, e)| {
|
||||
@@ -541,7 +570,7 @@ impl NodeRuntime {
|
||||
result
|
||||
}
|
||||
|
||||
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
||||
fn resolve_errors(&self, output: &OutputHandle, error: &NodeError) -> EvaluationErrors {
|
||||
let source_map = self.executor.tree().source_map();
|
||||
let paths = |node: NodeId| -> NodePaths {
|
||||
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
||||
@@ -549,7 +578,7 @@ impl NodeRuntime {
|
||||
paths.into()
|
||||
};
|
||||
let mut errors = Vec::new();
|
||||
let output = self.output.node();
|
||||
let output = output.node();
|
||||
let mut pending = vec![(vec![paths(output)], output, error)];
|
||||
while let Some((mut trace, node, error)) = pending.pop() {
|
||||
let passed = self.executor.trace_error(node, error);
|
||||
@@ -673,7 +702,7 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Sends a network update and a request to export it, as the editor does for an export.
|
||||
/// Sends a request to export the document, as the editor does for an export.
|
||||
fn send_export(editor: &mut EditorTestUtils, file_type: FileType) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
@@ -686,7 +715,7 @@ mod tests {
|
||||
bounds: ExportBounds::AllArtwork,
|
||||
..Default::default()
|
||||
};
|
||||
executor.submit_document_export(document, document_id, export_config).unwrap();
|
||||
executor.submit_document_export(document, export_config).unwrap();
|
||||
}
|
||||
|
||||
/// Whether the runtime evaluated the graph since this was last called.
|
||||
@@ -744,11 +773,60 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
fn send_request(editor: &mut EditorTestUtils) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
portfolio
|
||||
.executor
|
||||
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn run(editor: &mut EditorTestUtils) -> Option<Texture> {
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await
|
||||
}
|
||||
|
||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
|
||||
editor.runtime.pending.map(|request| request.execution_id)
|
||||
}
|
||||
|
||||
fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec<FrontendMessage> {
|
||||
let response = ExecutionResponse {
|
||||
execution_id: last_request(editor).unwrap(),
|
||||
result,
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
};
|
||||
editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).unwrap();
|
||||
editor.dispatch(Message::Wake)
|
||||
}
|
||||
|
||||
fn failed(messages: &[FrontendMessage]) -> bool {
|
||||
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }))
|
||||
}
|
||||
|
||||
fn drawn_in(messages: &[FrontendMessage]) -> Option<&str> {
|
||||
messages.iter().find_map(|message| match message {
|
||||
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn empty_svg() -> RenderOutputType {
|
||||
RenderOutputType::Svg {
|
||||
svg: String::new(),
|
||||
image_data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn rendered(data: RenderOutputType) -> TaggedValue {
|
||||
TaggedValue::RenderOutput(RenderOutput { data, metadata: Default::default() })
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_update_reads_the_channel() {
|
||||
let mut editor = editor().await;
|
||||
@@ -1032,28 +1110,141 @@ mod tests {
|
||||
assert!(shows_dialog, "the export should show why it saved nothing");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_goes_ahead_of_what_was_sent_after_it() {
|
||||
let mut editor = editor().await;
|
||||
let last = last_request(&editor);
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
send_update(&mut editor);
|
||||
fn rectangle_node(editor: &EditorTestUtils) -> NodeId {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use graphene_std::vector::generator_nodes::rectangle;
|
||||
|
||||
editor.runtime.update();
|
||||
assert!(editor.runtime.pending_export.is_some());
|
||||
assert_eq!(last_request(&editor), last, "the request sent after the export was read ahead of it");
|
||||
let interface = &editor.active_document().network_interface;
|
||||
let nodes = interface.document_network().nodes.keys().copied();
|
||||
let reference = Some(DefinitionIdentifier::ProtoNode(rectangle::IDENTIFIER));
|
||||
nodes.into_iter().find(|node_id| interface.reference(node_id, &[]) == reference).unwrap()
|
||||
}
|
||||
|
||||
editor.runtime.run().await;
|
||||
assert!(exported(&mut editor));
|
||||
fn set_layer_visible(editor: &mut EditorTestUtils, visible: bool) {
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
|
||||
editor.active_document_mut().network_interface.set_visibility(&layer, &[], visible);
|
||||
}
|
||||
|
||||
editor.runtime.update();
|
||||
assert_ne!(last_request(&editor), last);
|
||||
editor.runtime.run().await;
|
||||
assert!(evaluated(&mut editor), "the request sent after the export was lost");
|
||||
fn compiled_nodes(editor: &EditorTestUtils) -> HashMap<Vec<NodeId>, NodeId> {
|
||||
let document = &editor.active_document().network_interface.document_network().nodes;
|
||||
let source_map = editor.runtime.executor.tree().source_map();
|
||||
let of_the_document = source_map.iter().filter(|(path, _)| path.first().is_some_and(|node| document.contains_key(node)));
|
||||
of_the_document.map(|(path, (node, _))| (path.to_vec(), *node)).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_parked_export_holds_back_everything_sent_after_it() {
|
||||
async fn an_export_shows_the_network_it_was_sent_with_whatever_was_sent_after_it() {
|
||||
let mut editor = editor().await;
|
||||
|
||||
set_layer_visible(&mut editor, false);
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
set_layer_visible(&mut editor, true);
|
||||
send_update(&mut editor);
|
||||
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
let exported = messages.iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()),
|
||||
_ => None,
|
||||
});
|
||||
assert!(exported.is_some_and(|svg| !svg.contains("<path")), "the export should leave out the rectangle hidden when it was sent");
|
||||
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the update sent after the export should be drawn");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_leaves_what_the_viewport_shows_as_it_is() {
|
||||
let mut editor = editor().await;
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
|
||||
set_layer_visible(&mut editor, false);
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
send_request(&mut editor);
|
||||
run(&mut editor).await;
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
let exported = messages.iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()),
|
||||
_ => None,
|
||||
});
|
||||
assert!(exported.is_some_and(|svg| !svg.contains("<path")), "the export should show the document as the editor has it");
|
||||
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the export changed the network the viewport shows");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_shows_the_node_previewed_in_the_document() {
|
||||
let mut editor = editor().await;
|
||||
let below = editor.active_document().metadata().all_layers().next().unwrap().to_node();
|
||||
editor.draw_ellipse(0., 0., 100., 100.).await;
|
||||
editor.active_document_mut().network_interface.toggle_preview(below, &[]);
|
||||
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
run(&mut editor).await;
|
||||
let exported = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.into_vec()).unwrap()),
|
||||
_ => None,
|
||||
});
|
||||
assert!(
|
||||
exported.is_some_and(|svg| svg.matches("<path").count() == 1),
|
||||
"the export should show the previewed layer without the one above it"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_runs_the_nodes_the_viewport_runs_for_the_same_document() {
|
||||
let mut editor = editor().await;
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
let compiled = compiled_nodes(&editor);
|
||||
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
editor.runtime.update();
|
||||
assert!(!editor.runtime.exports.is_empty(), "the export's network should be inserted");
|
||||
assert_eq!(compiled_nodes(&editor), compiled, "the export compiled a node of the document anew");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_copied_group_runs_the_nodes_the_viewport_runs_for_the_layers_in_it() {
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
|
||||
let mut editor = editor().await;
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
let compiled = compiled_nodes(&editor);
|
||||
|
||||
editor.dispatch(ClipboardMessage::CopyLayers);
|
||||
editor.runtime.update();
|
||||
assert!(!editor.runtime.exports.is_empty(), "the group's network should be inserted");
|
||||
let copied = compiled_nodes(&editor);
|
||||
assert!(compiled.iter().all(|(path, node)| copied.get(path) == Some(node)), "the copy compiled a node of the document anew");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_parked_export_holds_back_nothing_sent_after_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
add_traced_noise_layer(&mut editor).await;
|
||||
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
|
||||
|
||||
let last = last_request(&editor);
|
||||
set_layer_visible(&mut editor, false);
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
assert_ne!(last_request(&editor), last, "the parked export held back the request sent after it");
|
||||
assert!(evaluated(&mut editor), "the request sent after the parked export was not evaluated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_that_finishes_after_what_was_sent_after_it_is_still_saved() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
@@ -1062,24 +1253,190 @@ mod tests {
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
editor.runtime.update();
|
||||
editor.runtime.run().await;
|
||||
assert!(editor.runtime.pending_export.is_some(), "the export took a single evaluation");
|
||||
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
|
||||
|
||||
let last = last_request(&editor);
|
||||
send_update(&mut editor);
|
||||
let mut saved = false;
|
||||
let mut runs = 0;
|
||||
while editor.runtime.pending_export.is_some() {
|
||||
while !editor.runtime.exports.is_empty() {
|
||||
editor.runtime.update();
|
||||
assert_eq!(last_request(&editor), last, "a request got ahead of the parked export");
|
||||
editor.runtime.run().await;
|
||||
saved |= exported(&mut editor);
|
||||
runs += 1;
|
||||
assert!(runs < 100_000, "the export never finished");
|
||||
}
|
||||
assert!(exported(&mut editor));
|
||||
assert!(saved, "the export was lost");
|
||||
}
|
||||
|
||||
editor.runtime.update();
|
||||
assert_ne!(last_request(&editor), last);
|
||||
editor.runtime.run().await;
|
||||
assert!(evaluated(&mut editor), "the request sent after the export was lost");
|
||||
#[tokio::test]
|
||||
async fn two_exports_sent_together_are_both_saved() {
|
||||
let mut editor = editor().await;
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
run(&mut editor).await;
|
||||
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
let saved = messages.iter().filter(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }));
|
||||
assert_eq!(saved.count(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_export_leaves_the_frame_that_follows_it_shown() {
|
||||
let mut editor = editor().await;
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
let id = *editor.portfolio_message_handler().executor.exports.keys().next().unwrap();
|
||||
let result = Box::new(ExecutionResult::Error(EvaluationErrors(Box::new([]))));
|
||||
editor.runtime.sender.send(NodeGraphUpdate::Export { id, result }).unwrap();
|
||||
let messages = respond_to_last_request(&mut editor, ExecutionResult::Value(rendered(empty_svg())));
|
||||
let shows_dialog = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
|
||||
assert!(shows_dialog, "the export should say it failed");
|
||||
assert!(!failed(&messages), "the failed export marked the viewport's render as failed");
|
||||
assert!(drawn_in(&messages).is_some(), "the frame that followed the failed export was dropped");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_export_answered_behind_a_failed_frame_is_still_saved() {
|
||||
let mut editor = editor().await;
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
|
||||
send_export(&mut editor, FileType::Svg);
|
||||
let failed_frame = ExecutionResponse {
|
||||
execution_id: last_request(&editor).unwrap(),
|
||||
result: ExecutionResult::Error(EvaluationErrors(Box::new([]))),
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
};
|
||||
editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(failed_frame))).unwrap();
|
||||
let id = *editor.portfolio_message_handler().executor.exports.keys().next().unwrap();
|
||||
let result = Box::new(ExecutionResult::Value(rendered(empty_svg())));
|
||||
editor.runtime.sender.send(NodeGraphUpdate::Export { id, result }).unwrap();
|
||||
|
||||
let messages = editor.dispatch(Message::Wake);
|
||||
let saved = messages.iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }));
|
||||
assert!(failed(&messages), "the frame should be reported as failed");
|
||||
assert!(saved, "the export answered behind the failed frame was dropped");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cutting_a_layer_still_being_traced_writes_its_svg_once_the_trace_is_done() {
|
||||
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
add_traced_noise_layer(&mut editor).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
send_update(&mut editor);
|
||||
let mut runs = 0;
|
||||
while editor.active_document().metadata().bounding_box_document(layer).is_none() {
|
||||
run(&mut editor).await;
|
||||
editor.dispatch(Message::Wake);
|
||||
runs += 1;
|
||||
assert!(runs < 100_000, "the trace never drew a shape");
|
||||
}
|
||||
|
||||
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
||||
editor.dispatch(ClipboardMessage::CutLayers);
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
|
||||
run(&mut editor).await;
|
||||
assert!(!editor.runtime.exports.is_empty(), "the copy took a single evaluation");
|
||||
|
||||
let mut written = None;
|
||||
runs = 0;
|
||||
while written.is_none() {
|
||||
run(&mut editor).await;
|
||||
written = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||
_ => None,
|
||||
});
|
||||
runs += 1;
|
||||
assert!(runs < 100_000, "the cut layer never reached the clipboard");
|
||||
}
|
||||
let svg = written.iter().flat_map(|content| &content.0).find_map(|item| match &item.data {
|
||||
TransferData::Svg(svg) => Some(svg.as_str()),
|
||||
_ => None,
|
||||
});
|
||||
assert!(svg.is_some_and(|svg| svg.contains("<path")), "the SVG should hold the shapes traced from the cut layer");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_layer_copied_out_of_an_artboard_is_framed_in_the_space_the_artboard_gives_it() {
|
||||
use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys;
|
||||
use crate::messages::tool::utility_types::ToolType;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.drag_tool(ToolType::Artboard, 100., 50., 300., 250., ModifierKeys::empty()).await;
|
||||
editor.draw_rect(120., 80., 160., 130.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected");
|
||||
|
||||
let document = editor.active_document();
|
||||
let metadata = document.metadata();
|
||||
let artboard = layer.parent(metadata).expect("the rectangle should be in the artboard");
|
||||
assert!(document.network_interface.is_artboard(&artboard.to_node(), &[]));
|
||||
let [artboard_min, _] = metadata.bounding_box_document(artboard).expect("the artboard has bounds");
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).expect("the rectangle has bounds");
|
||||
assert!(artboard_min.length() > 1., "the artboard should be away from the origin");
|
||||
|
||||
let (_, [framed_min, framed_max]) = copied_layers(document, &[layer]).expect("the rectangle should be copied");
|
||||
assert!(framed_min.abs_diff_eq(min - artboard_min, 1e-6), "{framed_min} should leave out where the artboard is");
|
||||
assert!(framed_max.abs_diff_eq(max - artboard_min, 1e-6), "{framed_max} should leave out where the artboard is");
|
||||
}
|
||||
|
||||
/// Feeds the rectangle into an 'Add' node, which takes numbers, so the graph compiles but fails to type check.
|
||||
fn break_type_check(editor: &mut EditorTestUtils) {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use graphene_std::math_nodes::add;
|
||||
|
||||
let rectangle = rectangle_node(editor);
|
||||
let content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
|
||||
let add_node = NodeId::new();
|
||||
let template = resolve_proto_node_type(add::IDENTIFIER).unwrap().default_node_template();
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.insert_node(add_node, template, &[]);
|
||||
network_interface.set_input(&InputConnector::node_at_index(add_node, 0), NodeInput::node(rectangle, 0), &[]);
|
||||
network_interface.set_input(&content, NodeInput::node(add_node, 0), &[]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_network_that_fails_to_type_check_leaves_no_output_and_keeps_the_last_one_that_did() {
|
||||
let mut editor = editor().await;
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
let output = editor.runtime.output.as_ref().expect("the network should compile").node();
|
||||
|
||||
break_type_check(&mut editor);
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
assert!(editor.runtime.output.is_none(), "a rectangle should not type check as a number");
|
||||
assert_eq!(editor.runtime.previous.as_ref().map(OutputHandle::node), Some(output));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_layer_hidden_and_shown_again_finds_its_nodes_again() {
|
||||
let mut editor = editor().await;
|
||||
let rectangle = rectangle_node(&editor);
|
||||
let compiled = |editor: &EditorTestUtils| {
|
||||
let tree = editor.runtime.executor.tree();
|
||||
tree.source_map().get([rectangle].as_slice()).and_then(|(node, _)| tree.get(*node))
|
||||
};
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
let before = compiled(&editor).expect("the rectangle should be compiled");
|
||||
|
||||
for visible in [false, true] {
|
||||
set_layer_visible(&mut editor, visible);
|
||||
send_update(&mut editor);
|
||||
run(&mut editor).await;
|
||||
}
|
||||
let after = compiled(&editor).expect("the rectangle should be compiled again");
|
||||
assert!(Arc::ptr_eq(&before, &after), "the rectangle was built again");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -12,8 +12,8 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
use graphene_std::renderer::Render;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -276,11 +276,11 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
|
||||
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
|
||||
/// The area the content covers once rendered, counting the effects drawn through maps and images.
|
||||
fn content_bounds(&self) -> RenderBoundingBox {
|
||||
match self {
|
||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
|
||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||
@@ -289,7 +289,7 @@ impl ThumbnailContent {
|
||||
|
||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||
fn bounds(&self) -> [DVec2; 2] {
|
||||
let bounds = match self.content_bounds(true) {
|
||||
let bounds = match self.content_bounds() {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||
_ => [DVec2::ZERO, DVec2::ONE],
|
||||
};
|
||||
@@ -297,38 +297,6 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
|
||||
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
||||
let contents: Vec<ThumbnailContent> = layers
|
||||
.iter()
|
||||
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||
.collect();
|
||||
|
||||
let bounds = contents
|
||||
.iter()
|
||||
.filter_map(|content| match content.content_bounds(false) {
|
||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||
_ => None,
|
||||
})
|
||||
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
||||
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
for content in &contents {
|
||||
content.graphic().render_svg(&mut render, &render_params);
|
||||
}
|
||||
if render.svg.is_empty() {
|
||||
return None;
|
||||
}
|
||||
render.format_svg(bounds[0], bounds[1]);
|
||||
|
||||
Some(render.svg.to_svg_string())
|
||||
}
|
||||
|
||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
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";
|
||||
@@ -25,15 +23,7 @@
|
||||
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
|
||||
@@ -46,8 +36,6 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
destroyDragToggleManager(dragToggleListener);
|
||||
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("pointercancel", abortDrag);
|
||||
|
||||
@@ -331,7 +331,6 @@
|
||||
}
|
||||
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
|
||||
activeGroupChanged: (group) => {
|
||||
activeDragToggleGroup = group;
|
||||
},
|
||||
@@ -343,15 +342,6 @@
|
||||
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);
|
||||
}
|
||||
@@ -1204,7 +1194,6 @@
|
||||
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)}
|
||||
>
|
||||
@@ -1354,8 +1343,6 @@
|
||||
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}
|
||||
@@ -1372,17 +1359,12 @@
|
||||
: 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}
|
||||
@@ -1413,15 +1395,10 @@
|
||||
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,12 +41,6 @@
|
||||
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 -->
|
||||
@@ -82,16 +76,7 @@
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
<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}
|
||||
>
|
||||
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
|
||||
<div
|
||||
class="icon-slot"
|
||||
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
||||
|
||||
@@ -8,30 +8,21 @@
|
||||
// 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);
|
||||
@@ -47,13 +38,12 @@ 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 && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
|
||||
if (engaged) listener.engagedChanged?.(false);
|
||||
listeners.delete(listener);
|
||||
|
||||
// Uninstall the window event listeners only once the last consumer leaves
|
||||
@@ -64,120 +54,83 @@ 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 listenersOfGroup(group: string): DragToggleListener[] {
|
||||
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
|
||||
}
|
||||
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
const previousGroup = activeGroup;
|
||||
activeGroup = group;
|
||||
|
||||
const notifiedGroup = group || previousGroup;
|
||||
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
listeners.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 {
|
||||
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
|
||||
if (!(target instanceof Element)) return undefined;
|
||||
const found = target.closest(`[${groupAttribute(middleButton)}]`);
|
||||
const found = target.closest("[data-drag-toggle-group]");
|
||||
return found instanceof HTMLElement ? found : undefined;
|
||||
}
|
||||
|
||||
function memberState(member: HTMLElement): string | undefined {
|
||||
return member.getAttribute("data-drag-toggle-state") || 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;
|
||||
if (e.button !== 0) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
const middleButton = e.button === MIDDLE_BUTTON;
|
||||
const found = findMember(e.target || undefined, middleButton);
|
||||
const found = findMember(e.target || undefined);
|
||||
if (!found) return;
|
||||
|
||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||
e.stopPropagation();
|
||||
|
||||
middleButtonGesture = middleButton;
|
||||
source = found;
|
||||
startingState = memberState(found);
|
||||
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
|
||||
|
||||
if (middleButton) engage();
|
||||
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
const member = findMember(e.target || undefined, middleButtonGesture);
|
||||
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
|
||||
const member = findMember(e.target || undefined);
|
||||
if (!member || member.getAttribute("data-drag-toggle-group") !== 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) engage();
|
||||
if (!engaged) {
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
listeners.forEach((listener) => listener.engagedChanged?.(true));
|
||||
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
|
||||
}
|
||||
|
||||
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
||||
if (memberState(member) !== startingState) return;
|
||||
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||
|
||||
visited.add(member);
|
||||
toggle(member);
|
||||
member.click();
|
||||
}
|
||||
|
||||
function onPointerUp(e: Event) {
|
||||
if (!activeGroup) return;
|
||||
const endedGroup = activeGroup;
|
||||
|
||||
// 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;
|
||||
}
|
||||
// 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;
|
||||
const wasEngaged = engaged;
|
||||
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(undefined);
|
||||
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
|
||||
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
|
||||
}
|
||||
|
||||
function onClickCapture(e: Event) {
|
||||
@@ -188,15 +141,6 @@ 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);
|
||||
|
||||
@@ -19,8 +19,6 @@ pub struct DynamicExecutor {
|
||||
typing_context: TypingContext,
|
||||
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
|
||||
outputs: Vec<Weak<NodeId>>,
|
||||
// Kept for one more update, so a node that comes back is reused
|
||||
orphaned_nodes: HashSet<NodeId>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -38,7 +36,6 @@ impl Default for DynamicExecutor {
|
||||
tree: Default::default(),
|
||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||
outputs: Vec::new(),
|
||||
orphaned_nodes: HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,16 +118,13 @@ impl DynamicExecutor {
|
||||
pending.extend(inputs.iter());
|
||||
}
|
||||
}
|
||||
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
||||
for node_id in old_to_remove {
|
||||
if self.orphaned_nodes.contains(&node_id) {
|
||||
let path = self.tree.free_node(node_id);
|
||||
self.typing_context.remove_inference(node_id);
|
||||
if let Some(path) = path {
|
||||
remove.push(path);
|
||||
}
|
||||
let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
||||
let mut remove = Vec::new();
|
||||
for node_id in orphaned {
|
||||
let path = self.tree.free_node(node_id);
|
||||
self.typing_context.remove_inference(node_id);
|
||||
if let Some(path) = path {
|
||||
remove.push(path);
|
||||
}
|
||||
}
|
||||
remove
|
||||
|
||||
@@ -1240,18 +1240,19 @@ fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
|
||||
|
||||
drop(output);
|
||||
executor.update(source_network(2)).unwrap();
|
||||
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
|
||||
executor.update(source_network(2)).unwrap();
|
||||
assert_eq!(kept(&executor), [false; 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_is_listed_for_as_long_as_its_node_lives() {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
executor.update(source_network(0)).unwrap();
|
||||
let (output, _) = executor.update(source_network(0)).unwrap();
|
||||
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
|
||||
|
||||
for _ in 0..3 {
|
||||
executor.update(source_network(1)).unwrap();
|
||||
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
|
||||
}
|
||||
executor.update(source_network(1)).unwrap();
|
||||
assert!(listed(&executor));
|
||||
|
||||
drop(output);
|
||||
executor.update(source_network(1)).unwrap();
|
||||
assert!(!listed(&executor));
|
||||
}
|
||||
@@ -423,11 +423,7 @@ 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 {
|
||||
super::shapes::HANDLE_OFFSET_FACTOR
|
||||
};
|
||||
let handle_offset_factor = if let Some(angle) = angle { 4. / 3. * (angle / 4.).tan() } else { 0.551784777779014 };
|
||||
|
||||
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,27 +5,19 @@
|
||||
mod heart;
|
||||
|
||||
use crate::vector::misc::{ArcType, SpiralType, bezpath_from_anchors_and_handles};
|
||||
use glam::{DMat2, DVec2};
|
||||
use glam::DVec2;
|
||||
pub use heart::{HEART_SIZE, HeartProportions, heart_bezpath};
|
||||
use kurbo::BezPath;
|
||||
use std::f64::consts::{PI, SQRT_2, TAU};
|
||||
use std::f64::consts::TAU;
|
||||
|
||||
/// 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.;
|
||||
/// Constant from <https://pomax.github.io/bezierinfo/#circles_cubic>
|
||||
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
|
||||
|
||||
/// 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 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 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 failure of [`regular_polygon_bezpath`] and [`star_polygon_bezpath`].
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -185,7 +177,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_SHAPE_ANCHORS {
|
||||
if sides > MAX_POLYGON_ANCHORS {
|
||||
return Err(PolygonError::TooManySides(sides));
|
||||
}
|
||||
|
||||
@@ -202,7 +194,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_SHAPE_ANCHORS / 2 {
|
||||
if sides > MAX_POLYGON_ANCHORS / 2 {
|
||||
return Err(PolygonError::TooManySides(sides));
|
||||
}
|
||||
|
||||
@@ -258,239 +250,151 @@ 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("A spiral with this many turns at this angular resolution is too large to fit in memory")]
|
||||
TooManySegments,
|
||||
#[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,
|
||||
}
|
||||
|
||||
/// 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());
|
||||
/// 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);
|
||||
}
|
||||
|
||||
// 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;
|
||||
let mut anchors = Vec::new();
|
||||
let mut prev_in_handle = None;
|
||||
let theta_end = turns * TAU + start_angle;
|
||||
|
||||
// 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 a = if spiral_type == SpiralType::Logarithmic { a.max(1e-10) } else { a };
|
||||
let b = calculate_growth_factor(a, turns, outer_radius, spiral_type);
|
||||
|
||||
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);
|
||||
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;
|
||||
}
|
||||
anchors.push(Anchor::new(spiral.point(sweep), in_handle, None));
|
||||
|
||||
Ok(bezpath_from_anchors(&anchors, false))
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 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),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,6 +3,7 @@ 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};
|
||||
@@ -1085,49 +1086,16 @@ impl VectorModification {
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
impl graphene_hash::CacheHash for VectorModification {
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
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);
|
||||
core::hash::Hash::hash(&generate_uuid(), 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)
|
||||
@@ -1295,23 +1263,6 @@ 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();
|
||||
|
||||
@@ -56,23 +56,17 @@ fn spiral(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
spiral_type: Item<SpiralType>,
|
||||
#[hard(0..)]
|
||||
#[default(5.)]
|
||||
turns: Item<f64>,
|
||||
#[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> {
|
||||
@@ -553,7 +547,6 @@ 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;
|
||||
|
||||
@@ -797,98 +790,6 @@ 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)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user