From d91f3878be8d85041506c68f2f1985bad5100048 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Wed, 14 Oct 2026 08:44:16 -0700 Subject: [PATCH 01/47] Make the shape gizmos snap their angles, radii, and turns through the new snapping engine (#4704) * Snap the shape gizmos' angles, radii, and turns through the snapping session as one-value gestures * Fix gizmo snapping on stretched shapes and keep trimmed arcs and spirals in place --- editor/src/consts.rs | 3 +- .../gizmos/gizmo_manager.rs | 19 +- .../shape_gizmos/circle_arc_radius_handle.rs | 86 ++++- .../shape_gizmos/point_radius_handle.rs | 67 ++-- .../shape_gizmos/spiral_turns_handle.rs | 90 ++++- .../gizmos/shape_gizmos/sweep_angle_gizmo.rs | 77 ++-- .../common_functionality/shapes/arc_shape.rs | 6 +- .../shapes/circle_shape.rs | 4 +- .../common_functionality/shapes/grid_shape.rs | 4 +- .../shapes/polygon_shape.rs | 6 +- .../shapes/shape_utility.rs | 16 +- .../shapes/spiral_shape.rs | 4 +- .../common_functionality/shapes/star_shape.rs | 6 +- .../tool/common_functionality/snap_session.rs | 198 ++++++++-- .../snap_session/presenter.rs | 4 + .../messages/tool/tool_messages/shape_tool.rs | 355 +++++++++++++++++- libraries/snapping/src/candidate.rs | 2 + 17 files changed, 820 insertions(+), 127 deletions(-) diff --git a/editor/src/consts.rs b/editor/src/consts.rs index 9a510bb805..16caf3362d 100644 --- a/editor/src/consts.rs +++ b/editor/src/consts.rs @@ -134,11 +134,10 @@ pub const BRUSH_FLOW_DEFAULT: f64 = 100.; pub const EYEDROPPER_PREVIEW_AREA_RESOLUTION: u32 = 11; // GIZMOS -pub const POINT_RADIUS_HANDLE_SNAP_THRESHOLD: f64 = 8.; +pub const SPIRAL_END_HOVER_RADIUS: f64 = 8.; pub const POINT_RADIUS_HANDLE_SEGMENT_THRESHOLD: f64 = 7.9; pub const NUMBER_OF_POINTS_DIAL_SPOKE_EXTENSION: f64 = 1.2; pub const NUMBER_OF_POINTS_DIAL_SPOKE_LENGTH: f64 = 10.; -pub const ARC_SNAP_THRESHOLD: f64 = 5.; pub const ARC_SWEEP_GIZMO_RADIUS: f64 = 14.; pub const ARC_SWEEP_GIZMO_TEXT_HEIGHT: f64 = 12.; pub const GIZMO_HIDE_THRESHOLD: f64 = 20.; diff --git a/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs b/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs index 962e9a5d06..c7a823c50e 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/gizmo_manager.rs @@ -12,6 +12,7 @@ use crate::messages::tool::common_functionality::shapes::polygon_shape::PolygonG use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeGizmoHandler; use crate::messages::tool::common_functionality::shapes::spiral_shape::SpiralGizmoHandler; use crate::messages::tool::common_functionality::shapes::star_shape::StarGizmoHandler; +use crate::messages::tool::common_functionality::snap_session::{SnapSession, SnapView}; use glam::DVec2; use std::collections::VecDeque; @@ -89,14 +90,14 @@ impl ShapeGizmoHandlers { } /// Updates the gizmo state while the user is dragging a handle (e.g., adjusting radius). - pub fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + pub fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { match self { - Self::Star(h) => h.handle_update(drag_start, document, input, responses), - Self::Polygon(h) => h.handle_update(drag_start, document, input, responses), - Self::Arc(h) => h.handle_update(drag_start, document, input, responses), - Self::Circle(h) => h.handle_update(drag_start, document, input, responses), - Self::Grid(h) => h.handle_update(drag_start, document, input, responses), - Self::Spiral(h) => h.handle_update(drag_start, document, input, responses), + Self::Star(h) => h.handle_update(drag_start, view, snap_session, responses), + Self::Polygon(h) => h.handle_update(drag_start, view, snap_session, responses), + Self::Arc(h) => h.handle_update(drag_start, view, snap_session, responses), + Self::Circle(h) => h.handle_update(drag_start, view, snap_session, responses), + Self::Grid(h) => h.handle_update(drag_start, view, snap_session, responses), + Self::Spiral(h) => h.handle_update(drag_start, view, snap_session, responses), Self::None => {} } } @@ -269,9 +270,9 @@ impl GizmoManager { } /// Passes drag update data to the active gizmo to update shape parameters live. - pub fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + pub fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if let Some(handle) = &mut self.active_shape_handler { - handle.handle_update(drag_start, document, input, responses); + handle.handle_update(drag_start, view, snap_session, responses); } } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs index fa507e5cab..5aad44524a 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/circle_arc_radius_handle.rs @@ -4,10 +4,11 @@ use crate::messages::message::Message; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; -use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage}; +use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage}; use crate::messages::prelude::{FrontendMessage, Responses}; use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_arc_id, get_stroke_width}; -use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_arc_parameters, extract_circle_radius}; +use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_arc_parameters, extract_circle_radius, extract_polygon_parameters, extract_star_parameters}; +use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate}; use glam::{DAffine2, DVec2}; use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; @@ -16,6 +17,9 @@ use graphene_std::core_types::FallibleVec2Operations; use std::collections::VecDeque; use std::f64::consts::FRAC_PI_2; +/// How many of the round shapes nearest the dragged one offer their radius to snap to. +const MAX_EQUAL_RADII: usize = 32; + #[derive(Clone, Debug, Default, PartialEq)] pub enum RadiusHandleState { #[default] @@ -28,6 +32,10 @@ pub enum RadiusHandleState { pub struct RadiusHandle { pub layer: Option, initial_radius: f64, + /// The radius the pointer asks for, before any snap. + free_radius: f64, + /// The radii of the other round shapes, gathered once a drag begins. + equal_radii: Option>, handle_state: RadiusHandleState, angle: f64, previous_mouse_position: DVec2, @@ -37,6 +45,7 @@ impl RadiusHandle { pub fn cleanup(&mut self) { self.handle_state = RadiusHandleState::Inactive; self.layer = None; + self.equal_radii = None; } pub fn hovered(&self) -> bool { @@ -98,6 +107,7 @@ impl RadiusHandle { if Self::check_if_inside_dash_lines(angle, mouse_position, viewport, radius.abs(), document, layer) { self.layer = Some(layer); self.initial_radius = radius; + self.free_radius = radius; self.previous_mouse_position = mouse_position; self.angle = angle; @@ -148,10 +158,11 @@ impl RadiusHandle { } } - pub fn update_inner_radius(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque, drag_start: DVec2) { + pub fn update_inner_radius(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque, drag_start: DVec2) { + let SnapView { document, input, .. } = view; let Some(layer) = self.layer else { return }; - // This gizmo serves both Circle and Arc layers, so resolve which node is present to know whose radius parameter to write + // This gizmo serves both Circle and Arc layers, so resolve which node is present to know which radius parameter to write let (node_id, radius_parameter) = if let Some(node_id) = graph_modification_utils::get_circle_id(layer, &document.network_interface) { (node_id, ParameterRef::from(graphene_std::vector::generator_nodes::circle::RadiusInput)) } else if let Some(node_id) = get_arc_id(layer, &document.network_interface) { @@ -159,9 +170,6 @@ impl RadiusHandle { } else { return; }; - let Some(current_radius) = extract_circle_radius(layer, document).or(extract_arc_parameters(Some(layer), document).map(|(r, _, _, _)| r)) else { - return; - }; let viewport_transform = document.network_interface.document_metadata().transform_to_viewport(layer); let center = viewport_transform.transform_point2(DVec2::ZERO); @@ -173,14 +181,76 @@ impl RadiusHandle { let net_delta = delta_vector.length() * sign * self.initial_radius.signum(); self.previous_mouse_position = input.mouse.position; + // Kept apart from the radius written, which a snap may have moved + self.free_radius += net_delta; + + // The handle is where the pointer took hold of the rim, which moves out along that angle as the radius grows + let spoke = calculate_circle_point_position(self.angle, 1.); + let equal_radii = self.equal_radii.get_or_insert_with(|| equal_radius_candidates(document, layer, spoke)); + let on_screen_per_unit = viewport_transform.transform_vector2(spoke).length(); + let to_document = document.metadata().document_to_viewport.inverse() * viewport_transform; + let position_of = |radius: f64| to_document.transform_point2(spoke * radius); + + // The size is snapped, which keeps whichever sign the radius has come to + let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum(); + responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, radius_parameter), - input: NodeInput::value(TaggedValue::Number(current_radius + net_delta), false), + input: NodeInput::value(TaggedValue::Number(snapped_radius), false), }); responses.add(NodeGraphMessage::RunDocumentGraph); } } +/// The sizes of the radii of the visible circles, arcs, polygons, and stars nearest a dragged one, in its units. +/// Each is measured in document space along the dragged handle's spoke, since a stretched shape reaches a different distance in each direction. +/// O(n) in the document's layers. +fn equal_radius_candidates(document: &DocumentMessageHandler, dragged: LayerNodeIdentifier, spoke: DVec2) -> Vec { + let metadata = document.metadata(); + + // The spoke's direction in document space, and how far the handle moves along it per unit of radius + let dragged_to_document = metadata.transform_to_document(dragged); + let document_spoke = dragged_to_document.transform_vector2(spoke); + let Some(direction) = document_spoke.try_normalize() else { return Vec::new() }; + let dragged_scale = document_spoke.length(); + let dragged_center = dragged_to_document.transform_point2(DVec2::ZERO); + + // A star offers its outer radius + let radius_of = |layer: LayerNodeIdentifier| { + extract_circle_radius(layer, document) + .or_else(|| extract_arc_parameters(Some(layer), document).map(|(radius, ..)| radius)) + .or_else(|| extract_polygon_parameters(Some(layer), document).map(|(_, radius)| radius)) + .or_else(|| extract_star_parameters(Some(layer), document).map(|(_, radius1, radius2)| radius1.abs().max(radius2.abs()))) + }; + + let mut nearest: Vec<(f64, ValueCandidate)> = metadata + .all_layers() + .filter(|&layer| layer != dragged && document.network_interface.is_layer_visible(layer)) + .filter_map(|layer| { + // The rim lies a radius out in the layer's own space, where the direction has its own length + let to_document = metadata.transform_to_document(layer); + if to_document.matrix2.determinant() == 0. { + return None; + } + let rim_along_direction = radius_of(layer)?.abs() / to_document.matrix2.inverse().mul_vec2(direction).length(); + let value = rim_along_direction / dragged_scale; + let distance = to_document.transform_point2(DVec2::ZERO).distance(dragged_center); + let candidate = ValueCandidate { + value, + kind: Kind::EqualRadius, + identity: layer.to_node().0, + }; + (value.is_finite() && value != 0.).then_some((distance, candidate)) + }) + .collect(); + + if nearest.len() > MAX_EQUAL_RADII { + nearest.select_nth_unstable_by(MAX_EQUAL_RADII, |a, b| a.0.total_cmp(&b.0)); + nearest.truncate(MAX_EQUAL_RADII); + } + nearest.into_iter().map(|(_, candidate)| candidate).collect() +} + fn calculate_circle_point_position(theta: f64, radius: f64) -> DVec2 { DVec2::new(radius * theta.cos(), -radius * theta.sin()) } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs index 4b00e73e5c..b4a79c0429 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/point_radius_handle.rs @@ -1,5 +1,5 @@ +use crate::consts::COLOR_OVERLAY_RED; use crate::consts::GIZMO_HIDE_THRESHOLD; -use crate::consts::{COLOR_OVERLAY_RED, POINT_RADIUS_HANDLE_SNAP_THRESHOLD}; use crate::messages::frontend::utility_types::MouseCursorIcon; use crate::messages::message::Message; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; @@ -7,11 +7,12 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::{overlays::utility_types::OverlayContext, utility_types::network_interface::InputConnector}; use crate::messages::prelude::FrontendMessage; use crate::messages::prelude::Responses; -use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage}; +use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage}; use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer; use crate::messages::tool::common_functionality::shapes::shape_utility::{draw_snapping_ticks, extract_polygon_parameters, polygon_outline, polygon_vertex_position, star_outline}; use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_star_parameters, star_vertex_position}; -use glam::DVec2; +use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate}; +use glam::{DAffine2, DVec2}; use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; use graphene_std::ParameterRef; @@ -397,29 +398,41 @@ impl PointRadiusHandle { snap_radii } - fn check_snapping(&self, new_radius: f64, original_radius: f64) -> Option<(usize, f64)> { - self.snap_radii + /// Snaps a radius to the ones in `snap_radii`, judged by how far the handle moves along its spoke on screen. + fn snap_radius(&self, view: SnapView, snap_session: &mut SnapSession, layer: LayerNodeIdentifier, free_radius: f64) -> f64 { + let document = view.document; + let layer_to_viewport = document.metadata().transform_to_viewport(layer); + let point = self.point as i32; + + // The unit spoke the handle moves along in the layer's space + let spoke = if let Some((sides, _, _)) = extract_star_parameters(Some(layer), document) { + star_vertex_position(DAffine2::IDENTITY, point, sides, 1., 1.) + } else if let Some((sides, _)) = extract_polygon_parameters(Some(layer), document) { + polygon_vertex_position(DAffine2::IDENTITY, point, sides, 1.) + } else { + return free_radius; + }; + + // The first two radii give the star right-angled tips, and the rest line the tips up with other vertices + let candidates: Vec = self + .snap_radii .iter() .enumerate() - .filter(|(_, rad)| (**rad - new_radius).abs() < POINT_RADIUS_HANDLE_SNAP_THRESHOLD) - .min_by(|(i_a, a), (i_b, b)| { - let dist_a = (**a - new_radius).abs(); - let dist_b = (**b - new_radius).abs(); - - // Check if either index is 0 or 1 and prioritize them - match (*i_a == 0 || *i_a == 1, *i_b == 0 || *i_b == 1) { - // `a` is priority index, `b` is not - (true, false) => std::cmp::Ordering::Less, - // `b` is priority index, `a` is not - (false, true) => std::cmp::Ordering::Greater, - // Normal comparison - _ => dist_a.partial_cmp(&dist_b).unwrap_or(std::cmp::Ordering::Equal), - } + .map(|(index, &value)| ValueCandidate { + value, + kind: if index < 2 { Kind::RightAngle } else { Kind::Through }, + identity: index as u64, }) - .map(|(i, rad)| (i, *rad - original_radius)) + .collect(); + + let on_screen_per_unit = layer_to_viewport.transform_vector2(spoke).length(); + let to_document = document.metadata().document_to_viewport.inverse() * layer_to_viewport; + let position_of = |radius: f64| to_document.transform_point2(spoke * radius); + snap_session.snap_value(view, position_of, free_radius, on_screen_per_unit, &candidates) } - pub fn update_inner_radius(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque, drag_start: DVec2) { + pub fn update_inner_radius(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque, drag_start: DVec2) { + let SnapView { document, input, .. } = view; let Some(layer) = self.layer else { return }; let Some(radius_parameter) = self.radius_parameter.clone() else { return }; @@ -438,21 +451,23 @@ impl PointRadiusHandle { let projection = delta.project_onto(radius); let sign = radius.dot(delta).signum(); - let mut net_delta = projection.length() * sign * original_radius.signum(); + let net_delta = projection.length() * sign * original_radius.signum(); let new_radius = original_radius + net_delta; self.update_state(PointRadiusHandleState::Dragging); self.check_if_radius_flipped(original_radius, new_radius, document, layer, &radius_parameter); - if let Some((index, snapped_delta)) = self.check_snapping(new_radius, original_radius) { - net_delta = snapped_delta; - self.update_state(PointRadiusHandleState::Snapped(index)); + // A snap's identity is the index of its radius, which picks the guides drawn for it + let snapped_radius = self.snap_radius(view, snap_session, layer, new_radius); + let engaged = snap_session.shown().and_then(|shown| shown.outcome.engaged_candidates().next()); + if let Some(candidate) = engaged { + self.update_state(PointRadiusHandleState::Snapped(candidate.key.identity[0] as usize)); } responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, radius_parameter), - input: NodeInput::value(TaggedValue::Number(original_radius + net_delta), false), + input: NodeInput::value(TaggedValue::Number(snapped_radius), false), }); responses.add(NodeGraphMessage::RunDocumentGraph); } diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs index 601c64efd2..a2053fe1af 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/spiral_turns_handle.rs @@ -1,14 +1,15 @@ -use crate::consts::{COLOR_OVERLAY_RED, POINT_RADIUS_HANDLE_SNAP_THRESHOLD}; +use crate::consts::{COLOR_OVERLAY_RED, SPIRAL_END_HOVER_RADIUS}; use crate::messages::message::Message; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::prelude::Responses; -use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage}; +use crate::messages::prelude::{DocumentMessageHandler, NodeGraphMessage}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::shape_editor::ShapeState; -use crate::messages::tool::common_functionality::shapes::shape_utility::extract_spiral_parameters; +use crate::messages::tool::common_functionality::shapes::shape_utility::{extract_spiral_parameters, pointer_travel_per_radian}; use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate_spiral_endpoints; +use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate}; use glam::DVec2; use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; @@ -103,9 +104,9 @@ impl SpiralTurns { 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) < POINT_RADIUS_HANDLE_SNAP_THRESHOLD { + 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); - } else if mouse_position.distance(start_point) < POINT_RADIUS_HANDLE_SNAP_THRESHOLD { + } else if mouse_position.distance(start_point) < SPIRAL_END_HOVER_RADIUS { self.store_initial_parameters(layer, inner_radius, outer_radius, turns, start_angle, mouse_position, GizmoType::Start, spiral_type); } } @@ -141,9 +142,65 @@ impl SpiralTurns { } } - pub fn update_number_of_turns(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + /// How much the outer radius grows as the spiral gains a number of turns, keeping its growth and tightness the same. + fn outer_radius_change(&self, turns_gained: f64) -> f64 { + match self.spiral_type { + SpiralType::Archimedean => turns_gained * self.initial_growth_factor * TAU, + SpiralType::Logarithmic => self.initial_outer_radius * ((self.initial_growth_factor * TAU * turns_gained).exp() - 1.), + } + } + + /// 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 turns_taken_off = self.initial_turns - turns; + let outer_radius = (self.initial_outer_radius + self.outer_radius_change(-turns_taken_off)).max(0.1); + (self.initial_start_angle + turns_taken_off * 360., turns.max(0.5), outer_radius) + } + + /// Snaps a number of turns to whole and half turns, judged by how far the pointer travels around the center on screen. + fn snap_turns(&self, view: SnapView, snap_session: &mut SnapSession, layer: LayerNodeIdentifier, free_turns: f64) -> f64 { + let document = view.document; + let Some((spiral_type, start_angle, inner_radius, outer_radius, turns, _)) = extract_spiral_parameters(layer, document) else { + return free_turns; + }; + if !free_turns.is_finite() { + return free_turns; + } + + // The turns follow the pointer's angle in the spiral's own space, which a stretched spiral spaces unevenly on screen + let layer_to_viewport = document.metadata().transform_to_viewport(layer); + let on_screen_per_turn = TAU * pointer_travel_per_radian(layer_to_viewport, view.input.mouse.position); + + let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type); + let viewport_to_document = document.metadata().document_to_viewport.inverse(); + let position_of = |turns_landed_on: f64| { + let (angle, growth_factor) = match self.gizmo_type { + GizmoType::Start => { + let (start_angle, turns, outer_radius) = self.start_dragged_to(turns_landed_on); + (start_angle.to_radians(), calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type)) + } + _ => (turns_landed_on * TAU + start_angle.to_radians(), growth_factor), + }; + 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 + let nearest_half_turns = (free_turns * 2.).round() as i64; + let candidates: Vec = (nearest_half_turns.saturating_sub(2).max(1)..=nearest_half_turns.saturating_add(2)) + .map(|half_turns| ValueCandidate { + value: half_turns as f64 / 2., + kind: if half_turns % 2 == 0 { Kind::WholeValue } else { Kind::AngleStep }, + identity: half_turns as u64, + }) + .collect(); + + snap_session.snap_value(view, position_of, free_turns, on_screen_per_turn, &candidates) + } + + pub fn update_number_of_turns(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { use graphene_std::vector::generator_nodes::spiral::*; + let SnapView { document, input, .. } = view; let Some(layer) = self.layer else { return; }; @@ -171,11 +228,18 @@ impl SpiralTurns { // Convert the total angle (in degrees) to number of full turns let turns_delta = total_delta / 360.; - // Calculate the new outer radius based on spiral type and turn change - let outer_radius_change = match self.spiral_type { - SpiralType::Archimedean => turns_delta * (self.initial_growth_factor) * TAU, - SpiralType::Logarithmic => self.initial_outer_radius * ((self.initial_growth_factor * TAU * turns_delta).exp() - 1.), + // Dragging the start takes turns away rather than adding them + let direction = match self.gizmo_type { + GizmoType::Start => -1., + GizmoType::End => 1., + GizmoType::None => return, }; + let free_turns = self.initial_turns + turns_delta * direction; + 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() { @@ -188,13 +252,11 @@ impl SpiralTurns { match self.gizmo_type { GizmoType::Start => { - let sign = -1.; - let new_turns = (self.initial_turns + turns_delta * sign).max(0.5); - let new_outer_radius = (self.initial_outer_radius + outer_radius_change * sign).max(0.1); + 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), - input: NodeInput::value(TaggedValue::Number(self.initial_start_angle + total_delta), false), + input: NodeInput::value(TaggedValue::Number(new_start_angle), false), }); responses.add(NodeGraphMessage::SetInput { input_connector: InputConnector::node(node_id, TurnsInput), diff --git a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs index 255c2d2634..4214546340 100644 --- a/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs +++ b/editor/src/messages/tool/common_functionality/gizmos/shape_gizmos/sweep_angle_gizmo.rs @@ -1,4 +1,4 @@ -use crate::consts::{ARC_SNAP_THRESHOLD, GIZMO_HIDE_THRESHOLD}; +use crate::consts::GIZMO_HIDE_THRESHOLD; use crate::messages::message::Message; use crate::messages::portfolio::document::overlays::utility_functions::text_width; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; @@ -6,13 +6,14 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::prelude::DocumentMessageHandler; use crate::messages::tool::common_functionality::graph_modification_utils; -use crate::messages::tool::common_functionality::shapes::shape_utility::{arc_end_points, calculate_arc_text_transform, extract_arc_parameters, format_rounded}; +use crate::messages::tool::common_functionality::shapes::shape_utility::{arc_end_points, calculate_arc_text_transform, extract_arc_parameters, format_rounded, pointer_travel_per_radian}; +use crate::messages::tool::common_functionality::snap_session::{Kind, SnapSession, SnapView, ValueCandidate}; use crate::messages::tool::tool_messages::tool_prelude::*; use glam::DVec2; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeInput}; use std::collections::VecDeque; -use std::f64::consts::FRAC_PI_4; +use std::f64::consts::PI; #[derive(Clone, Debug, Default, PartialEq)] pub enum SweepAngleGizmoState { @@ -40,7 +41,7 @@ pub struct SweepAngleGizmo { position_before_rotation: DVec2, previous_mouse_position: DVec2, total_angle_delta: f64, - snap_angles: Vec, + snap_angles: Vec, handle_state: SweepAngleGizmoState, } @@ -192,7 +193,8 @@ impl SweepAngleGizmo { overlay_context.arc_sweep_angle(offset_angle, angle, final_point, bold_radius, center, &text, transform); } - pub fn update_arc(&mut self, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + pub fn update_arc(&mut self, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { + let SnapView { document, input, .. } = view; let Some(layer) = self.layer else { return }; let Some((_, current_start_angle, current_sweep_angle, _)) = extract_arc_parameters(Some(layer), document) else { return; @@ -216,11 +218,10 @@ impl SweepAngleGizmo { EndpointType::Start => { // Dragging start changes both start and sweep - let sign = -angle.signum(); let mut total = angle; let new_start_angle = self.initial_start_angle + total; - let new_sweep_angle = self.initial_sweep_angle + total.abs() * sign; + let new_sweep_angle = self.initial_sweep_angle - total; match () { // Clamp sweep angle to 360° @@ -276,13 +277,14 @@ impl SweepAngleGizmo { self.apply_arc_update(node_id, self.initial_start_angle + underflow, self.initial_sweep_angle + underflow.abs(), input, responses); } _ => { - if let Some(snapped_delta) = self.check_snapping(self.initial_sweep_angle + total.abs() * sign) { - total += snapped_delta; + let free_sweep_angle = self.initial_sweep_angle - total; + total += free_sweep_angle - self.snap_sweep_angle(view, snap_session, free_sweep_angle); + if snap_session.caught() { self.update_state(SweepAngleGizmoState::Snapped); } self.total_angle_delta = angle; - self.apply_arc_update(node_id, self.initial_start_angle + total, self.initial_sweep_angle + total.abs() * sign, input, responses); + self.apply_arc_update(node_id, self.initial_start_angle + total, self.initial_sweep_angle - total, input, responses); } } } @@ -317,8 +319,9 @@ impl SweepAngleGizmo { self.apply_arc_update(node_id, self.initial_start_angle + angle_delta, self.initial_sweep_angle + angle_delta.abs() * sign, input, responses); } _ => { - if let Some(snapped_delta) = self.check_snapping(self.initial_sweep_angle + angle) { - total += snapped_delta; + let free_sweep_angle = self.initial_sweep_angle + angle; + total += self.snap_sweep_angle(view, snap_session, free_sweep_angle) - free_sweep_angle; + if snap_session.caught() { self.update_state(SweepAngleGizmoState::Snapped); } @@ -348,22 +351,44 @@ impl SweepAngleGizmo { responses.add(NodeGraphMessage::RunDocumentGraph); } - pub fn check_snapping(&self, new_sweep_angle: f64) -> Option { - self.snap_angles.iter().find(|angle| (**angle - new_sweep_angle).abs() <= ARC_SNAP_THRESHOLD).map(|angle| { - let delta = angle - new_sweep_angle; - if self.endpoint == EndpointType::End { delta } else { -delta } - }) + /// Snaps a sweep angle in degrees to the multiples of 45°, judged by how far the pointer travels around the center on screen. + fn snap_sweep_angle(&self, view: SnapView, snap_session: &mut SnapSession, free_sweep_angle: f64) -> f64 { + let document = view.document; + let Some(layer) = self.layer else { return free_sweep_angle }; + let Some((radius, start_angle, sweep_angle, _)) = extract_arc_parameters(Some(layer), document) else { + return free_sweep_angle; + }; + + // The sweep follows the pointer's angle in the arc's own space, which a stretched arc spaces unevenly on screen + let layer_to_viewport = document.metadata().transform_to_viewport(layer); + let on_screen_per_degree = pointer_travel_per_radian(layer_to_viewport, view.input.mouse.position) * PI / 180.; + + // The dragged end turns about the center in the arc's own space, the start leaving the far end where it is as it shrinks the sweep + let layer_to_document = document.metadata().document_to_viewport.inverse() * layer_to_viewport; + let position_of = |sweep_angle_landed_on: f64| { + let end_angle = match self.endpoint { + EndpointType::Start => start_angle + sweep_angle - sweep_angle_landed_on, + _ => start_angle + sweep_angle_landed_on, + }; + layer_to_document.transform_point2(radius * DVec2::from_angle(end_angle.to_radians())) + }; + + snap_session.snap_value(view, position_of, free_sweep_angle, on_screen_per_degree, &self.snap_angles) } - pub fn calculate_snap_angles() -> Vec { - let mut snap_points = Vec::new(); - - for i in 0..=8 { - let snap_point = i as f64 * FRAC_PI_4; - snap_points.push(snap_point.to_degrees()); - } - - snap_points + /// The multiples of 45° from 0° to 360°, of which 90° and 270° are right angles. + pub fn calculate_snap_angles() -> Vec { + (0..=8_u64) + .map(|step| { + let degrees = step * 45; + let kind = if degrees == 90 || degrees == 270 { Kind::RightAngle } else { Kind::AngleStep }; + ValueCandidate { + value: degrees as f64, + kind, + identity: degrees, + } + }) + .collect() } pub fn cleanup(&mut self) { diff --git a/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs b/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs index 33c740f43e..bf4480da7f 100644 --- a/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/arc_shape.rs @@ -53,13 +53,13 @@ impl ShapeGizmoHandler for ArcGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.sweep_angle_gizmo.is_dragging_or_snapped() { - self.sweep_angle_gizmo.update_arc(document, input, responses); + self.sweep_angle_gizmo.update_arc(view, snap_session, responses); } if self.arc_radius_handle.is_dragging() { - self.arc_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.arc_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs index 1eb4463095..95e0525c77 100644 --- a/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/circle_shape.rs @@ -33,9 +33,9 @@ impl ShapeGizmoHandler for CircleGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.circle_radius_handle.is_dragging() { - self.circle_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.circle_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs b/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs index 9efeb13690..eae6124383 100644 --- a/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/grid_shape.rs @@ -35,9 +35,9 @@ impl ShapeGizmoHandler for GridGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, _snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.row_column_gizmo.is_dragging() { - self.row_column_gizmo.update(document, input, responses, drag_start); + self.row_column_gizmo.update(view.document, view.input, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs b/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs index db0cfc13d4..605d4ed875 100644 --- a/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs @@ -43,13 +43,13 @@ impl ShapeGizmoHandler for PolygonGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.number_of_points_dial.is_dragging() { - self.number_of_points_dial.update_number_of_sides(document, input, responses, drag_start); + self.number_of_points_dial.update_number_of_sides(view.document, view.input, responses, drag_start); } if self.point_radius_handle.is_dragging_or_snapped() { - self.point_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.point_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs index 6e82f3e31a..1d29c8bbbc 100644 --- a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs +++ b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs @@ -10,6 +10,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::Inpu use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage, Responses}; use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer; use crate::messages::tool::common_functionality::shape_editor::ShapeState; +use crate::messages::tool::common_functionality::snap_session::{SnapSession, SnapView}; use crate::messages::tool::common_functionality::transformation_cage::BoundingBoxManager; use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::*; @@ -135,7 +136,7 @@ pub trait ShapeGizmoHandler { /// Called during a drag interaction to update the shape's parameters in real time. /// /// For example, a handle might calculate the distance from the drag start to determine a new radius or update the number of points. - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque); + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque); /// Draws the static or hover-dependent overlays associated with the gizmo. /// @@ -394,6 +395,19 @@ pub fn arc_end_points_ignore_layer(radius: f64, start_angle: f64, sweep_angle: f Some((start_point, end_point)) } +/// How far the pointer must move on screen to turn its angle about a layer's center, in the layer's own space, by a radian. +/// On a layer scaled evenly, that is its distance from the center. +pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) -> f64 { + let from_center = pointer - layer_to_viewport.translation; + let determinant = layer_to_viewport.matrix2.determinant(); + if determinant == 0. { + return f64::NAN; + } + + let in_layer = layer_to_viewport.matrix2.inverse() * from_center; + in_layer.length_squared() * determinant.abs() / from_center.length() +} + /// Calculate the viewport position of a star vertex given its index /// Extract the node input values of Circle. /// Returns an option of (radius). diff --git a/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs b/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs index 693b35a154..c49478ec78 100644 --- a/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/spiral_shape.rs @@ -38,9 +38,9 @@ impl ShapeGizmoHandler for SpiralGizmoHandler { } } - fn handle_update(&mut self, _drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, _drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.turns_handle.is_dragging() { - self.turns_handle.update_number_of_turns(document, input, responses); + self.turns_handle.update_number_of_turns(view, snap_session, responses); } } diff --git a/editor/src/messages/tool/common_functionality/shapes/star_shape.rs b/editor/src/messages/tool/common_functionality/shapes/star_shape.rs index d64403b547..1e31ddc287 100644 --- a/editor/src/messages/tool/common_functionality/shapes/star_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/star_shape.rs @@ -43,13 +43,13 @@ impl ShapeGizmoHandler for StarGizmoHandler { } } - fn handle_update(&mut self, drag_start: DVec2, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, responses: &mut VecDeque) { + fn handle_update(&mut self, drag_start: DVec2, view: SnapView, snap_session: &mut SnapSession, responses: &mut VecDeque) { if self.number_of_points_dial.is_dragging() { - self.number_of_points_dial.update_number_of_sides(document, input, responses, drag_start); + self.number_of_points_dial.update_number_of_sides(view.document, view.input, responses, drag_start); } if self.point_radius_handle.is_dragging_or_snapped() { - self.point_radius_handle.update_inner_radius(document, input, responses, drag_start); + self.point_radius_handle.update_inner_radius(view, snap_session, responses, drag_start); } } diff --git a/editor/src/messages/tool/common_functionality/snap_session.rs b/editor/src/messages/tool/common_functionality/snap_session.rs index 3067736dec..28825723d0 100644 --- a/editor/src/messages/tool/common_functionality/snap_session.rs +++ b/editor/src/messages/tool/common_functionality/snap_session.rs @@ -9,19 +9,19 @@ use crate::messages::input_mapper::utility_types::keyboard::Key; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::prelude::*; use crate::messages::tool::utility_types::{HintGroup, HintInfo}; -use glam::DVec2; +use glam::{DAffine2, DVec2}; use graphene_std::vector::PointId; use scene_mirror::layer_id; pub use scene_mirror::anchor_positions; use snapping::{ - AnchorId, Awake, Bounds, Candidate, Context, CrossingCache, Exclusions, Frame, Highlight, Incumbent, LayerId, LayerKind, Outcome, Request, Scene, Settings, Side, Snap, SpacedBox, Tunables, - ViewMapping, find_constructions, find_constructions_from, find_equal_sizes, find_spacing, + AnchorId, Awake, Bounds, Candidate, CandidateKey, Context, CrossingCache, Exclusions, Frame, Highlight, Incumbent, LayerId, LayerKind, Outcome, Request, Scene, Settings, Side, Snap, SpacedBox, + Tunables, ViewMapping, find_constructions, find_constructions_from, find_equal_sizes, find_spacing, }; use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; -pub use snapping::{FeatureMap, Locus}; +pub use snapping::{FeatureMap, Kind, Locus}; /// How long the pointer must rest on a target to wake it while a gesture is under way, in milliseconds. const WAKE_DWELL_IN_GESTURE: u64 = 250; @@ -104,6 +104,16 @@ pub struct BoxFeatures { pub sides: [[Option; 2]; 2], } +/// A value a gizmo's value may snap to. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ValueCandidate { + pub value: f64, + /// The relationship it gives, which names it in the label. + pub kind: Kind, + /// Tells it apart from others of its kind, so an engaged snap is recognized after the pointer moves. + pub identity: u64, +} + /// What the latest attempt to snap came to, kept for drawing. #[derive(Clone, Debug)] pub struct Shown { @@ -197,8 +207,8 @@ impl SnapSession { let SnapView { document, document_id, input } = view; // Held quiet, nothing is offered, so the scene can wait to be brought up to date - let quiet = !document.snapping_state.snapping_enabled || input.keyboard.key(Key::KeyQ); - if quiet { + let silenced = !document.snapping_state.snapping_enabled || input.keyboard.key(Key::KeyQ); + if silenced { self.follow_document(document_id); } else { self.bring_up_to_date(document, document_id); @@ -229,14 +239,9 @@ impl SnapSession { // A box is taken where the pointer asks for it, once any track it must stay on has had its say let asked = options.required.map_or(free, |track| track.nearest(free)); let kind = self.gesture.as_ref().map_or(LayerKind::Artwork, |gesture| gesture.kind); - let spaced = options.box_features.filter(|_| !quiet).and_then(|box_features| spaced_box(kind, &box_features, features, asked)); + let spaced = options.box_features.filter(|_| !silenced).and_then(|box_features| spaced_box(kind, &box_features, features, asked)); let awake = self.awake_around(spaced.as_ref()); - - // Nothing snaps until the pointer has moved past the drag threshold from where the gesture began - let within_threshold = self.gesture.as_mut().is_some_and(|gesture| { - gesture.dragged |= input.mouse.position.distance(gesture.pressed) > DRAG_THRESHOLD; - !gesture.dragged - }); + let (quiet, cycle) = self.steering(view); let (frame, tunables, nothing_moving) = (Frame::default(), Tunables::default(), Exclusions::default()); @@ -289,17 +294,12 @@ impl SnapSession { let probed: Option> = options.snapping.map(|count| (0..count.min(features.len()) as u32).collect()); - // A tap of the cycling key counts once, however long the key is held down - let cycle_key_held = input.keyboard.key(Key::KeyW); - let cycle = usize::from(cycle_key_held && !self.cycle_key_was_held); - self.cycle_key_was_held = cycle_key_held; - let request = Request { grid: grid.as_ref(), required: options.required, incumbent: self.incumbent, cycle, - quiet: quiet || within_threshold, + quiet, constructions: self.constructions.as_ref().map_or(&[], |(_, constructions)| constructions.as_slice()), lead_constructions: &self.constructions_from_previous, crossings: Some(&self.crossings), @@ -308,8 +308,8 @@ impl SnapSession { }; let outcome = snapping::snap_features(&context, &request, features, lead, free, options.previous); - // Until then, what a press landed somewhere stays there - let held = self.gesture.as_ref().and_then(|gesture| gesture.held).filter(|_| within_threshold); + // Until the pointer has moved past the drag threshold, what a press landed somewhere stays there + let held = self.gesture.as_ref().filter(|gesture| !gesture.dragged).and_then(|gesture| gesture.held); let held_parameters = held.and_then(|held| features.get(lead)?.parameters_for(held)).filter(|parameters| parameters.is_finite()); self.holding_press = held_parameters.is_some(); @@ -341,6 +341,67 @@ impl SnapSession { parameters } + /// Snaps one value that a gizmo's handle sets, such as an angle or a radius, and returns the value it lands on. + /// + /// The snap is shown where `position_of` puts the handle, in document space, for the value landed on. Reach is judged by `on_screen_per_unit`, how many viewport pixels the handle moves per unit of the value. + pub fn snap_value(&mut self, view: SnapView, position_of: impl Fn(f64) -> DVec2, free: f64, on_screen_per_unit: f64, candidates: &[ValueCandidate]) -> f64 { + // A value has no features in document space, which an empty list stands for + if !self.features.is_empty() { + self.features.clear(); + self.incumbent = None; + self.crossings.clear(); + } + + let (quiet, cycle) = self.steering(view); + let Some(view_mapping) = ViewMapping::from_affine(DAffine2::from_scale(DVec2::splat(on_screen_per_unit))) else { + self.forget(); + return free; + }; + + // The value is solved as a position along a line, with each candidate a spot on it and nothing else in the scene + let particular: Vec = candidates + .iter() + .map(|candidate| { + let key = CandidateKey { + kind: candidate.kind, + feature: 0, + identity: [candidate.identity, 0, 0], + }; + Candidate::spot(key, DVec2::new(candidate.value, 0.)) + }) + .collect(); + + let (scene, frame, tunables, settings, exclusions) = (Scene::new(), Frame::default(), Tunables::default(), Settings::default(), Exclusions::default()); + let context = Context { + scene: &scene, + view: &view_mapping, + frame: &frame, + tunables: &tunables, + settings: &settings, + exclusions: &exclusions, + awake: &[], + }; + let request = Request { + required: Locus::line(DVec2::ZERO, DVec2::X), + incumbent: self.incumbent, + cycle, + quiet, + particular: &particular, + ..Default::default() + }; + let outcome = snapping::snap_point(&context, &request, DVec2::new(free, 0.), None); + + self.incumbent = outcome.incumbent(); + let snapped = outcome.parameters.x; + self.shown = Some(Shown { + features: vec![position_of(snapped)], + lead: 0, + outcome, + }); + + snapped + } + /// Starts a gesture, which goes on snapping to the scene as it is now and to none of what it moves. /// /// What the pointer was snapped to on the approach is let go, so a press should take what was shown before starting the gesture. @@ -534,6 +595,25 @@ impl SnapSession { &self.awake } + /// Whether this attempt is quiet, as with the master switch off, Q held, or the pointer not yet past the drag threshold, and how many candidates W steps on by. + fn steering(&mut self, view: SnapView) -> (bool, usize) { + let SnapView { document, input, .. } = view; + + // Nothing snaps until the pointer has moved past the drag threshold from where the gesture began + let within_threshold = self.gesture.as_mut().is_some_and(|gesture| { + gesture.dragged |= input.mouse.position.distance(gesture.pressed) > DRAG_THRESHOLD; + !gesture.dragged + }); + + // A tap of the cycling key counts once, however long the key is held down + let cycle_key_held = input.keyboard.key(Key::KeyW); + let cycle = usize::from(cycle_key_held && !self.cycle_key_was_held); + self.cycle_key_was_held = cycle_key_held; + + let quiet = !document.snapping_state.snapping_enabled || input.keyboard.key(Key::KeyQ) || within_threshold; + (quiet, cycle) + } + /// The woken targets, joined while a box is moved by the nearest of the boxes sharing its parent, by any such box the snap is relying on, and by its artboard. fn awake_around(&mut self, spaced: Option<&SpacedBox>) -> Vec { let mut awake = self.awake.clone(); @@ -581,9 +661,9 @@ impl SnapSession { // A midpoint, or a place where paths cross, is a point of its own rather than the curves it was found on let engaged: Vec<&Candidate> = shown.outcome.engaged_candidates().collect(); - let on_a_path = |candidate: &&Candidate| matches!(candidate.key.kind, snapping::Kind::OnCurve | snapping::Kind::OnBoxEdge | snapping::Kind::OnArtboardEdge); + let on_a_path = |candidate: &&Candidate| matches!(candidate.key.kind, Kind::OnCurve | Kind::OnBoxEdge | Kind::OnArtboardEdge); let point_of_its_own = match engaged.as_slice() { - [midpoint] => midpoint.key.kind == snapping::Kind::Midpoint, + [midpoint] => midpoint.key.kind == Kind::Midpoint, [first, second] => first.key.feature == second.key.feature && on_a_path(first) && on_a_path(second), _ => false, }; @@ -1720,4 +1800,76 @@ mod tests { } } } + + /// Angles in degrees a gizmo might offer. + const ANGLES: [ValueCandidate; 2] = [ + ValueCandidate { + value: 90., + kind: Kind::RightAngle, + identity: 90, + }, + ValueCandidate { + value: 135., + kind: Kind::AngleStep, + identity: 135, + }, + ]; + + /// Where the handle of the gizmo snapping its angle sits for an angle, in document space. + fn handle_at(angle: f64) -> DVec2 { + DVec2::new(10., 20.) + DVec2::from_angle(angle.to_radians()) * 50. + } + + fn snap_angle(session: &mut SnapSession, document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, free: f64, on_screen_per_degree: f64) -> f64 { + session.snap_value(SnapView::new(document, DOCUMENT, input), handle_at, free, on_screen_per_degree, &ANGLES) + } + + #[test] + fn a_value_lands_on_a_candidate_within_reach_on_screen_and_stays_where_it_is_asked_for_beyond_it() { + let (document, input) = (DocumentMessageHandler::default(), InputPreprocessorMessageHandler::default()); + let mut session = SnapSession::default(); + + // Three degrees short of a right angle is six pixels at two pixels a degree, which is within reach, and the snap is shown where the handle lands + assert_eq!(snap_angle(&mut session, &document, &input, 87., 2.), 90.); + assert_eq!(engaged_kinds(&session), vec![Kind::RightAngle]); + assert_eq!(session.shown_position(), Some(handle_at(90.))); + + // At four pixels a degree the same three degrees are twelve pixels, which is beyond reach + session.forget(); + assert_eq!(snap_angle(&mut session, &document, &input, 87., 4.), 87.); + assert!(!session.caught()); + } + + #[test] + fn holding_q_or_turning_snapping_off_leaves_a_value_where_it_is_asked_for() { + let mut document = DocumentMessageHandler::default(); + let mut input = InputPreprocessorMessageHandler::default(); + let mut session = SnapSession::default(); + + input.keyboard.set(Key::KeyQ as usize); + assert_eq!(snap_angle(&mut session, &document, &input, 88., 2.), 88.); + assert!(!session.caught()); + + input.keyboard.unset(Key::KeyQ as usize); + document.snapping_state.snapping_enabled = false; + assert_eq!(snap_angle(&mut session, &document, &input, 88., 2.), 88.); + assert!(!session.caught()); + + document.snapping_state.snapping_enabled = true; + assert_eq!(snap_angle(&mut session, &document, &input, 88., 2.), 90.); + } + + #[test] + fn an_engaged_value_holds_beyond_the_reach_until_the_release_distance() { + let (document, input) = (DocumentMessageHandler::default(), InputPreprocessorMessageHandler::default()); + let mut session = SnapSession::default(); + + // At two pixels a degree, five degrees away is ten pixels, past the reach of eight but short of the release at twelve + assert_eq!(snap_angle(&mut session, &document, &input, 89.5, 2.), 90.); + assert_eq!(snap_angle(&mut session, &document, &input, 85., 2.), 90.); + + // Seven degrees away is fourteen pixels, where it lets go, and coming back to ten pixels does not catch it again + assert_eq!(snap_angle(&mut session, &document, &input, 83., 2.), 83.); + assert_eq!(snap_angle(&mut session, &document, &input, 85., 2.), 85.); + } } diff --git a/editor/src/messages/tool/common_functionality/snap_session/presenter.rs b/editor/src/messages/tool/common_functionality/snap_session/presenter.rs index fae320e04e..a16b4eb8af 100644 --- a/editor/src/messages/tool/common_functionality/snap_session/presenter.rs +++ b/editor/src/messages/tool/common_functionality/snap_session/presenter.rs @@ -185,6 +185,8 @@ fn name(kind: Kind) -> &'static str { Kind::AngleStep => "Angle", Kind::Spacing => "Evenly Spaced", Kind::EqualSize => "Equal Size", + Kind::EqualRadius => "Equal Radius", + Kind::WholeValue => "Whole Number", } } @@ -200,6 +202,8 @@ mod tests { assert_eq!(label(&[Kind::Extension, Kind::Extension]), "Extension"); assert_eq!(label(&[Kind::OnCurve, Kind::Alignment]), "On Path and Aligned"); assert_eq!(label(&[Kind::TangentLine, Kind::Extension]), "Tangent and Extension"); + assert_eq!(label(&[Kind::EqualRadius]), "Equal Radius"); + assert_eq!(label(&[Kind::WholeValue]), "Whole Number"); } #[test] diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index 482a1331aa..542a775ad4 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -583,6 +583,7 @@ impl<'a> MessageHandler> for Shap | ShapeToolFsmState::RotatingBounds | ShapeToolFsmState::SkewingBounds { .. } | ShapeToolFsmState::DraggingLineEndpoints + | ShapeToolFsmState::ModifyingGizmo ); if in_gesture && self.fsm_state != previous_state { if let Some(bounds) = &mut self.tool_data.bounding_box_manager { @@ -1052,6 +1053,7 @@ impl Fsm for ShapeToolFsmState { if tool_data.gizmo_manager.handle_click() && !input.keyboard.key(Key::Accel) { tool_data.data.drag_start = document.metadata().document_to_viewport.inverse().transform_point2(mouse_pos); + snap_session.begin_gesture(SnapView::new(document, *document_id, input), Moving::default()); responses.add(DocumentMessage::StartTransaction); let cursor = tool_data.gizmo_manager.mouse_cursor_icon().unwrap_or(MouseCursorIcon::Crosshair); @@ -1253,7 +1255,8 @@ impl Fsm for ShapeToolFsmState { self } (ShapeToolFsmState::ModifyingGizmo, ShapeToolMessage::PointerMove { .. }) => { - tool_data.gizmo_manager.handle_update(tool_data.data.viewport_drag_start(document), document, input, responses); + let drag_start = tool_data.data.viewport_drag_start(document); + tool_data.gizmo_manager.handle_update(drag_start, SnapView::new(document, *document_id, input), snap_session, responses); responses.add(OverlaysMessage::Draw); @@ -1574,7 +1577,10 @@ fn update_dynamic_hints(state: &ShapeToolFsmState, responses: &mut VecDeque HintData(vec![HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()])]), + ShapeToolFsmState::ModifyingGizmo => HintData(vec![ + HintGroup(vec![HintInfo::mouse(MouseMotion::Rmb, ""), HintInfo::keys([Key::Escape], "Cancel").prepend_slash()]), + snapping_hints(), + ]), }; hint_data.send_layout(responses); } @@ -1584,9 +1590,22 @@ mod test_shape_tool { use super::ShapeOptionsUpdate; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::misc::{GridSnapping, GridType}; - use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeType, regular_polygon_points}; + use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; + use crate::messages::tool::common_functionality::graph_modification_utils::get_arc_id; + use crate::messages::tool::common_functionality::shapes::shape_utility::{ + ShapeType, arc_end_points, extract_arc_parameters, extract_circle_radius, extract_spiral_parameters, extract_star_parameters, regular_polygon_points, star_vertex_position, + }; + use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate_spiral_endpoints; + use crate::messages::tool::common_functionality::snap_session::Kind; use crate::test_utils::test_prelude::*; + use glam::DAffine2; + use graph_craft::document::NodeInput; + use graph_craft::document::value::TaggedValue; + use graphene_std::vector::algorithms::shapes::calculate_growth_factor; + use graphene_std::vector::generator_nodes::arc; + use graphene_std::vector::misc::SpiralType; use kurbo::PathEl; + use std::f64::consts::{PI, TAU}; /// The anchors a layer draws, in document space, counting the one a closed path returns to only once. fn drawn_anchors(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Vec { @@ -1814,4 +1833,334 @@ mod test_shape_tool { assert_bounds(&editor, layer, [DVec2::new(300., 300.), DVec2::new(480., 380.)]); } + + /// Draws a shape between two viewport positions, and returns its layer. + async fn draw_shape(editor: &mut EditorTestUtils, shape: ShapeType, from: DVec2, to: DVec2) -> LayerNodeIdentifier { + press_drawing(editor, shape, from, ModifierKeys::empty()).await; + editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await; + editor.get_selected_layer().await.expect("the shape drawn should be selected") + } + + /// Takes hold of a gizmo's handle at a viewport position, once drawing the overlays has found it under the pointer, and drags it along a path without letting go. + async fn drag_gizmo_handle(editor: &mut EditorTestUtils, handle: DVec2, path: &[DVec2]) { + editor.move_mouse(handle.x, handle.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + editor.left_mousedown(handle.x, handle.y, ModifierKeys::empty()).await; + for position in path { + editor.move_mouse(position.x, position.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + } + } + + fn engaged_kinds(editor: &EditorTestUtils) -> Vec { + let session = &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session; + let shown = session.shown().expect("the gizmo should have tried to snap"); + shown.outcome.engaged_candidates().map(|candidate| candidate.key.kind).collect() + } + + #[tokio::test] + async fn an_arc_with_its_end_dragged_to_a_few_degrees_from_a_right_angle_sweeps_a_right_angle() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + + // The end of the arc, which sweeps 270° from its start, is carried around the center by way of 180° to 93° + let document = editor.active_document(); + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + let center = document.metadata().transform_to_viewport(layer).transform_point2(DVec2::ZERO); + let at_sweep = |degrees: f64| center + DVec2::from_angle(degrees.to_radians()) * end.distance(center); + drag_gizmo_handle(&mut editor, end, &[at_sweep(180.), at_sweep(93.)]).await; + + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), editor.active_document()).expect("the arc should have its parameters"); + assert!((sweep - 90.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::RightAngle]); + + editor.left_mouseup(at_sweep(93.).x, at_sweep(93.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_star_with_its_inner_radius_dragged_near_the_one_giving_right_angled_tips_lands_on_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Star, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + + let document = editor.active_document(); + let (sides, outer_radius, inner_radius) = extract_star_parameters(Some(layer), document).expect("the star should have its parameters"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let handle = star_vertex_position(to_viewport, 1, sides, outer_radius, inner_radius); + + // A tip is right-angled where the inner vertices on either side lie at right angles from it, which takes this inner radius + let half_point = PI / sides as f64; + let right_angled = outer_radius / (half_point.sin() + half_point.cos()); + + // The inner vertex is drawn out along its spoke to a radius one and a half short of that + let spoke = star_vertex_position(DAffine2::IDENTITY, 1, sides, 1., 1.); + let pointer = to_viewport.transform_point2(spoke * (right_angled - 1.5)); + drag_gizmo_handle(&mut editor, handle, &[pointer]).await; + + let (_, _, dragged) = extract_star_parameters(Some(layer), editor.active_document()).expect("the star should have its parameters"); + assert!((dragged - right_angled).abs() < 1e-9, "the inner radius is {dragged} rather than {right_angled}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::RightAngle]); + + editor.left_mouseup(pointer.x, pointer.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_circle_with_its_radius_dragged_near_that_of_another_circle_comes_to_the_same_radius() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let other = draw_shape(&mut editor, ShapeType::Circle, DVec2::new(100., 100.), DVec2::new(180., 180.)).await; + let layer = draw_shape(&mut editor, ShapeType::Circle, DVec2::new(300., 300.), DVec2::new(360., 360.)).await; + + // The rim of the smaller circle is taken hold of on its right and drawn out to one and a half short of the other's radius + let document = editor.active_document(); + let radius_of = |layer: LayerNodeIdentifier, document: &DocumentMessageHandler| extract_circle_radius(layer, document).expect("the circle should have a radius"); + let (radius, other_radius) = (radius_of(layer, document), radius_of(other, document)); + let to_viewport = document.metadata().transform_to_viewport(layer); + let (rim, pointer) = (to_viewport.transform_point2(DVec2::X * radius), to_viewport.transform_point2(DVec2::X * (other_radius - 1.5))); + drag_gizmo_handle(&mut editor, rim, &[pointer]).await; + + let dragged = radius_of(layer, editor.active_document()); + assert!((dragged - other_radius).abs() < 1e-9, "the radius is {dragged} rather than {other_radius}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::EqualRadius]); + + editor.left_mouseup(pointer.x, pointer.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_spiral_with_its_end_turned_to_just_short_of_a_whole_number_of_turns_lands_on_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + + let document = editor.active_document(); + let turns_of = |document: &DocumentMessageHandler| extract_spiral_parameters(layer, document).expect("the spiral should have its parameters").4; + let turns = turns_of(document); + let whole = turns.floor() + 1.; + let to_viewport = document.metadata().transform_to_viewport(layer); + let end = calculate_spiral_endpoints(layer, document, to_viewport, TAU).expect("the spiral should have an end"); + let center = to_viewport.transform_point2(DVec2::ZERO); + + // The end is carried around the center in four steps to a hundredth of a turn short of the next whole number of turns + let step = (whole - 0.01 - turns) * 360. / 4.; + let path: Vec = (1..=4).map(|i| center + DVec2::from_angle(-(step * i as f64).to_radians()).rotate(end - center)).collect(); + drag_gizmo_handle(&mut editor, end, &path).await; + + let dragged = turns_of(editor.active_document()); + assert!((dragged - whole).abs() < 1e-9, "the spiral has {dragged} turns rather than {whole}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::WholeValue]); + + let last = path.last().copied().unwrap_or(end); + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + /// Takes hold of a spiral's start and draws the pointer out to 100 pixels from the center, then around it by a number of turns, which the start takes away. + /// Returns where the pointer ends up, still pressed. + async fn turn_spiral_start(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, turns_taken_away: f64) -> DVec2 { + let document = editor.active_document(); + let to_viewport = document.metadata().transform_to_viewport(layer); + let start = calculate_spiral_endpoints(layer, document, to_viewport, 0.).expect("the spiral should have a start"); + let center = to_viewport.transform_point2(DVec2::ZERO); + let out = center + (start - center).normalize_or(DVec2::X) * 100.; + + let step = turns_taken_away * 360. / 4.; + let mut path = vec![out]; + path.extend((1..=4).map(|i| center + DVec2::from_angle(-(step * i as f64).to_radians()).rotate(out - center))); + drag_gizmo_handle(editor, start, &path).await; + + path.last().copied().unwrap_or(out) + } + + #[tokio::test] + async fn a_spiral_with_its_start_turned_well_short_of_a_half_turn_keeps_the_turns_it_was_turned_to() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + let turns_of = |document: &DocumentMessageHandler| extract_spiral_parameters(layer, document).expect("the spiral should have its parameters").4; + let turns = turns_of(editor.active_document()); + + // A fifth of a turn from the nearest half turn is far beyond reach for a pointer circling 100 pixels out + let free = turns.floor() - 0.3; + let last = turn_spiral_start(&mut editor, layer, turns - free).await; + + let dragged = turns_of(editor.active_document()); + assert!((dragged - free).abs() < 1e-6, "the spiral has {dragged} turns rather than {free}"); + assert!(engaged_kinds(&editor).is_empty()); + + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_spiral_with_its_start_turned_to_just_past_a_whole_number_of_turns_lands_on_it_and_marks_the_start_where_it_went() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + let turns_of = |document: &DocumentMessageHandler| extract_spiral_parameters(layer, document).expect("the spiral should have its parameters").4; + let turns = turns_of(editor.active_document()); + + let whole = turns.ceil() - 1.; + let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await; + + let document = editor.active_document(); + let dragged = turns_of(document); + assert!((dragged - whole).abs() < 1e-9, "the spiral has {dragged} turns rather than {whole}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::WholeValue]); + + let to_viewport = document.metadata().transform_to_viewport(layer); + let start = calculate_spiral_endpoints(layer, document, to_viewport, 0.).expect("the spiral should have a start"); + let session = &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session; + let marked = document.metadata().document_to_viewport.transform_point2(session.shown_position().expect("the snap should be shown")); + assert!(marked.distance(start) < 1e-6, "the snap is marked at {marked} rather than at the start, {start}"); + + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn on_a_flipped_canvas_an_arc_end_dragged_near_a_half_turn_sweeps_one_and_is_marked_where_it_went() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + editor.handle_message(NavigationMessage::CanvasFlip).await; + + // The end is carried around the arc in its own space, which the flip mirrors on screen + let document = editor.active_document(); + let (radius, start_angle, _, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let at_sweep = |degrees: f64| to_viewport.transform_point2(DVec2::from_angle((start_angle + degrees).to_radians()) * radius); + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + drag_gizmo_handle(&mut editor, end, &[at_sweep(225.), at_sweep(183.)]).await; + + // A half turn is no right angle + let document = editor.active_document(); + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + assert!((sweep - 180.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::AngleStep]); + + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + let session = &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session; + let marked = document.metadata().document_to_viewport.transform_point2(session.shown_position().expect("the snap should be shown")); + assert!(marked.distance(end) < 1e-6, "the snap is marked at {marked} rather than at the end, {end}"); + + editor.left_mouseup(at_sweep(183.).x, at_sweep(183.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_circle_with_its_radius_dragged_near_the_rim_of_a_stretched_arc_meets_that_rim_in_the_direction_it_is_pulled() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + // Drawn twice as wide as it is tall, the arc reaches twice as far from its center across as it does up and down + let arc = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(100., 100.), DVec2::new(300., 200.)).await; + + // With the arc left selected, the Shape tool would go on drawing arcs + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + let layer = draw_shape(&mut editor, ShapeType::Circle, DVec2::new(400., 400.), DVec2::new(460., 460.)).await; + + let document = editor.active_document(); + let (arc_radius, ..) = extract_arc_parameters(Some(arc), document).expect("the arc should have its parameters"); + let arc_to_document = document.metadata().transform_to_document(arc); + let arc_rim = arc_to_document.transform_vector2(DVec2::X * arc_radius).length(); + + // The circle's rim is taken hold of on its right and drawn out to one and a half short of how far the arc reaches across + let radius = extract_circle_radius(layer, document).expect("the circle should have a radius"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let (rim, pointer) = (to_viewport.transform_point2(DVec2::X * radius), to_viewport.transform_point2(DVec2::X * (arc_rim - 1.5))); + drag_gizmo_handle(&mut editor, rim, &[pointer]).await; + + let dragged = extract_circle_radius(layer, editor.active_document()).expect("the circle should have a radius"); + assert!((dragged - arc_rim).abs() < 1e-9, "the radius is {dragged} rather than {arc_rim}"); + assert_eq!(engaged_kinds(&editor), vec![Kind::EqualRadius]); + + editor.left_mouseup(pointer.x, pointer.y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_stretched_arc_with_its_end_dragged_a_few_degrees_from_a_half_turn_where_it_crosses_the_screen_slowest_sweeps_one() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(500., 400.)).await; + + let document = editor.active_document(); + let (radius, start_angle, _, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let at_sweep = |degrees: f64| to_viewport.transform_point2(DVec2::from_angle((start_angle + degrees).to_radians()) * radius); + let (_, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + + // Seven degrees short of a half turn, the end lies a hundred pixels from the center but only six pixels from where a half turn takes it + drag_gizmo_handle(&mut editor, end, &[at_sweep(200.), at_sweep(173.)]).await; + + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), editor.active_document()).expect("the arc should have its parameters"); + assert!((sweep - 180.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::AngleStep]); + + editor.left_mouseup(at_sweep(173.).x, at_sweep(173.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn an_arc_with_its_start_dragged_to_just_inside_a_larger_snap_angle_grows_to_it_and_keeps_its_far_end() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_shape(&mut editor, ShapeType::Arc, DVec2::new(300., 300.), DVec2::new(400., 400.)).await; + + // The arc sweeps two degrees short of a three-quarter turn + let node_id = get_arc_id(layer, &editor.active_document().network_interface).expect("the arc should have its node"); + editor + .handle_message(NodeGraphMessage::SetInput { + input_connector: InputConnector::node(node_id, arc::SweepAngleInput), + input: NodeInput::value(TaggedValue::Number(268.), false), + }) + .await; + editor.handle_message(NodeGraphMessage::RunDocumentGraph).await; + + let document = editor.active_document(); + let (radius, start_angle, _, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + let (start, end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + let to_viewport = document.metadata().transform_to_viewport(layer); + let at_angle = |degrees: f64| to_viewport.transform_point2(DVec2::from_angle((start_angle + degrees).to_radians()) * radius); + + // The start is carried along the arc and back to two degrees on, which shrinks the sweep to four short of the three-quarter turn + drag_gizmo_handle(&mut editor, start, &[at_angle(30.), at_angle(2.)]).await; + + let document = editor.active_document(); + let (_, _, sweep, _) = extract_arc_parameters(Some(layer), document).expect("the arc should have its parameters"); + assert!((sweep - 270.).abs() < 1e-9, "the arc sweeps {sweep}°"); + assert_eq!(engaged_kinds(&editor), vec![Kind::RightAngle]); + + let (_, dragged_end) = arc_end_points(Some(layer), document).expect("the arc should have two ends"); + assert!(dragged_end.distance(end) < 1e-6, "the far end moved from {end} to {dragged_end}"); + + editor.left_mouseup(at_angle(2.).x, at_angle(2.).y, ModifierKeys::empty()).await; + } + + #[tokio::test] + async fn a_logarithmic_spiral_with_a_turn_taken_off_its_start_winds_as_tightly_as_before() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Shape).await; + editor + .handle_message(ShapeToolMessage::UpdateOptions { + options: ShapeOptionsUpdate::SpiralType(SpiralType::Logarithmic), + }) + .await; + let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await; + + let turns_and_growth_factor_of = |document: &DocumentMessageHandler| { + let (spiral_type, _, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document).expect("the spiral should have its parameters"); + (turns, calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type)) + }; + let (turns, growth_factor) = turns_and_growth_factor_of(editor.active_document()); + + // The start lands on a whole turn fewer, and the outer radius shrinks so the spiral keeps winding as it did + let whole = turns.ceil() - 1.; + let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await; + + let (dragged, dragged_growth_factor) = turns_and_growth_factor_of(editor.active_document()); + assert!((dragged - whole).abs() < 1e-9, "the spiral has {dragged} turns rather than {whole}"); + assert!( + (dragged_growth_factor - growth_factor).abs() < 1e-9, + "the growth factor is {dragged_growth_factor} rather than {growth_factor}" + ); + + editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; + } } diff --git a/libraries/snapping/src/candidate.rs b/libraries/snapping/src/candidate.rs index 9f354faeb9..b8b0c49cda 100644 --- a/libraries/snapping/src/candidate.rs +++ b/libraries/snapping/src/candidate.rs @@ -30,6 +30,8 @@ pub enum Kind { AngleStep, Spacing, EqualSize, + EqualRadius, + WholeValue, } /// Identifies a candidate from one moment to the next, so an engaged snap can be recognized again after the pointer moves. From 1829e1b80a07f0271a0acb828461d632239c33a1 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Wed, 14 Oct 2026 09:50:58 -0700 Subject: [PATCH 02/47] Fix the Inspector crashing on 'Text' and 'QR Code' nodes from a recursivenode metadata lock (#4706) Fix the Inspector crashing on Text and QR Code nodes from a recursive node metadata lock Fixes #4705 --- .../node_graph/document_node_definitions.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 437e329de7..dd68588034 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -1001,14 +1001,13 @@ fn static_input_inspector() -> InputInspector { // The custom number input settings are only available on proto nodes "optional_f64".to_string(), Box::new(|node_id, index, context| { - let node_metadata = registry::NODE_METADATA.lock().unwrap(); let mut number_input = NumberInput::default(); + // The field is cloned so the lock is released before building the row below, which locks the node metadata again if let Some(field) = context .network_interface .implementation(&node_id, context.selection_network_path) .and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None }) - .and_then(|proto_node_identifier| node_metadata.get(proto_node_identifier)) - .and_then(|metadata| metadata.fields.get(index)) + .and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned()) { if let Some(unit) = field.unit { number_input = number_input.unit(unit); @@ -1722,6 +1721,19 @@ mod test { .await; editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await; } + + // Guards the `optional_f64` widget override against holding the node metadata lock while building rows that lock it again + #[tokio::test] + async fn optional_f64_inspector_row_builds() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let node_id = editor + .create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::qr_code::IDENTIFIER)) + .await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }).await; + editor.handle_message(InspectorMessage::Refresh).await; + } } #[cfg(test)] From 53dcdc194a5ddb36f3de865501af2a4e26657f21 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:29:31 +0000 Subject: [PATCH 03/47] Fix arrow-key node moves in the node graph merging into the previous undo step (#4709) --- .../messages/input_mapper/input_mappings.rs | 8 +++---- .../document/node_graph/node_graph_message.rs | 4 ++++ .../node_graph/node_graph_message_handler.rs | 7 ++++++- .../characterization_tests.rs | 21 +++++++++++++++++++ 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/editor/src/messages/input_mapper/input_mappings.rs b/editor/src/messages/input_mapper/input_mappings.rs index 2bdb1eb6eb..3765b0ed8f 100644 --- a/editor/src/messages/input_mapper/input_mappings.rs +++ b/editor/src/messages/input_mapper/input_mappings.rs @@ -89,10 +89,10 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping { entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets), entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes), entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets), - entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Up, rubber_band: false }), - entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Right, rubber_band: false }), - entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down, rubber_band: false }), - entry!(KeyDown(ArrowLeft); action_dispatch=NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Left, rubber_band: false }), + entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }), + entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }), + entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }), + entry!(KeyDown(ArrowLeft); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Left }), // // TransformLayerMessage entry!(KeyDown(Enter); action_dispatch=TransformLayerMessage::ApplyTransformOperation { final_transform: true }), diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs index c418323ec1..60d26bfb0f 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs @@ -227,6 +227,10 @@ pub enum NodeGraphMessage { x: i32, y: i32, }, + /// Moves the selected nodes one grid cell with the arrow keys, as an undo step of its own. + NudgeSelectedNodes { + direction: Direction, + }, ShiftSelectedNodes { direction: Direction, rubber_band: bool, diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index 9da6c7da2f..8a0db8caec 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -2038,6 +2038,11 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::SetInput { input_connector, input } => { network_interface.set_input(&input_connector, input, selection_network_path); } + NodeGraphMessage::NudgeSelectedNodes { direction } => { + responses.add(DocumentMessage::StartTransaction); + responses.add(NodeGraphMessage::ShiftSelectedNodes { direction, rubber_band: false }); + responses.add(DocumentMessage::EndTransaction); + } NodeGraphMessage::ShiftSelectedNodes { direction, rubber_band } => { network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path); @@ -2701,7 +2706,7 @@ impl NodeGraphMessageHandler { ToggleSelectedAsLayersOrNodes, ToggleSelectedLocked, ToggleSelectedVisibility, - ShiftSelectedNodes, + NudgeSelectedNodes, )); } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs index 2a6588aa80..3ca256aa03 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs @@ -948,6 +948,27 @@ async fn drag_offsets_do_not_outlive_programmatic_shifts() { assert_invariants(&editor, "after stack pushes, a delete collapse, and a nudge"); } +#[tokio::test] +async fn each_arrow_key_nudge_is_its_own_undo_step() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + + let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await; + let start = editor.active_document().network_interface.position(&node, &[]).expect("The node should have a position"); + + editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; + editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await; + + // Undoing takes back only the last nudge, not the node's creation before them + editor.handle_message(DocumentMessage::Undo).await; + let network_interface = &editor.active_document().network_interface; + let position = network_interface.position(&node, &[]).expect("Undo should keep the node created before the nudges"); + assert_eq!(position.x - start.x, 1, "Undo should take back only the last nudge"); + + assert_invariants(&editor, "after nudging and undoing"); +} + #[tokio::test] async fn signature_edits_keep_parallel_metadata_in_sync() { let mut editor = EditorTestUtils::create(); From e0936929da7fb063bd62e59882397b70f99208bf Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:29:36 +0000 Subject: [PATCH 04/47] Fix keys typed in text fields also triggering editor shortcuts (#4713) --- frontend/src/components/panels/Layers.svelte | 5 +++-- frontend/src/components/views/Graph.svelte | 3 +-- .../src/components/widgets/inputs/MathExpressionInput.svelte | 2 +- frontend/src/components/widgets/inputs/SliderInput.svelte | 2 ++ frontend/src/utility-functions/input.ts | 5 +++-- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/frontend/src/components/panels/Layers.svelte b/frontend/src/components/panels/Layers.svelte index b8488e1c8a..3cd6945754 100644 --- a/frontend/src/components/panels/Layers.svelte +++ b/frontend/src/components/panels/Layers.svelte @@ -11,6 +11,7 @@ import type { PortfolioStore } from "/src/stores/portfolio"; import type { TooltipStore } from "/src/stores/tooltip"; import { pasteFile } from "/src/utility-functions/files"; + import { targetIsTextField } from "/src/utility-functions/input"; import { operatingSystem } from "/src/utility-functions/platform"; import type { EditorWrapper, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry, LayerStructureEntry } from "/wrapper/pkg/graphite_wasm_wrapper"; @@ -814,8 +815,8 @@ function handleLayerPanelKeyDown(e: KeyboardEvent) { // TODO: Handle this F2 shortcut detection in the backend, not frontend, so it uses the standard key binding system - // Only handle F2 if not currently editing a layer name - if (e.key === "F2" && !layers.some((layer) => layer.editingName)) { + // Only handle F2 if not currently editing a layer name or typing in another text field + if (e.key === "F2" && !layers.some((layer) => layer.editingName) && !targetIsTextField(e.target || undefined)) { // Find the first selected layer const selectedLayer = layers.find((layer) => layer.entry.selected); if (selectedLayer) { diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index 1bc6733c6e..1706d9c98f 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -63,8 +63,7 @@ else editor.setExportName(target.index, editingNameText); } - // The name fields stop propagation of the keys they handle so the global keyboard forwarder (`shouldRedirectKeyboardEventToBackend`) doesn't also dispatch them. - // Its Escape carve-out would otherwise close the graph view, and Enter could trigger unrelated bindings. + // The name fields stop propagation of the keys they handle so no window listener also acts on them function onNameInputKeyDown(e: KeyboardEvent) { if (e.key === "Enter") commitEditingName(); else if (e.key === "Escape") editingName = undefined; diff --git a/frontend/src/components/widgets/inputs/MathExpressionInput.svelte b/frontend/src/components/widgets/inputs/MathExpressionInput.svelte index 983de162c8..e80291df1a 100644 --- a/frontend/src/components/widgets/inputs/MathExpressionInput.svelte +++ b/frontend/src/components/widgets/inputs/MathExpressionInput.svelte @@ -938,7 +938,7 @@ const asksForCompletions = (e.ctrlKey && e.key === " ") || (operatingSystem() === "Mac" && e.altKey && e.key === "Escape"); if (asksForCompletions) { e.preventDefault(); - // The editor's shortcuts hear Escape even from a text field + // A parent floating menu mustn't also close e.stopPropagation(); suggest(); } else if (e.key === "Tab") { diff --git a/frontend/src/components/widgets/inputs/SliderInput.svelte b/frontend/src/components/widgets/inputs/SliderInput.svelte index a171f3421b..150e7279d6 100644 --- a/frontend/src/components/widgets/inputs/SliderInput.svelte +++ b/frontend/src/components/widgets/inputs/SliderInput.svelte @@ -3,6 +3,7 @@ import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte"; import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import LayoutRow from "/src/components/layout/LayoutRow.svelte"; + import { targetIsTextField } from "/src/utility-functions/input"; import type { GradientInterpolation, GradientSample, SliderInputUpdate, SliderMarker } from "/wrapper/pkg/graphite_wasm_wrapper"; const BUTTON_LEFT = 0; @@ -361,6 +362,7 @@ function deleteShortcut(e: KeyboardEvent) { if (disabled) return; if (e.key !== "Delete" && e.key !== "Backspace") return; + if (targetIsTextField(e.target || undefined)) return; if (activeMarkerIndex === undefined) return; stopDrag(); diff --git a/frontend/src/utility-functions/input.ts b/frontend/src/utility-functions/input.ts index f90e996d09..c743e323c3 100644 --- a/frontend/src/utility-functions/input.ts +++ b/frontend/src/utility-functions/input.ts @@ -39,8 +39,9 @@ export async function shouldRedirectKeyboardEventToBackend(e: KeyboardEvent, dia // But on web, we want to not redirect paste if (import.meta.env.MODE !== "native" && key === "KeyV" && accelKey) return false; - // Don't redirect user input from text entry into HTML elements - if (targetIsTextField(e.target || undefined) && key !== "Escape" && !(accelKey && ["Enter", "NumpadEnter"].includes(key))) return false; + // Don't redirect user input from text entry into HTML elements, except the keys that end the Text tool's editing in the backend + const endsTextToolEditing = e.target === textToolInteractiveInputElement && (key === "Escape" || (accelKey && ["Enter", "NumpadEnter"].includes(key))); + if (targetIsTextField(e.target || undefined) && !endsTextToolEditing) return false; // Don't redirect if a MenuList is open if (window.document.querySelector("[data-floating-menu-content]")) return false; From 1478a14ebb3d3f7045c4fa330411652961a88599 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:33:31 +0000 Subject: [PATCH 05/47] Fix the 'Round Corners' node flattening curves and moving short subpaths (#4720) --- node-graph/nodes/vector/src/vector_nodes.rs | 254 ++++++++++++++------ 1 file changed, 186 insertions(+), 68 deletions(-) diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index 615f4d18ba..1c43b43fc6 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -29,8 +29,8 @@ use vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt; use vector_types::vector::algorithms::offset_bezpath::offset_bezpath; use vector_types::vector::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_first_handle_open}; use vector_types::vector::misc::{ - BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, HandleId, InterpolationDistribution, ManipulatorGroup, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, - bezpath_from_manipulator_groups, bezpath_to_manipulator_groups, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles, + BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, HandleId, InterpolationDistribution, ManipulatorGroup, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, Tangent, + bezpath_from_manipulator_groups, dvec2_to_point, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles, }; use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use vector_types::vector::{PointDomain, PointId, SegmentDomain, SegmentId, VectorExt}; @@ -597,75 +597,17 @@ async fn round_corners( let mut result = Vector::default(); - // Grab the initial point ID as a stable starting point - let mut initial_point_id = source.point_domain.ids().first().copied().unwrap_or(PointId::generate()); + for bezpath in source.stroke_bezpath_iter() { + // The radius is measured after the transform, so scaling the layer doesn't scale its rounding + let mut document_bezpath = bezpath.clone(); + document_bezpath.apply_affine(Affine::new(source_transform.to_cols_array())); - for mut bezpath in source.stroke_bezpath_iter() { - bezpath.apply_affine(Affine::new(source_transform.to_cols_array())); - let (manipulator_groups, is_closed) = bezpath_to_manipulator_groups(&bezpath); - - // End if not enough points for corner rounding - if manipulator_groups.len() < 3 { + // A subpath without corners to round passes through as it was + let Some(mut rounded_subpath) = round_subpath_corners(&document_bezpath, radius, roundness, edge_length_limit, min_angle_threshold.to_radians()) else { result.append_bezpath(bezpath); continue; - } + }; - let mut new_manipulator_groups = Vec::new(); - - for i in 0..manipulator_groups.len() { - // Skip first and last points for open paths - if !is_closed && (i == 0 || i == manipulator_groups.len() - 1) { - new_manipulator_groups.push(manipulator_groups[i]); - continue; - } - - // Not the prettiest, but it makes the rest of the logic more readable - let prev_index = if i == 0 { if is_closed { manipulator_groups.len() - 1 } else { 0 } } else { i - 1 }; - let curr_index = i; - let next_index = if i == manipulator_groups.len() - 1 { if is_closed { 0 } else { i } } else { i + 1 }; - - let prev = manipulator_groups[prev_index].anchor; - let curr = manipulator_groups[curr_index].anchor; - let next = manipulator_groups[next_index].anchor; - - let dir1 = (curr - prev).normalize_or(DVec2::X); - let dir2 = (next - curr).normalize_or(DVec2::X); - - let theta = PI - dir1.angle_to(dir2).abs(); - - // Skip near-straight corners - if theta > PI - min_angle_threshold.to_radians() { - new_manipulator_groups.push(manipulator_groups[curr_index]); - continue; - } - - // Calculate L, with limits to avoid extreme values - let distance_along_edge = radius / (theta / 2.).sin(); - let distance_along_edge = distance_along_edge.min(edge_length_limit * (curr - prev).length().min((next - curr).length())).max(0.01); - - // Find points on each edge at distance L from corner - let p1 = curr - dir1 * distance_along_edge; - let p2 = curr + dir2 * distance_along_edge; - - // Add first point (coming into the rounded corner) - new_manipulator_groups.push(ManipulatorGroup { - anchor: p1, - in_handle: None, - out_handle: Some(curr - dir1 * distance_along_edge * roundness), - id: initial_point_id.next_id(), - }); - - // Add second point (coming out of the rounded corner) - new_manipulator_groups.push(ManipulatorGroup { - anchor: p2, - in_handle: Some(curr + dir2 * distance_along_edge * roundness), - out_handle: None, - id: initial_point_id.next_id(), - }); - } - - // One subpath for each shape - let mut rounded_subpath = bezpath_from_manipulator_groups(&new_manipulator_groups, is_closed); rounded_subpath.apply_affine(Affine::new(source_transform_inverse.to_cols_array())); result.append_bezpath(rounded_subpath); } @@ -674,6 +616,102 @@ async fn round_corners( }) } +/// Rounds off the anchors where a subpath's direction turns, cutting back along both segments' curves, and leaves smooth joins as they are. +/// Returns `None` when there's no corner to round. +fn round_subpath_corners(subpath: &BezPath, radius: f64, roundness: f64, edge_length_limit: f64, min_angle_threshold: f64) -> Option { + let closed = matches!(subpath.elements().last(), Some(PathEl::ClosePath)); + let segments: Vec = subpath.segments().collect(); + let count = segments.len(); + + // Anchor `i` joins segment `i - 1` to segment `i`, and a closed subpath's first anchor also ends its last segment + let anchor_count = if closed { count } else { count + 1 }; + if anchor_count < 3 { + return None; + } + let previous_segment = |anchor: usize| (anchor + count - 1) % count; + + let lengths: Vec = segments.iter().map(|segment| segment.arclen(DEFAULT_ACCURACY)).collect(); + + // How far back along both of its segments each anchor's corner is cut, or `None` where there's no corner to round + let cut_distances: Vec> = (0..anchor_count) + .map(|anchor| { + if !closed && (anchor == 0 || anchor == count) { + return None; + } + + let arriving = segments[previous_segment(anchor)].tangent_at_end().try_normalize()?; + let leaving = segments[anchor % count].tangent_at_start().try_normalize()?; + let theta = PI - arriving.angle_to(leaving).abs(); + + // Skip near-straight corners + if theta > PI - min_angle_threshold { + return None; + } + + // Calculate the distance, with limits to avoid extreme values + let distance = radius / (theta / 2.).sin(); + let shorter_length = lengths[previous_segment(anchor)].min(lengths[anchor % count]); + Some(distance.min(edge_length_limit * shorter_length).max(0.01)) + }) + .collect(); + if cut_distances.iter().all(Option::is_none) { + return None; + } + + // Trim each segment back from the corners at its ends, keeping the part between them with its curvature + let trimmed: Vec = segments + .iter() + .zip(&lengths) + .enumerate() + .map(|(index, (&segment, &length))| { + let start_cut = cut_distances[index].unwrap_or_default(); + let end_cut = cut_distances[(index + 1) % anchor_count].unwrap_or_default(); + if start_cut == 0. && end_cut == 0. { + return segment; + } + + let start_t = if start_cut > 0. { segment.inv_arclen(start_cut.min(length), DEFAULT_ACCURACY) } else { 0. }; + let end_t = if end_cut > 0. { segment.inv_arclen((length - end_cut).max(0.), DEFAULT_ACCURACY) } else { 1. }; + segment.subsegment(start_t..end_t.max(start_t)) + }) + .collect(); + + // Joins the end of the trimmed segment arriving at a corner to the start of the one leaving it + let corner_curve = |rounded: &mut BezPath, arriving: PathSeg, leaving: PathSeg, cut_distance: f64| { + let (start, end) = (point_to_dvec2(arriving.end()), point_to_dvec2(leaving.start())); + let fallback = (end - start).normalize_or_zero(); + let handle_length = cut_distance * (1. - roundness); + + let start_handle = start + arriving.tangent_at_end().try_normalize().unwrap_or(fallback) * handle_length; + let end_handle = end - leaving.tangent_at_start().try_normalize().unwrap_or(fallback) * handle_length; + rounded.curve_to(dvec2_to_point(start_handle), dvec2_to_point(end_handle), dvec2_to_point(end)); + }; + + // A closed subpath with a corner at its first anchor starts where that corner's rounding begins + let mut rounded = BezPath::new(); + let corner_at_start = cut_distances[0]; + rounded.move_to(if corner_at_start.is_some() { trimmed[count - 1].end() } else { trimmed[0].start() }); + if let Some(cut_distance) = corner_at_start { + corner_curve(&mut rounded, trimmed[count - 1], trimmed[0], cut_distance); + } + + for index in 0..count { + rounded.push(trimmed[index].as_path_el()); + + if index + 1 < count + && let Some(cut_distance) = cut_distances[index + 1] + { + corner_curve(&mut rounded, trimmed[index], trimmed[index + 1], cut_distance); + } + } + + if closed { + rounded.close_path(); + } + + Some(rounded) +} + #[node_macro::node(name("Merge by Distance"), category("Vector: Modifier"), icon("NodeMergeByDistance"), path(core_types::vector))] fn merge_by_distance( _: impl Ctx, @@ -3573,7 +3611,7 @@ fn element_centroid(element: &Vector, transform: DAffine2, centroid_type: Centro mod test { use super::*; use core_types::Node; - use kurbo::{CubicBez, Point, Rect}; + use kurbo::{CubicBez, ParamCurveNearest, Point, Rect}; use std::future::Future; use std::pin::Pin; use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg}; @@ -4203,4 +4241,84 @@ mod test { assert_eq!(visited[0].1, transform, "its own transform attribute should come along for placement"); assert!(visited[0].0.is_some(), "its geometry should be measurable for the automatic gradient bounds"); } + + async fn round_corners_of(bezpath: BezPath, transform: DAffine2) -> Vec { + let rounded = super::round_corners((), create_vector_item(bezpath, transform), item(10.), item(0.5), item(100.), item(5.)).await; + rounded.element().stroke_bezpath_iter().collect() + } + + fn distance_to_path(point: DVec2, bezpath: &BezPath) -> f64 { + bezpath + .segments() + .map(|segment| segment.nearest(dvec2_to_point(point), 1e-6).distance_sq.sqrt()) + .fold(f64::INFINITY, f64::min) + } + + #[tokio::test] + async fn round_corners_leaves_a_circle_unchanged() { + let circle = ellipse_bezpath(DVec2::ZERO, DVec2::splat(200.)); + let transform = DAffine2::from_scale_angle_translation(DVec2::splat(1.5), 0.4, DVec2::new(30., -20.)); + + let rounded = round_corners_of(circle.clone(), transform).await; + assert_eq!(rounded.len(), 1); + assert_eq!(rounded[0].segments().count(), circle.segments().count(), "a circle has no corners to round"); + for (rounded, original) in rounded[0].segments().zip(circle.segments()) { + assert!(pathseg_abs_diff_eq(rounded, original, 1e-6), "the circle's curves should be kept: {rounded:?} != {original:?}"); + } + } + + #[tokio::test] + async fn round_corners_rounds_a_rectangles_corners() { + let rounded = round_corners_of(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY).await; + let segments: Vec = rounded[0].segments().collect(); + assert_eq!(segments.len(), 8, "each of the four corners becomes a curve between two edges"); + + // A right angle is cut back by the radius divided by sin(45°) along both edges + let cut_distance = 10. / std::f64::consts::FRAC_PI_4.sin(); + for segment in &segments { + match segment { + PathSeg::Line(line) => assert!((line.length() - (100. - 2. * cut_distance)).abs() < 1e-9, "the edges are shortened at both ends"), + PathSeg::Cubic(cubic) => assert!((point_to_dvec2(cubic.p0).distance(point_to_dvec2(cubic.p3)) - cut_distance * 2_f64.sqrt()).abs() < 1e-9), + PathSeg::Quad(_) => panic!("rounded corners are cubic"), + } + } + } + + #[tokio::test] + async fn round_corners_keeps_curves_beside_a_corner() { + // A half-disc, whose two corners join its arc to its flat side, and whose arc is smooth where its two curves meet + let handle = 50. * 0.552_284_749_8; + let mut half_disc = BezPath::new(); + half_disc.move_to((-50., 0.)); + half_disc.curve_to((-50., -handle), (-handle, -50.), (0., -50.)); + half_disc.curve_to((handle, -50.), (50., -handle), (50., 0.)); + half_disc.line_to((-50., 0.)); + half_disc.close_path(); + + let rounded = round_corners_of(half_disc.clone(), DAffine2::IDENTITY).await; + assert_eq!(rounded[0].segments().count(), 5, "only the two corners are rounded"); + + // The arc away from the corners, up to and past the smooth join at its top + let arc: Vec = half_disc.segments().take(2).collect(); + for (segment, t) in [(arc[0], 0.5), (arc[0], 0.8), (arc[0], 1.), (arc[1], 0.2), (arc[1], 0.5)] { + let on_arc = point_to_dvec2(segment.eval(t)); + assert!(distance_to_path(on_arc, &rounded[0]) < 1e-6, "the arc at {on_arc} should be kept"); + } + assert!(distance_to_path(DVec2::new(-50., 0.), &rounded[0]) > 1., "the corner should be rounded off"); + } + + #[tokio::test] + async fn round_corners_leaves_short_subpaths_in_place() { + let mut line = BezPath::new(); + line.move_to((0., 0.)); + line.line_to((40., 10.)); + let transform = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.3, DVec2::new(100., 50.)); + + let rounded = round_corners_of(line.clone(), transform).await; + assert_eq!(rounded.len(), 1); + assert!( + pathseg_abs_diff_eq(rounded[0].segments().next().unwrap(), line.segments().next().unwrap(), 1e-9), + "a subpath too short to have corners should stay where it was" + ); + } } From 70a51a5fb5612ac8865588effb81a01672a7d364 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:44:36 +0000 Subject: [PATCH 06/47] Fix renaming layers in the node graph and hiding nodes from the Inspector inside subgraphs (#4717) --- .../portfolio/document/document_message.rs | 9 +++++++++ .../portfolio/document/document_message_handler.rs | 14 ++++++++++++++ frontend/src/components/views/Graph.svelte | 2 +- frontend/src/components/widgets/NodeSection.svelte | 2 +- frontend/wrapper/src/editor_commands.rs | 14 ++++++++++++-- 5 files changed, 37 insertions(+), 4 deletions(-) diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index 71e6f041cb..de7589019c 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -199,6 +199,11 @@ pub enum DocumentMessage { SetGraphFadeArtwork { percentage: f64, }, + /// Renames a layer in the network the node graph is showing, which may be a subgraph. + SetLayerNameInGraph { + node_id: NodeId, + name: String, + }, SetLayersPanelHoveredLayer { id: Option, }, @@ -263,6 +268,10 @@ pub enum DocumentMessage { ToggleLayerChainExpanded { layer_id: NodeId, }, + /// Hides or shows a node in the network holding the selection, which may be a subgraph. + ToggleNodeVisibility { + node_id: NodeId, + }, ToggleSelectedVisibility, ToggleSelectedLocked, ToggleGridVisibility, diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 33b8ab8f2a..9c91f62e7b 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -1485,6 +1485,14 @@ impl MessageHandler> for DocumentMes self.graph_fade_artwork_percentage = percentage; responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage }); } + DocumentMessage::SetLayerNameInGraph { node_id, name } => { + responses.add(NodeGraphMessage::SetDisplayName { + node_id, + network_path: self.breadcrumb_network_path.clone(), + alias: name, + skip_adding_history_step: false, + }); + } DocumentMessage::SetLayersPanelHoveredLayer { id } => { let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked); if layer != self.layers_panel_hovered_layer { @@ -1716,6 +1724,12 @@ impl MessageHandler> for DocumentMes responses.add(NodeGraphMessage::UpdateLayerPanel); } + DocumentMessage::ToggleNodeVisibility { node_id } => { + responses.add(NodeGraphMessage::ToggleVisibility { + node_id, + network_path: self.selection_network_path.clone(), + }); + } DocumentMessage::ToggleSelectedLocked => responses.add(NodeGraphMessage::ToggleSelectedLocked), DocumentMessage::ToggleSelectedVisibility => { responses.add(NodeGraphMessage::ToggleSelectedVisibility); diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index 1706d9c98f..35eeb69735 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -58,7 +58,7 @@ editingName = undefined; if (!target || editingNameText === target.initialText) return; - if (target.kind === "Layer") editor.setLayerName(target.nodeId, editingNameText); + if (target.kind === "Layer") editor.setLayerNameInGraph(target.nodeId, editingNameText); else if (target.kind === "Import") editor.setImportName(target.index, editingNameText); else editor.setExportName(target.index, editingNameText); } diff --git a/frontend/src/components/widgets/NodeSection.svelte b/frontend/src/components/widgets/NodeSection.svelte index 14262cebbe..8dcefc8f5f 100644 --- a/frontend/src/components/widgets/NodeSection.svelte +++ b/frontend/src/components/widgets/NodeSection.svelte @@ -107,7 +107,7 @@ tooltipDescription={widgetData.visible ? "Hide this node." : "Show this node."} size={24} action={(e) => { - editor.toggleNodeVisibilityLayerPanel(widgetData.id); + editor.toggleNodeVisibilityInspector(widgetData.id); e?.stopPropagation(); }} class={widgetData.visible ? "show-only-on-hover" : ""} diff --git a/frontend/wrapper/src/editor_commands.rs b/frontend/wrapper/src/editor_commands.rs index 2bdeaa15d8..480d94afda 100644 --- a/frontend/wrapper/src/editor_commands.rs +++ b/frontend/wrapper/src/editor_commands.rs @@ -587,7 +587,7 @@ mod editor_commands { .into() } - /// Set the name for the layer + /// Set the name for the layer in the document network, as listed in the Layers panel fn set_layer_name(id: u64, name: String) -> Message { let layer = LayerNodeIdentifier::new_unchecked(NodeId(id)); NodeGraphMessage::SetDisplayName { @@ -599,6 +599,11 @@ mod editor_commands { .into() } + /// Set the name for a layer in the network shown by the node graph, which may be a subgraph + fn set_layer_name_in_graph(id: u64, name: String) -> Message { + DocumentMessage::SetLayerNameInGraph { node_id: NodeId(id), name }.into() + } + /// Translates document (in viewport coords) fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message { NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into() @@ -688,7 +693,7 @@ mod editor_commands { .into() } - /// Toggle visibility of a layer or node given its node ID + /// Toggle visibility of a layer or node in the document network, as listed in the Layers panel fn toggle_node_visibility_layer_panel(id: u64) -> Message { NodeGraphMessage::ToggleVisibility { node_id: NodeId(id), @@ -697,6 +702,11 @@ mod editor_commands { .into() } + /// Toggle visibility of a node shown in the Inspector, which may be in a subgraph + fn toggle_node_visibility_inspector(id: u64) -> Message { + DocumentMessage::ToggleNodeVisibility { node_id: NodeId(id) }.into() + } + /// Pin or unpin a node given its node ID fn set_node_pinned(id: u64, pinned: bool) -> Message { DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into() From a5106771b6f710c41c32a568696dcae98f5c80a0 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:47:57 +0000 Subject: [PATCH 07/47] Fix the Spline tool discarding the whole spline when switching tools mid-draw (#4723) --- .../src/messages/tool/tool_message_handler.rs | 3 +- .../tool/tool_messages/spline_tool.rs | 50 ++++++++++++++++++- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/editor/src/messages/tool/tool_message_handler.rs b/editor/src/messages/tool/tool_message_handler.rs index 9196dba4e4..dab9598047 100644 --- a/editor/src/messages/tool/tool_message_handler.rs +++ b/editor/src/messages/tool/tool_message_handler.rs @@ -162,8 +162,9 @@ impl ToolMessageHandler { } }; - send_abort_to_tool(old_tool, tool_type, true); + // The old tool goes first so it can finish its edit before the new tool's abort, which also leaves the new tool's hints and cursor showing send_abort_to_tool(old_tool, old_tool, false); + send_abort_to_tool(old_tool, tool_type, true); // Nothing a tool was snapping, or had woken, carries over to the next tool self.snap_session.end_gesture(); diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index 7ec6c579be..e2674cce35 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -565,7 +565,15 @@ impl Fsm for SplineToolFsmState { SplineToolFsmState::MergingEndpoints } (SplineToolFsmState::Drawing, SplineToolMessage::Abort) => { - responses.add(DocumentMessage::AbortTransaction); + // Switching tools keeps the spline drawn so far, like the Pen tool, but leaves its ends unjoined as the tool won't be active to finish them + if tool_data.points.len() <= 1 { + responses.add(DocumentMessage::AbortTransaction); + } else { + delete_preview(tool_data, responses); + responses.add(DocumentMessage::EndTransaction); + } + + tool_data.cleanup(); SplineToolFsmState::Ready } (SplineToolFsmState::Ready, SplineToolMessage::Confirm | SplineToolMessage::Abort) => { @@ -1132,8 +1140,9 @@ mod test_spline_tool { editor.draw_spline(&ARCH).await; let first = spline_layers(&editor)[0]; + // Aborted before placing a point of its own, the extension is dropped editor.click_tool(ToolType::Spline, MouseKeys::LEFT, ARCH[2], ModifierKeys::empty()).await; - editor.click_tool(ToolType::Spline, MouseKeys::LEFT, DVec2::new(500., 200.), ModifierKeys::empty()).await; + editor.move_mouse(500., 200., ModifierKeys::empty(), MouseKeys::empty()).await; editor.handle_message(SplineToolMessage::Abort).await; assert_spline_points(&editor, first, &ARCH); @@ -1144,4 +1153,41 @@ mod test_spline_tool { let second = spline_layers(&editor).into_iter().find(|&layer| layer != first).expect("A second spline should have been drawn"); assert_spline_points(&editor, second, &[center, points[1], points[2]]); } + + #[tokio::test] + async fn switching_tools_mid_spline_keeps_the_spline() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Spline).await; + for point in ARCH { + editor.click_tool(ToolType::Spline, MouseKeys::LEFT, point, ModifierKeys::empty()).await; + } + editor.move_mouse(500., 200., ModifierKeys::empty(), MouseKeys::empty()).await; + + // The Select tool's own abort, which runs as it becomes active, would otherwise cancel the spline's open edit + editor.select_tool(ToolType::Select).await; + + let splines = spline_layers(&editor); + assert_eq!(splines.len(), 1); + assert_spline_points(&editor, splines[0], &ARCH); + + // The finished spline is one step of history + editor.press(Key::KeyZ, ModifierKeys::CONTROL).await; + assert!(spline_layers(&editor).is_empty(), "Undo should remove the whole spline"); + } + + #[tokio::test] + async fn an_extension_is_kept_when_switching_tools() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_spline(&ARCH).await; + let first = spline_layers(&editor)[0]; + + editor.click_tool(ToolType::Spline, MouseKeys::LEFT, ARCH[2], ModifierKeys::empty()).await; + let extension = DVec2::new(500., 200.); + editor.click_tool(ToolType::Spline, MouseKeys::LEFT, extension, ModifierKeys::empty()).await; + editor.select_tool(ToolType::Rectangle).await; + + assert_spline_points(&editor, first, &[ARCH[0], ARCH[1], ARCH[2], extension]); + } } From fc9b616814e1684285ca03a6eccfcb01cf5e4b30 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:51:53 +0000 Subject: [PATCH 08/47] Fix Esc closing the node graph or exiting a subgraph when canceling a pan or zoom (#4711) --- .../messages/portfolio/document/document_message_handler.rs | 5 +++++ .../document/navigation/navigation_message_handler.rs | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index 9c91f62e7b..f99f053197 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -626,6 +626,11 @@ impl MessageHandler> for DocumentMes responses.add(NodeGraphMessage::UpdateNodeGraphWidth); } DocumentMessage::Escape => { + // The same Esc cancels the pan, tilt, or zoom drag through its own binding + if self.navigation_handler.is_navigating() { + return; + } + // Abort dragging nodes if self.node_graph_handler.drag_start.is_some() { responses.add(DocumentMessage::AbortTransaction); diff --git a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs index 297b8763ab..09db062282 100644 --- a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs +++ b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs @@ -529,6 +529,11 @@ impl MessageHandler> for Navigat } impl NavigationMessageHandler { + /// Whether a pan, tilt, or zoom drag is in progress. + pub fn is_navigating(&self) -> bool { + self.navigation_operation != NavigationOperation::None + } + pub fn snapped_tilt(&self, tilt: f64) -> f64 { let increment_radians: f64 = VIEWPORT_ROTATE_SNAP_INTERVAL.to_radians(); if matches!(self.navigation_operation, NavigationOperation::Tilt { snap: true, .. }) { From 15a7d080a280a0f44442dc5316d1972e3b57f5a6 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 08:58:48 +0000 Subject: [PATCH 09/47] Restore the upward-drag flip for odd-sided shapes lost in the unified Shape tool (#4724) --- .../shapes/polygon_shape.rs | 15 +++++-- .../shapes/shape_utility.rs | 42 ++----------------- .../common_functionality/shapes/star_shape.rs | 17 +++++--- .../messages/tool/tool_messages/shape_tool.rs | 15 +++++++ 4 files changed, 41 insertions(+), 48 deletions(-) diff --git a/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs b/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs index 605d4ed875..0c7331dea4 100644 --- a/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/polygon_shape.rs @@ -1,4 +1,4 @@ -use super::shape_utility::{ShapeToolModifierKey, update_radius_sign}; +use super::shape_utility::{ShapeToolModifierKey, drawn_flipped}; use super::*; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type}; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; @@ -128,11 +128,17 @@ impl Polygon { let document = view.document; let [center, lock_ratio, _] = modifier; - let vertices = extract_polygon_parameters(Some(layer), document).map(|(sides, _)| regular_polygon_points(sides)).unwrap_or_default(); + let sides = extract_polygon_parameters(Some(layer), document).map(|(sides, _)| sides); + let flipped = sides.is_some_and(|sides| drawn_flipped(sides, shape_tool_data.data.viewport_drag_start(document), view.input.mouse.position)); + let vertices: Vec = sides + .map(regular_polygon_points) + .unwrap_or_default() + .into_iter() + .map(|vertex| if flipped { -vertex } else { vertex }) + .collect(); + if let Some([start, end]) = shape_tool_data.data.calculate_points(snap_session, view, center, lock_ratio, &vertices) { // TODO: We need to determine how to allow the polygon node to make irregular shapes - update_radius_sign(end, start, layer, document, responses); - let dimensions = (start - end).abs(); // We keep the smaller dimension's scale at 1 and scale the other dimension accordingly @@ -146,6 +152,7 @@ impl Polygon { }; let radius = radius / viewport_zoom(document); + let radius = if flipped { -radius } else { radius }; let Some(node_id) = graph_modification_utils::get_polygon_id(layer, &document.network_interface) else { return; diff --git a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs index 1d29c8bbbc..1ffb4538b0 100644 --- a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs +++ b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs @@ -6,8 +6,7 @@ use crate::messages::message::Message; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; -use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; -use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler, NodeGraphMessage, Responses}; +use crate::messages::prelude::{DocumentMessageHandler, InputPreprocessorMessageHandler}; use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer; use crate::messages::tool::common_functionality::shape_editor::ShapeState; use crate::messages::tool::common_functionality::snap_session::{SnapSession, SnapView}; @@ -15,7 +14,6 @@ use crate::messages::tool::common_functionality::transformation_cage::BoundingBo use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::*; use glam::{DAffine2, DMat2, DVec2}; -use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; use graphene_std::core_types::misc::format_f64; use graphene_std::math::float_noise::round_away_float_noise; @@ -210,41 +208,9 @@ pub fn clicked_on_shape_endpoints(layer: LayerNodeIdentifier, document: &Documen endpoint_click } -/// Center, Lock Ratio, Lock Angle, Snap Angle, Increase/Decrease Side -pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier, document: &DocumentMessageHandler, responses: &mut VecDeque) { - let sign_num = if end[1] > start[1] { 1. } else { -1. }; - let new_layer = NodeGraphLayer::new(layer, &document.network_interface); - - if let Some(&TaggedValue::Integer(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput) - && sides % 2 != 0 - { - let Some(polygon_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::regular_polygon::IDENTIFIER)) else { - return; - }; - - responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(polygon_node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput), - input: NodeInput::value(TaggedValue::Number(sign_num * 0.5), false), - }); - return; - } - - if let Some(&TaggedValue::Integer(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput) - && sides % 2 != 0 - { - let Some(star_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::star::IDENTIFIER)) else { - return; - }; - - responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius1Input), - input: NodeInput::value(TaggedValue::Number(sign_num * 0.5), false), - }); - responses.add(NodeGraphMessage::SetInput { - input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius2Input), - input: NodeInput::value(TaggedValue::Number(sign_num * 0.25), false), - }); - } +/// Whether an odd-sided polygon or star being drawn is flipped to point down, which it is when dragged upward. It's flipped by negating its radius. +pub fn drawn_flipped(sides: u32, viewport_drag_start: DVec2, pointer: DVec2) -> bool { + sides % 2 == 1 && pointer.y < viewport_drag_start.y } pub fn transform_cage_overlays(document: &DocumentMessageHandler, tool_data: &mut ShapeToolData, overlay_context: &mut OverlayContext) { diff --git a/editor/src/messages/tool/common_functionality/shapes/star_shape.rs b/editor/src/messages/tool/common_functionality/shapes/star_shape.rs index 1e31ddc287..c4b9c6db45 100644 --- a/editor/src/messages/tool/common_functionality/shapes/star_shape.rs +++ b/editor/src/messages/tool/common_functionality/shapes/star_shape.rs @@ -1,4 +1,4 @@ -use super::shape_utility::{ShapeToolModifierKey, update_radius_sign}; +use super::shape_utility::{ShapeToolModifierKey, drawn_flipped}; use super::*; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type}; use crate::messages::portfolio::document::overlays::utility_types::OverlayContext; @@ -132,13 +132,17 @@ impl Star { let document = view.document; let [center, lock_ratio, _] = modifier; - let points = extract_star_parameters(Some(layer), document) - .map(|(sides, _, _)| star_points(sides, INNER_RADIUS_WHILE_DRAWING)) - .unwrap_or_default(); + let sides = extract_star_parameters(Some(layer), document).map(|(sides, _, _)| sides); + let flipped = sides.is_some_and(|sides| drawn_flipped(sides, shape_tool_data.data.viewport_drag_start(document), view.input.mouse.position)); + let points: Vec = sides + .map(|sides| star_points(sides, INNER_RADIUS_WHILE_DRAWING)) + .unwrap_or_default() + .into_iter() + .map(|point| if flipped { -point } else { point }) + .collect(); + if let Some([start, end]) = shape_tool_data.data.calculate_points(snap_session, view, center, lock_ratio, &points) { // TODO: We need to determine how to allow the polygon node to make irregular shapes - update_radius_sign(end, start, layer, document, responses); - let dimensions = (start - end).abs(); // We keep the smaller dimension's scale at 1 and scale the other dimension accordingly @@ -152,6 +156,7 @@ impl Star { }; let radius = radius / viewport_zoom(document); + let radius = if flipped { -radius } else { radius }; let Some(node_id) = graph_modification_utils::get_star_id(layer, &document.network_interface) else { return; diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index 542a775ad4..5c755a388b 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -1715,6 +1715,21 @@ mod test_shape_tool { } } + #[tokio::test] + async fn an_odd_polygon_or_star_dragged_upward_is_drawn_flipped_to_point_down() { + for (shape, point_count) in [(ShapeType::Polygon, 5), (ShapeType::Star, 10)] { + for (from, to, flipped) in [(DVec2::new(300., 300.), DVec2::new(380., 380.), false), (DVec2::new(300., 380.), DVec2::new(380., 300.), true)] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_checking_shape_points(&mut editor, shape, from, to, ModifierKeys::empty(), point_count).await; + + // The tip of an upright shape is in the middle of the top of its box, and a flipped one's is in the middle of the bottom + let tip = DVec2::new(340., if flipped { 380. } else { 300. }); + assert_has_anchor_at(&drawn_anchors(&editor, layer), tip); + } + } + } + /// Where the second vertex of a pentagon dragged out from `start` lands for a pointer at `pointer`, in the viewport. fn second_vertex(start: DVec2, pointer: DVec2) -> DVec2 { let vertex = regular_polygon_points(5)[1]; From 6b2241fdb6edece55a9bbb59c6794312c8919a54 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:10:35 +0000 Subject: [PATCH 10/47] Fix canceling a held Fill tool click not undoing the fill (#4715) --- .../messages/tool/tool_messages/fill_tool.rs | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/editor/src/messages/tool/tool_messages/fill_tool.rs b/editor/src/messages/tool/tool_messages/fill_tool.rs index 17e42582fc..574e97bd4d 100644 --- a/editor/src/messages/tool/tool_messages/fill_tool.rs +++ b/editor/src/messages/tool/tool_messages/fill_tool.rs @@ -190,7 +190,8 @@ impl Fsm for FillToolFsmState { _ => return self, }; - responses.add(DocumentMessage::AddTransaction); + // Left open until the release, so Esc or right-click while the button is held can still roll the fill back + responses.add(DocumentMessage::StartTransaction); if route_to_color_chain { responses.add(GraphOperationMessage::ColorValueSet { layer: layer_identifier, color }); } else { @@ -202,7 +203,11 @@ impl Fsm for FillToolFsmState { FillToolFsmState::Filling } - (FillToolFsmState::Filling, FillToolMessage::PointerUp) => FillToolFsmState::Ready, + (FillToolFsmState::Filling, FillToolMessage::PointerUp) => { + responses.add(DocumentMessage::EndTransaction); + + FillToolFsmState::Ready + } (FillToolFsmState::Filling, FillToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); @@ -328,6 +333,30 @@ mod test_fill { assert_eq!(SRGBA8::from(*color), SRGBA8::from(Color::YELLOW)); } + #[tokio::test] + async fn esc_while_held_cancels_the_fill() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + let original = *get_fills(&mut editor).await.first().expect("the rectangle should have a fill").element(); + + editor.select_primary_color(Color::GREEN).await; + editor.select_tool(ToolType::Fill).await; + editor.left_mousedown(50., 50., ModifierKeys::empty()).await; + editor.press(Key::Escape, ModifierKeys::empty()).await; + editor.left_mouseup(50., 50., ModifierKeys::empty()).await; + + let fills = get_fills(&mut editor).await; + assert_eq!(fills.len(), 1); + assert_eq!(SRGBA8::from(*fills[0].element()), SRGBA8::from(original), "Esc while the button is held should undo the fill"); + + // Without the Esc, the fill sticks and is one undo step + editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(50., 50.), ModifierKeys::empty()).await; + assert_eq!(SRGBA8::from(*get_fills(&mut editor).await[0].element()), SRGBA8::from(Color::GREEN)); + editor.handle_message(DocumentMessage::Undo).await; + assert_eq!(SRGBA8::from(*get_fills(&mut editor).await[0].element()), SRGBA8::from(original), "one undo should take the fill back"); + } + #[tokio::test] async fn blank_layer_gets_whole_expanse_color() { use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id; From b5b6664d9aa85ebbe3639f723135c5206f716f48 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:14:49 +0000 Subject: [PATCH 11/47] Fix undoing a number field arrow click also undoing the edit before it (#4718) --- .../src/components/widgets/inputs/NumberInput.svelte | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/frontend/src/components/widgets/inputs/NumberInput.svelte b/frontend/src/components/widgets/inputs/NumberInput.svelte index b62144dfbf..93f818c856 100644 --- a/frontend/src/components/widgets/inputs/NumberInput.svelte +++ b/frontend/src/components/widgets/inputs/NumberInput.svelte @@ -502,6 +502,13 @@ initialValueBeforeDragging = value; initialExactBeforeDragging = exact; if (exact !== undefined) steppingDigit = useShownDigit(); + + // A press and the repeats while it's held are one history step, as a drag is (exact mode's owner keeps its own history) + if (exact === undefined && (incrementBehavior === "Add" || incrementBehavior === "Multiply")) { + dispatch("startHistoryTransaction"); + transactionInProgress = true; + } + let afterInitialDelay = false; sendAction(); repeatTimeout = setTimeout(sendAction, PRESS_REPEAT_DELAY_MS); @@ -513,6 +520,7 @@ steppingDigit = undefined; clearTimeout(repeatTimeout); removeEventListener("keydown", incrementPressAbort); + commitTransactionIfInProgress(); } function incrementPressAbort(e: KeyboardEvent | MouseEvent) { @@ -531,6 +539,7 @@ if (initialExact) updateExact(initialExact, initialExactBeforeDragging); else updateValue(initialValueBeforeDragging); removeEventListener("keydown", incrementPressAbort); + commitTransactionIfInProgress(); } // ======================================= From 6373264efab0edd23583bc3aaf1e287bd0ea898d Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:21:44 +0000 Subject: [PATCH 12/47] Fix SVG rendering leaking memory for every image on each zoom or pan (#4722) --- frontend/wrapper/src/helpers.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/frontend/wrapper/src/helpers.rs b/frontend/wrapper/src/helpers.rs index a808874e9e..d8f5adf86f 100644 --- a/frontend/wrapper/src/helpers.rs +++ b/frontend/wrapper/src/helpers.rs @@ -12,6 +12,8 @@ use editor::messages::input_mapper::utility_types::keyboard::Key; #[cfg(not(feature = "native"))] use editor::messages::prelude::*; use js_sys::{Object, Reflect}; +use std::cell::RefCell; +use std::collections::HashSet; #[cfg(not(feature = "native"))] use std::sync::atomic::Ordering; use std::time::Duration; @@ -123,6 +125,11 @@ pub(crate) fn async_wake_callback() -> Wake { }) } +thread_local! { + // The placeholder IDs of the last rendered artwork's images, each with its canvas on `window.imageCanvases` + static SHOWN_IMAGE_IDS: RefCell> = RefCell::new(HashSet::new()); +} + /// Blits each rasterized image to a canvas registered on `window.imageCanvases` pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator) { let window = match window() { @@ -149,6 +156,16 @@ pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator>(); + let shown = image_data.iter().map(|image| image.id).collect::>(); + let previously_shown = SHOWN_IMAGE_IDS.replace(shown.clone()); + for stale in previously_shown.difference(&shown) { + if Reflect::delete_property(&canvases_obj, &JsValue::from_str(&stale.to_string())).is_err() { + error!("Failed to free the canvas of image {stale}"); + } + } + for image in image_data { let (placeholder_id, width, height) = (image.id, image.width, image.height); let pixels = image.pixels.as_slice(); From f20825d8ba8de03830546fb8dd6804026dc687c7 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:26:10 +0000 Subject: [PATCH 13/47] Fix a Gradient tool click that barely moves replacing the fill with a broken gradient (#4707) * Fix a Gradient tool click that barely moves replacing the fill with a broken gradient * Take back a new gradient whose drag is released where it was pressed --- .../tool/tool_messages/gradient_tool.rs | 75 +++++++++++++++++-- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index 3cdc466eb1..af02c3b050 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -619,14 +619,18 @@ impl SelectedGradient { lock_angle: bool, gradient_form: GradientForm, drag_start: DVec2, + press_unsnapped: DVec2, snap_session: &mut SnapSession, view: SnapView, gradient_angle: &mut f64, ) { - if mouse.distance(drag_start) < DRAG_THRESHOLD { - self.gradient = self.initial_gradient.clone(); - self.appearance.transform = self.initial_gradient_transform; - self.render_gradient(responses); + if mouse.distance(press_unsnapped) <= DRAG_THRESHOLD { + // A new gradient's initial line is only a placeholder, so nothing is written until the drag passes the threshold + if self.dragging != GradientDragTarget::New { + self.gradient = self.initial_gradient.clone(); + self.appearance.transform = self.initial_gradient_transform; + self.render_gradient(responses); + } return; } @@ -1559,6 +1563,7 @@ impl Fsm for GradientToolFsmState { // Convert drag_start from document space to effective viewport space let document_to_viewport = document.metadata().document_to_viewport; let drag_start_viewport = document_to_viewport.transform_point2(tool_data.drag_start) + tool_data.auto_pan_shift; + let press_unsnapped_viewport = document_to_viewport.transform_point2(tool_data.drag_start_unsnapped) + tool_data.auto_pan_shift; tool_data.auto_pan_shift = DVec2::ZERO; selected_gradient.update_gradient( @@ -1568,6 +1573,7 @@ impl Fsm for GradientToolFsmState { input.keyboard.get(lock_angle as usize), selected_gradient.appearance.gradient_form, drag_start_viewport, + press_unsnapped_viewport, snap_session, SnapView::new(document, *document_id, input), &mut tool_data.gradient_angle, @@ -1604,7 +1610,13 @@ impl Fsm for GradientToolFsmState { state } (GradientToolFsmState::Drawing { .. }, GradientToolMessage::PointerUp) => { - responses.add(DocumentMessage::EndTransaction); + // A new gradient released where it was pressed is a click, so anything its drag wrote along the way is taken back + if tool_data.selected_gradient.as_ref().is_some_and(|selected| selected.dragging == GradientDragTarget::New) { + let press = document.metadata().document_to_viewport.transform_point2(tool_data.drag_start_unsnapped); + input.mouse.finish_transaction(press, responses); + } else { + responses.add(DocumentMessage::EndTransaction); + } // Clear the selection if we were dragging an endpoint of the gradient which isn't a stop if tool_data.selected_gradient.as_ref().is_some_and(|selected| match selected.dragging { @@ -2717,6 +2729,59 @@ mod test_gradient { assert!(!final_positions.iter().any(|pos| (pos - 0.75).abs() < 0.05), "Stop at position 0.75 should have been deleted"); } + #[tokio::test] + async fn a_click_slipping_under_the_drag_threshold_draws_no_gradient() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.active_document_mut().snapping_state.snapping_enabled = false; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + editor.drag_tool(ToolType::Gradient, 30., 40., 30.5, 40., ModifierKeys::empty()).await; + + assert!( + get_gradients_from_fill(&mut editor).await.is_empty(), + "a click that barely moves shouldn't replace the fill with a gradient" + ); + } + + #[tokio::test] + async fn a_new_gradient_drag_released_back_where_it_was_pressed_draws_no_gradient() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.active_document_mut().snapping_state.snapping_enabled = false; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + editor.select_tool(ToolType::Gradient).await; + editor.move_mouse(30., 40., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(30., 40., ModifierKeys::empty()).await; + editor.move_mouse(60., 40., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.move_mouse(30.5, 40., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(30.5, 40., ModifierKeys::empty()).await; + + assert!( + get_gradients_from_fill(&mut editor).await.is_empty(), + "a drag that comes back to where it was pressed shouldn't replace the fill with a gradient" + ); + } + + #[tokio::test] + async fn a_click_beside_a_snap_target_slipping_under_the_drag_threshold_draws_no_gradient() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + // The press lands a few pixels inside the left edge, which it snaps onto + editor.drag_tool(ToolType::Gradient, 3., 50., 3.5, 50., ModifierKeys::empty()).await; + + assert!( + get_gradients_from_fill(&mut editor).await.is_empty(), + "a click that snaps and barely moves shouldn't replace the fill with a gradient" + ); + } + #[tokio::test] async fn delete_removes_layer_when_no_stop_selected() { let mut editor = EditorTestUtils::create(); From 1185d1de4543d1cd7bef8bce01603a14e2284e47 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:26:21 +0000 Subject: [PATCH 14/47] Fix the Path tool crashing when Alt-clicking an anchor with no segments (#4728) --- .../messages/tool/tool_messages/path_tool.rs | 59 +++++++++++++------ 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index 51f099bb8f..b9c5d8d800 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -828,27 +828,27 @@ impl PathToolData { shape_editor.disable_colinear_handles_state_on_selected(&document.network_interface, responses); } - if handle_drag_from_anchor && let Some((layer, point)) = shape_editor.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) { - // Check that selected point is an anchor - if let (Some(point_id), Some(vector)) = (point.as_anchor(), document.network_interface.compute_modified_vector(layer)) { - let handles = vector.all_connected(point_id).collect::>(); - self.alt_clicked_on_anchor = true; - for handle in &handles { - let modification_type = handle.set_relative_position(DVec2::ZERO); - responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in &vector.colinear_manipulators { - if handles.contains(handle) { - let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; - responses.add(GraphOperationMessage::Vector { layer, modification_type }); - } + // Alt held at drag start on an anchor makes it sharp, unless it's a lone anchor with no handles to retract + if handle_drag_from_anchor + && let Some((layer, point)) = shape_editor.find_nearest_point_indices(&document.network_interface, input.mouse.position, SELECTION_THRESHOLD) + && let (Some(point_id), Some(vector)) = (point.as_anchor(), document.network_interface.compute_modified_vector(layer)) + && let Some(first_handle) = vector.all_connected(point_id).next() + { + self.alt_clicked_on_anchor = true; + for handle in vector.all_connected(point_id) { + let modification_type = handle.set_relative_position(DVec2::ZERO); + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + for &handles in &vector.colinear_manipulators { + if handles.contains(&handle) { + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } - - let manipulator_point_id = handles[0].to_manipulator_point(); - shape_editor.deselect_all_points(); - shape_editor.select_point_by_layer_and_id(manipulator_point_id, layer); - responses.add(PathToolMessage::SelectedPointUpdated); } + + shape_editor.deselect_all_points(); + shape_editor.select_point_by_layer_and_id(first_handle.to_manipulator_point(), layer); + responses.add(PathToolMessage::SelectedPointUpdated); } if let Some((Some(point), Some(vector), layer)) = shape_editor @@ -3777,6 +3777,10 @@ mod test_path_tool { } } + fn selected_points(editor: &EditorTestUtils) -> Vec { + editor.editor.dispatcher.message_handlers.tool_message_handler.shape_editor.selected_points().copied().collect() + } + /// Presses the Path tool at a viewport position, which picks up whatever point is there. async fn press_at(editor: &mut EditorTestUtils, position: DVec2) { editor.select_tool(ToolType::Path).await; @@ -4015,4 +4019,23 @@ mod test_path_tool { let moved = DVec2::new(3., 0.); assert_anchors(&editor, layer, &[first + moved, second + moved, unselected]); } + + #[tokio::test] + async fn alt_clicking_an_anchor_without_segments_selects_it() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let layer = draw_path(&mut editor, &[A, B, C]).await; + + // Deleting the middle anchor without joining its neighbors leaves both ends without segments + editor.click_tool(ToolType::Path, MouseKeys::LEFT, B, ModifierKeys::empty()).await; + editor.handle_message(PathToolMessage::DeleteAndBreakPath).await; + assert_anchors(&editor, layer, &[A, C]); + + editor.click_tool(ToolType::Path, MouseKeys::LEFT, A, ModifierKeys::ALT).await; + let selected = selected_points(&editor); + assert!( + matches!(selected[..], [ManipulatorPointId::Anchor(_)]), + "only the Alt-clicked anchor should be selected, not {selected:?}" + ); + } } From 26c808d374dde92feb7a60e04fb50f8dd26512a8 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:32:20 +0000 Subject: [PATCH 15/47] Fix the Pen tool's G grab moving a handle too far or too little when zoomed (#4719) --- .../messages/tool/tool_messages/pen_tool.rs | 31 +++++++++++++++++++ .../transform_layer_message_handler.rs | 1 + 2 files changed, 32 insertions(+) diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index f7fe4ab7c8..8bee8c725a 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -3002,4 +3002,35 @@ mod test_pen_tool { let incoming = editor.active_document().metadata().transform_to_viewport(layer).transform_point2(incoming); assert!(incoming.distance(corner + anchor - handle) < 1e-6, "the incoming handle is at {incoming}"); } + + #[tokio::test] + async fn a_handle_grabbed_with_g_follows_the_pointer_when_zoomed() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.handle_message(NavigationMessage::CanvasZoomIncrease { center_on_mouse: false }).await; + let zoom = editor.active_document().metadata().document_to_viewport.matrix2.x_axis.length(); + assert!((zoom - 1.).abs() > 0.1, "the view should be zoomed, not at {zoom}"); + + // The second anchor's outgoing handle is dragged out, then grabbed and moved by as much as the pointer + let (start, anchor, handle) = (DVec2::new(100., 300.), DVec2::new(250., 220.), DVec2::new(330., 230.)); + click_pen(&mut editor, start).await; + editor.move_mouse(anchor.x, anchor.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(anchor.x, anchor.y, ModifierKeys::empty()).await; + editor.move_mouse(handle.x, handle.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(handle.x, handle.y, ModifierKeys::empty()).await; + + let (grip, travel) = (DVec2::new(500., 150.), DVec2::new(40., 70.)); + editor.move_mouse(grip.x, grip.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.press(Key::KeyG, ModifierKeys::empty()).await; + editor.move_mouse(grip.x + travel.x, grip.y + travel.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.press(Key::Enter, ModifierKeys::empty()).await; + + // The next segment starts with the moved handle + click_pen(&mut editor, DVec2::new(450., 400.)).await; + let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); + let segment = vector.segment_domain.ids()[1]; + let outgoing = ManipulatorPointId::PrimaryHandle(segment).get_position(&vector).expect("The segment should have an outgoing handle"); + let outgoing = editor.active_document().metadata().transform_to_viewport(layer).transform_point2(outgoing); + assert!(outgoing.distance(handle + travel) < 1e-6, "the handle is at {outgoing} rather than {}", handle + travel); + } } diff --git a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs index de3ca5f008..e2bdff5374 100644 --- a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs +++ b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs @@ -400,6 +400,7 @@ impl MessageHandler> for self.grs_pen_handle = true; self.mouse_position = input.mouse.position; self.start_mouse = input.mouse.position; + self.initial_transform = document_to_viewport; let top_left = DVec2::new(last_point.x, handle.y); let bottom_right = DVec2::new(handle.x, last_point.y); From 7cd8477c1ad4d91540634ff9ac47520f4829daee Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 09:47:20 +0000 Subject: [PATCH 16/47] Fix the Shape tool's own hotkey mid-drag freezing the shape and later deleting it (#4726) --- .../messages/tool/tool_messages/shape_tool.rs | 119 +++++++++++++----- 1 file changed, 85 insertions(+), 34 deletions(-) diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index 5c755a388b..ccbac07d6f 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -22,7 +22,7 @@ use crate::messages::tool::common_functionality::shapes::shape_utility::{ShapeTo use crate::messages::tool::common_functionality::shapes::spiral_shape::Spiral; use crate::messages::tool::common_functionality::shapes::star_shape::Star; use crate::messages::tool::common_functionality::shapes::{Ellipse, Line, Rectangle}; -use crate::messages::tool::common_functionality::snap_session::{Drawn, Moving, PointOptions, SnapView, snapping_hints}; +use crate::messages::tool::common_functionality::snap_session::{Drawn, Moving, PointOptions, SnapSession, SnapView, snapping_hints}; use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget}; use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, EdgeBool}; use crate::messages::tool::common_functionality::utility_functions::{closest_point, resize_bounds, rotate_bounds, skew_bounds, transforming_transform_cage}; @@ -593,7 +593,8 @@ impl<'a> MessageHandler> for Shap responses.add(OverlaysMessage::Draw); } - if is_set_shape { + // A shape's own key pressed mid-drag leaves the drag as it is + if is_set_shape && matches!(self.fsm_state, ShapeToolFsmState::Ready(_)) { handle_shape_mode_change(&mut self.options, self.tool_data.current_shape, shape_before, context.global_tool_data, context.document); self.send_layout(responses, LayoutTarget::ToolOptions); } @@ -1403,22 +1404,7 @@ impl Fsm for ShapeToolFsmState { | ShapeToolFsmState::ModifyingGizmo, ShapeToolMessage::Abort, ) => { - responses.add(DocumentMessage::AbortTransaction); - tool_data.data.cleanup(); - snap_session.end_gesture(); - responses.add(OverlaysMessage::Draw); - tool_data.line_data.dragging_endpoint = None; - tool_data.line_data.editing_layer = None; - - tool_data.gizmo_manager.handle_cleanup(); - - if let Some(bounds) = &mut tool_data.bounding_box_manager { - bounds.original_transforms.clear(); - } - - tool_data.cursor = MouseCursorIcon::Crosshair; - responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); - + cancel_drag(tool_data, snap_session, responses); ShapeToolFsmState::Ready(tool_data.current_shape) } (_, ShapeToolMessage::WorkingColorChanged) => { @@ -1427,22 +1413,10 @@ impl Fsm for ShapeToolFsmState { }); self } - (_, ShapeToolMessage::SetShape { shape }) => { - responses.add(DocumentMessage::AbortTransaction); - tool_data.data.cleanup(); - snap_session.end_gesture(); - responses.add(OverlaysMessage::Draw); - tool_data.current_shape = shape; - // Update hints for the new shape (without updating options.shape_type) - update_dynamic_hints(&ShapeToolFsmState::Ready(shape), responses, tool_data); - ShapeToolFsmState::Ready(shape) - } - (_, ShapeToolMessage::SyncShapeWithOptions) => { - // Sync current_shape with the dropdown selection when returning from alias tools - tool_data.current_shape = tool_options.shape_type; - update_dynamic_hints(&ShapeToolFsmState::Ready(tool_options.shape_type), responses, tool_data); - ShapeToolFsmState::Ready(tool_options.shape_type) - } + // The Line, Rectangle, and Ellipse tools set their own shape (without updating options.shape_type) + (_, ShapeToolMessage::SetShape { shape }) => switch_shape(self, shape, tool_data, snap_session, responses), + // Returning to the Shape tool from one of those draws the dropdown's shape again + (_, ShapeToolMessage::SyncShapeWithOptions) => switch_shape(self, tool_options.shape_type, tool_data, snap_session, responses), (_, ShapeToolMessage::HideShapeTypeWidget { hide }) => { tool_data.hide_shape_option_widget = hide; responses.add(ToolMessage::RefreshToolOptions); @@ -1461,6 +1435,39 @@ impl Fsm for ShapeToolFsmState { } } +/// Ends a drag without keeping anything it changed. +fn cancel_drag(tool_data: &mut ShapeToolData, snap_session: &mut SnapSession, responses: &mut VecDeque) { + responses.add(DocumentMessage::AbortTransaction); + tool_data.data.cleanup(); + snap_session.end_gesture(); + responses.add(OverlaysMessage::Draw); + tool_data.line_data.dragging_endpoint = None; + tool_data.line_data.editing_layer = None; + + tool_data.gizmo_manager.handle_cleanup(); + + if let Some(bounds) = &mut tool_data.bounding_box_manager { + bounds.original_transforms.clear(); + } + + tool_data.cursor = MouseCursorIcon::Crosshair; + responses.add(FrontendMessage::UpdateMouseCursor { cursor: MouseCursorIcon::Crosshair }); +} + +/// Switches to drawing another shape. Mid-drag, this cancels the drag as changing tools does, unless the shape is the one already being drawn, whose key is ignored as other tools ignore their own. +fn switch_shape(state: ShapeToolFsmState, shape: ShapeType, tool_data: &mut ShapeToolData, snap_session: &mut SnapSession, responses: &mut VecDeque) -> ShapeToolFsmState { + if !matches!(state, ShapeToolFsmState::Ready(_)) { + if shape == tool_data.current_shape { + return state; + } + cancel_drag(tool_data, snap_session, responses); + } + + tool_data.current_shape = shape; + update_dynamic_hints(&ShapeToolFsmState::Ready(shape), responses, tool_data); + ShapeToolFsmState::Ready(shape) +} + fn update_dynamic_hints(state: &ShapeToolFsmState, responses: &mut VecDeque, tool_data: &ShapeToolData) { let hint_data = match state { ShapeToolFsmState::Ready(_) => { @@ -2178,4 +2185,48 @@ mod test_shape_tool { editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; } + + /// Presses at one viewport position, drags halfway to another, sends a tool key's message, then finishes the drag. + async fn drag_pressing_mid_way(editor: &mut EditorTestUtils, from: DVec2, to: DVec2, key_message: ToolMessage) { + let halfway = from.midpoint(to); + editor.move_mouse(from.x, from.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(from.x, from.y, ModifierKeys::empty()).await; + editor.move_mouse(halfway.x, halfway.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.handle_message(key_message).await; + editor.move_mouse(to.x, to.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(to.x, to.y, ModifierKeys::empty()).await; + } + + fn layer_count(editor: &EditorTestUtils) -> usize { + editor.active_document().metadata().all_layers().count() + } + + #[tokio::test] + async fn the_shape_tools_own_key_mid_drag_is_ignored_and_leaves_nothing_to_undo_later() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Shape).await; + drag_pressing_mid_way(&mut editor, DVec2::new(300., 300.), DVec2::new(400., 380.), ToolMessage::ActivateToolShape).await; + + // The pentagon reaches nearly the right of the drag's box, as its side vertices sit at 95% of the box's half width + let layer = editor.get_selected_layer().await.expect("the pentagon drawn should be selected"); + let [_, max] = editor.active_document().metadata().bounding_box_viewport(layer).expect("the pentagon should have a bounding box"); + assert!(max.x > 395., "the pentagon reaches only {max} rather than the release"); + + // Switching to another of the Shape tool's modes finds no drawing left to cancel + let count = layer_count(&editor); + editor.select_tool(ToolType::Ellipse).await; + assert_eq!(layer_count(&editor), count, "the pentagon should survive switching to the Ellipse tool"); + } + + #[tokio::test] + async fn switching_to_the_shape_tool_mid_drag_cancels_the_rectangle() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.select_tool(ToolType::Rectangle).await; + let count = layer_count(&editor); + drag_pressing_mid_way(&mut editor, DVec2::new(300., 300.), DVec2::new(400., 380.), ToolMessage::ActivateToolShape).await; + + assert_eq!(layer_count(&editor), count, "switching tools mid-drag should cancel the rectangle"); + } } From 13b481da1c42ba9bada3db2fefa7e0c1ead5165e Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 10:04:39 +0000 Subject: [PATCH 17/47] Fix Inspector slider drags not making an undo step (#4721) * Fix Inspector slider drags not making an undo step * Reset a slider's joined marker pair in one undo step --- .../src/components/widgets/WidgetSpan.svelte | 1 + .../widgets/inputs/SliderInput.svelte | 34 +++++++++++++++---- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/widgets/WidgetSpan.svelte b/frontend/src/components/widgets/WidgetSpan.svelte index 5382ce083d..e391d0e66c 100644 --- a/frontend/src/components/widgets/WidgetSpan.svelte +++ b/frontend/src/components/widgets/WidgetSpan.svelte @@ -283,6 +283,7 @@ $$events: { update: (e: CustomEvent) => widgetValueUpdate(index, e.detail, false), dragging: (e: CustomEvent) => colorPickerStore.setDragging(e.detail), + startHistoryTransaction: () => widgetValueCommit(index, undefined), }, }), }, diff --git a/frontend/src/components/widgets/inputs/SliderInput.svelte b/frontend/src/components/widgets/inputs/SliderInput.svelte index 150e7279d6..24682b1490 100644 --- a/frontend/src/components/widgets/inputs/SliderInput.svelte +++ b/frontend/src/components/widgets/inputs/SliderInput.svelte @@ -9,7 +9,7 @@ const BUTTON_LEFT = 0; const BUTTON_RIGHT = 2; - const dispatch = createEventDispatcher<{ update: SliderInputUpdate; dragging: boolean }>(); + const dispatch = createEventDispatcher<{ update: SliderInputUpdate; dragging: boolean; startHistoryTransaction: undefined }>(); // Document-unique `id` for this instance's SVG gradient, referenced by its `url(#...)` const gradientId = `slider-input-gradient-${String(Math.random()).substring(2)}`; @@ -61,6 +61,10 @@ // Where selecting is allowed, these follow the selection, which Rust renumbers across structural changes. let dragIndex: number | undefined = undefined; let dragIsMidpoint = false; + // Whether a drag's pointer and key listeners are attached + let listening = false; + // Whether the current drag (or single change outside one) has started its undo step, so it undoes as one step + let historyStepStarted = false; $: if (allowSelect) { dragIndex = activeMarkerIndex; dragIsMidpoint = activeMarkerIsMidpoint; @@ -93,8 +97,17 @@ return WHOLE_PATHS; } - function emit(intent: SliderInputUpdate) { + function emit(intent: SliderInputUpdate, continuesStep?: boolean) { + // Making a marker active is only a selection, so it doesn't start an undo step + if (!("ActiveMarker" in intent) && !historyStepStarted) { + historyStepStarted = true; + dispatch("startHistoryTransaction"); + } + dispatch("update", intent); + + // Outside a drag, a change ends its undo step unless more of its run follows + if (!listening && !continuesStep) historyStepStarted = false; } function setActive(index: number | undefined, isMidpoint: boolean) { @@ -314,7 +327,9 @@ function resetRun(first: number, last: number) { if (disabled || dragMoved) return; - for (let index = first; index <= last; index += 1) emit({ ResetMarker: { index } }); + + // The whole run resets as one undo step + for (let index = first; index <= last; index += 1) emit({ ResetMarker: { index } }, index < last); } function trackPointerDown(e: PointerEvent) { @@ -335,8 +350,6 @@ let insertIndex = markers.findIndex((m) => m.position > position); if (insertIndex === -1) insertIndex = markers.length; - emit({ InsertMarker: { position } }); - activeMarkerIndexRestore = activeMarkerIndex; activeMarkerIsMidpointRestore = activeMarkerIsMidpoint; dragRestorePosition = position; @@ -351,6 +364,9 @@ activeMarkerIndex = insertIndex; activeMarkerIsMidpoint = false; addEvents(); + + // Inserted once the drag is underway, so the insertion and the drag after it undo as one step + emit({ InsertMarker: { position } }); } // The lane the handles hang in picks up the nearest marker like the strip does, except where the click landed on a marker itself @@ -517,7 +533,10 @@ const dragged = dragIndex; const anchor = duplicateActive ? findDuplicateAnchorIndex() : undefined; - if (dragInsertedMarker) { + // A drag that changed nothing yet has nothing to put back, and putting it back anyway would leave an empty undo step + if (!historyStepStarted) { + // Nothing to restore + } else if (dragInsertedMarker) { // The dragged marker was created by this drag, so delete it. emit({ DeleteMarker: { index: dragged } }); } else if (anchor !== undefined) { @@ -601,6 +620,7 @@ } function addEvents() { + listening = true; document.addEventListener("pointermove", onPointerMove); document.addEventListener("pointerup", onPointerUp); document.addEventListener("mousedown", onMouseDown); @@ -609,6 +629,8 @@ } function removeEvents() { + listening = false; + historyStepStarted = false; document.removeEventListener("pointermove", onPointerMove); document.removeEventListener("pointerup", onPointerUp); document.removeEventListener("mousedown", onMouseDown); From e62977e73dcb53238f96faa302570e1848071bc4 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 10:23:45 +0000 Subject: [PATCH 18/47] Fix Alt-clicking the node already feeding the output blanking all the artwork (#4708) --- .../network_interface/characterization_tests.rs | 8 ++++---- .../utility_types/network_interface/mutations.rs | 13 +++++++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs index 3ca256aa03..b7d24ba9a9 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/characterization_tests.rs @@ -1353,15 +1353,15 @@ async fn toggle_preview_transitions_with_a_connected_export() { assert_eq!(export_node(network_interface), Some(artboard)); assert_eq!(network_interface.previewing(&[]), Previewing::No); - // Toggling the restore node while previewing promotes it to the export with nothing left to restore + // Toggling the restore node while previewing ends the preview by restoring it network_interface.toggle_preview(node, &[]); network_interface.toggle_preview(artboard, &[]); assert_eq!(export_node(network_interface), Some(artboard)); - assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None }); + assert_eq!(network_interface.previewing(&[]), Previewing::No); - // Toggling it once more ends the preview by disconnecting the export entirely + // Toggling the node already feeding the export changes nothing network_interface.toggle_preview(artboard, &[]); - assert_eq!(export_node(network_interface), None); + assert_eq!(export_node(network_interface), Some(artboard)); assert_eq!(network_interface.previewing(&[]), Previewing::No); assert_invariants(&editor, "after cycling through the preview states"); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs index dbc373783c..905d1accd5 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs @@ -1291,8 +1291,13 @@ impl NodeNetworkInterface { new_export = root_node_to_restore.map(|root_node| root_node.to_connector()); new_previewing_state = Previewing::No; } - // The export is clicked and there is no preview + // The export is clicked and there is no preview, so it already shows the primary output a preview would + else if previous_output_index == 0 { + return; + } + // The export is clicked and there is no preview, but it comes from another output, so preview the primary one and restore that afterward else { + new_export = Some(OutputConnector::primary_output(toggle_id)); new_previewing_state = Previewing::Yes { root_node_to_restore: Some(RootNode { node_id: previous_export_id, @@ -1309,10 +1314,10 @@ impl NodeNetworkInterface { if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) { // There is also a solid line being drawn if let Some(root_node_to_restore) = root_node_to_restore { - // If the node with the solid line is clicked, then start previewing that node without restore + // If the node with the solid line is clicked, then end the preview by restoring it if root_node_to_restore.node_id == toggle_id { - new_export = Some(OutputConnector::primary_output(toggle_id)); - new_previewing_state = Previewing::Yes { root_node_to_restore: None }; + new_export = Some(root_node_to_restore.to_connector()); + new_previewing_state = Previewing::No; } else { // Root node to restore does not change new_previewing_state = Previewing::Yes { From a89f1c5c9bc25ab2d9fdd0d4ce1f46f72f8ca354 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 11:00:47 +0000 Subject: [PATCH 19/47] Fix the Artboard tool resizing and nudging locked or hidden artboards (#4729) * Fix the Artboard tool resizing and nudging locked or hidden artboards * Test that the Artboard tool's lock guards hold before its overlays redraw --- .../tool/tool_messages/artboard_tool.rs | 66 +++++++++++++++++-- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/editor/src/messages/tool/tool_messages/artboard_tool.rs b/editor/src/messages/tool/tool_messages/artboard_tool.rs index 8f566c59c0..146d79bee1 100644 --- a/editor/src/messages/tool/tool_messages/artboard_tool.rs +++ b/editor/src/messages/tool/tool_messages/artboard_tool.rs @@ -237,6 +237,14 @@ impl ArtboardToolData { } } + /// The selected artboard, unless it's locked or hidden, which puts it out of reach of the tool as on the canvas. + fn editable_artboard(&self, document: &DocumentMessageHandler) -> Option { + let artboard = self.selected_artboard?; + let selected_nodes = document.network_interface.selected_nodes(); + let editable = selected_nodes.layer_visible(artboard, &document.network_interface) && !selected_nodes.layer_locked(artboard, &document.network_interface); + editable.then_some(artboard) + } + fn hovered_artboard(document: &DocumentMessageHandler, input: &InputPreprocessorMessageHandler, viewport: &ViewportMessageHandler) -> Option { document.click_xray(input, viewport).find(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[])) } @@ -329,14 +337,14 @@ impl Fsm for ArtboardToolFsmState { (state, ArtboardToolMessage::Overlays { context: mut overlay_context }) => { let display_transform_cage = overlay_context.visibility_settings.transform_cage(); if display_transform_cage && state != ArtboardToolFsmState::Drawing { - if let Some(bounds) = tool_data.selected_artboard.and_then(|layer| document.metadata().bounding_box_document(layer)) { + if let Some(bounds) = tool_data.editable_artboard(document).and_then(|layer| document.metadata().bounding_box_document(layer)) { let bounding_box_manager = tool_data.bounding_box_manager.get_or_insert(BoundingBoxManager::default()); bounding_box_manager.bounds = bounds; bounding_box_manager.transform = document.metadata().document_to_viewport; bounding_box_manager.render_overlays(&mut overlay_context, true); } else { - // If the bounding box is not resolved (e.g. if the artboard is deleted), then discard the bounding box. + // Without an editable artboard (one deleted, locked, or hidden), discard the bounding box tool_data.bounding_box_manager.take(); } } else { @@ -387,7 +395,8 @@ impl Fsm for ArtboardToolFsmState { self } (ArtboardToolFsmState::Ready { .. }, ArtboardToolMessage::PointerDown) => { - let state = if let Some(selected_edges) = tool_data.check_dragging_bounds(input.mouse.position) { + let resize_edges = tool_data.editable_artboard(document).and_then(|_| tool_data.check_dragging_bounds(input.mouse.position)); + let state = if let Some(selected_edges) = resize_edges { tool_data.start_resizing(selected_edges, document, input); // The artboard's own box follows the resize, while what is inside it stays put and can be snapped to @@ -580,7 +589,7 @@ impl Fsm for ArtboardToolFsmState { let Some(bounds) = &tool_data.bounding_box_manager else { return ArtboardToolFsmState::Ready { hovered }; }; - let Some(selected_artboard) = tool_data.selected_artboard else { + let Some(selected_artboard) = tool_data.editable_artboard(document) else { return ArtboardToolFsmState::Ready { hovered }; }; if selected_artboard == LayerNodeIdentifier::ROOT_PARENT { @@ -1127,4 +1136,53 @@ mod test_artboard { assert_bounds(&editor, artboard, [DVec2::new(104., 32.), DVec2::new(164., 76.)]); } + + #[tokio::test] + async fn a_locked_artboard_selected_in_the_layers_panel_cant_be_nudged_or_resized() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let artboard = draw_artboard(&mut editor, DVec2::new(100., 100.), DVec2::new(200., 160.)).await; + editor + .handle_message(NodeGraphMessage::SetLocked { + node_id: artboard.to_node(), + network_path: Vec::new(), + locked: true, + }) + .await; + + // Selected in the Layers panel, as the canvas leaves locked artboards out of reach + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![artboard.to_node()] }).await; + editor.handle_message(ArtboardToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.press(Key::ArrowRight, ModifierKeys::SHIFT).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + + // Where its bottom edge's handle would be + drag(&mut editor, DVec2::new(150., 160.), DVec2::new(150., 220.), ModifierKeys::empty()).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + } + + #[tokio::test] + async fn an_artboard_locked_while_its_cage_is_shown_cant_be_nudged_or_resized_before_the_overlays_redraw() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let artboard = draw_artboard(&mut editor, DVec2::new(100., 100.), DVec2::new(200., 160.)).await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![artboard.to_node()] }).await; + editor.handle_message(ArtboardToolMessage::Overlays { context: OverlayContext::default() }).await; + + // No overlay pass follows the lock, so the cage drawn before it is still there to grab + editor + .handle_message(NodeGraphMessage::SetLocked { + node_id: artboard.to_node(), + network_path: Vec::new(), + locked: true, + }) + .await; + + editor.press(Key::ArrowRight, ModifierKeys::SHIFT).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + + drag(&mut editor, DVec2::new(150., 160.), DVec2::new(150., 220.), ModifierKeys::empty()).await; + assert_bounds(&editor, artboard, [DVec2::new(100., 100.), DVec2::new(200., 160.)]); + } } From 64fc98e0d87054eeb3b72aea03571bc1707125f1 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 11:46:49 +0000 Subject: [PATCH 20/47] Fix canceling a Select tool pivot drag leaving the pivot where it was dragged (#4712) * Fix canceling a Select tool pivot drag leaving the pivot where it was dragged * Make keyboard transforms use the pivot Esc restored after the view pans --- .../tool/tool_messages/select_tool.rs | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/editor/src/messages/tool/tool_messages/select_tool.rs b/editor/src/messages/tool/tool_messages/select_tool.rs index 66ce265b73..8d5b16e254 100644 --- a/editor/src/messages/tool/tool_messages/select_tool.rs +++ b/editor/src/messages/tool/tool_messages/select_tool.rs @@ -17,7 +17,7 @@ use crate::messages::tool::common_functionality::color_selector::{ use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose}; use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::measure; -use crate::messages::tool::common_functionality::pivot::{PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget}; +use crate::messages::tool::common_functionality::pivot::{Pivot, PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget}; use crate::messages::tool::common_functionality::shape_editor::SelectionShapeType; use crate::messages::tool::common_functionality::snap_session::{BoxFeatures, FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView, snapping_hints}; use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget}; @@ -545,6 +545,8 @@ struct SelectToolData { bounding_box_manager: Option, cursor: MouseCursorIcon, pivot_gizmo: PivotGizmo, + /// The pivot as it was when a drag of it began, restored if the drag is aborted. + pivot_before_drag: Option, pivot_gizmo_start: Option, pivot_gizmo_shift: Option, compass_rose: CompassRose, @@ -1358,6 +1360,7 @@ impl Fsm for SelectToolFsmState { let state = if let Some(state) = tool_data.state_from_pivot_gizmo(input.mouse.position) { responses.add(DocumentMessage::StartTransaction); + tool_data.pivot_before_drag = Some(tool_data.pivot_gizmo.pivot.clone()); // The pivot snaps to the selected layers too, since they stay put while it moves snap_session.begin_gesture(SnapView::new(document, *document_id, input), Moving::default()); @@ -1463,6 +1466,19 @@ impl Fsm for SelectToolFsmState { (SelectToolFsmState::DraggingPivot, SelectToolMessage::Abort) => { responses.add(DocumentMessage::AbortTransaction); + // The pivot lives in the tool rather than the document, so aborting the transaction doesn't put it back + if let Some(pivot) = tool_data.pivot_before_drag.take() { + let reported = tool_data.pivot_gizmo.pivot.old_pivot_position; + tool_data.pivot_gizmo.pivot = pivot; + + let pivot_gizmo = tool_data.pivot_gizmo(); + responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo }); + responses.add(OverlaysMessage::Draw); + + // Only the tool keeps its last reported reference point, which makes the control bar refresh + tool_data.pivot_gizmo.pivot.old_pivot_position = reported; + } + let selection = tool_data.nested_selection_behavior; SelectToolFsmState::Ready { selection } } @@ -1817,6 +1833,7 @@ impl Fsm for SelectToolFsmState { let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON; let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction }; + tool_data.pivot_before_drag = None; let pivot_gizmo = tool_data.pivot_gizmo(); responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo }); @@ -3030,6 +3047,34 @@ mod test_select_tool { assert_bounds(&editor, layer, turned_bounds([from, to], middle, FRAC_PI_2)); } + #[tokio::test] + async fn a_typed_turn_after_escaping_a_pivot_drag_and_panning_goes_about_the_restored_pivot() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (from, to) = (DVec2::new(300., 300.), DVec2::new(420., 380.)); + let layer = draw_rectangle(&mut editor, from, to).await; + turn_on_the_pivot(&mut editor).await; + + // The pivot is taken out of the way, put back in the middle by Esc, then followed by a pan of the view + let middle = DVec2::new(360., 340.); + press_cage_at(&mut editor, middle).await; + move_to(&mut editor, DVec2::new(500., 220.), ModifierKeys::empty()).await; + editor.press(Key::Escape, ModifierKeys::empty()).await; + editor.left_mouseup(500., 220., ModifierKeys::empty()).await; + let pan = DVec2::new(40., -30.); + editor.handle_message(NavigationMessage::CanvasPan { delta: pan }).await; + editor.handle_message(SelectToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.move_mouse(600., 500., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.handle_message(TransformLayerMessage::BeginRotate).await; + for digit in [9, 0] { + editor.handle_message(TransformLayerMessage::TypeDigit { digit }).await; + } + editor.handle_message(TransformLayerMessage::ApplyTransformOperation { final_transform: true }).await; + + assert_bounds(&editor, layer, turned_bounds([from + pan, to + pan], middle + pan, FRAC_PI_2)); + } + fn snap_session(editor: &EditorTestUtils) -> &SnapSession { &editor.editor.dispatcher.message_handlers.tool_message_handler.snap_session } From 3f23ae7550947230cb5d98dd37526c8e9166d28d Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 14:07:29 +0000 Subject: [PATCH 21/47] Fix the Fill and Gradient tools painting over geometry wired from another layer (#4714) --- .../document/graph_operation/utility_types.rs | 4 +- .../graph_modification_utils.rs | 22 +++---- .../messages/tool/tool_messages/fill_tool.rs | 57 +++++++++++++++++++ .../tool/tool_messages/gradient_tool.rs | 57 +++++++++++++++++++ 4 files changed, 128 insertions(+), 12 deletions(-) diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index d5eb57eedc..8511b1076c 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -247,8 +247,8 @@ impl<'a> ModifyInputsContext<'a> { } /// Clear the whole-expanse paint one tool left on a layer so the other can start its own chain there. - /// Severing at the attachment detaches the layer from whatever the walk stopped at, which is the only part a node - /// the rest of the graph also draws from is subjected to, since such a node is never among those deleted. + /// Severing at the attachment detaches the layer from the old chain, which is all that a node the rest of + /// the graph also draws from is subjected to, since such a node is never among those deleted. fn clear_paint_chain(&mut self, paint_chain: &ReplaceablePaintChain) { self.network_interface.disconnect_input(&paint_chain.attachment_input, &[]); diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index 24a9dbe96a..7da430d59a 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -324,8 +324,8 @@ pub struct ReplaceablePaintChain { /// The whole-expanse paint on a 'Merge' layer that a paint tool may take over, or `None` /// when the layer isn't one or its chain holds anything the tools didn't put there. -/// The walk stops at the first node the rest of the graph also draws from, since repainting through it would change -/// what those other consumers see, and it passes through 'Transform' nodes so a swap keeps the layer's placement. +/// Nodes from the first one the rest of the graph also draws from are detached rather than deleted, so those other +/// consumers see no change, and the walk passes through 'Transform' nodes so a swap keeps the layer's placement. pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option { if !network_interface.is_merge(&layer.to_node(), &[]) { return None; @@ -344,17 +344,17 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N let mut input = InputConnector::layer_secondary_input(layer.to_node()); // Trails the walk over the 'Transform' nodes that survive, then holds still once the paint to clear away begins let mut attachment_input = input; + // Everything upstream of a shared node is shared too, so it's kept, though it must still be paint for the layer to count as blank + let mut shared = false; while let Some(upstream) = network_interface.upstream_output_connector(&input, &[]) { let node_id = upstream.node_id()?; // Arriving here means this layer consumes the node, so a further consumer makes it shared - let shared = network_interface - .with_outward_wires(&[], |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).is_some_and(|inputs| inputs.len() > 1)) - .unwrap_or(true); - if shared { - break; - } + shared = shared + || network_interface + .with_outward_wires(&[], |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).is_some_and(|inputs| inputs.len() > 1)) + .unwrap_or(true); let Some(DefinitionIdentifier::ProtoNode(identifier)) = network_interface.reference(&node_id, &[]) else { return None; @@ -362,7 +362,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N if identifier == graphene_std::transform_nodes::transform::IDENTIFIER { input = InputConnector::primary_input(node_id); - if nodes.is_empty() { + if nodes.is_empty() && !shared { attachment_input = input; } continue; @@ -373,7 +373,9 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N return None; } - nodes.push(node_id); + if !shared { + nodes.push(node_id); + } if generator { break; diff --git a/editor/src/messages/tool/tool_messages/fill_tool.rs b/editor/src/messages/tool/tool_messages/fill_tool.rs index 574e97bd4d..48a2435922 100644 --- a/editor/src/messages/tool/tool_messages/fill_tool.rs +++ b/editor/src/messages/tool/tool_messages/fill_tool.rs @@ -571,6 +571,63 @@ mod test_fill { ); } + #[tokio::test] + async fn a_layer_drawing_shared_geometry_keeps_it() { + use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; + use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_color_value_node_id; + use graph_craft::document::NodeId; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + let rectangle = editor.active_document().metadata().all_layers().next().unwrap(); + + // A new layer above the rectangle, whose content is wired from the end of the rectangle's chain so both draw it + let sharing_id = NodeId::new(); + editor + .handle_message(GraphOperationMessage::NewCustomLayer { + id: sharing_id, + nodes: Vec::new(), + parent: LayerNodeIdentifier::ROOT_PARENT, + insert_index: 0, + }) + .await; + let sharing = LayerNodeIdentifier::new_unchecked(sharing_id); + let shared_id = editor + .active_document() + .network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(rectangle.to_node()), &[]) + .and_then(|output| output.node_id()) + .expect("the rectangle should have a chain"); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(shared_id), &InputConnector::layer_secondary_input(sharing_id), &[]); + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![sharing_id] }).await; + + editor.select_primary_color(Color::GREEN).await; + editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(50., 50.), ModifierKeys::empty()).await; + + let network_interface = &editor.active_document().network_interface; + assert!( + get_upstream_color_value_node_id(sharing, network_interface).is_none(), + "a layer drawing shared geometry isn't blank, so it mustn't get a whole-expanse color" + ); + assert_eq!( + network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(sharing_id), &[]) + .and_then(|output| output.node_id()), + Some(shared_id), + "the layer should still draw the shared rectangle" + ); + + let fills = get_fills(&mut editor).await; + assert!( + fills.iter().any(|fill| SRGBA8::from(*fill.element()) == SRGBA8::from(Color::GREEN)), + "the shared rectangle's Fill should take the color" + ); + } + #[tokio::test] async fn nudged_blank_layer_keeps_its_transform() { use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index af02c3b050..94e9d5ca21 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -3361,6 +3361,63 @@ mod test_gradient { assert_eq!(stops.len(), 2); } + #[tokio::test] + async fn drag_on_a_layer_drawing_shared_geometry_paints_its_fill() { + use graph_craft::document::NodeId; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await; + let rectangle = editor.active_document().metadata().all_layers().next().unwrap(); + + // A new layer above the rectangle, whose content is wired from the end of the rectangle's chain so both draw it + let sharing_id = NodeId::new(); + editor + .handle_message(GraphOperationMessage::NewCustomLayer { + id: sharing_id, + nodes: Vec::new(), + parent: LayerNodeIdentifier::ROOT_PARENT, + insert_index: 0, + }) + .await; + let sharing = LayerNodeIdentifier::new_unchecked(sharing_id); + let shared_id = editor + .active_document() + .network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(rectangle.to_node()), &[]) + .and_then(|output| output.node_id()) + .expect("the rectangle should have a chain"); + editor + .active_document_mut() + .network_interface + .create_wire(&OutputConnector::primary_output(shared_id), &InputConnector::layer_secondary_input(sharing_id), &[]); + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![sharing_id] }).await; + + editor.drag_tool(ToolType::Gradient, 10., 50., 90., 50., ModifierKeys::empty()).await; + + let network_interface = &editor.active_document().network_interface; + assert!( + get_upstream_gradient_value_node_id(sharing, network_interface).is_none(), + "a layer drawing shared geometry isn't blank, so it mustn't get a whole-expanse gradient" + ); + assert_eq!( + network_interface + .upstream_output_connector(&InputConnector::layer_secondary_input(sharing_id), &[]) + .and_then(|output| output.node_id()), + Some(shared_id), + "the layer should still draw the shared rectangle" + ); + + let fill_node_id = get_fill_node_id_with_direct_fill_input(rectangle, network_interface).expect("the rectangle should have a Fill node"); + let paint = network_interface + .document_network() + .nodes + .get(&fill_node_id) + .and_then(|node| node.input(fill::PaintInput)) + .and_then(|input| input.as_value()); + assert!(matches!(paint, Some(TaggedValue::GradientRamp(_))), "the shared rectangle's Fill should take the gradient"); + } + #[tokio::test] async fn replaces_a_whole_expanse_color_with_a_gradient() { use crate::messages::tool::common_functionality::graph_modification_utils::{get_gradient_stops, get_upstream_color_value_node_id}; From 5ba834f92c4ee2661c9f6b81794468b2a9fa56fc Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 14:08:02 +0000 Subject: [PATCH 22/47] Fix a crash when hiding a node that has nothing flowing into it (#4716) --- node-graph/graph-craft/src/document.rs | 88 +++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 2 deletions(-) diff --git a/node-graph/graph-craft/src/document.rs b/node-graph/graph-craft/src/document.rs index 51034f7434..fc9a1d8fed 100644 --- a/node-graph/graph-craft/src/document.rs +++ b/node-graph/graph-craft/src/document.rs @@ -916,20 +916,29 @@ impl NodeNetwork { if !node.visible && node.implementation != passthrough_node { node.implementation = passthrough_node; - // Connect layer node to the group below + // A node without inputs has nothing to pass through, so it passes through the unit value instead + if node.inputs.is_empty() { + node.inputs.push(NodeInput::value(TaggedValue::None, false)); + } + + // Keep only the primary input, which the passthrough forwards let removed_inputs = node.inputs.split_off(1); // Remove the dependants on the ignored inputs for removed_input in removed_inputs { if let NodeInput::Node { node_id, output_index } = removed_input && let Some(former_dependency) = self.nodes.get_mut(&node_id) - // Ensure that the other node inputs do not also reference the dependancy + // Ensure that the other node inputs do not also reference the dependency && !node.inputs.iter().any(|input| matches!(input, NodeInput::Node { node_id: other, .. } if *other == node_id)) { former_dependency.original_location.dependants[output_index].retain(|&dependant| dependant != id); } } + // Removing the passthrough later splices its input into its consumers, which accept only node wires, so an unwired input becomes a value node + let path = node.original_location.path.clone().unwrap_or_default(); + Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id); + node.call_argument = concrete!(()); self.nodes.insert(id, node); return; @@ -1772,5 +1781,80 @@ mod test { network.validate_dependants(); } + /// A hidden node with nothing wired into it (a layer chain's first node, or a generator) feeding a node with several inputs. + fn hidden_source_network(source_inputs: Vec) -> NodeNetwork { + NodeNetwork { + exports: vec![NodeInput::node(NodeId(2), 0)], + nodes: [ + ( + NodeId(1), + DocumentNode { + inputs: source_inputs, + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Source")), + visible: false, + ..Default::default() + }, + ), + ( + NodeId(2), + DocumentNode { + inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(2.), false)], + implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Consumer")), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + } + } + + // Flattens and strips passthroughs as the compiler does, then resolves the proto nodes, where an unwired input would panic + fn compile_hidden_source(mut network: NodeNetwork) -> ProtoNetwork { + network.generate_node_paths(&[]); + network.populate_dependants(); + let ids: Vec<_> = network.nodes.keys().copied().collect(); + ids.into_iter() + .for_each(|id| network.flatten_with_fns(id, |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_node_id)); + network.remove_all_passthrough_nodes(); + network.into_proto_networks().next().expect("The network should give a proto network") + } + + #[test] + fn hidden_node_with_an_unwired_input_passes_its_value() { + let proto_network = compile_hidden_source(hidden_source_network(vec![NodeInput::value(TaggedValue::Number(1.), true)])); + + // The consumer's first input is now a value node holding the hidden node's unwired value + let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain"); + let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else { + panic!("The consumer should take node inputs") + }; + let value_node = proto_network + .nodes + .iter() + .find(|(id, _)| *id == inputs[0]) + .map(|(_, node)| node) + .expect("The consumer's first input should be a node"); + assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::Number(1.))); + } + + #[test] + fn hidden_node_without_inputs_passes_the_unit_value() { + let proto_network = compile_hidden_source(hidden_source_network(vec![])); + + let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain"); + let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else { + panic!("The consumer should take node inputs") + }; + let value_node = proto_network + .nodes + .iter() + .find(|(id, _)| *id == inputs[0]) + .map(|(_, node)| node) + .expect("The consumer's first input should be a node"); + assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::None)); + } + // TODO: Write more tests } From b796a326173da808f512afcb3b70094d3a86d0f9 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 14:22:55 +0000 Subject: [PATCH 23/47] Fix the Line tool reversing a new line Ctrl-dragged from a selected line's end (#4727) --- .../messages/tool/tool_messages/shape_tool.rs | 50 +++++++++++++++---- 1 file changed, 40 insertions(+), 10 deletions(-) diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index ccbac07d6f..fa20406008 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -1052,7 +1052,8 @@ impl Fsm for ShapeToolFsmState { tool_data.line_data.drag_current = mouse_pos; - if tool_data.gizmo_manager.handle_click() && !input.keyboard.key(Key::Accel) { + // The modifiers are checked first in these, as the gizmo and line end checks mark what they find as being dragged + if !input.keyboard.key(Key::Accel) && tool_data.gizmo_manager.handle_click() { tool_data.data.drag_start = document.metadata().document_to_viewport.inverse().transform_point2(mouse_pos); snap_session.begin_gesture(SnapView::new(document, *document_id, input), Moving::default()); responses.add(DocumentMessage::StartTransaction); @@ -1071,14 +1072,14 @@ impl Fsm for ShapeToolFsmState { } // If clicked on endpoints of a selected line or arrow, drag its endpoints - if let Some((layer, _, _)) = closest_point( - document, - mouse_pos, - SNAP_POINT_TOLERANCE, - document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface), - |_| false, - ) && clicked_on_shape_endpoints(layer, document, input, tool_data) - && !input.keyboard.key(Key::Control) + if !input.keyboard.key(Key::Control) + && let Some((layer, _, _)) = closest_point( + document, + mouse_pos, + SNAP_POINT_TOLERANCE, + document.network_interface.selected_nodes().selected_visible_and_unlocked_layers(&document.network_interface), + |_| false, + ) && clicked_on_shape_endpoints(layer, document, input, tool_data) { responses.add(DocumentMessage::StartTransaction); @@ -1595,10 +1596,11 @@ fn update_dynamic_hints(state: &ShapeToolFsmState, responses: &mut VecDeque Date: Thu, 15 Oct 2026 14:31:28 +0000 Subject: [PATCH 24/47] Fix the Shape tool grabbing an invisible leftover transform cage instead of drawing (#4725) * Fix the Shape tool grabbing an invisible leftover transform cage instead of drawing * Keep a leftover Shape tool cage from catching a press before overlays redraw --- .../messages/tool/tool_messages/shape_tool.rs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/editor/src/messages/tool/tool_messages/shape_tool.rs b/editor/src/messages/tool/tool_messages/shape_tool.rs index fa20406008..3bef7104bc 100644 --- a/editor/src/messages/tool/tool_messages/shape_tool.rs +++ b/editor/src/messages/tool/tool_messages/shape_tool.rs @@ -919,6 +919,9 @@ impl Fsm for ShapeToolFsmState { Arrow::overlays(document, tool_data, input.mouse.position, &mut overlay_context); if all_selected_layers_line_or_arrow { + // Lines, arrows, and an empty selection have no cage, so an earlier selection's cage mustn't stay behind to catch presses + tool_data.bounding_box_manager = None; + let cursor = if hovering_over_endpoint { MouseCursorIcon::Default } else { MouseCursorIcon::Crosshair }; tool_data.cursor = cursor; responses.add(FrontendMessage::UpdateMouseCursor { cursor }); @@ -1092,6 +1095,11 @@ impl Fsm for ShapeToolFsmState { return ShapeToolFsmState::DraggingLineEndpoints; } + // The overlay pass that clears it may not have run since the selection changed + if all_selected_layers_line_or_arrow { + tool_data.bounding_box_manager = None; + } + let (resize, rotate, skew) = transforming_transform_cage(document, &mut tool_data.bounding_box_manager, input, responses, &mut tool_data.layers_dragging, None); if !input.keyboard.key(Key::Control) { @@ -2188,6 +2196,59 @@ mod test_shape_tool { editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await; } + #[tokio::test] + async fn a_drag_from_where_a_cage_was_draws_once_the_selection_has_no_cage() { + for leave_cage in [DocumentMessage::Undo, DocumentMessage::DeselectAllLayers] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(300., 300., 400., 380.).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.handle_message(leave_cage).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.draw_rect(400., 380., 480., 440.).await; + let layer = editor.get_selected_layer().await.expect("the drag should draw a rectangle"); + assert_bounds(&editor, layer, [DVec2::new(400., 380.), DVec2::new(480., 440.)]); + } + } + + #[tokio::test] + async fn a_drag_from_where_a_cage_was_draws_before_the_overlays_next_update() { + for leave_cage in [DocumentMessage::Undo, DocumentMessage::DeselectAllLayers, DocumentMessage::DeleteSelectedLayers] { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(300., 300., 400., 380.).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + // The press comes within the same frame, or with overlays hidden, so no overlay pass clears the cage first + editor.handle_message(leave_cage).await; + + editor.draw_rect(400., 380., 480., 440.).await; + let layer = editor.get_selected_layer().await.expect("the drag should draw a rectangle"); + assert_bounds(&editor, layer, [DVec2::new(400., 380.), DVec2::new(480., 440.)]); + } + } + + #[tokio::test] + async fn a_drag_from_where_a_cage_was_draws_once_only_a_line_is_selected() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(300., 300., 400., 380.).await; + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.drag_tool(ToolType::Line, 100., 100., 200., 100., ModifierKeys::empty()).await; + let line = editor.get_selected_layer().await.expect("the line drawn should be selected"); + let line_bounds = editor.active_document().metadata().bounding_box_viewport(line); + editor.handle_message(ShapeToolMessage::Overlays { context: OverlayContext::default() }).await; + + editor.draw_rect(400., 380., 480., 440.).await; + let layer = editor.get_selected_layer().await.expect("the drag should draw a rectangle"); + assert_ne!(layer, line, "the drag should draw a new layer rather than change the line"); + assert_bounds(&editor, layer, [DVec2::new(400., 380.), DVec2::new(480., 440.)]); + assert_eq!(editor.active_document().metadata().bounding_box_viewport(line), line_bounds, "the line should be left as it was"); + } + /// Presses at one viewport position, drags halfway to another, sends a tool key's message, then finishes the drag. async fn drag_pressing_mid_way(editor: &mut EditorTestUtils, from: DVec2, to: DVec2, key_message: ToolMessage) { let halfway = from.midpoint(to); From 006807fafeb417a435bf70142ab30b31f52bcefd Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 18:15:51 +0000 Subject: [PATCH 25/47] Fix Delete mid-drag in the Gradient tool so it restores the original line but removes the end segment (#4710) --- .../tool/tool_messages/gradient_tool.rs | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index 94e9d5ca21..e779f93fb5 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -1185,9 +1185,10 @@ impl Fsm for GradientToolFsmState { return ready_default; } - // If we're in the middle of a drag, abort it first and revert to the initial gradient + // If we're in the middle of a drag, abort it first and revert to the gradient as it began if matches!(state, GradientToolFsmState::Drawing { .. }) { selected_gradient.gradient = selected_gradient.initial_gradient.clone(); + selected_gradient.appearance.transform = selected_gradient.initial_gradient_transform; selected_gradient.render_gradient(responses); responses.add(DocumentMessage::AbortTransaction); } @@ -2782,6 +2783,34 @@ mod test_gradient { ); } + #[tokio::test] + async fn delete_mid_drag_of_an_end_restores_its_line() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.active_document_mut().snapping_state.snapping_enabled = false; + + editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await; + editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await; + + // A middle stop, so deleting an end leaves a gradient + editor.move_mouse(60., 0., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(60., 0., ModifierKeys::empty()).await; + editor.left_mouseup(60., 0., ModifierKeys::empty()).await; + + // Drag the end down, then press Delete before releasing + editor.move_mouse(100., 0., ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(100., 0., ModifierKeys::empty()).await; + editor.move_mouse(100., 50., ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.press(Key::Delete, ModifierKeys::empty()).await; + editor.left_mouseup(100., 50., ModifierKeys::empty()).await; + + let (gradient, transform) = get_gradient_from_fill(&mut editor).await; + assert_eq!(gradient.stops.len(), 2, "the end stop should be deleted"); + let (start, end) = (transform.transform_point2(gradient.start()), transform.transform_point2(gradient.end())); + assert!(start.abs_diff_eq(DVec2::new(0., 0.), 1e-6), "the start should stay put, got {start:?}"); + assert!(end.abs_diff_eq(DVec2::new(60., 0.), 1e-6), "the line should end at the middle stop on the undragged line, got {end:?}"); + } + #[tokio::test] async fn delete_removes_layer_when_no_stop_selected() { let mut editor = EditorTestUtils::create(); From 243a83ce1743809e124aca8d4c0b08a3b2ddb127 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Thu, 15 Oct 2026 18:18:47 +0000 Subject: [PATCH 26/47] Fix multi user undo model (#4639) * Undo by restoring each step's exact prior state, and only this user's own steps * Split up prior variants --- document/graph-storage/src/attributes.rs | 4 +- document/graph-storage/src/crdt.rs | 26 +- document/graph-storage/src/document.rs | 196 ++----------- document/graph-storage/src/lib.rs | 2 + document/graph-storage/src/prior.rs | 339 +++++++++++++++++++++++ document/graph-storage/src/registry.rs | 2 + document/graph-storage/src/resources.rs | 13 +- document/graph-storage/src/session.rs | 93 +++---- document/graph-storage/src/tests/crdt.rs | 287 +++++++++++++------ node-graph/rfcs/document-format.md | 11 +- 10 files changed, 622 insertions(+), 351 deletions(-) create mode 100644 document/graph-storage/src/prior.rs diff --git a/document/graph-storage/src/attributes.rs b/document/graph-storage/src/attributes.rs index 5c4d8af165..568508535e 100644 --- a/document/graph-storage/src/attributes.rs +++ b/document/graph-storage/src/attributes.rs @@ -102,10 +102,10 @@ impl Attributes { /// Lands a single-key write if it is newer than the key's value, or than the floor for a key the map lacks. A /// deletion leaves a tombstone. - pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp, force: bool) { + pub(crate) fn apply_delta(&mut self, delta: AttributeDelta, timestamp: TimeStamp) { let AttributeDelta { key, value } = delta; let decided = self.get(&key).map_or(self.floor, |existing| existing.timestamp); - if !force && timestamp <= decided { + if timestamp <= decided { return; } let entry = match value { diff --git a/document/graph-storage/src/crdt.rs b/document/graph-storage/src/crdt.rs index 2c1d308cc2..4eb23f3c05 100644 --- a/document/graph-storage/src/crdt.rs +++ b/document/graph-storage/src/crdt.rs @@ -1,4 +1,6 @@ -use crate::{Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev}; +use crate::{ + Attributes, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Prior, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev, +}; use graphene_resource::ResourceHash; use serde::{Deserialize, Serialize}; @@ -13,7 +15,8 @@ pub struct Delta { pub author: PeerId, pub timestamp: TimeStamp, pub kind: RegistryDelta, - pub reverse: RegistryDelta, + /// What every slot `kind` wrote held before it, stamps included, in write order. See [`Prior`]. + pub reverse: Vec, /// Local, mutable annotations on this commit (interaction-end marker, future commit messages / labels). /// Deliberately excluded from `compute_rev`: relabeling a commit must not change its content-addressed /// identity, and two peers annotating the same op differently must still dedup to one `Rev`. @@ -26,7 +29,7 @@ pub struct Delta { } impl Delta { - pub fn new(parent: Option, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: RegistryDelta) -> Self { + pub fn new(parent: Option, author: PeerId, timestamp: TimeStamp, kind: RegistryDelta, reverse: Vec) -> Self { let id = compute_rev(parent, author, timestamp, &kind); Self { id, @@ -54,7 +57,7 @@ impl Delta { parent, author, timestamp, - reverse: kind.clone(), + reverse: Vec::new(), kind, attributes: Attributes::default(), retired_at_ms: 0, @@ -219,26 +222,13 @@ pub struct AttributeDelta { pub value: Option, } -pub(crate) fn reverse_attribute_delta(delta: &AttributeDelta, attributes: &Attributes) -> AttributeDelta { - AttributeDelta { - key: delta.key.clone(), - value: attributes.get(&delta.key).filter(|previous| !previous.deleted).map(|previous| previous.value.clone()), - } -} - #[cfg(test)] mod tests { use super::*; #[test] fn unrecorded_retired_at_costs_one_byte_and_round_trips() { - let base = Delta::new( - None, - PeerId(1), - TimeStamp { counter: 1, peer: PeerId(1) }, - RegistryDelta::Other(Value::None), - RegistryDelta::Other(Value::None), - ); + let base = Delta::new(None, PeerId(1), TimeStamp { counter: 1, peer: PeerId(1) }, RegistryDelta::Other(Value::None), Vec::new()); let mut stamped = base.clone(); stamped.retired_at_ms = 1_790_000_000_000; diff --git a/document/graph-storage/src/document.rs b/document/graph-storage/src/document.rs index 9a349c7bd1..0e3ca48836 100644 --- a/document/graph-storage/src/document.rs +++ b/document/graph-storage/src/document.rs @@ -3,9 +3,8 @@ use std::hash::Hash; use crate::{ Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput, - PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId, Value, reverse_attribute_delta, + PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId, }; -use std::borrow::Cow; #[derive(Clone, Debug)] pub struct Document { @@ -76,17 +75,12 @@ impl Document { NodeId(u64::from_le_bytes(truncated)) } - /// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural - /// ops are idempotent, and LWW arms assign the reverse value unconditionally even though it carries - /// the same timestamp as the forward op it undoes. - pub(crate) fn revert_delta(&mut self, target: RegistryTarget, mut delta: Delta) -> Result<(), CrdtError> { - for parent in delta.all_parents() { - if !self.history.contains(parent) { - return Err(CrdtError::NotFoundInHistory(parent)); - } + /// Undo `delta` by putting back what it overwrote: in the snapshot, and in the working registry when nothing is hot. + pub(crate) fn revert_delta(&mut self, delta: &Delta) { + crate::prior::restore(&mut self.retired_snapshot, &delta.reverse); + if self.hot_log.is_empty() { + crate::prior::restore(&mut self.working_registry, &delta.reverse); } - std::mem::swap(&mut delta.kind, &mut delta.reverse); - self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force) } /// Stage a local op onto the working registry and the hot log, skipping the retired check so local work is never dropped. @@ -190,13 +184,6 @@ impl Document { self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent) } - /// Silent-zone undo/redo rewind against the working registry: structural ops are idempotent, and - /// LWW arms assign unconditionally. We own the single-writer chain here, so the precomputed reverse - /// (undo) or forward (redo) value is authoritative even though its timestamp ties what it replaces. - pub(crate) fn force_apply_op(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> { - self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Force) - } - /// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order: /// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an /// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives. @@ -206,7 +193,6 @@ impl Document { self.clock.observe(timestamp); let strict = mode == ApplyMode::Strict; - let force = mode == ApplyMode::Force; let registry = self.registry_mut(target); match op { @@ -215,10 +201,10 @@ impl Document { return Err(CrdtError::NodeAlreadyExists(id)); } write_network(registry, node.network, timestamp, mode, |_| Ok(()))?; - add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp, force); + add_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, node, timestamp); } RegistryDelta::RemoveNode { id, snapshot } => { - remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp, force); + remove_entity(&mut registry.node_instances, &mut registry.removed_nodes, id, snapshot, timestamp); } RegistryDelta::SetNodeInputs { id, mut inputs } => { inputs.iter_mut().for_each(|slot| stamp_listed_slot(slot, timestamp)); @@ -231,12 +217,7 @@ impl Document { .collect(); ensure_seen(registry, &referenced, mode)?; write_node(registry, id, timestamp, mode, |node| { - if force { - node.inputs = inputs; - node.inputs_timestamp = timestamp; - } else { - merge_inputs(node, inputs, timestamp); - } + merge_inputs(node, inputs, timestamp); Ok(()) })?; for referenced in referenced { @@ -251,7 +232,7 @@ impl Document { ensure_seen(registry, referenced.as_slice(), mode)?; write_node(registry, id, timestamp, mode, |node| { let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) }; - if force || timestamp > input.timestamp { + if timestamp > input.timestamp { input.input = new_input; input.timestamp = timestamp; } @@ -267,7 +248,7 @@ impl Document { write_network(registry, network, timestamp, mode, |_| Ok(()))?; } write_node(registry, id, timestamp, mode, |node| { - if force || timestamp > node.implementation_timestamp { + if timestamp > node.implementation_timestamp { node.implementation = implementation; node.implementation_timestamp = timestamp; } @@ -276,14 +257,14 @@ impl Document { } RegistryDelta::ChangeNodeAttribute { id, delta } => { write_node(registry, id, timestamp, mode, |node| { - node.attributes.apply_delta(delta, timestamp, force); + node.attributes.apply_delta(delta, timestamp); Ok(()) })?; } RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => { write_node(registry, id, timestamp, mode, |node| { let Some(input) = slot_for_write(node, index as usize, timestamp, mode)? else { return Ok(()) }; - input.attributes.apply_delta(delta, timestamp, force); + input.attributes.apply_delta(delta, timestamp); Ok(()) })?; } @@ -300,7 +281,7 @@ impl Document { return Err(CrdtError::ExportSlotOutOfBounds(index)); } // Past the end of a newer list the slot is gone, as with input slots. - if !force && timestamp <= net.exports_timestamp { + if timestamp <= net.exports_timestamp { return Ok(()); } let shape = net.exports_timestamp; @@ -308,7 +289,7 @@ impl Document { } let existing = &mut net.exports[slot_idx]; - if force || timestamp > existing.timestamp { + if timestamp > existing.timestamp { existing.target = export; existing.timestamp = timestamp; } @@ -322,20 +303,20 @@ impl Document { if strict && registry.networks.contains_key(&id) { return Err(CrdtError::NetworkAlreadyExists(id)); } - add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp, force); + add_entity(&mut registry.networks, &mut registry.removed_networks, id, network, timestamp); } RegistryDelta::RemoveNetwork { id, snapshot } => { - remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp, force); + remove_entity(&mut registry.networks, &mut registry.removed_networks, id, snapshot, timestamp); } RegistryDelta::ChangeNetworkAttribute { id, delta } => { write_network(registry, id, timestamp, mode, |net| { - net.attributes.apply_delta(delta, timestamp, force); + net.attributes.apply_delta(delta, timestamp); Ok(()) })?; } RegistryDelta::SetResourceHash { id, hash } => { upsert_resource(registry, id, timestamp, |entry| { - if force || timestamp > entry.hash_timestamp { + if timestamp > entry.hash_timestamp { entry.hash = hash; entry.hash_timestamp = timestamp; } @@ -344,24 +325,20 @@ impl Document { RegistryDelta::AddSource { id, key, source } => { upsert_resource(registry, id, timestamp, |entry| { let value = SourceValue { source, timestamp, deleted: false }; - if force { entry.force_set_source(key, value) } else { entry.set_source(key, value) } + entry.set_source(key, value); }); } RegistryDelta::RemoveSource { id, key } => { // An upsert, so a removal for an entry never seen leaves a tombstone its addition loses to. upsert_resource(registry, id, timestamp, |entry| { - if force { - entry.force_remove_source(&key); - } else { - entry.remove_source(&key, timestamp); - } + entry.remove_source(&key, timestamp); }); } RegistryDelta::AddResource { id, entry } => { - add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp, force); + add_entity(&mut registry.resources, &mut registry.removed_resources, id, entry, timestamp); } RegistryDelta::RemoveResource { id, snapshot } => { - remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp, force); + remove_entity(&mut registry.resources, &mut registry.removed_resources, id, snapshot, timestamp); } RegistryDelta::RegisterPeer { peer, user } => { // The newest registration of a device wins, whatever order they land in. @@ -370,117 +347,13 @@ impl Document { } } RegistryDelta::ChangeDocumentAttribute { delta } => { - registry.attributes.apply_delta(delta, timestamp, force); + registry.attributes.apply_delta(delta, timestamp); } // Merge is a structural sync point only; it mutates no registry state. RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {} } Ok(()) } - - /// Compute the inverse of `delta` against the registry named by `target`. Retirement passes - /// [`RegistryTarget::Retired`] so LWW reverses (export target, inputs, attributes, resource hash) - /// capture the true pre-op value rather than the hot-polluted working state. - /// - /// A write reads its pre-op value from wherever it lands: the live entity, its tombstone, or for an - /// entity never seen, a placeholder. - pub(crate) fn compute_reverse_delta(&self, target: RegistryTarget, delta: &RegistryDelta) -> Result { - let registry = self.registry_ref(target); - let node = |id: NodeId| registry.node_or_removed(id).map_or_else(|| Cow::Owned(Node::placeholder()), Cow::Borrowed); - let unset = InputSlot::unset(TimeStamp::ORIGIN); - let network = |id: NetworkId| registry.network_or_removed(id); - let resource = |id: ResourceId| registry.resources.get(&id).or_else(|| registry.removed_resources.get(&id).map(|mark| &mark.content)); - Ok(match delta { - RegistryDelta::AddNode { id, node } => RegistryDelta::RemoveNode { id: *id, snapshot: node.clone() }, - RegistryDelta::RemoveNode { id, snapshot } => RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, - &RegistryDelta::SetNodeInputs { id, .. } => RegistryDelta::SetNodeInputs { id, inputs: node(id).inputs.clone() }, - &RegistryDelta::SetNodeImplementation { id, .. } => RegistryDelta::SetNodeImplementation { - id, - implementation: node(id).implementation.clone(), - }, - &RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => { - let node = node(id); - let slot = node.inputs().get(input_idx as usize).unwrap_or(&unset); - RegistryDelta::ChangeNodeInput { - id, - index: input_idx, - new_input: slot.input.clone(), - } - } - &RegistryDelta::ChangeNodeAttribute { id, ref delta } => RegistryDelta::ChangeNodeAttribute { - id, - delta: reverse_attribute_delta(delta, node(id).attributes()), - }, - &RegistryDelta::ChangeNodeInputAttribute { id, index, ref delta } => { - let node = node(id); - let input = node.inputs().get(index as usize).unwrap_or(&unset); - RegistryDelta::ChangeNodeInputAttribute { - id, - index, - delta: reverse_attribute_delta(delta, &input.attributes), - } - } - &RegistryDelta::SetNetworkExport { id, index, .. } => { - // Absent network or slot: pre-op there was no export to point at. - let export_target = network(id).and_then(|net| net.exports.get(index as usize)).and_then(|s| s.target.clone()); - RegistryDelta::SetNetworkExport { id, index, export: export_target } - } - RegistryDelta::AddNetwork { id, network } => RegistryDelta::RemoveNetwork { id: *id, snapshot: network.clone() }, - &RegistryDelta::RemoveNetwork { id, ref snapshot } => RegistryDelta::AddNetwork { id, network: snapshot.clone() }, - &RegistryDelta::ChangeNetworkAttribute { id, ref delta } => { - let empty = Attributes::new(); - let current = network(id).map_or(&empty, |net| &net.attributes); - RegistryDelta::ChangeNetworkAttribute { - id, - delta: reverse_attribute_delta(delta, current), - } - } - RegistryDelta::ChangeDocumentAttribute { delta } => RegistryDelta::ChangeDocumentAttribute { - delta: reverse_attribute_delta(delta, ®istry.attributes), - }, - // Registrations are append-only and not user-undoable; reverse is the same op, - // which applies as a no-op on the already-registered PeerId. - &RegistryDelta::RegisterPeer { peer, user } => RegistryDelta::RegisterPeer { peer, user }, - &RegistryDelta::SetResourceHash { id, .. } => RegistryDelta::SetResourceHash { - id, - hash: resource(id).and_then(|entry| entry.hash), - }, - &RegistryDelta::AddSource { id, key, .. } => match resource(id).and_then(|entry| entry.source(&key)) { - // The slot already held a source: undo restores it. - Some(existing) => RegistryDelta::AddSource { - id, - key, - source: existing.source.clone(), - }, - // The slot was empty: undo removes what this op added. - None => RegistryDelta::RemoveSource { id, key }, - }, - &RegistryDelta::RemoveSource { id, key } => match resource(id).and_then(|entry| entry.source(&key)) { - Some(existing) => RegistryDelta::AddSource { - id, - key, - source: existing.source.clone(), - }, - // Nothing to restore; reverse is a no-op removal. - None => RegistryDelta::RemoveSource { id, key }, - }, - &RegistryDelta::AddResource { id, .. } => match registry.resources.get(&id) { - // Overwrote an existing entry: undo restores it. - Some(existing) => RegistryDelta::AddResource { id, entry: existing.clone() }, - // Created a new entry: undo removes what this op added (snapshot is empty since there was nothing prior). - None => RegistryDelta::RemoveResource { - id, - snapshot: ResourceEntry::default(), - }, - }, - &RegistryDelta::RemoveResource { id, .. } => { - let snapshot = registry.resources.get(&id).cloned().unwrap_or_default(); - RegistryDelta::AddResource { id, entry: snapshot } - } - RegistryDelta::Merge { extra_parents } => RegistryDelta::Merge { extra_parents: extra_parents.clone() }, - &RegistryDelta::Other(_) => RegistryDelta::Other(Value::None), - }) - } } /// An entity whose existence and every field are last-writer-wins on a timestamp. @@ -649,7 +522,7 @@ fn slot_for_write(node: &mut Node, index: usize, timestamp: TimeStamp, mode: App if index >= MAX_INPUT_SLOTS || mode == ApplyMode::Strict { return Err(CrdtError::InputIndexOutOfBounds(index)); } - if mode != ApplyMode::Force && timestamp <= node.inputs_timestamp { + if timestamp <= node.inputs_timestamp { return Ok(None); } let shape = node.inputs_timestamp; @@ -688,23 +561,18 @@ fn merge_entity(live: &mut HashMap, dead: } /// An addition at `timestamp`: every field written at `timestamp`, live unless a newer removal holds it dead. -fn add_entity(live: &mut HashMap, dead: &mut HashMap>, id: K, mut content: T, timestamp: TimeStamp, force: bool) { - if force { - dead.remove(&id); - live.insert(id, content); - return; - } +fn add_entity(live: &mut HashMap, dead: &mut HashMap>, id: K, mut content: T, timestamp: TimeStamp) { content.stamp_all(timestamp); merge_entity(live, dead, id, content); } /// A removal at `timestamp`: dead unless a newer addition or write holds it live. The snapshot folds in first, so a removal of an /// entity never seen still lands. -fn remove_entity(live: &mut HashMap, dead: &mut HashMap>, id: K, snapshot: T, timestamp: TimeStamp, force: bool) { +fn remove_entity(live: &mut HashMap, dead: &mut HashMap>, id: K, snapshot: T, timestamp: TimeStamp) { merge_entity(live, dead, id, snapshot); if let Some(mark) = dead.get_mut(&id) { - mark.timestamp = if force { timestamp } else { mark.timestamp.max(timestamp) }; - } else if live.get(&id).is_some_and(|content| force || timestamp > content.presence()) { + mark.timestamp = mark.timestamp.max(timestamp); + } else if live.get(&id).is_some_and(|content| timestamp > content.presence()) { let content = live.remove(&id).expect("checked above"); dead.insert( id, @@ -728,7 +596,6 @@ fn write_entity( missing: impl FnOnce() -> CrdtError, f: impl FnOnce(&mut T) -> Result<(), CrdtError>, ) -> Result<(), CrdtError> { - let force = mode == ApplyMode::Force; let unseen = !live.contains_key(&id) && !dead.contains_key(&id); if unseen { if mode == ApplyMode::Strict { @@ -752,9 +619,6 @@ fn write_entity( return Err(error); } content.set_presence(content.presence().max(timestamp)); - if force && let Some(mark) = dead.remove(&id) { - live.insert(id, mark.content); - } revive_if_newer(live, dead, id); Ok(()) } @@ -818,6 +682,4 @@ pub(crate) enum ApplyMode { Strict, /// An op from a peer or from persisted state: every arm is a timestamp comparison. Idempotent, - /// Silent-zone undo/redo rewind: every write lands, whatever its timestamp. - Force, } diff --git a/document/graph-storage/src/lib.rs b/document/graph-storage/src/lib.rs index 4290a2ad95..10160e0fe9 100644 --- a/document/graph-storage/src/lib.rs +++ b/document/graph-storage/src/lib.rs @@ -7,6 +7,7 @@ pub mod document; pub mod history; pub mod ids; pub mod model; +mod prior; pub mod registry; pub mod resources; pub mod session; @@ -25,6 +26,7 @@ pub use document::*; pub use history::History; pub use ids::*; pub use model::*; +pub use prior::{NetworkField, NodeField, Prior}; pub use registry::*; pub use resources::*; pub use session::*; diff --git a/document/graph-storage/src/prior.rs b/document/graph-storage/src/prior.rs new file mode 100644 index 0000000000..d66bfad852 --- /dev/null +++ b/document/graph-storage/src/prior.rs @@ -0,0 +1,339 @@ +use crate::{ + AttributeValue, ExportSlot, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, TimeStamp, + Tombstone, +}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::hash::Hash; + +/// What a slot held before a delta wrote it, stamps included. Undo puts it back bypassing LWW, so the registry is again +/// the fold of history up to the delta's parent. Never sent or applied as an op. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum Prior { + /// The whole entity, live, tombstoned, or absent. Restoring an absent one leaves no tombstone, so undoing an addition erases it. + Node { + id: NodeId, + node: Node, + }, + RemovedNode { + id: NodeId, + tombstone: Tombstone, + }, + AbsentNode { + id: NodeId, + }, + Network { + id: NetworkId, + network: Network, + }, + RemovedNetwork { + id: NetworkId, + tombstone: Tombstone, + }, + AbsentNetwork { + id: NetworkId, + }, + Resource { + id: ResourceId, + resource: ResourceEntry, + }, + RemovedResource { + id: ResourceId, + tombstone: Tombstone, + }, + AbsentResource { + id: ResourceId, + }, + /// One field of a live node, and the node's presence, which every write moves. + NodeField { + id: NodeId, + presence: TimeStamp, + field: NodeField, + }, + /// One field of a live network, and its presence. + NetworkField { + id: NetworkId, + presence: TimeStamp, + field: NetworkField, + }, + DocumentAttribute { + key: String, + previous: Option, + }, + PeerUser { + peer: PeerId, + previous: Option, + }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum NodeField { + /// Only the presence moved, by a reference from another entity's op. + Presence, + Attribute { + key: String, + previous: Option, + }, + Input { + index: u32, + previous: InputSlot, + }, + InputAttribute { + index: u32, + key: String, + previous: Option, + }, + Inputs { + previous: Vec, + inputs_timestamp: TimeStamp, + }, + Implementation { + previous: Implementation, + implementation_timestamp: TimeStamp, + }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum NetworkField { + /// Only the presence moved, by a node added to or implemented by it. + Presence, + Attribute { + key: String, + previous: Option, + }, + Exports { + previous: Vec, + }, +} + +/// What `op` is about to write in `registry`, in write order. Taken before the op applies. +pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec { + let mut priors = Vec::new(); + let node_input = |input: &NodeInput| match input { + NodeInput::Node { id, .. } => Some(*id), + _ => None, + }; + match op { + RegistryDelta::AddNode { id, node } => { + priors.push(network_field(registry, node.network, |_| NetworkField::Presence)); + priors.push(whole_node(registry, *id)); + } + RegistryDelta::RemoveNode { id, .. } => priors.push(whole_node(registry, *id)), + RegistryDelta::SetNodeInputs { id, inputs } => { + priors.push(node_field(registry, *id, |node| NodeField::Inputs { + previous: node.inputs.clone(), + inputs_timestamp: node.inputs_timestamp, + })); + priors.extend( + inputs + .iter() + .filter_map(|slot| node_input(&slot.input)) + .map(|referenced| node_field(registry, referenced, |_| NodeField::Presence)), + ); + } + RegistryDelta::ChangeNodeInput { id, index, new_input } => { + priors.push(node_field(registry, *id, |node| { + input_field(node, *index, |slot| NodeField::Input { + index: *index, + previous: slot.clone(), + }) + })); + priors.extend(node_input(new_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence))); + } + RegistryDelta::SetNodeImplementation { id, implementation } => { + if let Implementation::Network(network) = implementation { + priors.push(network_field(registry, *network, |_| NetworkField::Presence)); + } + priors.push(node_field(registry, *id, |node| NodeField::Implementation { + previous: node.implementation.clone(), + implementation_timestamp: node.implementation_timestamp, + })); + } + RegistryDelta::ChangeNodeAttribute { id, delta } => priors.push(node_field(registry, *id, |node| NodeField::Attribute { + key: delta.key.clone(), + previous: node.attributes.get(&delta.key).cloned(), + })), + RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => priors.push(node_field(registry, *id, |node| { + input_field(node, *index, |slot| NodeField::InputAttribute { + index: *index, + key: delta.key.clone(), + previous: slot.attributes.get(&delta.key).cloned(), + }) + })), + RegistryDelta::SetNetworkExport { id, export, .. } => { + priors.push(network_field(registry, *id, |network| NetworkField::Exports { previous: network.exports.clone() })); + priors.extend(export.as_ref().and_then(node_input).map(|referenced| node_field(registry, referenced, |_| NodeField::Presence))); + } + RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => priors.push(whole_network(registry, *id)), + RegistryDelta::ChangeNetworkAttribute { id, delta } => { + priors.push(network_field(registry, *id, |network| NetworkField::Attribute { + key: delta.key.clone(), + previous: network.attributes.get(&delta.key).cloned(), + })); + } + RegistryDelta::AddResource { id, .. } + | RegistryDelta::RemoveResource { id, .. } + | RegistryDelta::SetResourceHash { id, .. } + | RegistryDelta::AddSource { id, .. } + | RegistryDelta::RemoveSource { id, .. } => priors.push(whole_resource(registry, *id)), + RegistryDelta::RegisterPeer { peer, .. } => priors.push(Prior::PeerUser { + peer: *peer, + previous: registry.peer_users.get(peer).copied(), + }), + RegistryDelta::ChangeDocumentAttribute { delta } => priors.push(Prior::DocumentAttribute { + key: delta.key.clone(), + previous: registry.attributes.get(&delta.key).cloned(), + }), + RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {} + } + priors +} + +/// Puts back what `priors` recorded, newest write first. +pub(crate) fn restore(registry: &mut Registry, priors: &[Prior]) { + for prior in priors.iter().rev() { + match prior { + Prior::Node { id, node } => put_live(&mut registry.node_instances, &mut registry.removed_nodes, *id, node), + Prior::RemovedNode { id, tombstone } => put_removed(&mut registry.node_instances, &mut registry.removed_nodes, *id, tombstone), + Prior::AbsentNode { id } => put_absent(&mut registry.node_instances, &mut registry.removed_nodes, *id), + Prior::Network { id, network } => put_live(&mut registry.networks, &mut registry.removed_networks, *id, network), + Prior::RemovedNetwork { id, tombstone } => put_removed(&mut registry.networks, &mut registry.removed_networks, *id, tombstone), + Prior::AbsentNetwork { id } => put_absent(&mut registry.networks, &mut registry.removed_networks, *id), + Prior::Resource { id, resource } => put_live(&mut registry.resources, &mut registry.removed_resources, *id, resource), + Prior::RemovedResource { id, tombstone } => put_removed(&mut registry.resources, &mut registry.removed_resources, *id, tombstone), + Prior::AbsentResource { id } => put_absent(&mut registry.resources, &mut registry.removed_resources, *id), + Prior::NodeField { id, presence, field } => { + let Some(node) = registry.node_instances.get_mut(id) else { + debug_assert!(false, "a field prior is taken from a live node, which the later priors put back"); + continue; + }; + node.presence = *presence; + match field { + NodeField::Presence => {} + NodeField::Attribute { key, previous } => put_attribute(&mut node.attributes, key, previous.as_ref()), + NodeField::Input { index, previous } => { + if let Some(slot) = node.inputs.get_mut(*index as usize) { + *slot = previous.clone(); + } + } + NodeField::InputAttribute { index, key, previous } => { + if let Some(slot) = node.inputs.get_mut(*index as usize) { + put_attribute(&mut slot.attributes, key, previous.as_ref()); + } + } + NodeField::Inputs { previous, inputs_timestamp } => { + node.inputs = previous.clone(); + node.inputs_timestamp = *inputs_timestamp; + } + NodeField::Implementation { previous, implementation_timestamp } => { + node.implementation = previous.clone(); + node.implementation_timestamp = *implementation_timestamp; + } + } + } + Prior::NetworkField { id, presence, field } => { + let Some(network) = registry.networks.get_mut(id) else { + debug_assert!(false, "a field prior is taken from a live network, which the later priors put back"); + continue; + }; + network.presence = *presence; + match field { + NetworkField::Presence => {} + NetworkField::Attribute { key, previous } => put_attribute(&mut network.attributes, key, previous.as_ref()), + NetworkField::Exports { previous } => network.exports = previous.clone(), + } + } + Prior::DocumentAttribute { key, previous } => put_attribute(&mut registry.attributes, key, previous.as_ref()), + Prior::PeerUser { peer, previous } => match previous { + Some(registration) => _ = registry.peer_users.insert(*peer, *registration), + None => _ = registry.peer_users.remove(peer), + }, + } + } +} + +fn whole_node(registry: &Registry, id: NodeId) -> Prior { + if let Some(node) = registry.node_instances.get(&id) { + Prior::Node { id, node: node.clone() } + } else if let Some(tombstone) = registry.removed_nodes.get(&id) { + Prior::RemovedNode { id, tombstone: tombstone.clone() } + } else { + Prior::AbsentNode { id } + } +} + +fn whole_network(registry: &Registry, id: NetworkId) -> Prior { + if let Some(network) = registry.networks.get(&id) { + Prior::Network { id, network: network.clone() } + } else if let Some(tombstone) = registry.removed_networks.get(&id) { + Prior::RemovedNetwork { id, tombstone: tombstone.clone() } + } else { + Prior::AbsentNetwork { id } + } +} + +fn whole_resource(registry: &Registry, id: ResourceId) -> Prior { + if let Some(resource) = registry.resources.get(&id) { + Prior::Resource { id, resource: resource.clone() } + } else if let Some(tombstone) = registry.removed_resources.get(&id) { + Prior::RemovedResource { id, tombstone: tombstone.clone() } + } else { + Prior::AbsentResource { id } + } +} + +/// One field of a live node; a write landing on a tombstone or placeholder records the whole entity instead. +fn node_field(registry: &Registry, id: NodeId, field: impl FnOnce(&Node) -> NodeField) -> Prior { + match registry.node_instances.get(&id) { + Some(node) => Prior::NodeField { + id, + presence: node.presence, + field: field(node), + }, + None => whole_node(registry, id), + } +} + +fn network_field(registry: &Registry, id: NetworkId, field: impl FnOnce(&Network) -> NetworkField) -> Prior { + match registry.networks.get(&id) { + Some(network) => Prior::NetworkField { + id, + presence: network.presence, + field: field(network), + }, + None => whole_network(registry, id), + } +} + +/// A write to one slot, or to the whole list when the slot doesn't exist yet, since writing past the end grows it. +fn input_field(node: &Node, index: u32, field: impl FnOnce(&InputSlot) -> NodeField) -> NodeField { + match node.inputs.get(index as usize) { + Some(slot) => field(slot), + None => NodeField::Inputs { + previous: node.inputs.clone(), + inputs_timestamp: node.inputs_timestamp, + }, + } +} + +fn put_live(live: &mut HashMap, dead: &mut HashMap>, id: K, content: &T) { + dead.remove(&id); + live.insert(id, content.clone()); +} + +fn put_removed(live: &mut HashMap, dead: &mut HashMap>, id: K, tombstone: &Tombstone) { + live.remove(&id); + dead.insert(id, tombstone.clone()); +} + +fn put_absent(live: &mut HashMap, dead: &mut HashMap>, id: K) { + live.remove(&id); + dead.remove(&id); +} + +fn put_attribute(attributes: &mut crate::Attributes, key: &str, previous: Option<&AttributeValue>) { + match previous { + Some(value) => _ = attributes.insert(key.to_string(), value.clone()), + None => _ = attributes.remove(key), + } +} diff --git a/document/graph-storage/src/registry.rs b/document/graph-storage/src/registry.rs index 4267a40f17..2ca35ef518 100644 --- a/document/graph-storage/src/registry.rs +++ b/document/graph-storage/src/registry.rs @@ -44,11 +44,13 @@ pub struct Tombstone { impl Registry { /// The node under `id`, live or as removed, for a reference to a node the runtime cannot hold. + #[cfg(any(feature = "conversion", test))] pub(crate) fn node_or_removed(&self, id: NodeId) -> Option<&Node> { self.node_instances.get(&id).or_else(|| self.removed_nodes.get(&id).map(|mark| &mark.content)) } /// The network under `id`, live or as it was when removed. + #[cfg(any(feature = "conversion", test))] pub(crate) fn network_or_removed(&self, id: NetworkId) -> Option<&Network> { self.networks.get(&id).or_else(|| self.removed_networks.get(&id).map(|mark| &mark.content)) } diff --git a/document/graph-storage/src/resources.rs b/document/graph-storage/src/resources.rs index 8033c3328d..2f65d80a20 100644 --- a/document/graph-storage/src/resources.rs +++ b/document/graph-storage/src/resources.rs @@ -173,7 +173,7 @@ impl ResourceEntry { } } - /// Like [`set_source`](Self::set_source) but assigns unconditionally (silent-zone rewind, or building an entry). + /// Like [`set_source`](Self::set_source) but assigns unconditionally, for building an entry. pub fn force_set_source(&mut self, key: SourceKey, value: SourceValue) { self.put(key, value); } @@ -187,17 +187,6 @@ impl ResourceEntry { true } - /// Like [`remove_source`](Self::remove_source) but removes unconditionally (silent-zone rewind). - pub fn force_remove_source(&mut self, key: &SourceKey) -> bool { - match self.sources.binary_search_by(|(candidate, _)| candidate.cmp(key)) { - Ok(index) => { - self.sources.remove(index); - true - } - _ => false, - } - } - /// True if the chain already carries a `DataSource::Embedded` source. Decodes each source body into /// `DataSource` so a shape change in the serialized form can't slip an embedded source past detection. pub fn has_embedded_source(&self) -> bool { diff --git a/document/graph-storage/src/session.rs b/document/graph-storage/src/session.rs index 9a5112a53a..4cb6c33be7 100644 --- a/document/graph-storage/src/session.rs +++ b/document/graph-storage/src/session.rs @@ -214,7 +214,7 @@ impl Session { self.document.redo_stack.clear(); } - let reverse = self.document.compute_reverse_delta(target, &op)?; + let reverse = crate::prior::capture(self.document.registry_ref(target), &op); let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick()); let parent = self.document.head; let author = timestamp.peer; @@ -383,33 +383,29 @@ impl Session { self.document.history.annotate(rev, key, value, timestamp) } - /// Whether there is a retired commit at `head` that can be undone in the silent zone (a commit - /// after `last_broadcast_rev`). `head == 0` is the empty history; published commits aren't - /// silently undoable (that needs a forward reverse-delta op, deferred until transport lands). - /// - /// The earliest interaction (the document's loaded/created base) is *not* undoable: undoing it would - /// rewind into the pre-base state, which legacy never offers (opening a document gives an empty undo - /// history). We detect "head is on the earliest interaction" by walking `head`'s interaction back along - /// first-parents and checking whether it bottoms out at the root with no earlier interaction boundary to - /// land on. If so, there is nothing before this interaction to undo to, so undo is disabled. + /// Whether the interaction at `head` undoes silently: this user's own, no merge, nothing a peer holds. The document's + /// first interaction is not undoable, as opening a document starts with an empty undo history. pub fn can_undo(&self) -> bool { - let Some(head) = self.document.head else { return false }; - if self.document.last_broadcast_rev == Some(head) { - return false; - } - self.interaction_start_parent(head).is_some() + self.document.head.is_some_and(|head| self.interaction_start_parent(head, true).is_some()) } - /// Walk the interaction containing `rev` back along first-parents to its first delta, returning the - /// rev the cursor would rest on after undoing this interaction, or `None` if that is the root (the - /// earliest interaction, which is not undoable). Mirrors the boundary condition in [`undo`](Self::undo): - /// stop when the parent is an `interaction_end` boundary or the root. - fn interaction_start_parent(&self, rev: Rev) -> Option { - let mut current = rev; + /// Where the cursor rests once the interaction ending at `end` is undone: the previous interaction's end, a merge, or + /// another user's delta. `None` for a merge, the first interaction, and for a `silent` undo of another's or a published one. + fn interaction_start_parent(&self, end: Rev, silent: bool) -> Option { + let history = &self.document.history; + let mut current = history.get(end)?; + let user = self.user_of(current.author); + if matches!(current.kind, RegistryDelta::Merge { .. }) || (silent && user != Some(self.document.user)) { + return None; + } + let boundary = |delta: &Delta| delta.is_interaction_end() || matches!(delta.kind, RegistryDelta::Merge { .. }) || self.user_of(delta.author) != user; loop { - let parent = self.document.history.get(current)?.parent?; - if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) { - return Some(parent); + if silent && self.document.last_broadcast_rev == Some(current.id) { + return None; + } + let parent = history.get(current.parent?)?; + if boundary(parent) { + return Some(parent.id); } current = parent; } @@ -419,37 +415,22 @@ impl Session { !self.document.redo_stack.is_empty() } - /// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until - /// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One - /// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run, - /// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's - /// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten. + /// Silent-zone undo of one interaction: put back what its deltas overwrote, newest first, until `head` rests where it + /// began (see [`can_undo`](Self::can_undo)). Its `head` rev goes on the redo stack; the DAG is not rewritten. pub fn undo(&mut self) -> Result { - if !self.can_undo() { - return Err(CrdtError::NothingToUndo); - } let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?; + let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?; - // Revert this interaction's last delta, then keep going back until `head` rests on the previous - // interaction's boundary (its `interaction_end` delta) or the root. - loop { - let rev = self.document.head.ok_or(CrdtError::NothingToUndo)?; + while let Some(rev) = self.document.head.filter(|&rev| rev != base) { let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone(); - let parent = delta.parent; - - self.document.revert_delta(RegistryTarget::Working, delta)?; - self.document.head = parent; - - match parent { - None => break, - Some(parent) if self.document.history.get(parent).is_some_and(|d| d.is_interaction_end()) => break, - Some(_) => {} - } + self.document.revert_delta(&delta); + self.document.head = delta.parent; } - // Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound - // working registry (the next interaction's reverses are computed against it). - self.document.retired_snapshot = self.document.working_registry.clone(); + // With ops hot, working is the rewound snapshot plus them. + if !self.document.hot_log.is_empty() { + self.document.rebuild_working(); + } self.document.redo_stack.push(checkpoint); Ok(checkpoint) } @@ -469,15 +450,19 @@ impl Session { forward.push(delta); } - // Force-apply so each forward value wins the LWW tie against the reverse that undo force-applied - // at the same timestamp. Symmetric with `revert_delta`. + // The snapshot is the fold up to `head`, so applying the deltas as retirement did folds them in again. + let hot = !self.document.hot_log.is_empty(); for delta in forward.into_iter().rev() { - self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?; + self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?; + if !hot { + self.document.apply_op_with(RegistryTarget::Working, delta.kind, delta.timestamp, ApplyMode::Idempotent)?; + } + } + if hot { + self.document.rebuild_working(); } self.document.head = Some(checkpoint); - // Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry. - self.document.retired_snapshot = self.document.working_registry.clone(); Ok(checkpoint) } diff --git a/document/graph-storage/src/tests/crdt.rs b/document/graph-storage/src/tests/crdt.rs index 518078736b..b56aa8b7ad 100644 --- a/document/graph-storage/src/tests/crdt.rs +++ b/document/graph-storage/src/tests/crdt.rs @@ -4,7 +4,7 @@ use graph_craft::concrete; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork}; use crate::InputSlot; -use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, RegistryTarget, Session, TimeStamp, Value}; +use crate::{Delta, Document, HotOp, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, RegistryDelta, Session, TimeStamp, Value}; fn fresh_document(peer: PeerId) -> Document { Session::with_peer(peer).document @@ -20,7 +20,7 @@ fn remove_node_op(node_id: NodeId) -> RegistryDelta { /// Commit a single op to a document as a retired delta. Mints a fresh timestamp, links to /// current head, applies, records in history, advances head. fn commit_op(document: &mut Document, op: RegistryDelta) { - let reverse = document.compute_reverse_delta(RegistryTarget::Working, &op).expect("compute_reverse_delta failed"); + let reverse = crate::prior::capture(&document.working_registry, &op); let timestamp = document.clock.tick(); let delta = Delta::new(document.head, document.peer, timestamp, op, reverse); let rev = delta.id; @@ -420,6 +420,11 @@ fn source_key(priority: f64, peer: u64) -> SourceKey { } } +/// Whether the map holds a live value under `key`: a deleted key stays as a tombstone. +fn holds(attributes: &crate::Attributes, key: &str) -> bool { + attributes.live().any(|(held, _)| held == key) +} + fn ts(counter: u64, peer: u64) -> TimeStamp { TimeStamp { counter, peer: PeerId(peer) } } @@ -519,85 +524,146 @@ fn register_resource_hash_is_last_writer_wins() { assert_eq!(document.working_registry.resources.get(&id).unwrap().hash, Some(hash_b), "later resolve wins"); } -/// The reverse delta of a RemoveSource restores the prior source body, and applying op-then-reverse -/// round-trips the source chain. +/// For every kind of op, landing on a live entity, a removed one or one never seen. #[test] -fn remove_source_reverse_restores_prior() { +fn restoring_what_an_op_overwrote_gives_back_the_registry_exactly() { + use crate::{AttributeDelta, Implementation, Network, NodeInput, ROOT_NETWORK}; + let attribute = |key: &str, value: i64| AttributeDelta { + key: key.into(), + value: Some(Value::Int(value.into())), + }; + let reference = |id: u64| NodeInput::Node { id: NodeId(id), index: 0 }; + let (live, removed, unseen, network, resource) = (NodeId(1), NodeId(2), NodeId(3), NetworkId(7), ResourceId::new()); + let node = || Node::new(ROOT_NETWORK, Implementation::ProtoNode(ResourceId::from(1)), 2); + let mut document = fresh_document(PeerId(1)); - let id = ResourceId::new(); - let key = source_key(0.5, 1); - - commit_op( - &mut document, - RD::AddSource { - id, - key, - source: Value::Str("kept".into()), - }, - ); - - // Compute the reverse while the body is still present, then apply the removal. - let reverse = document.compute_reverse_delta(RegistryTarget::Working, &RD::RemoveSource { id, key }).unwrap(); - match &reverse { - RD::AddSource { source, .. } => assert_eq!(*source, Value::Str("kept".into()), "reverse of removal re-adds the body"), - other => panic!("expected AddSource reverse, got {other:?}"), + for (op, at) in [ + ( + RD::AddNetwork { + id: ROOT_NETWORK, + network: Network::default(), + }, + 1, + ), + ( + RD::AddNetwork { + id: network, + network: Network::default(), + }, + 1, + ), + (RD::AddNode { id: live, node: node() }, 2), + (RD::AddNode { id: removed, node: node() }, 2), + (RD::RemoveNode { id: removed, snapshot: node() }, 3), + ( + RD::ChangeNodeAttribute { + id: live, + delta: attribute("kept", 1), + }, + 4, + ), + ( + RD::AddSource { + id: resource, + key: source_key(0.5, 1), + source: Value::Str("kept".into()), + }, + 4, + ), + (RD::ChangeDocumentAttribute { delta: attribute("kept", 1) }, 4), + ( + RD::SetNetworkExport { + id: network, + index: 0, + export: Some(reference(1)), + }, + 4, + ), + ] { + document.apply_op_idempotent(op, ts(at, 2)).unwrap(); } - document.apply_op(RD::RemoveSource { id, key }, ts(5, 1)).unwrap(); - assert!( - document.working_registry.resources.get(&id).unwrap().live_sources().next().is_none(), - "source removed, a tombstone left" - ); - - // Applying the reverse restores the chain. - document.apply_op(reverse, ts(6, 1)).unwrap(); - assert_eq!(document.working_registry.resources.get(&id).unwrap().source(&key).unwrap().source, Value::Str("kept".into())); -} - -/// AddSource on a fresh slot reverses to a RemoveSource; on an occupied slot it restores the prior body. -#[test] -fn add_source_reverse_depends_on_prior_state() { - let mut document = fresh_document(PeerId(1)); - let id = ResourceId::new(); - let key = source_key(0.5, 1); - - // Fresh slot: reverse removes. - let reverse_fresh = document - .compute_reverse_delta( - RegistryTarget::Working, - &RD::AddSource { - id, - key, - source: Value::Str("first".into()), - }, - ) - .unwrap(); - assert!(matches!(reverse_fresh, RD::RemoveSource { .. }), "reverse of add-to-empty is remove, got {reverse_fresh:?}"); - - // Occupy the slot, then reverse of a new add restores the existing body. - document - .apply_op( - RD::AddSource { - id, - key, - source: Value::Str("existing".into()), - }, - ts(1, 1), - ) - .unwrap(); - let reverse_overwrite = document - .compute_reverse_delta( - RegistryTarget::Working, - &RD::AddSource { - id, - key, - source: Value::Str("overwrite".into()), - }, - ) - .unwrap(); - match reverse_overwrite { - RD::AddSource { source, .. } => assert_eq!(source, Value::Str("existing".into()), "reverse restores prior body"), - other => panic!("expected AddSource reverse, got {other:?}"), + let ops = [ + RD::AddNode { id: live, node: node() }, + RD::AddNode { id: unseen, node: node() }, + RD::RemoveNode { id: live, snapshot: node() }, + RD::ChangeNodeAttribute { + id: live, + delta: attribute("kept", 2), + }, + RD::ChangeNodeAttribute { id: live, delta: attribute("new", 2) }, + RD::ChangeNodeAttribute { + id: removed, + delta: attribute("new", 2), + }, + RD::ChangeNodeAttribute { + id: unseen, + delta: attribute("new", 2), + }, + RD::ChangeNodeInput { + id: live, + index: 1, + new_input: reference(2), + }, + RD::ChangeNodeInput { + id: live, + index: 5, + new_input: reference(3), + }, + RD::ChangeNodeInputAttribute { + id: live, + index: 0, + delta: attribute("name", 2), + }, + RD::SetNodeInputs { + id: live, + inputs: vec![crate::InputSlot::unset(TimeStamp::ORIGIN); 3], + }, + RD::SetNodeImplementation { + id: live, + implementation: Implementation::Network(NetworkId(8)), + }, + RD::SetNetworkExport { + id: network, + index: 3, + export: Some(reference(3)), + }, + RD::ChangeNetworkAttribute { + id: network, + delta: attribute("new", 2), + }, + RD::RemoveNetwork { + id: network, + snapshot: Network::default(), + }, + RD::AddSource { + id: resource, + key: source_key(0.5, 1), + source: Value::Str("new".into()), + }, + RD::RemoveSource { + id: resource, + key: source_key(0.5, 1), + }, + RD::SetResourceHash { id: ResourceId::new(), hash: None }, + RD::RemoveResource { + id: resource, + snapshot: Default::default(), + }, + RD::ChangeDocumentAttribute { delta: attribute("kept", 2) }, + RD::RegisterPeer { + peer: PeerId(5), + user: crate::UserId(5), + }, + ]; + for op in ops { + let before = document.working_registry.clone(); + let priors = crate::prior::capture(&before, &op); + let mut after = document.clone(); + after.apply_op_idempotent(op.clone(), ts(10, 2)).unwrap(); + assert_ne!(after.working_registry, before, "{op:?} should change something for this to check anything"); + crate::prior::restore(&mut after.working_registry, &priors); + assert_eq!(after.working_registry, before, "restoring {op:?}"); } } @@ -867,10 +933,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() { id: NodeId(9), node: make_node(&forward), }, - RegistryDelta::AddNode { - id: NodeId(9), - node: make_node(&forward), - }, + Vec::new(), ); let delta_reversed = Delta::new( parent, @@ -880,15 +943,22 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() { id: NodeId(9), node: make_node(&reversed), }, - RegistryDelta::AddNode { - id: NodeId(9), - node: make_node(&reversed), - }, + Vec::new(), ); assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order"); } +/// Commit a retired delta and mirror it onto the working registry, which `commit_op_for_test` leaves alone. +fn commit_retired(session: &mut Session, op: RegistryDelta) { + let before = session.history().count(); + session.commit_op_for_test(op).expect("commit failed"); + + for delta in session.cloned_deltas().into_iter().skip(before) { + session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry"); + } +} + fn add_network(id: u64) -> RegistryDelta { let network = Network::default(); RegistryDelta::AddNetwork { id: NetworkId(id), network } @@ -964,6 +1034,31 @@ fn retiring_over_a_gap_lands_beyond_the_prefix() { assert!(marks.covers(second.id())); } +/// Undo and redo never promote the hot tail, a fold skips undone deltas, and a published commit is not rewound. +#[test] +fn undo_and_redo_move_only_unpublished_retired_history() { + let mut session = Session::with_peer(PeerId(1)); + commit_retired(&mut session, set_document_attribute("first", 1)); + let boundary = session.history().last().expect("a committed delta").id; + session.mark_interaction_end(boundary); + commit_retired(&mut session, set_document_attribute("second", 2)); + session.stage_ops([set_document_attribute("hot", 3)]).expect("stage"); + + let mut published = session.clone(); + published.publish_up_to(published.head_rev().expect("a head")); + assert!(session.can_undo() && !published.can_undo()); + + let retired = |session: &Session, key| holds(&session.retired_registry().attributes, key); + session.undo().expect("undo"); + assert!(!retired(&session, "second") && !retired(&session, "hot")); + let folded = session.snapshot_from_history().expect("fold"); + assert!(holds(&folded.attributes, "first") && !holds(&folded.attributes, "second")); + + session.redo().expect("redo"); + assert!(retired(&session, "second") && !retired(&session, "hot")); + assert!(holds(&session.registry().attributes, "hot")); +} + /// So the snapshot and a replay keep the LWW winner the live view did, whether the straggler retires with it or after. #[test] fn retirement_preserves_the_live_lww_winner() { @@ -985,7 +1080,7 @@ fn retirement_preserves_the_live_lww_winner() { } /// Random ops over a few colliding ids fold to one registry in any order. Removal snapshots are constant or, as a remover -/// sends them, a fold of some earlier ops. +/// sends them, a fold of some earlier ops; restoring each op's priors gives back the registry it applied to. #[test] fn a_set_of_ops_folds_to_one_registry_in_any_order() { use crate::{Implementation, Priority, ResourceEntry, SourceKey, SourceValue, UserId}; @@ -999,11 +1094,17 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() { } } - /// Folds the ops in order. - fn fold(ops: &[(RegistryDelta, TimeStamp)]) -> crate::Registry { + /// Folds the ops in order; `check_restore` also checks each op's priors restore the registry it applied to. + fn fold(ops: &[(RegistryDelta, TimeStamp)], check_restore: bool) -> crate::Registry { let mut document = fresh_document(PeerId(9)); for (op, at) in ops { + let before = check_restore.then(|| (document.working_registry.clone(), crate::prior::capture(&document.working_registry, op))); document.apply_op_idempotent(op.clone(), *at).unwrap_or_else(|error| panic!("{op:?} at {at:?}: {error}")); + if let Some((registry, priors)) = before { + let mut restored = document.working_registry.clone(); + crate::prior::restore(&mut restored, &priors); + assert_eq!(restored, registry, "restoring what {op:?} overwrote"); + } } document.working_registry } @@ -1033,7 +1134,7 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() { }; // What a remover saw: some of the ops before it. Two snapshots agreeing on a stamp then agree on the value, // which a fabricated snapshot only does by being constant. - let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::>()); + let saw = |rng: &mut Lcg| fold(&seen.iter().filter(|_| rng.below(2) == 0).cloned().collect::>(), false); match rng.below(22) { 0 => { // An export list of its own, so additions of different lengths meet. @@ -1181,14 +1282,18 @@ fn a_set_of_ops_folds_to_one_registry_in_any_order() { ops.push((op, at)); } - let reference = fold(&ops); + let reference = fold(&ops, true); for _ in 0..6 { let mut shuffled = ops.clone(); for i in (1..shuffled.len()).rev() { shuffled.swap(i, rng.below(i as u64 + 1) as usize); } let order: Vec = shuffled.iter().map(|(_, at)| at.counter).collect(); - assert_eq!(fold(&shuffled), reference, "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}"); + assert_eq!( + fold(&shuffled, false), + reference, + "seed {seed}, real snapshots {real_snapshots}: folded differently in the order {order:?}" + ); } } } diff --git a/node-graph/rfcs/document-format.md b/node-graph/rfcs/document-format.md index d3e8a52aac..fff4b46ec5 100644 --- a/node-graph/rfcs/document-format.md +++ b/node-graph/rfcs/document-format.md @@ -144,7 +144,7 @@ pub struct Delta { pub author: PeerId, pub timestamp: TimeStamp, pub kind: RegistryDelta, - pub reverse: RegistryDelta, // precomputed for undo; excluded from id + pub reverse: Vec, // what the op overwrote, stamps included; excluded from id pub attributes: Attributes, // mutable local annotations; excluded from id } ``` @@ -197,14 +197,11 @@ The silent zone is the implemented path (solo editing has no transport yet). **Silent-zone cursor.** `head: Option` is a movable pointer into the append-only DAG (`None` on an empty document with no commits yet). Undo/redo move it but never delete deltas (that would make redo impossible and discard branch history). The extra state is a redo stack `Vec`, the checkpoints the user has undone past, because the DAG alone cannot say which child a `head` was undone *from*. New state persists in `session.json` alongside `head`, so redo survives reopen. A new edit while the redo stack is non-empty clears it (the undone-forward branch stays physically in the DAG but is no longer reachable via redo). -**Interactions, not deltas.** One user action diffs into several deltas (one per changed field, slot, or attribute), so undo steps per *interaction* rather than per delta. The last delta of each interaction is tagged with the `interaction_end` attribute, and undo reverts deltas walking the first-parent chain until the parent is an `interaction_end` boundary or the root. The starting `head` (the checkpoint) is pushed to the redo stack, and redo re-applies forward to it. +**Interactions, not deltas.** One user action diffs into several deltas (one per changed field, slot, or attribute), so undo steps per *interaction* rather than per delta. The last delta of each interaction is tagged with the `interaction_end` attribute, and undo reverts deltas walking the first-parent chain until the parent is an `interaction_end` boundary, a merge, another user's delta, or the root. The starting `head` (the checkpoint) is pushed to the redo stack, and redo re-applies forward to it. +**Restore, not reverse ops.** A delta's `reverse` is a list of `Prior`s: the state of every slot the op wrote, as it was just before, stamps included (a whole node, network, or resource where the op added, removed, or landed on a tombstone; otherwise one field plus the entity's presence stamp). Undo writes these back as they were, bypassing LWW, so the registry is again exactly the fold of history up to the new `head`. An op applied at its own timestamp could not express that: it can only write a value or a tombstone at that timestamp, while the prior state may be an older stamp or no entry at all, and a stamp the history does not account for decides later concurrent writes differently on different peers. Redo re-applies the forward ops with plain LWW, which folds them in exactly as retirement did. Both are O(steps moved), no clock advances, and identities are unchanged. Undo only takes this user's own interactions and never one containing a merge, since restoring past another peer's write would rewind it. -**Force-apply.** Rewinding re-applies each delta's precomputed `reverse` (for redo, the forward `kind`). These carry the *original* timestamp, which would tie (and so lose) the LWW arms' strict `>` comparison, since the forward op already stamped each field at that timestamp. In the single-writer silent zone the rewind value is authoritative, so silent undo/redo apply in a **force** mode where LWW arms assign unconditionally and structural ops are idempotent. Undo and redo are symmetric (force-reverse, force-forward), so no clock advances and identities are unchanged. - - -**Two registries.** Computing a correct `reverse` for an LWW field means reading the field's *pre-op* value. But staged edits apply to the live registry immediately (for responsiveness), so by retirement time it already holds the *post*-op value. `Document` therefore keeps two registries: a **working** registry (committed state plus live un-retired ops, what reads and the cursor see) and a **retired snapshot** (committed deltas only). Retirement computes reverses against, and forward-applies to, the snapshot, so the reverse captures the true prior value, and the working registry already reflects the ops and is left as-is. When there are no un-retired ops the two are equal *by value* (their LWW field timestamps can differ, since retirement re-stamps the snapshot at a fresh time), and undo/redo rewind both. - +**Two registries.** Computing a correct `reverse` for an LWW field means reading the field's *pre-op* value. But staged edits apply to the live registry immediately (for responsiveness), so by retirement time it already holds the *post*-op value. `Document` therefore keeps two registries: a **working** registry (committed state plus live un-retired ops, what reads and the cursor see) and a **retired snapshot** (committed deltas only). Retirement computes reverses against, and forward-applies to, the snapshot, so the reverse captures the true prior value, and the working registry already reflects the ops and is left as-is. When there are no un-retired ops the two are equal, and undo/redo restore both; with ops still hot, the working registry is rebuilt as the rewound snapshot plus them. ## Concurrency model: CmRDT From 46f48a54106dc67d91feda8b316788394c493b8e Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Thu, 15 Oct 2026 23:49:07 -0700 Subject: [PATCH 27/47] Add new vector pool storage types, not yet used (#4732) * Add the Path and CurveType primitives for the pool-based Vector format * Resolve path segments and emit contours against the Vector point pool * Read a vector's paths and their curve types off its holder item * Weave bezpath contours into pool points and stride-uniform paths * Index which paths meet at each pool point for topology queries * Assemble render contours by following welds across split paths * Address segments as path spans while keeping stable point and segment IDs * Give the 'flatten_add' test its own node ID counter so it can't flake --- node-graph/graph-craft/src/document.rs | 8 +- node-graph/libraries/core-types/src/list.rs | 14 + .../vector-types/src/vector/addressing.rs | 229 +++++++++ .../src/vector/algorithms/consts.rs | 4 + .../vector-types/src/vector/connectivity.rs | 155 ++++++ .../vector-types/src/vector/contour.rs | 352 ++++++++++++++ .../libraries/vector-types/src/vector/mod.rs | 8 + .../libraries/vector-types/src/vector/path.rs | 450 ++++++++++++++++++ .../src/vector/vector_attributes.rs | 4 +- .../src/vector/vector_modification.rs | 5 +- 10 files changed, 1222 insertions(+), 7 deletions(-) create mode 100644 node-graph/libraries/vector-types/src/vector/addressing.rs create mode 100644 node-graph/libraries/vector-types/src/vector/connectivity.rs create mode 100644 node-graph/libraries/vector-types/src/vector/contour.rs create mode 100644 node-graph/libraries/vector-types/src/vector/path.rs diff --git a/node-graph/graph-craft/src/document.rs b/node-graph/graph-craft/src/document.rs index fc9a1d8fed..6297ceab3e 100644 --- a/node-graph/graph-craft/src/document.rs +++ b/node-graph/graph-craft/src/document.rs @@ -1339,6 +1339,7 @@ mod test { use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; use std::sync::atomic::AtomicU64; + /// Generates IDs from a counter all tests share, so the IDs a test gets depend on what else runs in parallel. fn gen_node_id() -> NodeId { static NODE_ID: AtomicU64 = AtomicU64::new(4); NodeId(NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst)) @@ -1450,7 +1451,12 @@ mod test { ..Default::default() }; network.populate_dependants(); - network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_node_id); + + // A counter of its own, since the expected network names the nodes by the IDs it generates + let next_id = AtomicU64::new(4); + let gen_id = || NodeId(next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst)); + network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_id); + let expected = flatten_add_expected(); println!("{expected:#?}"); println!("{network:#?}"); diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index 534a98079e..d9f75d319a 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -105,6 +105,20 @@ pub const ATTR_DIAMETER: &str = "diameter"; pub const ATTR_HARDNESS: &str = "hardness"; /// Brush stroke item's per-pass paint coverage from `0.` to `1.` (`f64`). pub const ATTR_FLOW: &str = "flow"; +/// `List` of connected strokes woven through the point pool, on the item holding a `Vector`. +/// Absent means the pool is a point cloud. +pub const ATTR_PATHS: &str = "paths"; +/// Path's `CurveType` naming the stride its point references weave in, on the `List` item +/// holding the path (implicit default `Linear`). +pub const ATTR_CURVE_TYPE: &str = "curve_type"; +/// Point reference's `bool` tool state marking the tangent pair at this anchor occurrence as smooth, +/// on the `List` inside a `Path` (implicit default `false`). Editing tools keep a smooth pair +/// colinear. Rendering derives continuity from actual tangent geometry and does not read this. +pub const ATTR_SMOOTH: &str = "smooth"; +/// Item's stable ID for external addressing (modifications, tools, animation), opt-in because indices are +/// the internal addressing: a `PointId` on a `Vector`'s point pool, or a `SegmentId` on the `List` +/// inside a `Path` at the anchor reference the segment departs from. +pub const ATTR_ID: &str = "id"; /// Text item's font size in document-space units (`f64`, implicit default `24.`). pub const ATTR_FONT_SIZE: &str = "font_size"; /// Text item's font, as a `Resource` of the loaded font file. diff --git a/node-graph/libraries/vector-types/src/vector/addressing.rs b/node-graph/libraries/vector-types/src/vector/addressing.rs new file mode 100644 index 0000000000..a78719c368 --- /dev/null +++ b/node-graph/libraries/vector-types/src/vector/addressing.rs @@ -0,0 +1,229 @@ +use super::connectivity::Connectivity; +use super::misc::HandleId; +use super::path::{CurveType, Path, curve_type_at}; +use super::vector_attributes::{PointId, SegmentId}; +use core_types::list::{ATTR_ID, List}; +use glam::DVec2; + +/// A segment's place in the weave: the span of one path between two consecutive anchors. +/// Segments are never stored, so this is how one is named. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Span { + pub path: u32, + pub index: u32, +} + +impl Span { + /// The reference index where this span's starting anchor sits. + pub fn start_reference(&self, curve_type: CurveType) -> usize { + self.index as usize * curve_type.stride() + } + + /// The reference index where this span's ending anchor sits. + pub fn end_reference(&self, curve_type: CurveType) -> usize { + self.start_reference(curve_type) + curve_type.stride() + } +} + +/// Every span of every path, in path order. +pub fn spans(paths: &List) -> impl Iterator + '_ { + paths.iter_element_values().enumerate().flat_map(|(path_index, path)| { + let curve_type = curve_type_at(paths, path_index); + (0..path.segment_count(curve_type) as u32).map(move |index| Span { path: path_index as u32, index }) + }) +} + +/// The stable ID naming a span, stored on the anchor reference the span departs from. A reference cell left unnamed +/// holds `SegmentId::ZERO`, which sequential IDs never take. +pub fn segment_id_of(paths: &List, span: Span) -> Option { + let path = paths.element(span.path as usize)?; + let reference = span.start_reference(curve_type_at(paths, span.path as usize)); + + path.0.attribute::(ATTR_ID, reference).copied() +} + +/// The span a segment ID names, found by scanning every span in O(references). +pub fn span_of_segment_id(paths: &List, segment: SegmentId) -> Option { + spans(paths).find(|&span| segment_id_of(paths, span) == Some(segment)) +} + +/// The pool points a span runs between. +pub fn span_endpoints(paths: &List, span: Span) -> Option<(u32, u32)> { + let path = paths.element(span.path as usize)?; + let curve_type = curve_type_at(paths, span.path as usize); + let start = path.0.element(span.start_reference(curve_type))?; + let end = path.0.element(span.end_reference(curve_type))?; + + Some((*start, *end)) +} + +/// The pool point a handle of the given span occupies, absent on a linear span that has no handles. +pub fn handle_point(paths: &List, span: Span, primary: bool) -> Option { + let path = paths.element(span.path as usize)?; + let curve_type = curve_type_at(paths, span.path as usize); + if curve_type == CurveType::Linear { + return None; + } + + // A quadratic span's single handle answers to either side + let offset = if primary || curve_type == CurveType::Quadratic { 1 } else { 2 }; + + path.0.element(span.start_reference(curve_type) + offset).copied() +} + +/// The stable ID of a pool point. +pub fn point_id_at(pool: &List, index: u32) -> Option { + pool.attribute::(ATTR_ID, index as usize).copied() +} + +/// The pool index a point ID names. +pub fn index_of_point_id(pool: &List, point: PointId) -> Option { + pool.iter_attribute_values::(ATTR_ID)?.position(|&id| id == point).map(|index| index as u32) +} + +/// The spans meeting at a pool point, each paired with whether the point is where that span ends. +pub fn spans_at(pool_index: u32, paths: &List, connectivity: &Connectivity) -> Vec<(Span, bool)> { + let mut found = Vec::new(); + + for reference in connectivity.references(pool_index) { + let path_index = reference.path as usize; + let Some(path) = paths.element(path_index) else { continue }; + + let curve_type = curve_type_at(paths, path_index); + if !path.is_anchor_reference(reference.index as usize, curve_type) { + continue; + } + + // An anchor departs the span starting at it and arrives on the one before it + let anchor = reference.index as usize / curve_type.stride(); + if anchor < path.segment_count(curve_type) { + found.push(( + Span { + path: reference.path, + index: anchor as u32, + }, + false, + )); + } + if let Some(previous) = anchor.checked_sub(1) { + found.push(( + Span { + path: reference.path, + index: previous as u32, + }, + true, + )); + } + } + + found +} + +/// The segments departing the given pool point. +pub fn start_connected(pool_index: u32, paths: &List, connectivity: &Connectivity) -> Vec { + spans_at(pool_index, paths, connectivity) + .into_iter() + .filter(|&(_, arriving)| !arriving) + .filter_map(|(span, _)| segment_id_of(paths, span)) + .collect() +} + +/// The segments arriving at the given pool point. +pub fn end_connected(pool_index: u32, paths: &List, connectivity: &Connectivity) -> Vec { + spans_at(pool_index, paths, connectivity) + .into_iter() + .filter(|&(_, arriving)| arriving) + .filter_map(|(span, _)| segment_id_of(paths, span)) + .collect() +} + +/// The handles of every segment meeting the given pool point, naming the side that faces it. +pub fn all_connected(pool_index: u32, paths: &List, connectivity: &Connectivity) -> Vec { + spans_at(pool_index, paths, connectivity) + .into_iter() + .filter_map(|(span, arriving)| { + let segment = segment_id_of(paths, span)?; + Some(if arriving { HandleId::end(segment) } else { HandleId::primary(segment) }) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use core_types::list::{ATTR_CURVE_TYPE, Item}; + + fn pool(count: u32) -> List { + (0..count) + .map(|index| Item::new_from_element(DVec2::new(index as f64, 0.)).with_attribute(ATTR_ID, PointId::generate())) + .collect() + } + + fn paths_of(specs: &[(CurveType, &[u32])]) -> List { + let mut paths = List::new(); + + for &(curve_type, references) in specs { + let mut path = Path(references.iter().map(|&reference| Item::new_from_element(reference)).collect()); + + // Name each span on the anchor it departs from + for span in 0..path.segment_count(curve_type) { + path.0.set_attribute(ATTR_ID, span * curve_type.stride(), SegmentId::generate()); + } + + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); + } + + paths + } + + #[test] + fn spans_name_every_segment() { + let paths = paths_of(&[(CurveType::Linear, &[0, 1, 2]), (CurveType::Cubic, &[2, 3, 4, 5])]); + + let all: Vec<_> = spans(&paths).collect(); + assert_eq!(all.len(), 3); + assert_eq!(all[2], Span { path: 1, index: 0 }); + + for span in all { + let id = segment_id_of(&paths, span).expect("every span was named"); + assert_eq!(span_of_segment_id(&paths, id), Some(span)); + } + } + + #[test] + fn spans_resolve_their_endpoints_and_handles() { + let paths = paths_of(&[(CurveType::Cubic, &[0, 1, 2, 3])]); + let span = Span { path: 0, index: 0 }; + + assert_eq!(span_endpoints(&paths, span), Some((0, 3))); + assert_eq!(handle_point(&paths, span, true), Some(1)); + assert_eq!(handle_point(&paths, span, false), Some(2)); + + let linear = paths_of(&[(CurveType::Linear, &[0, 1])]); + assert_eq!(handle_point(&linear, Span { path: 0, index: 0 }, true), None); + } + + // A welded anchor reports the segments on both sides, each from the path that owns it + #[test] + fn connectivity_by_segment_id() { + let paths = paths_of(&[(CurveType::Linear, &[0, 1]), (CurveType::Linear, &[1, 2])]); + let connectivity = Connectivity::build(3, &paths); + + assert_eq!(start_connected(0, &paths, &connectivity).len(), 1); + assert!(end_connected(0, &paths, &connectivity).is_empty()); + + assert_eq!(start_connected(1, &paths, &connectivity).len(), 1); + assert_eq!(end_connected(1, &paths, &connectivity).len(), 1); + assert_eq!(all_connected(1, &paths, &connectivity).len(), 2); + } + + #[test] + fn point_ids_resolve_both_ways() { + let pool = pool(4); + + for index in 0..4 { + let id = point_id_at(&pool, index).expect("every point was named"); + assert_eq!(index_of_point_id(&pool, id), Some(index)); + } + } +} diff --git a/node-graph/libraries/vector-types/src/vector/algorithms/consts.rs b/node-graph/libraries/vector-types/src/vector/algorithms/consts.rs index 46eec7326b..15b93a5e83 100644 --- a/node-graph/libraries/vector-types/src/vector/algorithms/consts.rs +++ b/node-graph/libraries/vector-types/src/vector/algorithms/consts.rs @@ -6,3 +6,7 @@ pub(crate) const MAX_ABSOLUTE_DIFFERENCE: f64 = 1e-3; /// Maximum distance at which two points are treated as one and the same point. pub(crate) const MAX_COINCIDENT_POINT_DISTANCE: f64 = 1e-7; + +/// Distance below which a path's closing point is treated as coincident with its start point. +/// Matches Kurbo's default path accuracy, so points within an offset operation's own precision are not split into separate anchors. +pub(crate) const CLOSE_POINT_TOLERANCE: f64 = 1e-6; diff --git a/node-graph/libraries/vector-types/src/vector/connectivity.rs b/node-graph/libraries/vector-types/src/vector/connectivity.rs new file mode 100644 index 0000000000..bcd42d3c90 --- /dev/null +++ b/node-graph/libraries/vector-types/src/vector/connectivity.rs @@ -0,0 +1,155 @@ +use super::path::{Path, curve_type_at}; +use core_types::list::List; + +/// One path's reference to a pool point, naming where in the weave that point is used. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Reference { + pub path: u32, + pub index: u32, +} + +/// Reverse index from each pool point to the references naming it. +/// +/// Paths store their own traversal order, so connectivity never has to be searched for. This index +/// answers the remaining question of which paths meet at a point, built in one pass over every +/// reference and read afterwards as a slice per point. +#[derive(Clone, Debug, Default)] +pub struct Connectivity { + starts: Vec, + references: Vec, +} + +impl Connectivity { + /// Indexes every reference by the pool point it names, in O(points + references). + pub fn build(point_count: usize, paths: &List) -> Self { + let mut starts = vec![0_u32; point_count + 1]; + for path in paths.iter_element_values() { + for &point in path.0.iter_element_values() { + if let Some(count) = (point as usize).checked_add(1).and_then(|slot| starts.get_mut(slot)) { + *count += 1; + } + } + } + + // Summing the per-point counts in place turns them into the offset where each point's run begins + for index in 1..starts.len() { + starts[index] += starts[index - 1]; + } + + let mut cursors = starts[..point_count].to_vec(); + let mut references = vec![Reference::default(); starts[point_count] as usize]; + for (path_index, path) in paths.iter_element_values().enumerate() { + for (reference_index, &point) in path.0.iter_element_values().enumerate() { + let Some(cursor) = cursors.get_mut(point as usize) else { continue }; + references[*cursor as usize] = Reference { + path: path_index as u32, + index: reference_index as u32, + }; + *cursor += 1; + } + } + + Self { starts, references } + } + + /// The references naming the given pool point, ordered by path. + pub fn references(&self, point: u32) -> &[Reference] { + let (Some(&start), Some(&end)) = (self.starts.get(point as usize), (point as usize).checked_add(1).and_then(|next| self.starts.get(next))) else { + return &[]; + }; + + &self.references[start as usize..end as usize] + } + + /// Whether any path names this point, false for a free point carried by the pool alone. + pub fn is_referenced(&self, point: u32) -> bool { + !self.references(point).is_empty() + } + + /// The segment ends meeting at this point: 1 at a free end, 2 along a chain, 3 or more at a junction. + /// Handle references contribute none, since only anchors have segments radiating from them. + pub fn spokes(&self, point: u32, paths: &List) -> usize { + self.references(point) + .iter() + .filter_map(|reference| { + let path = paths.element(reference.path as usize)?; + if !path.is_anchor_reference(reference.index as usize, curve_type_at(paths, reference.path as usize)) { + return None; + } + + let last = path.0.len().saturating_sub(1) as u32; + Some(usize::from(reference.index > 0) + usize::from(reference.index < last)) + }) + .sum() + } +} + +#[cfg(test)] +mod tests { + use super::super::path::CurveType; + use super::*; + use core_types::list::{ATTR_CURVE_TYPE, Item}; + + fn paths(specs: &[(CurveType, &[u32])]) -> List { + let mut paths = List::new(); + + for &(curve_type, references) in specs { + let path = Path(references.iter().map(|&reference| Item::new_from_element(reference)).collect()); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); + } + + paths + } + + // A closed circle crossed by a chord welded at two of its anchors, plus two points no path names + #[test] + fn spokes_at_welds_and_free_points() { + let paths = paths(&[(CurveType::Cubic, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0]), (CurveType::Linear, &[0, 12, 6])]); + let connectivity = Connectivity::build(15, &paths); + + // The seam contributes two spokes and the chord a third + assert_eq!(connectivity.spokes(0, &paths), 3); + assert_eq!(connectivity.spokes(6, &paths), 3); + + assert_eq!(connectivity.spokes(3, &paths), 2); + assert_eq!(connectivity.spokes(12, &paths), 2); + + // Handles carry no segments, and unreferenced points are free + assert_eq!(connectivity.spokes(1, &paths), 0); + assert!(!connectivity.is_referenced(13)); + assert!(connectivity.is_referenced(12)); + } + + #[test] + fn references_name_every_use() { + let paths = paths(&[(CurveType::Linear, &[0, 1, 2]), (CurveType::Linear, &[2, 3])]); + let connectivity = Connectivity::build(4, &paths); + + assert_eq!(connectivity.references(0), [Reference { path: 0, index: 0 }]); + assert_eq!(connectivity.references(2), [Reference { path: 0, index: 2 }, Reference { path: 1, index: 0 }]); + assert_eq!(connectivity.spokes(2, &paths), 2); + } + + // References falling anywhere outside the pool are ignored, including one exactly at its end + #[test] + fn dangling_references_are_ignored() { + let paths = paths(&[(CurveType::Linear, &[0, 3, 1, 4])]); + let connectivity = Connectivity::build(3, &paths); + + assert_eq!(connectivity.references(0), [Reference { path: 0, index: 0 }]); + assert_eq!(connectivity.references(1), [Reference { path: 0, index: 2 }]); + assert_eq!(connectivity.references(3), []); + assert_eq!(connectivity.references(4), []); + } + + // An open end has one spoke, which is what makes it a cap site + #[test] + fn free_ends_have_one_spoke() { + let paths = paths(&[(CurveType::Linear, &[0, 1, 2])]); + let connectivity = Connectivity::build(3, &paths); + + assert_eq!(connectivity.spokes(0, &paths), 1); + assert_eq!(connectivity.spokes(2, &paths), 1); + assert_eq!(connectivity.spokes(1, &paths), 2); + } +} diff --git a/node-graph/libraries/vector-types/src/vector/contour.rs b/node-graph/libraries/vector-types/src/vector/contour.rs new file mode 100644 index 0000000000..cbcf5648f3 --- /dev/null +++ b/node-graph/libraries/vector-types/src/vector/contour.rs @@ -0,0 +1,352 @@ +use super::misc::dvec2_to_point; +use super::path::{Path, append_segment, curve_type_at}; +use core_types::list::List; +use glam::DVec2; +use kurbo::BezPath; + +/// One span of a path as a subpath walks it, running against its stored direction when reversed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Step { + pub path: u32, + pub span: u32, + pub reversed: bool, +} + +/// Spans walked end to end across the anchors they share, from one pool point to another. +/// A closed subpath arrives back at the point it left from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Subpath { + pub steps: Vec, + pub closed: bool, + pub entry: u32, + pub exit: u32, +} + +/// A span flattened out of its path, naming the anchors at its two ends. +struct Edge { + path: u32, + span: u32, + start: u32, + end: u32, +} + +/// Each anchor's span ends in the order the spans were woven, consumed as the walk uses them up. +/// An end is named by twice its edge's index, plus one for the end the span arrives at. +struct SpanEnds { + offsets: Vec, + ends: Vec, + cursors: Vec, + used: Vec, + remaining: Vec, +} + +impl SpanEnds { + fn new(point_count: usize, edges: &[Edge]) -> Self { + let mut offsets = vec![0; point_count + 1]; + for edge in edges { + offsets[edge.start as usize + 1] += 1; + offsets[edge.end as usize + 1] += 1; + } + for point in 0..point_count { + offsets[point + 1] += offsets[point]; + } + + let mut ends = vec![0; edges.len() * 2]; + let mut fill = offsets.clone(); + for (index, edge) in edges.iter().enumerate() { + for (point, end) in [(edge.start as usize, index * 2), (edge.end as usize, index * 2 + 1)] { + ends[fill[point]] = end; + fill[point] += 1; + } + } + + let remaining = (0..point_count).map(|point| offsets[point + 1] - offsets[point]).collect(); + + Self { + cursors: offsets[..point_count].to_vec(), + offsets, + ends, + used: vec![false; edges.len() * 2], + remaining, + } + } + + /// Uses up the earliest woven span end still waiting at the point. + fn take_earliest(&mut self, point: usize) -> Option { + while self.cursors[point] < self.offsets[point + 1] { + let end = self.ends[self.cursors[point]]; + self.cursors[point] += 1; + + if !self.used[end] { + self.used[end] = true; + self.remaining[point] -= 1; + return Some(end); + } + } + + None + } + + /// Uses up one particular span end, which is the far side of a span the walk just crossed. + fn take(&mut self, point: usize, end: usize) { + if !self.used[end] { + self.used[end] = true; + self.remaining[point] -= 1; + } + } +} + +/// Walks every span into subpaths in O(points + spans): open ones first, each from a point one span end meets, +/// then the rest from the lowest point with spans left. A walk follows the earliest woven span waiting at each +/// point, backwards when that span ends there, and closes on arriving back where it began. +pub fn subpaths(point_count: usize, paths: &List) -> Vec { + let mut edges = Vec::new(); + for (path_index, path) in paths.iter_element_values().enumerate() { + let curve_type = curve_type_at(paths, path_index); + let stride = curve_type.stride(); + + for span in 0..path.segment_count(curve_type) { + let references = (span * stride..=(span + 1) * stride).map(|index| path.0.element(index).copied()); + let Some(references) = references.collect::>>() else { continue }; + + // A span naming a point outside the pool cannot be drawn, so it takes no part in the walk + if references.iter().any(|&reference| reference as usize >= point_count) { + continue; + } + let (Some(&start), Some(&end)) = (references.first(), references.last()) else { continue }; + + edges.push(Edge { + path: path_index as u32, + span: span as u32, + start, + end, + }); + } + } + + let mut span_ends = SpanEnds::new(point_count, &edges); + let mut found = Vec::new(); + let (mut skip, mut open_ends_done) = (0, false); + + loop { + let mut entry = None; + if !open_ends_done { + entry = (skip..point_count).find(|&point| span_ends.remaining[point] == 1); + open_ends_done = entry.is_none(); + skip = entry.map_or(0, |point| point + 1); + } + if entry.is_none() { + entry = (skip..point_count).find(|&point| span_ends.remaining[point] > 0); + skip = entry.unwrap_or(point_count); + } + let Some(entry) = entry else { break }; + + let (mut point, mut steps, mut closed) = (entry, Vec::new(), false); + while let Some(end) = span_ends.take_earliest(point) { + let edge = &edges[end / 2]; + let reversed = end % 2 == 1; + let next = if reversed { edge.start } else { edge.end } as usize; + + steps.push(Step { + path: edge.path, + span: edge.span, + reversed, + }); + span_ends.take(next, end ^ 1); + point = next; + + if next == entry { + closed = true; + break; + } + } + + found.push(Subpath { + steps, + closed, + entry: entry as u32, + exit: point as u32, + }); + } + + found +} + +/// Emits one subpath as a bezpath, or `None` when it has no drawable geometry. +pub fn subpath_to_bezpath(pool: &List, paths: &List, subpath: &Subpath) -> Option { + let mut bezpath = BezPath::new(); + bezpath.move_to(dvec2_to_point(*pool.element(subpath.entry as usize)?)); + + for step in &subpath.steps { + let path = paths.element(step.path as usize)?; + let segment = path.segment(pool, curve_type_at(paths, step.path as usize), step.span as usize)?; + + append_segment(&mut bezpath, if step.reversed { segment.reverse() } else { segment }); + } + + if subpath.closed { + bezpath.close_path(); + } + + Some(bezpath) +} + +/// Assembles the paths into contours for rendering, one bezpath per subpath in the order they are walked. +pub fn contours(pool: &List, paths: &List) -> Vec { + subpaths(pool.len(), paths).iter().filter_map(|subpath| subpath_to_bezpath(pool, paths, subpath)).collect() +} + +#[cfg(test)] +mod tests { + use super::super::path::pool_and_paths_from_bezpath; + use super::*; + use core_types::list::Item; + use kurbo::PathEl; + + fn bezpath_of(build: impl FnOnce(&mut BezPath)) -> BezPath { + let mut bezpath = BezPath::new(); + build(&mut bezpath); + + bezpath + } + + /// Linear paths over a pool of the given size, one path per list of references. + fn linear(point_count: usize, paths: &[&[u32]]) -> (List, List) { + let pool = (0..point_count).map(|index| Item::new_from_element(DVec2::new(index as f64, (index * index) as f64))).collect(); + let paths = paths + .iter() + .map(|references| Item::new_from_element(Path(references.iter().copied().map(Item::new_from_element).collect()))) + .collect(); + + (pool, paths) + } + + /// The anchors each subpath visits, with whether it closed. + fn walked(point_count: usize, paths: &List) -> Vec<(Vec, bool)> { + subpaths(point_count, paths) + .into_iter() + .map(|subpath| { + let mut anchors = vec![subpath.entry]; + for step in &subpath.steps { + let path = paths.element(step.path as usize).expect("the step names a path"); + let (start, end) = (path.0.element(step.span as usize), path.0.element(step.span as usize + 1)); + anchors.push(*if step.reversed { start } else { end }.expect("the span has both ends")); + } + if subpath.closed { + anchors.pop(); + } + + (anchors, subpath.closed) + }) + .collect() + } + + // The three paths a mixed-verb subpath weaves into rejoin as the one contour the artist drew + #[test] + fn split_subpath_rejoins_as_one_contour() { + let source = bezpath_of(|bezpath| { + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.curve_to((15., 5.), (15., 10.), (10., 15.)); + bezpath.close_path(); + }); + let (pool, paths) = pool_and_paths_from_bezpath(&source); + assert_eq!(paths.len(), 3); + + let assembled = contours(&pool, &paths); + assert_eq!(assembled.len(), 1); + assert!(matches!( + assembled[0].elements(), + [PathEl::MoveTo(_), PathEl::LineTo(_), PathEl::CurveTo(..), PathEl::LineTo(_), PathEl::ClosePath] + )); + } + + // Separate shapes stay separate contours + #[test] + fn disjoint_shapes_emit_separately() { + let source = bezpath_of(|bezpath| { + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.line_to((10., 10.)); + bezpath.close_path(); + bezpath.move_to((20., 20.)); + bezpath.line_to((30., 20.)); + bezpath.close_path(); + }); + let (pool, paths) = pool_and_paths_from_bezpath(&source); + + assert_eq!(contours(&pool, &paths).len(), 2); + } + + // An open subpath emits one contour that stays open + #[test] + fn open_subpath_joins_without_closing() { + let source = bezpath_of(|bezpath| { + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.curve_to((15., 5.), (15., 10.), (10., 15.)); + }); + let (pool, paths) = pool_and_paths_from_bezpath(&source); + assert_eq!(paths.len(), 2); + + let assembled = contours(&pool, &paths); + assert_eq!(assembled.len(), 1); + assert!(matches!(assembled[0].elements(), [PathEl::MoveTo(_), PathEl::LineTo(_), PathEl::CurveTo(..)])); + } + + // A loop leaves from its lowest point along the earliest span there, which it crosses backwards when that span ends at the point + #[test] + fn loop_walks_backwards_when_its_earliest_span_arrives() { + let (_, paths) = linear(4, &[&[1, 2, 3, 0, 1]]); + + assert_eq!(walked(4, &paths), [(vec![0, 3, 2, 1], true)]); + } + + // An open subpath leaves from its lower end even when that is where it was woven to + #[test] + fn open_subpath_leaves_from_its_lower_end() { + let (_, paths) = linear(4, &[&[0, 1, 2], &[3, 0]]); + + assert_eq!(walked(4, &paths), [(vec![2, 1, 0, 3], false)]); + } + + // Open subpaths lead, however high their points, and loops follow in the order of their lowest points + #[test] + fn open_subpaths_lead_the_loops() { + let (_, paths) = linear(8, &[&[5, 6, 7, 5], &[0, 1, 2, 0], &[3, 4]]); + + assert_eq!(walked(8, &paths), [(vec![3, 4], false), (vec![0, 1, 2], true), (vec![5, 6, 7], true)]); + } + + // Loops that touch an outline are walked apart from it, since the outline's own spans were woven first + #[test] + fn touching_loops_walk_apart_from_the_outline() { + let (_, paths) = linear(6, &[&[0, 1, 2, 3, 0], &[1, 4, 1], &[3, 5, 3]]); + + assert_eq!(walked(6, &paths), [(vec![0, 1, 2, 3], true), (vec![1, 4], true), (vec![3, 5], true)]); + } + + // A walk carries on through a junction along its earliest span and ends where none are left + #[test] + fn junction_is_walked_through_along_its_earliest_span() { + let (_, paths) = linear(4, &[&[0, 3], &[1, 3], &[2, 3]]); + + assert_eq!(walked(4, &paths), [(vec![0, 3, 1], false), (vec![2, 3], false)]); + } + + // A walk that arrives back at a point other than the one it left from stays open + #[test] + fn loop_on_a_tail_stays_open() { + let (_, paths) = linear(4, &[&[0, 1, 2, 3, 1]]); + + assert_eq!(walked(4, &paths), [(vec![0, 1, 2, 3, 1], false)]); + } + + // A span naming a point outside the pool is left out of the walk + #[test] + fn dangling_span_is_left_out() { + let (_, paths) = linear(3, &[&[0, 1, 9], &[1, 2]]); + + assert_eq!(walked(3, &paths), [(vec![0, 1, 2], false)]); + } +} diff --git a/node-graph/libraries/vector-types/src/vector/mod.rs b/node-graph/libraries/vector-types/src/vector/mod.rs index edc01337cd..e290c269b0 100644 --- a/node-graph/libraries/vector-types/src/vector/mod.rs +++ b/node-graph/libraries/vector-types/src/vector/mod.rs @@ -1,12 +1,20 @@ +mod addressing; pub mod algorithms; pub mod click_target; +mod connectivity; +mod contour; pub mod misc; +mod path; pub mod reference_point; pub mod style; mod vector_attributes; mod vector_modification; mod vector_types; +pub use addressing::*; +pub use connectivity::*; +pub use contour::*; +pub use path::*; pub use reference_point::*; pub use vector_attributes::*; pub use vector_modification::*; diff --git a/node-graph/libraries/vector-types/src/vector/path.rs b/node-graph/libraries/vector-types/src/vector/path.rs new file mode 100644 index 0000000000..4227f610ae --- /dev/null +++ b/node-graph/libraries/vector-types/src/vector/path.rs @@ -0,0 +1,450 @@ +use super::algorithms::consts::CLOSE_POINT_TOLERANCE; +use super::misc::{dvec2_to_point, point_to_dvec2}; +use core_types::list::{ATTR_CURVE_TYPE, ATTR_PATHS, Item, List}; +use glam::DVec2; +use graphene_hash::CacheHash; +use kurbo::{BezPath, CubicBez, Line, PathEl, PathSeg, Point, QuadBez}; + +/// The curve family a path's point references weave in, fixing the stride of its reference pattern. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)] +pub enum CurveType { + /// Straight segments between consecutive anchors, with every reference an anchor. + #[default] + Linear, + /// Quadratic Bézier segments, with one handle reference between each pair of anchors. + Quadratic, + /// Cubic Bézier segments, with two handle references between each pair of anchors. + Cubic, +} + +impl CurveType { + /// Returns the number of references stepping from one anchor to the next: the segment's handle count plus one. + pub fn stride(&self) -> usize { + match self { + Self::Linear => 1, + Self::Quadratic => 2, + Self::Cubic => 3, + } + } +} + +impl std::fmt::Display for CurveType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Linear => write!(f, "Linear"), + Self::Quadratic => write!(f, "Quadratic"), + Self::Cubic => write!(f, "Cubic"), + } + } +} + +/// One connected stroke of geometry: an ordered list of references (indices into the owning `Vector`'s point pool) +/// woven in its curve type's stride order. Welding is two paths, or two ends of one path, referencing the same anchor. +/// Per-reference data such as `ATTR_SMOOTH` rides this list's attributes. +#[derive(Clone, Debug, Default, PartialEq, CacheHash)] +pub struct Path(pub List); + +impl Path { + /// Whether this path is closed, indicated by its first and last references naming the same pool point. + pub fn is_closed(&self) -> bool { + let len = self.0.len(); + len > 1 && self.0.element(0) == self.0.element(len - 1) + } + + /// Whether the reference at the given index is an anchor (rather than a handle) under the given curve type. + pub fn is_anchor_reference(&self, index: usize, curve_type: CurveType) -> bool { + index.is_multiple_of(curve_type.stride()) + } + + /// The number of segments this path draws, one fewer than its anchor count when open and equal to it when closed. + pub fn segment_count(&self, curve_type: CurveType) -> usize { + self.0.len().saturating_sub(1) / curve_type.stride() + } + + /// The pool position named by the reference at `index`, or `None` if either lookup falls out of bounds. + pub fn position(&self, pool: &List, index: usize) -> Option { + pool.element(*self.0.element(index)? as usize).copied() + } + + /// The segment at `index`, resolved against the point pool. + pub fn segment(&self, pool: &List, curve_type: CurveType, index: usize) -> Option { + let start = index * curve_type.stride(); + let point = |offset: usize| self.position(pool, start + offset).map(dvec2_to_point); + + Some(match curve_type { + CurveType::Linear => PathSeg::Line(Line::new(point(0)?, point(1)?)), + CurveType::Quadratic => PathSeg::Quad(QuadBez::new(point(0)?, point(1)?, point(2)?)), + CurveType::Cubic => PathSeg::Cubic(CubicBez::new(point(0)?, point(1)?, point(2)?, point(3)?)), + }) + } +} + +/// Appends a segment to a bezpath already positioned at that segment's start point. +pub fn append_segment(bezpath: &mut BezPath, segment: PathSeg) { + match segment { + PathSeg::Line(line) => bezpath.line_to(line.p1), + PathSeg::Quad(quad) => bezpath.quad_to(quad.p1, quad.p2), + PathSeg::Cubic(cubic) => bezpath.curve_to(cubic.p1, cubic.p2, cubic.p3), + } +} + +/// The paths an item carries beside a vector element, absent when the pool is a bare point cloud. +pub fn paths_from_item_attributes(item: &Item) -> Option<&List> { + item.attribute(ATTR_PATHS) +} + +/// The paths a list carries at `index` beside a vector element, absent when the pool is a bare point cloud. +pub fn paths_from_list_row_attributes(list: &List, index: usize) -> Option<&List> { + list.attribute(ATTR_PATHS, index) +} + +/// The curve type the path at `index` weaves in. +pub fn curve_type_at(paths: &List, index: usize) -> CurveType { + paths.attribute_cloned_or_default(ATTR_CURVE_TYPE, index) +} + +/// Weaves bezpath contours into pool points and paths, starting a new path at each verb change so every +/// path keeps one stride. The runs of a split subpath share the anchor they meet at, welding them. +struct PathWeaver { + positions: Vec, + offset: u32, + woven: Vec<(CurveType, Vec)>, + references: Vec, + curve_type: Option, + subpath_start: Option, +} + +impl PathWeaver { + fn new(offset: u32) -> Self { + Self { + positions: Vec::new(), + offset, + woven: Vec::new(), + references: Vec::new(), + curve_type: None, + subpath_start: None, + } + } + + /// Adds a point to the pool being built and returns the reference naming it. + fn push_point(&mut self, point: Point) -> u32 { + self.positions.push(point_to_dvec2(point)); + self.offset + self.positions.len() as u32 - 1 + } + + fn position(&self, reference: u32) -> Option { + self.positions.get(reference.checked_sub(self.offset)? as usize).copied() + } + + /// Banks the references woven so far as a finished path, dropping a lone anchor that drew nothing. + fn flush(&mut self) { + if self.references.len() >= 2 { + let curve_type = self.curve_type.unwrap_or_default(); + self.woven.push((curve_type, std::mem::take(&mut self.references))); + } + + self.references.clear(); + self.curve_type = None; + } + + /// Prepares to weave a segment of the given curve type, splitting at the shared anchor when the verb changes. + /// Returns whether an anchor exists to draw from. + fn begin_segment(&mut self, verb: CurveType) -> bool { + // After a close the pen rests on the subpath's first point, so a segment drawn with no new MoveTo departs from there + let weld = match self.references.last() { + Some(&weld) => weld, + None => { + let Some(start) = self.subpath_start else { return false }; + self.references.push(start); + start + } + }; + + if let Some(current) = self.curve_type + && current != verb + { + self.flush(); + self.references.push(weld); + } + self.curve_type = Some(verb); + + true + } + + fn push_element(&mut self, element: PathEl) { + match element { + PathEl::MoveTo(point) => { + self.flush(); + let reference = self.push_point(point); + self.subpath_start = Some(reference); + self.references.push(reference); + } + PathEl::LineTo(anchor) => self.push_segment(CurveType::Linear, &[anchor]), + PathEl::QuadTo(handle, anchor) => self.push_segment(CurveType::Quadratic, &[handle, anchor]), + PathEl::CurveTo(start_handle, end_handle, anchor) => self.push_segment(CurveType::Cubic, &[start_handle, end_handle, anchor]), + PathEl::ClosePath => self.close(), + } + } + + fn push_segment(&mut self, verb: CurveType, points: &[Point]) { + if !self.begin_segment(verb) { + return; + } + + for &point in points { + let reference = self.push_point(point); + self.references.push(reference); + } + } + + /// Closes the subpath by naming its first point again, drawing a straight line home when the pen sits elsewhere. + fn close(&mut self) { + let (Some(start), Some(&last)) = (self.subpath_start, self.references.last()) else { return }; + + if last == start { + self.flush(); + return; + } + + // A final anchor resting on the subpath's first point is that same point, so name it instead of duplicating it + let coincident = matches!((self.position(last), self.position(start)), (Some(last), Some(start)) if last.distance_squared(start) <= CLOSE_POINT_TOLERANCE * CLOSE_POINT_TOLERANCE); + if coincident { + self.references.pop(); + self.references.push(start); + if last as usize + 1 == self.offset as usize + self.positions.len() { + self.positions.pop(); + } + } else if self.begin_segment(CurveType::Linear) { + self.references.push(start); + } + + self.flush(); + } + + fn finish(mut self, pool: &mut List, paths: &mut List) { + self.flush(); + + for position in self.positions { + pool.push(Item::new_from_element(position)); + } + + for (curve_type, references) in self.woven { + let path = Path(references.into_iter().map(Item::new_from_element).collect()); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); + } + } +} + +/// Appends a bezpath's contours to a point pool and its paths. +pub fn append_bezpath(pool: &mut List, paths: &mut List, bezpath: &BezPath) { + let mut weaver = PathWeaver::new(pool.len() as u32); + + for &element in bezpath.elements() { + weaver.push_element(element); + } + + weaver.finish(pool, paths); +} + +/// Builds a fresh point pool and its paths from a bezpath. +pub fn pool_and_paths_from_bezpath(bezpath: &BezPath) -> (List, List) { + let (mut pool, mut paths) = (List::new(), List::new()); + append_bezpath(&mut pool, &mut paths, bezpath); + + (pool, paths) +} + +#[cfg(test)] +mod tests { + use super::*; + use kurbo::{Rect, Shape}; + + fn pool(positions: &[(f64, f64)]) -> List { + positions.iter().map(|&(x, y)| Item::new_from_element(DVec2::new(x, y))).collect() + } + + fn path(references: &[u32]) -> Path { + Path(references.iter().map(|&reference| Item::new_from_element(reference)).collect()) + } + + #[test] + fn open_linear_path() { + let pool = pool(&[(0., 0.), (10., 0.), (10., 10.)]); + let path = path(&[0, 1, 2]); + + assert!(!path.is_closed()); + assert_eq!(path.segment_count(CurveType::Linear), 2); + assert_eq!(path.segment(&pool, CurveType::Linear, 1), Some(PathSeg::Line(Line::new((10., 0.), (10., 10.))))); + assert_eq!(path.segment(&pool, CurveType::Linear, 2), None); + } + + // A closed path repeats its first reference last, so anchors and segments count alike + #[test] + fn closed_cubic_path() { + let pool = pool(&[(0., 0.), (5., 0.), (10., 5.), (10., 10.), (10., 15.), (5., 20.)]); + let path = path(&[0, 1, 2, 3, 4, 5, 0]); + + assert!(path.is_closed()); + assert_eq!(path.segment_count(CurveType::Cubic), 2); + assert_eq!( + path.segment(&pool, CurveType::Cubic, 1), + Some(PathSeg::Cubic(CubicBez::new((10., 10.), (10., 15.), (5., 20.), (0., 0.)))) + ); + } + + // Anchor occurrences fall on stride multiples, and the references between them are handles + #[test] + fn anchor_references_by_stride() { + let path = path(&[0, 1, 2, 3]); + + assert!(path.is_anchor_reference(0, CurveType::Cubic)); + assert!(!path.is_anchor_reference(1, CurveType::Cubic)); + assert!(!path.is_anchor_reference(2, CurveType::Cubic)); + assert!(path.is_anchor_reference(3, CurveType::Cubic)); + assert!(path.is_anchor_reference(2, CurveType::Quadratic)); + assert!(path.is_anchor_reference(2, CurveType::Linear)); + } + + // A reference naming a point the pool does not have drops its segment instead of panicking + #[test] + fn dangling_reference_skips_its_segment() { + let pool = pool(&[(0., 0.), (10., 0.)]); + let path = path(&[0, 1, 99]); + + assert_eq!(path.segment_count(CurveType::Linear), 2); + assert!(path.segment(&pool, CurveType::Linear, 0).is_some()); + assert_eq!(path.segment(&pool, CurveType::Linear, 1), None); + } + + // Four corners draw four sides from five references, the last repeating the first to close the shape + #[test] + fn closed_rectangle() { + let pool = pool(&[(-36.25, -17.5), (36.25, -17.5), (36.25, 17.5), (-36.25, 17.5)]); + let mut paths = List::new(); + paths.push(Item::new_from_element(path(&[0, 1, 2, 3, 0]))); + paths.set_attribute(ATTR_CURVE_TYPE, 0, CurveType::Linear); + + let rectangle = paths.element(0).unwrap(); + assert!(rectangle.is_closed()); + assert_eq!(rectangle.segment_count(CurveType::Linear), 4); + + let closing_side = rectangle.segment(&pool, curve_type_at(&paths, 0), 3); + assert_eq!(closing_side, Some(PathSeg::Line(Line::new((-36.25, 17.5), (-36.25, -17.5))))); + } + + // Connectivity rides the holder, so a pool with a holder that declares no paths is a point cloud + #[test] + fn paths_ride_the_holder() { + let mut item = Item::new_from_element(pool(&[(0., 0.), (10., 0.)])); + assert!(paths_from_item_attributes(&item).is_none()); + + let mut paths = List::new(); + paths.push(Item::new_from_element(path(&[0, 1]))); + item.set_attribute(ATTR_PATHS, paths); + + assert_eq!(paths_from_item_attributes(&item).map(List::len), Some(1)); + assert_eq!(curve_type_at(paths_from_item_attributes(&item).unwrap(), 0), CurveType::Linear); + } + + // Two merged rectangles keep their own paths on their own items + #[test] + fn each_list_item_carries_its_own_paths() { + let mut vectors = List::new(); + for _ in 0..2 { + let mut paths = List::new(); + paths.push(Item::new_from_element(path(&[0, 1, 2, 3, 0]))); + vectors.push(Item::new_from_element(pool(&[(0., 0.), (1., 0.), (1., 1.), (0., 1.)])).with_attribute(ATTR_PATHS, paths)); + } + + assert_eq!(vectors.len(), 2); + for index in 0..vectors.len() { + let paths = paths_from_list_row_attributes(&vectors, index).unwrap(); + assert_eq!(paths.element(0).unwrap().segment_count(CurveType::Linear), 4); + } + } + + // A rectangle weaves to four pool points and five references, the fifth naming the first again + #[test] + fn weave_rectangle() { + let (pool, paths) = pool_and_paths_from_bezpath(&Rect::new(-36.25, -17.5, 36.25, 17.5).to_path(0.)); + + assert_eq!(pool.len(), 4); + assert_eq!(paths.len(), 1); + assert_eq!(curve_type_at(&paths, 0), CurveType::Linear); + + let rectangle = paths.element(0).unwrap(); + assert_eq!(rectangle.0.iter_element_values().copied().collect::>(), vec![0, 1, 2, 3, 0]); + assert!(rectangle.is_closed()); + assert_eq!(rectangle.segment_count(CurveType::Linear), 4); + } + + // A closed contour landing back on its first point names that point rather than duplicating it + #[test] + fn weave_closed_cubic_contour() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.curve_to((5., 0.), (10., 5.), (10., 10.)); + bezpath.curve_to((5., 15.), (0., 5.), (0., 0.)); + bezpath.close_path(); + + let (pool, paths) = pool_and_paths_from_bezpath(&bezpath); + + assert_eq!(pool.len(), 6); + let contour = paths.element(0).unwrap(); + assert_eq!(contour.0.iter_element_values().copied().collect::>(), vec![0, 1, 2, 3, 4, 5, 0]); + assert!(contour.is_closed()); + assert_eq!(contour.segment_count(CurveType::Cubic), 2); + } + + // Mixing verbs splits the subpath into one path per stride, welded where they meet + #[test] + fn weave_splits_at_verb_changes() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.curve_to((15., 5.), (15., 10.), (10., 15.)); + bezpath.close_path(); + + let (_, paths) = pool_and_paths_from_bezpath(&bezpath); + + assert_eq!(paths.len(), 3); + assert_eq!(curve_type_at(&paths, 0), CurveType::Linear); + assert_eq!(curve_type_at(&paths, 1), CurveType::Cubic); + assert_eq!(curve_type_at(&paths, 2), CurveType::Linear); + + let references = |index: usize| paths.element(index).unwrap().0.iter_element_values().copied().collect::>(); + assert_eq!(references(0), vec![0, 1]); + assert_eq!(references(1), vec![1, 2, 3, 4]); + assert_eq!(references(2), vec![4, 0]); + } + + // A lone move leaves a free point in the pool and draws no path + #[test] + fn weave_lone_move_is_a_free_point() { + let mut bezpath = BezPath::new(); + bezpath.move_to((5., 5.)); + + let (pool, paths) = pool_and_paths_from_bezpath(&bezpath); + + assert_eq!(pool.len(), 1); + assert!(paths.is_empty()); + } + + // A segment drawn straight after a close departs from the closed subpath's first point + #[test] + fn weave_continues_from_subpath_start_after_close() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.close_path(); + bezpath.line_to((5., 5.)); + + let (pool, paths) = pool_and_paths_from_bezpath(&bezpath); + + assert_eq!(pool.len(), 3); + assert_eq!(paths.len(), 2); + let references = |index: usize| paths.element(index).unwrap().0.iter_element_values().copied().collect::>(); + assert_eq!(references(0), vec![0, 1, 0]); + assert_eq!(references(1), vec![0, 2]); + } +} diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index 023b086a4a..16fb9a092c 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -12,9 +12,9 @@ use std::iter::zip; macro_rules! create_ids { ($($id:ident),*) => { $( - #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq, Hash, graphene_hash::CacheHash, DynAny)] + #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Ord, Eq, Hash, graphene_hash::CacheHash, DynAny)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] - /// A strongly typed ID + /// A strongly typed ID, defaulting to [`Self::ZERO`]. pub struct $id(u64); impl $id { diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index 70c55b7550..1fedf925ce 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -1,4 +1,5 @@ use super::*; +use crate::vector::algorithms::consts::CLOSE_POINT_TOLERANCE; use crate::vector::misc::BezierHandles; use crate::vector::misc::{HandleId, HandleType, point_to_dvec2, segment_to_handles}; use core_types::uuid::generate_uuid; @@ -587,10 +588,6 @@ where deserializer.deserialize_seq(visitor) } -/// Distance below which a path's closing point is treated as coincident with its start point. -/// Matches Kurbo's default path accuracy, so points within an offset operation's own precision are not split into separate anchors. -const CLOSE_POINT_TOLERANCE: f64 = 1e-6; - pub(crate) struct AppendBezpath<'a> { first_point: Option, last_point: Option, From 347e6ac7e40463812da88592fd0bdb5ebcd9bffa Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 16 Oct 2026 14:27:23 -0700 Subject: [PATCH 28/47] Switch vector data to the new pool storage throughout the editor and nodes (#4733) * Swap Vector storage to the point pool and rebuild the vector-types crate on it * Port graphic types, rendering, and the outer node crates to pool storage * Migrate legacy document vector data onto pool storage * Bridge the editor onto pool storage with the VectorGeometry bundle * Port the editor tools to the vector geometry bundle * Show the point pool and paths directly in the Data panel * Port the vector nodes to pool storage and bring the workspace green * Cover the stored modification format with the demo artwork that leans on it --- Cargo.lock | 1 + .../clipboard/clipboard_message_handler.rs | 21 +- .../src/messages/clipboard/utility_types.rs | 4 +- .../document/data_panel/data_panel_message.rs | 12 - .../data_panel/data_panel_message_handler.rs | 110 +- .../portfolio/document/document_message.rs | 10 +- .../document/graph_operation/utility_types.rs | 4 +- .../document/overlays/utility_functions.rs | 8 +- .../document/overlays/utility_types_native.rs | 9 +- .../document/overlays/utility_types_web.rs | 4 +- .../storage_tests/round_trip_tests.rs | 51 + .../utility_types/document_metadata.rs | 12 +- .../network_interface/structure.rs | 25 +- .../document/utility_types/transformation.rs | 10 +- .../graph_modification_utils.rs | 8 +- .../tool/common_functionality/shape_editor.rs | 202 +- .../shapes/shape_utility.rs | 2 +- .../snap_session/scene_mirror.rs | 2 +- .../common_functionality/utility_functions.rs | 44 +- .../tool/tool_messages/freehand_tool.rs | 32 +- .../messages/tool/tool_messages/path_tool.rs | 229 ++- .../messages/tool/tool_messages/pen_tool.rs | 114 +- .../tool/tool_messages/spline_tool.rs | 28 +- .../transform_layer_message_handler.rs | 34 +- editor/src/node_graph_executor.rs | 7 +- editor/src/node_graph_executor/runtime.rs | 12 +- node-graph/graph-craft/src/document/value.rs | 4 +- node-graph/libraries/core-types/src/bounds.rs | 28 + node-graph/libraries/core-types/src/list.rs | 18 +- .../core-types/src/render_complexity.rs | 21 +- node-graph/libraries/graphene-hash/Cargo.toml | 3 +- node-graph/libraries/graphene-hash/src/lib.rs | 38 + .../libraries/graphic-types/src/graphic.rs | 22 +- node-graph/libraries/graphic-types/src/lib.rs | 178 +- .../libraries/rendering/src/renderer.rs | 126 +- .../vector-types/src/vector/addressing.rs | 57 +- .../vector/algorithms/merge_by_distance.rs | 170 +- .../vector-types/src/vector/connectivity.rs | 6 +- .../vector-types/src/vector/contour.rs | 11 +- .../vector-types/src/vector/flatten.rs | 352 ++++ .../vector-types/src/vector/geometry.rs | 254 +++ .../libraries/vector-types/src/vector/misc.rs | 55 +- .../libraries/vector-types/src/vector/mod.rs | 4 + .../libraries/vector-types/src/vector/path.rs | 83 +- .../src/vector/vector_attributes.rs | 1710 +++++++---------- .../src/vector/vector_modification.rs | 426 ++-- .../vector-types/src/vector/vector_types.rs | 1087 +++++++---- node-graph/nodes/graphic/src/graphic.rs | 2 +- node-graph/nodes/gstd/src/lib.rs | 1 + node-graph/nodes/path-bool/src/lib.rs | 21 +- node-graph/nodes/repeat/src/repeat_nodes.rs | 35 +- node-graph/nodes/text/src/path_builder.rs | 30 +- .../nodes/vector/src/generator_nodes.rs | 100 +- .../nodes/vector/src/merge_qr_squares.rs | 10 +- .../vector/src/vector_modification_nodes.rs | 16 +- node-graph/nodes/vector/src/vector_nodes.rs | 1271 +++++++----- 56 files changed, 4235 insertions(+), 2899 deletions(-) create mode 100644 node-graph/libraries/vector-types/src/vector/flatten.rs create mode 100644 node-graph/libraries/vector-types/src/vector/geometry.rs diff --git a/Cargo.lock b/Cargo.lock index b47acff397..28be754b33 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2168,6 +2168,7 @@ version = "0.0.0" dependencies = [ "glam 0.33.10", "graphene-hash-derive", + "kurbo", ] [[package]] diff --git a/editor/src/messages/clipboard/clipboard_message_handler.rs b/editor/src/messages/clipboard/clipboard_message_handler.rs index 333af93eff..77d0da3c56 100644 --- a/editor/src/messages/clipboard/clipboard_message_handler.rs +++ b/editor/src/messages/clipboard/clipboard_message_handler.rs @@ -12,8 +12,9 @@ use crate::messages::tool::utility_types::ToolType; use graph_craft::application_io::resource::{DataSource, ResourceHash}; use graph_craft::document::NodeId; use graphene_std::Color; +use graphene_std::list::List; use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles}; -use graphene_std::vector::{PointId, SegmentId, VectorModificationType}; +use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType}; use graphite_proc_macros::{ExtractField, message_handler_data}; use kurbo::ParamCurve; use std::sync::Arc; @@ -434,18 +435,26 @@ impl MessageHandler> for Clipboard let stroke = graphene_std::vector::style::Stroke::new(DEFAULT_STROKE_WIDTH); responses.add(GraphOperationMessage::StrokeSet { layer, color, stroke }); - // Create new point ids and add those into the existing Vector path + // Materialize the copied snapshot so its points and segments can replay with fresh IDs + let (mut pasted_vector, mut pasted_paths) = (Vector::default(), List::new()); + new_vector.apply(&mut pasted_vector, &mut pasted_paths); + + // Create new point IDs and add those into the existing Vector path let mut points_map = HashMap::new(); - for (point, position) in new_vector.point_domain.iter() { + for index in pasted_vector.anchor_indices(&pasted_paths) { + let (Some(point), Some(position)) = (pasted_vector.point_id_at(index as u32), pasted_vector.position(index)) else { + continue; + }; + let new_point_id = PointId::generate(); points_map.insert(point, new_point_id); let modification_type = VectorModificationType::InsertPoint { id: new_point_id, position }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } - // Create new segment ids and add the segments into the existing Vector path + // Create new segment IDs and add the segments into the existing Vector path let mut segments_map = HashMap::new(); - for (segment_id, segment, start, end) in new_vector.segment_iter() { + for (segment_id, segment, start, end) in pasted_vector.segment_iter(&pasted_paths) { let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else { warn!("Skipping pasted vector segment with an unknown endpoint"); continue; @@ -468,7 +477,7 @@ impl MessageHandler> for Clipboard } // Set G1 continuity - for handles in new_vector.colinear_manipulators { + for handles in pasted_vector.colinear_pairs(&pasted_paths) { let to_new_handle = |handle: HandleId| -> Option { Some(HandleId { ty: handle.ty, diff --git a/editor/src/messages/clipboard/utility_types.rs b/editor/src/messages/clipboard/utility_types.rs index 421215d111..fb8689d992 100644 --- a/editor/src/messages/clipboard/utility_types.rs +++ b/editor/src/messages/clipboard/utility_types.rs @@ -5,7 +5,7 @@ use base64::engine::general_purpose::STANDARD as BASE64; use glam::DAffine2; use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId}; use graph_craft::document::NodeId; -use graphene_std::vector::Vector; +use graphene_std::vector::VectorModification; #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum ClipboardContentRaw { @@ -20,7 +20,7 @@ pub enum ClipboardContent { Image { data: Vec, width: u32, height: u32 }, } -pub type ClipboardVectorEntry = (LayerNodeIdentifier, Vector, DAffine2); +pub type ClipboardVectorEntry = (LayerNodeIdentifier, VectorModification, DAffine2); /// An entry in the `graphite:` clipboard payload. #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs index 9efc67eba8..1fdd7f506f 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message.rs @@ -20,10 +20,6 @@ pub enum DataPanelMessage { TruncateElementPath { len: usize, }, - - ViewVectorTableTab { - tab: VectorTableTab, - }, } /// One hop in the breadcrumb path through nested data the Data panel is displaying. @@ -33,11 +29,3 @@ pub enum PathStep { Element(usize), Attribute { row: usize, key: String }, } - -#[derive(PartialEq, Eq, Clone, Copy, Default, Debug, serde::Serialize, serde::Deserialize)] -pub enum VectorTableTab { - #[default] - Points, - Segments, - Handles, -} diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index 4f0c0145a6..0eb405616e 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -1,4 +1,3 @@ -use super::VectorTableTab; use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup, LayoutTarget}; use crate::messages::portfolio::document::data_panel::{DataPanelMessage, PathStep}; use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface; @@ -25,14 +24,14 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::transfer_curve::TransferCurve; use graphene_std::transform::{ReferencePoint, ScaleType}; use graphene_std::vector::misc::{ - ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, - SpiralType, + ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType, }; use graphene_std::vector::style::{ DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin, }; -use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector}; +use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector}; use graphene_std::{Appearance, Artboard, Color, Context, Cover, Coverage, Graphic}; +use kurbo::BezPath; use std::any::Any; use std::sync::Arc; @@ -51,7 +50,6 @@ pub struct DataPanelMessageHandler { introspected_node_path: Vec, introspected_data: Option>, element_path: Vec, - active_vector_table_tab: VectorTableTab, } #[message_handler_data] @@ -67,7 +65,6 @@ impl MessageHandler> for DataPanel self.introspected_node_path.clear(); self.introspected_data = None; self.element_path.clear(); - self.active_vector_table_tab = VectorTableTab::default(); self.update_layout(responses, context); } DataPanelMessage::Refresh => { @@ -85,11 +82,6 @@ impl MessageHandler> for DataPanel self.element_path.truncate(len); self.update_layout(responses, context); } - - DataPanelMessage::ViewVectorTableTab { tab } => { - self.active_vector_table_tab = tab; - self.update_layout(responses, context); - } } } @@ -114,7 +106,6 @@ impl DataPanelMessageHandler { node_lookup_network_path: Vec::new(), gradient_settings: GradientSettings::default(), breadcrumbs: Vec::new(), - vector_table_tab: self.active_vector_table_tab, }; // Main data visualization @@ -172,7 +163,6 @@ struct LayoutData<'a> { /// rather than in the stop list itself. The enclosing `Item`/`List` sets it to the owning row's attributes. gradient_settings: GradientSettings, breadcrumbs: Vec, - vector_table_tab: VectorTableTab, } macro_rules! generate_layout_downcast { @@ -655,70 +645,42 @@ impl TableItemLayout for Graphic { } } +// The pool is a plain point list with its IDs riding its attributes, so the generic list layout shows it as-is impl TableItemLayout for Vector { fn type_name() -> &'static str { "Vector" } fn identifier(&self) -> String { - format!( - "Vector ({} point{}, {} segment{})", - self.point_domain.ids().len(), - if self.point_domain.ids().len() == 1 { "" } else { "s" }, - self.segment_domain.ids().len(), - if self.segment_domain.ids().len() == 1 { "" } else { "s" } - ) + self.0.identifier() } fn value_page(&self, data: &mut LayoutData) -> Vec { - let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Handles] - .into_iter() - .map(|tab| { - RadioEntryData::new(format!("{tab:?}")) - .label(format!("{tab:?}")) - .on_update(move |_| DataPanelMessage::ViewVectorTableTab { tab }.into()) - }) - .collect(); - let table_tabs = vec![RadioInput::new(table_tab_entries).selected_index(Some(data.vector_table_tab as u32)).widget_instance()]; + self.0.value_page(data) + } +} - let mut table_rows = Vec::new(); - match data.vector_table_tab { - VectorTableTab::Handles => { - table_rows.push(column_headings(&["", "colinear_manipulators[0]", "colinear_manipulators[1]"])); - table_rows.extend(self.colinear_manipulators.iter().enumerate().map(|(index, [a, b])| { - vec![ - TextLabel::new(format!("{index}")).narrow(true).widget_instance(), - TextLabel::new(format!("{a}")).narrow(true).widget_instance(), - TextLabel::new(format!("{b}")).narrow(true).widget_instance(), - ] - })); - } - VectorTableTab::Points => { - table_rows.push(column_headings(&["", "position"])); - table_rows.extend(self.point_domain.iter().map(|(id, position)| { - vec![ - TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(), - TextLabel::new(format_dvec2(position)).narrow(true).widget_instance(), - ] - })); - } - VectorTableTab::Segments => { - table_rows.push(column_headings(&["", "start_point", "end_point", "handles"])); - table_rows.extend(self.segment_domain.iter().map(|(id, start, end, handles)| { - let handles = match handles { - BezierHandles::Linear => "Linear".to_string(), - BezierHandles::Quadratic { handle } => format!("Quadratic — {}", format_dvec2(handle)), - BezierHandles::Cubic { handle_start, handle_end } => format!("Cubic — start: {}, end: {}", format_dvec2(handle_start), format_dvec2(handle_end)), - }; - vec![ - TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(), - TextLabel::new(format!("Point {start}")).narrow(true).widget_instance(), - TextLabel::new(format!("Point {end}")).narrow(true).widget_instance(), - TextLabel::new(handles).narrow(true).widget_instance(), - ] - })); - } - } +// A path is its list of point references, with segment IDs and smooth flags riding its attributes +impl TableItemLayout for Path { + fn type_name() -> &'static str { + "Path" + } + fn identifier(&self) -> String { + self.0.identifier() + } + fn value_page(&self, data: &mut LayoutData) -> Vec { + self.0.value_page(data) + } +} - vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)] +// Only the click target attribute holds a bezpath, so it's named for what it does +impl TableItemLayout for BezPath { + fn type_name() -> &'static str { + "Click Target" + } + fn identifier(&self) -> String { + Self::type_name().to_string() + } + fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec { + vec![TextLabel::new(self.identifier()).narrow(true).widget_instance()] } } @@ -1151,6 +1113,7 @@ macro_rules! known_item_types { List, List, List, + List, List>, List>, List, @@ -1170,6 +1133,8 @@ macro_rules! known_item_types { bool, String, Vector, + Path, + BezPath, Raster, Raster, Graphic, @@ -1230,6 +1195,15 @@ fn display_value_override(any: &dyn Any) -> Option { if let Some(value) = any.downcast_ref::() { return Some(value.to_string()); } + if let Some(value) = any.downcast_ref::() { + return Some(if *value == PointId::UNNAMED { String::new() } else { value.inner().to_string() }); + } + if let Some(value) = any.downcast_ref::() { + return Some(if *value == SegmentId::ZERO { String::new() } else { value.inner().to_string() }); + } + if let Some(value) = any.downcast_ref::() { + return Some(value.to_string()); + } None } diff --git a/editor/src/messages/portfolio/document/document_message.rs b/editor/src/messages/portfolio/document/document_message.rs index de7589019c..c94ce044dd 100644 --- a/editor/src/messages/portfolio/document/document_message.rs +++ b/editor/src/messages/portfolio/document/document_message.rs @@ -13,6 +13,7 @@ use crate::messages::prelude::*; use glam::{DAffine2, IVec2, UVec2}; use graph_craft::document::NodeId; use graphene_std::Appearance; +use graphene_std::list::Item; use graphene_std::raster::BlendMode; use graphene_std::transform::Footprint; use graphene_std::vector::Vector; @@ -295,11 +296,12 @@ pub enum DocumentMessage { UpdateClipTargets { clip_targets: HashSet, }, - UpdateVectorData { - vector_data: HashMap>, - }, // `Message` is only serialized at `editor_wrapper.rs`, and only inputs from JS pass through it. - // `UpdateAppearanceAttributes` is produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so it never reaches that serialization point. + // `UpdateVectorData` and `UpdateAppearanceAttributes` are produced inside `editor.handle_message` by `node_graph_executor.rs` and consumed in the same dispatch loop, so they never reach that serialization point. + #[serde(skip)] + UpdateVectorData { + vector_data: HashMap>>, + }, #[serde(skip)] UpdateAppearanceAttributes { appearance_attributes: HashMap>, diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index 8511b1076c..033b1dbe78 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -147,8 +147,8 @@ impl<'a> ModifyInputsContext<'a> { pub fn insert_vector(&mut self, bezpath: BezPath, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) { // Build a VectorModification that reproduces the geometry (same format the Pen tool uses) - let vector = Vector::from_bezpath(bezpath); - let modification = Box::new(VectorModification::create_from_vector(&vector)); + let (vector, paths) = Vector::from_bezpath(&bezpath); + let modification = Box::new(VectorModification::create_from_vector(&vector, &paths)); let shape = resolve_network_node_type("Path") .expect("Path node does not exist") diff --git a/editor/src/messages/portfolio/document/overlays/utility_functions.rs b/editor/src/messages/portfolio/document/overlays/utility_functions.rs index 59de9f797e..76bc5f2823 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_functions.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_functions.rs @@ -8,7 +8,7 @@ use crate::messages::tool::common_functionality::utility_functions::closest_open use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler; use glam::{DAffine2, DVec2}; use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, point_to_dvec2, segment_to_handles}; -use graphene_std::vector::{PointId, SegmentId, Vector}; +use graphene_std::vector::{PointId, SegmentId, VectorGeometry}; use kurbo::{Affine, ParamCurve, PathSeg}; use std::collections::HashMap; #[cfg(target_family = "wasm")] @@ -44,7 +44,7 @@ pub fn selected_segments(network_interface: &NodeNetworkInterface, shape_editor: map } -pub fn selected_segments_for_layer(vector: &Vector, state: &SelectedLayerState) -> Vec { +pub fn selected_segments_for_layer(vector: &VectorGeometry, state: &SelectedLayerState) -> Vec { let selected_anchors = state .selected_points() .filter_map(|point| if let ManipulatorPointId::Anchor(p) = point { Some(p) } else { None }) @@ -195,7 +195,7 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle } if display_anchors { - for (&id, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (id, position) in vector.anchors() { overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(ManipulatorPointId::Anchor(id)), None); } } @@ -226,7 +226,7 @@ pub fn open_path_endpoint_overlays(document: &DocumentMessageHandler, shape_edit if hovered.is_some_and(|(hovered_layer, hovered_id, _)| hovered_layer == layer && hovered_id == id) { continue; } - let Some(position) = vector.point_domain.position_from_id(id) else { continue }; + let Some(position) = vector.position_from_id(id) else { continue }; overlay_context.manipulator_anchor(transform.transform_point2(position), is_selected(layer, id), None); } diff --git a/editor/src/messages/portfolio/document/overlays/utility_types_native.rs b/editor/src/messages/portfolio/document/overlays/utility_types_native.rs index 5be859a73f..d4dcfdf9b9 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types_native.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types_native.rs @@ -18,7 +18,7 @@ use graphene_std::math::quad::Quad; use graphene_std::text::{TextAlign, TextContext, TypesettingConfig}; use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::misc::point_to_dvec2; -use graphene_std::vector::{PointId, SegmentId, Vector}; +use graphene_std::vector::{PointId, SegmentId, Vector, VectorGeometry, no_paths, paths_from_list_row_attributes}; use kurbo::{self, BezPath, ParamCurve}; use kurbo::{Affine, PathSeg}; use std::collections::HashMap; @@ -379,7 +379,7 @@ impl OverlayContext { } /// Used by the Pen and Path tools to outline the path of the shape. - pub fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) { + pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) { self.internal().outline_vector(vector, transform); } @@ -930,7 +930,7 @@ impl OverlayContextInternal { } /// Used by the Pen and Path tools to outline the path of the shape. - fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) { + fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) { let vello_transform = self.get_transform(); let mut path = BezPath::new(); @@ -1148,7 +1148,8 @@ impl OverlayContextInternal { let transform: DAffine2 = text_list.attribute_cloned_or_default(ATTR_TRANSFORM, index); let Some(element) = text_list.element(index) else { continue }; - for (_, bezier, start_id, end_id) in element.segment_iter() { + let paths = paths_from_list_row_attributes(text_list, index).unwrap_or_else(|| no_paths()); + for (_, bezier, start_id, end_id) in element.segment_iter(paths) { let move_to = last_point != Some(start_id); last_point = Some(end_id); diff --git a/editor/src/messages/portfolio/document/overlays/utility_types_web.rs b/editor/src/messages/portfolio/document/overlays/utility_types_web.rs index 53eb93bf8d..5419513385 100644 --- a/editor/src/messages/portfolio/document/overlays/utility_types_web.rs +++ b/editor/src/messages/portfolio/document/overlays/utility_types_web.rs @@ -15,7 +15,7 @@ use glam::{DAffine2, DVec2}; use graphene_std::math::quad::Quad; use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2}; -use graphene_std::vector::{PointId, SegmentId, Vector}; +use graphene_std::vector::{PointId, SegmentId, VectorGeometry}; use kurbo::{self, Affine, BezPath, CubicBez, ParamCurve, PathSeg}; use std::collections::HashMap; use wasm_bindgen::{JsCast, JsValue}; @@ -854,7 +854,7 @@ impl OverlayContext { } /// Used by the Pen and Path tools to outline the path of the shape. - pub fn outline_vector(&mut self, vector: &Vector, transform: DAffine2) { + pub fn outline_vector(&mut self, vector: &VectorGeometry, transform: DAffine2) { self.start_dpi_aware_transform(); self.render_context.begin_path(); diff --git a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs index 7f4ad9d14a..b7ba3327c3 100644 --- a/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/round_trip_tests.rs @@ -716,6 +716,57 @@ async fn demo_artwork_edit_autosaves_and_round_trips() { editor.active_document_mut().commit_storage_snapshot(&byte_store, true); } +/// Manual edits ride a saved document as a folded `VectorModification`, so opening the artworks carrying the most +/// of them is what proves the stored format still reads and applies. Their Path nodes sit on pen-drawn layers, so +/// each layer's geometry, curves included, comes from its stored modification alone. +#[tokio::test] +async fn demo_artwork_vector_modifications_still_apply() { + use graph_craft::document::value::TaggedValue; + + for name in ["red-dress", "isometric-fountain", "valley-of-spires"] { + let mut editor = EditorTestUtils::create(); + + let data = std::fs::read(format!("../demo-artwork/{name}.graphite")).expect("read demo artwork"); + editor + .handle_message(IngestMessage::Ingest { + data, + action: IngestAction::Open, + mime_type: String::new(), + path: Some(format!("{name}.graphite").into()), + }) + .await; + + let document = editor.active_document(); + let network = &document.network_interface; + let path_definition = DefinitionIdentifier::Network("Path".into()); + let mut path_layers = 0; + let mut any_curve = false; + + for layer in document.metadata().all_layers() { + let Some(path_node) = NodeGraphLayer::new(layer, network).upstream_visible_node_id_from_name_in_layer(&path_definition) else { + continue; + }; + path_layers += 1; + + let stored = network.document_network().nodes.get(&path_node).and_then(|node| node.inputs.get(1)).and_then(|input| input.as_value()); + let Some(TaggedValue::VectorModification(modification)) = stored else { + panic!("{name} layer {layer:?} has a Path node without a stored modification"); + }; + assert!(!modification.is_empty(), "{name} layer {layer:?} stored a modification that changes nothing"); + + let upstream = document.metadata().vector_modify.get(&path_node).expect("the graph run should capture what reaches the Path node"); + assert!(upstream.anchor_points().next().is_none(), "{name} layer {layer:?} has geometry upstream of its Path node"); + + let geometry = network.compute_modified_vector(layer).expect("a layer with a Path node should have a vector"); + assert!(geometry.anchor_points().next().is_some(), "{name} layer {layer:?} surfaced no anchors from its stored modification"); + any_curve |= geometry.segment_iter().any(|(_, segment, ..)| !matches!(segment, kurbo::PathSeg::Line(_))); + } + + assert!(path_layers > 0, "{name} has no layers edited through a Path node"); + assert!(any_curve, "{name} drew no curves from its stored modifications"); + } +} + /// The document's single Fill node, as `(network_path, node_id)`. fn find_fill_node(document: &DocumentMessageHandler) -> (Vec, graph_craft::document::NodeId) { node_paths(&document.network_interface) diff --git a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs index d78eebc3d2..abab0d2276 100644 --- a/editor/src/messages/portfolio/document/utility_types/document_metadata.rs +++ b/editor/src/messages/portfolio/document/utility_types/document_metadata.rs @@ -7,10 +7,11 @@ use crate::messages::tool::common_functionality::graph_modification_utils; use glam::{DAffine2, DVec2}; use graph_craft::document::NodeId; use graphene_std::Appearance; +use graphene_std::list::Item; use graphene_std::math::quad::Quad; use graphene_std::transform::Footprint; -use graphene_std::vector::Vector; use graphene_std::vector::click_target::{ClickTarget, ClickTargetType}; +use graphene_std::vector::{Vector, VectorGeometry, no_paths, paths_from_item_attributes}; use kurbo::BezPath; use std::collections::{HashMap, HashSet}; use std::num::NonZeroU64; @@ -37,10 +38,10 @@ pub struct DocumentMetadata { /// The Text tool composes this with `transform_to_viewport(layer)` to position its drag cage. pub text_frames: HashMap, pub clip_targets: HashSet, - pub vector_modify: HashMap, + pub vector_modify: HashMap, /// Vector data keyed by layer ID, used as fallback when no Path node exists. /// This provides accurate SegmentIds for layers without explicit Path nodes. - pub layer_vector_data: HashMap>, + pub layer_vector_data: HashMap>>, /// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list. pub layer_appearance_attributes: HashMap>, /// Transform from document space to viewport space. @@ -243,13 +244,14 @@ impl DocumentMetadata { /// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based /// bounds for non-vector layers (groups, raster, text, color, gradient). pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> { - if let Some(vector) = self.layer_vector_data.get(&layer) { + if let Some(item) = self.layer_vector_data.get(&layer) { let stroke = self .layer_appearance_attributes .get(&layer) .and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke)) .map(graphene_std::Coverage::stroke_params); - if let Some(bounds) = vector.stroke_inclusive_bounding_box_with_transform(self.transform_to_document(layer), stroke.as_ref()) { + let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths()); + if let Some(bounds) = item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref()) { return Some(bounds); } } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs index 077bc6985f..ac69f4d841 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/structure.rs @@ -1,30 +1,32 @@ use super::*; +use graphene_std::list::Item; +use graphene_std::vector::VectorGeometry; impl NodeNetworkInterface { - pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option { + pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option { let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self); if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into())) - && let Some(vector) = self.document_metadata.vector_modify.get(&path_node) + && let Some(geometry) = self.document_metadata.vector_modify.get(&path_node) { - let mut modified = vector.clone(); + let mut modified = geometry.clone(); let path_node = self.document_network().nodes.get(&path_node); let modification_input = path_node.and_then(|node: &DocumentNode| node.inputs.get(1)).and_then(|input| input.as_value()); if let Some(TaggedValue::VectorModification(modification)) = modification_input { - modification.apply(&mut modified); + modification.apply(&mut modified.vector, &mut modified.paths); } return Some(modified); } - self.document_metadata.layer_vector_data.get(&layer).map(|arc| arc.as_ref().clone()) + self.document_metadata.layer_vector_data.get(&layer).map(|item| VectorGeometry::from_item(item)) } /// The vector geometry an upstream Path node would surface for editing. /// This is the result of `compute_modified_vector`, but only if a visible 'Path' node is actually upstream. /// Useful for tool overlays and snap target collection usages that want to match the Path tool's view /// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing. - pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option { + pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option { let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self); graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?; self.compute_modified_vector(layer) @@ -46,11 +48,8 @@ impl NodeNetworkInterface { targets.push(ClickTargetType::Path(combined)); } - for &point_id in vector.point_domain.ids() { - if !vector.any_connected(point_id) { - let position = vector.point_domain.position_from_id(point_id).unwrap_or_default(); - targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position))); - } + for (point_id, position) in vector.free_points() { + targets.push(ClickTargetType::FreePoint(FreePoint::new(point_id, position))); } Some(targets) @@ -183,13 +182,13 @@ impl NodeNetworkInterface { } /// Update the vector modify of the layers - pub fn update_vector_modify(&mut self, new_vector_modify: HashMap) { + pub fn update_vector_modify(&mut self, new_vector_modify: HashMap) { self.document_metadata.mark_changed(); self.document_metadata.vector_modify = new_vector_modify; } /// Update the layer vector data (for layers without Path nodes) - pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap>) { + pub fn update_vector_data(&mut self, new_layer_vector_data: HashMap>>) { self.document_metadata.mark_changed(); self.document_metadata.layer_vector_data = new_layer_vector_data; } diff --git a/editor/src/messages/portfolio/document/utility_types/transformation.rs b/editor/src/messages/portfolio/document/utility_types/transformation.rs index 36bd24b4ee..ad0b79b446 100644 --- a/editor/src/messages/portfolio/document/utility_types/transformation.rs +++ b/editor/src/messages/portfolio/document/utility_types/transformation.rs @@ -102,7 +102,7 @@ impl OriginalTransforms { // Anchors also move their handles let anchor_ids = selected_points.iter().filter_map(|point| point.as_anchor()); - let anchors = anchor_ids.filter_map(|id| vector.point_domain.position_from_id(id).map(|pos| (id, AnchorPoint { initial: pos, current: pos }))); + let anchors = anchor_ids.filter_map(|id| vector.position_from_id(id).map(|pos| (id, AnchorPoint { initial: pos, current: pos }))); let anchors = anchors.collect(); let selected_handles = selected_points.iter().filter_map(|point| point.as_handle()); @@ -112,13 +112,13 @@ impl OriginalTransforms { let handles = all_handles .filter_map(|id| { - let anchor = id.to_manipulator_point().get_anchor(&vector)?; - let initial = id.to_manipulator_point().get_position(&vector)?; - let relative = vector.point_domain.position_from_id(anchor)?; + let anchor = vector.anchor_of(id.to_manipulator_point())?; + let initial = vector.position_of(id.to_manipulator_point())?; + let relative = vector.position_from_id(anchor)?; let other_handle = vector .other_colinear_handle(id) .filter(|other| !selected_points.contains(&other.to_manipulator_point()) && !selected_points.contains(&ManipulatorPointId::Anchor(anchor))); - let mirror = other_handle.and_then(|id| Some((id, id.to_manipulator_point().get_position(&vector)?))); + let mirror = other_handle.and_then(|id| Some((id, vector.position_of(id.to_manipulator_point())?))); Some((id, HandlePoint { initial, relative, anchor, mirror })) }) diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index 7da430d59a..d3b73dd857 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -175,15 +175,15 @@ pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifie }; let mut handles = [None; 2]; - if let Some(handle_position) = ManipulatorPointId::PrimaryHandle(segment).get_position(&vector) { - let anchor_position = ManipulatorPointId::Anchor(segment_start_point).get_position(&vector).unwrap(); + if let Some(handle_position) = vector.position_of(ManipulatorPointId::PrimaryHandle(segment)) { + let anchor_position = vector.position_of(ManipulatorPointId::Anchor(segment_start_point)).unwrap(); let handle_position = transform.transform_point2(handle_position); let anchor_position = transform.transform_point2(anchor_position); let anchor_to_handle = handle_position - anchor_position; handles[0] = Some(anchor_to_handle); } - if let Some(handle_position) = ManipulatorPointId::EndHandle(segment).get_position(&vector) { - let anchor_position = ManipulatorPointId::Anchor(segment_end_point).get_position(&vector).unwrap(); + if let Some(handle_position) = vector.position_of(ManipulatorPointId::EndHandle(segment)) { + let anchor_position = vector.position_of(ManipulatorPointId::Anchor(segment_end_point)).unwrap(); let handle_position = transform.transform_point2(handle_position); let anchor_position = transform.transform_point2(anchor_position); let anchor_to_handle = handle_position - anchor_position; diff --git a/editor/src/messages/tool/common_functionality/shape_editor.rs b/editor/src/messages/tool/common_functionality/shape_editor.rs index 186dd2d68d..f2ab877275 100644 --- a/editor/src/messages/tool/common_functionality/shape_editor.rs +++ b/editor/src/messages/tool/common_functionality/shape_editor.rs @@ -12,7 +12,7 @@ use glam::{DAffine2, DVec2}; use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table; use graphene_std::vector::algorithms::shapes::polyline_bezpath; use graphene_std::vector::misc::{BezierHandles, HandleId, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModificationType}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{Affine, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveNearest, PathSeg, Rect, Shape}; use std::f64::consts::TAU; @@ -163,13 +163,13 @@ pub struct ShapeState { pub struct SelectedPointsInfo { pub points: Vec, pub offset: DVec2, - pub vector: Vector, + pub vector: VectorGeometry, } #[derive(Debug)] pub struct SelectedSegmentsInfo { pub segments: Vec, - pub vector: Vector, + pub vector: VectorGeometry, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -325,10 +325,7 @@ impl ClosestSegment { } else { let [first_point, last_point] = self.points(); if let Some(vector) = document.network_interface.compute_modified_vector(self.layer()) { - if let (Some(pos1), Some(pos2)) = ( - ManipulatorPointId::Anchor(first_point).get_position(&vector), - ManipulatorPointId::Anchor(last_point).get_position(&vector), - ) { + if let (Some(pos1), Some(pos2)) = (vector.position_of(ManipulatorPointId::Anchor(first_point)), vector.position_of(ManipulatorPointId::Anchor(last_point))) { (pos1 - pos2).try_normalize() } else { None @@ -441,8 +438,8 @@ impl ShapeState { responses: &mut VecDeque, ) { // Get the local positions of the selected points - let start_local_pos = document.network_interface.compute_modified_vector(layer1).and_then(|v| v.point_domain.position_from_id(start_point)); - let end_local_pos = document.network_interface.compute_modified_vector(layer2).and_then(|v| v.point_domain.position_from_id(end_point)); + let start_local_pos = document.network_interface.compute_modified_vector(layer1).and_then(|v| v.position_from_id(start_point)); + let end_local_pos = document.network_interface.compute_modified_vector(layer2).and_then(|v| v.position_from_id(end_point)); // Transform to document/world space let start_transform = document.metadata().transform_to_document(layer1); @@ -541,7 +538,7 @@ impl ShapeState { for &layer in self.selected_shape_state.keys() { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; - let endpoints: Vec = vector.point_domain.ids().iter().copied().filter(|&point_id| vector.all_connected(point_id).count() == 1).collect(); + let endpoints: Vec = vector.anchor_endpoints().collect(); if endpoints.len() == 2 { let start_point = endpoints[0]; @@ -575,7 +572,7 @@ impl ShapeState { if let Some((layer, manipulator_point_id)) = self.find_nearest_visible_point_indices(network_interface, mouse_position, select_threshold, path_overlay_mode, frontier_handles_info) { let vector = network_interface.compute_modified_vector(layer)?; - let point_position = manipulator_point_id.get_position(&vector)?; + let point_position = vector.position_of(manipulator_point_id)?; let selected_shape_state = self.selected_shape_state.get(&layer)?; let already_selected = selected_shape_state.is_point_selected(manipulator_point_id); @@ -629,7 +626,7 @@ impl ShapeState { return None; } let vector = network_interface.compute_modified_vector(layer)?; - let point_position = manipulator_point_id.get_position(&vector)?; + let point_position = vector.position_of(manipulator_point_id)?; let selected_shape_state = self.selected_shape_state.get(&layer)?; // Check if point is visible under current overlay mode or not let selected_segments_for_layer = selected_segments_for_layer(&vector, selected_shape_state); @@ -701,12 +698,12 @@ impl ShapeState { if selected_stack.is_empty() { // Fall back on just selecting all points/segments in the layer if points { - for &point in vector.point_domain.ids() { + for point in vector.anchor_points() { state.select_point(ManipulatorPointId::Anchor(point)); } } if segments { - for &segment in vector.segment_domain.ids() { + for segment in vector.segment_ids() { state.select_segment(segment); } } @@ -761,7 +758,7 @@ impl ShapeState { state.clear_points(); - for &point in vector.point_domain.ids() { + for point in vector.anchor_points() { state.select_point(ManipulatorPointId::Anchor(point)) } } @@ -770,7 +767,7 @@ impl ShapeState { fn select_all_segments_in_layer_with_state(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, state: &mut SelectedLayerState) { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - for &segment in vector.segment_domain.ids() { + for segment in vector.segment_ids() { state.select_segment(segment); } } @@ -880,7 +877,7 @@ impl ShapeState { }); } - pub fn move_anchor(&self, point: PointId, vector: &Vector, delta: DVec2, layer: LayerNodeIdentifier, selected: Option<&SelectedLayerState>, responses: &mut VecDeque) { + pub fn move_anchor(&self, point: PointId, vector: &VectorGeometry, delta: DVec2, layer: LayerNodeIdentifier, selected: Option<&SelectedLayerState>, responses: &mut VecDeque) { // Move anchor responses.add(GraphOperationMessage::Vector { layer, @@ -921,7 +918,7 @@ impl ShapeState { let vector = network_interface.compute_modified_vector(layer)?; let transform = network_interface.document_metadata().transform_to_document_if_feeds(layer, network_interface).inverse(); let position = transform.transform_point2(new_position); - let current_position = point.get_position(&vector)?; + let current_position = vector.position_of(*point)?; let delta = position - current_position; match *point { @@ -929,18 +926,18 @@ impl ShapeState { ManipulatorPointId::PrimaryHandle(segment) => { self.move_primary(segment, delta, layer, responses); if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_manipulators.iter().find(|handles| handles[0] == handle || handles[1] == handle) + && let Some(handles) = vector.colinear_pair_containing(handle) { - let modification_type = VectorModificationType::SetG1Continuous { handles: *handles, enabled: false }; + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } ManipulatorPointId::EndHandle(segment) => { self.move_end(segment, delta, layer, responses); if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_manipulators.iter().find(|handles| handles[0] == handle || handles[1] == handle) + && let Some(handles) = vector.colinear_pair_containing(handle) { - let modification_type = VectorModificationType::SetG1Continuous { handles: *handles, enabled: false }; + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } @@ -960,7 +957,7 @@ impl ShapeState { .flat_map(|(data, selection_state)| { selection_state.selected_points.iter().filter_map(move |&point| { let Some(data) = &data else { return None }; - let _ = point.get_handle_pair(data)?; // ignores the endpoints. + let _ = data.handle_pair_of(point)?; // ignores the endpoints. Some(data.colinear(point)) }) }); @@ -972,12 +969,12 @@ impl ShapeState { if first_is_colinear { ManipulatorAngle::Colinear } else { ManipulatorAngle::Free } } - pub fn convert_manipulator_handles_to_colinear(&self, vector: &Vector, point_id: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier) { - let Some(anchor_position) = ManipulatorPointId::Anchor(point_id).get_position(vector) else { + pub fn convert_manipulator_handles_to_colinear(&self, vector: &VectorGeometry, point_id: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier) { + let Some(anchor_position) = vector.position_of(ManipulatorPointId::Anchor(point_id)) else { return; }; let handles = vector.all_connected(point_id).take(2).collect::>(); - let non_zero_handles = handles.iter().filter(|handle| handle.length(vector) > 1e-6).count(); + let non_zero_handles = handles.iter().filter(|handle| vector.handle_length(**handle) > 1e-6).count(); let handle_segments = handles.iter().map(|handles| handles.segment).collect::>(); // Check if the anchor is connected to linear segments and has no handles @@ -985,7 +982,7 @@ impl ShapeState { // Grab the next and previous manipulator groups by simply looking at the next / previous index let points = handles.iter().map(|handle| vector.other_point(handle.segment, point_id)); - let anchor_positions = points.map(|point| point.and_then(|point| ManipulatorPointId::Anchor(point).get_position(vector))).collect::>(); + let anchor_positions = points.map(|point| point.and_then(|point| vector.position_of(ManipulatorPointId::Anchor(point)))).collect::>(); let mut segment_angle = 0.; let mut segment_count = 0.; @@ -1024,15 +1021,14 @@ impl ShapeState { if non_zero_handles != 0 && !linear_segments { let [a, b] = handles.as_slice() else { return }; - let (non_zero_handle, zero_handle) = if a.length(vector) > 1e-6 { (a, b) } else { (b, a) }; - let Some(direction) = non_zero_handle - .to_manipulator_point() - .get_position(vector) + let (non_zero_handle, zero_handle) = if vector.handle_length(*a) > 1e-6 { (a, b) } else { (b, a) }; + let Some(direction) = vector + .position_of(non_zero_handle.to_manipulator_point()) .and_then(|position| (position - anchor_position).try_normalize()) else { return; }; - let new_position = -direction * non_zero_handle.length(vector); + let new_position = -direction * vector.handle_length(*non_zero_handle); let modification_type = zero_handle.set_relative_position(new_position); responses.add(GraphOperationMessage::Vector { layer, modification_type }); } else { @@ -1053,7 +1049,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Create the opposite handle if it doesn't exist (if it is not a cubic segment) - if handle.opposite().to_manipulator_point().get_position(vector).is_none() { + if vector.position_of(handle.opposite().to_manipulator_point()).is_none() { let modification_type = handle.opposite().set_relative_position(DVec2::ZERO); responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1085,28 +1081,27 @@ impl ShapeState { // Here we take handles as the current handle and the most opposite non-colinear-handle - let is_handle_colinear = |handle: HandleId| -> bool { vector.colinear_manipulators.iter().any(|&handles| handles[0] == handle || handles[1] == handle) }; + let is_handle_colinear = |handle: HandleId| -> bool { vector.colinear(handle.to_manipulator_point()) }; let other_handles = if matches!(point, ManipulatorPointId::Anchor(_)) { - point.get_handle_pair(&vector) + vector.handle_pair_of(point) } else { - let Some(anchor) = point.get_anchor_position(&vector) else { continue }; - let Some(orig_handle_pos) = point.get_position(&vector) else { continue }; + let Some(anchor) = vector.anchor_position_of(point) else { continue }; + let Some(orig_handle_pos) = vector.position_of(point) else { continue }; let Some(v_orig) = (orig_handle_pos - anchor).try_normalize() else { continue }; - point.get_all_connected_handles(&vector).and_then(|handles| { + vector.all_connected_handles_of(point).and_then(|handles| { let mut non_colinear_handles = handles.iter().filter(|&handle| !is_handle_colinear(*handle)).clone().collect::>(); // Skip handles with no position or with the same position as the anchor non_colinear_handles.retain(|&handle| { - let Some(handle) = handle.to_manipulator_point().get_position(&vector) else { return false }; + let Some(handle) = vector.position_of(handle.to_manipulator_point()) else { return false }; (handle - anchor).is_non_zero() }); // Find the most colinear handle (maximum absolute angle from the original) let most_colinear = non_colinear_handles.into_iter().max_by(|&handle_a, &handle_b| { - let [Some(angle_a), Some(angle_b)] = - [handle_a, handle_b].map(|handle| handle.to_manipulator_point().get_position(&vector).and_then(|pos| v_orig.try_angle_to(pos - anchor))) + let [Some(angle_a), Some(angle_b)] = [handle_a, handle_b].map(|handle| vector.position_of(handle.to_manipulator_point()).and_then(|pos| v_orig.try_angle_to(pos - anchor))) else { error!("invalid handles (e.g. no handle or zero length) should be filtered above"); return core::cmp::Ordering::Equal; @@ -1133,13 +1128,13 @@ impl ShapeState { skip_set.insert(handles); let [selected0, selected1] = handles.map(|handle| layer_state.selected_points.contains(&handle.to_manipulator_point())); - let handle_positions = handles.map(|handle| handle.to_manipulator_point().get_position(&vector)); + let handle_positions = handles.map(|handle| vector.position_of(handle.to_manipulator_point())); - let Some(anchor_id) = point.get_anchor(&vector) else { continue }; - let Some(anchor) = vector.point_domain.position_from_id(anchor_id) else { continue }; + let Some(anchor_id) = vector.anchor_of(point) else { continue }; + let Some(anchor) = vector.position_from_id(anchor_id) else { continue }; let anchor_points = handles.map(|handle| vector.other_point(handle.segment, anchor_id)); - let anchor_positions = anchor_points.map(|point| point.and_then(|point| vector.point_domain.position_from_id(point))); + let anchor_positions = anchor_points.map(|point| point.and_then(|point| vector.position_from_id(point))); // If one handle is selected (but both exist), only move the other handle if let (true, [Some(pos0), Some(pos1)]) = ((selected0 ^ selected1), handle_positions) { @@ -1181,7 +1176,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Create the opposite handle if it doesn't exist (if it is not a cubic segment) - if handles[index].opposite().to_manipulator_point().get_position(&vector).is_none() { + if vector.position_of(handles[index].opposite().to_manipulator_point()).is_none() { let modification_type = handles[index].opposite().set_relative_position(DVec2::ZERO); responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1245,14 +1240,14 @@ impl ShapeState { ManipulatorPointId::EndHandle(segment) => HandleId::end(segment), }; - let Some(anchor_id) = point.get_anchor(&vector) else { continue }; + let Some(anchor_id) = vector.anchor_of(point) else { continue }; if state.is_point_selected(ManipulatorPointId::Anchor(anchor_id)) { continue; } - let Some(anchor_position) = vector.point_domain.position_from_id(anchor_id) else { continue }; + let Some(anchor_position) = vector.position_from_id(anchor_id) else { continue }; - let Some(handle_position) = point.get_position(&vector) else { continue }; + let Some(handle_position) = vector.position_of(point) else { continue }; let handle_position = handle_position + delta; let modification_type = handle.set_relative_position(handle_position - anchor_position); @@ -1283,7 +1278,7 @@ impl ShapeState { } else { // TODO: Is this equivalent to `transform_to_document_space`? If changed, the before and after should be tested. let transform = document.metadata().document_to_viewport.inverse() * transform_to_viewport_space; - let Some(other_position) = other.to_manipulator_point().get_position(&vector) else { + let Some(other_position) = vector.position_of(other.to_manipulator_point()) else { continue; }; let direction = transform.transform_vector2(handle_position - anchor_position).try_normalize(); @@ -1308,14 +1303,14 @@ impl ShapeState { let vector = document.network_interface.compute_modified_vector(layer)?; let transform = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface); let opposing_handle_lengths = vector - .colinear_manipulators - .iter() - .filter_map(|&handles| { + .colinear_pairs() + .into_iter() + .filter_map(|handles| { // We will keep track of the opposing handle length when: // i) Exactly one handle is selected. // ii) The anchor is not selected. - let anchor = handles[0].to_manipulator_point().get_anchor(&vector)?; + let anchor = vector.anchor_of(handles[0].to_manipulator_point())?; let anchor_selected = state.is_point_selected(ManipulatorPointId::Anchor(anchor)); if anchor_selected { return None; @@ -1329,8 +1324,8 @@ impl ShapeState { _ => return None, }; - let opposing_handle_position = other.to_manipulator_point().get_position(&vector)?; - let anchor_position = vector.point_domain.position_from_id(anchor)?; + let opposing_handle_position = vector.position_of(other.to_manipulator_point())?; + let anchor_position = vector.position_from_id(anchor)?; let opposing_handle_length = transform.transform_vector2(opposing_handle_position - anchor_position).length(); Some((other, opposing_handle_length)) @@ -1341,7 +1336,7 @@ impl ShapeState { .collect::>() } - pub fn dissolve_segment(&self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &Vector, segment: SegmentId, points: [PointId; 2]) { + pub fn dissolve_segment(&self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &VectorGeometry, segment: SegmentId, points: [PointId; 2]) { // Checking which point is terminal point let is_point1_terminal = vector.connected_count(points[0]) == 1; let is_point2_terminal = vector.connected_count(points[1]) == 1; @@ -1349,7 +1344,7 @@ impl ShapeState { // Delete the segment and terminal points let modification_type = VectorModificationType::RemoveSegment { id: segment }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in vector.colinear_manipulators.iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { + for handles in vector.colinear_pairs().into_iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1364,27 +1359,28 @@ impl ShapeState { } } - fn dissolve_anchor(anchor: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &Vector) -> Option<[(HandleId, PointId); 2]> { + fn dissolve_anchor(anchor: PointId, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &VectorGeometry) -> Option<[(HandleId, PointId); 2]> { // Delete point let modification_type = VectorModificationType::RemovePoint { id: anchor }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Delete connected segments + let colinear_pairs = vector.colinear_pairs(); for HandleId { segment, .. } in vector.all_connected(anchor) { let modification_type = VectorModificationType::RemoveSegment { id: segment }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in vector.colinear_manipulators.iter().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { + for handles in colinear_pairs.iter().copied().filter(|handles| handles.iter().any(|handle| handle.segment == segment)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } // Add in new segment if possible - let mut handles = ManipulatorPointId::Anchor(anchor).get_handle_pair(vector)?; + let mut handles = vector.handle_pair_of(ManipulatorPointId::Anchor(anchor))?; handles.reverse(); let opposites = handles.map(|handle| handle.opposite()); - let [Some(start), Some(end)] = opposites.map(|opposite| opposite.to_manipulator_point().get_anchor(vector)) else { + let [Some(start), Some(end)] = opposites.map(|opposite| vector.anchor_of(opposite.to_manipulator_point())) else { return None; }; Some([(handles[0], start), (handles[1], end)]) @@ -1398,6 +1394,7 @@ impl ShapeState { let mut missing_anchors = HashMap::new(); let mut deleted_anchors = HashSet::new(); let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; + let colinear_pairs = vector.colinear_pairs(); let selected_segments = &state.selected_segments; @@ -1425,7 +1422,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Disable the g1 continuous - for &handles in &vector.colinear_manipulators { + for &handles in &colinear_pairs { if handles.contains(&handle) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -1463,8 +1460,8 @@ impl ShapeState { // Grab the handles from the opposite side of the segment(s) being deleted and make it relative to the anchor let [handle_start, handle_end] = [start, end].map(|(handle, _)| { let handle = handle.opposite(); - let handle_position = handle.to_manipulator_point().get_position(&vector); - let relative_position = handle.to_manipulator_point().get_anchor(&vector).and_then(|anchor| vector.point_domain.position_from_id(anchor)); + let handle_position = vector.position_of(handle.to_manipulator_point()); + let relative_position = vector.anchor_of(handle.to_manipulator_point()).and_then(|anchor| vector.position_from_id(anchor)); handle_position.and_then(|handle| relative_position.map(|relative| handle - relative)).unwrap_or_default() }); @@ -1478,12 +1475,12 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in vector.colinear_manipulators.iter() { + for &handles in &colinear_pairs { if !handles.iter().any(|&handle| handle == start.0.opposite() || handle == end.0.opposite()) { continue; } - let Some(anchor) = handles[0].to_manipulator_point().get_anchor(&vector) else { continue }; + let Some(anchor) = vector.anchor_of(handles[0].to_manipulator_point()) else { continue }; let Some(other) = handles.iter().find(|&&handle| handle != start.0.opposite() && handle != end.0.opposite()) else { continue; }; @@ -1551,15 +1548,16 @@ impl ShapeState { for (&layer, state) in &self.selected_shape_state { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; + let colinear_pairs = vector.colinear_pairs(); for &delete in &state.selected_points { - let Some(point) = delete.get_anchor(&vector) else { continue }; - let Some(pos) = vector.point_domain.position_from_id(point) else { continue }; + let Some(point) = vector.anchor_of(delete) else { continue }; + let Some(pos) = vector.position_from_id(point) else { continue }; let mut used_initial_point = false; for handle in vector.all_connected(point) { // Disable the g1 continuous - for &handles in &vector.colinear_manipulators { + for &handles in &colinear_pairs { if !transaction_started { responses.add(DocumentMessage::AddTransaction); transaction_started = true; @@ -1610,7 +1608,7 @@ impl ShapeState { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; for delete in std::mem::take(&mut state.selected_points) { - let Some(point) = delete.get_anchor(&vector) else { continue }; + let Some(point) = vector.anchor_of(delete) else { continue }; if !transaction_started { responses.add(DocumentMessage::AddTransaction); @@ -1635,19 +1633,20 @@ impl ShapeState { pub fn disable_colinear_handles_state_on_selected(&self, network_interface: &NodeNetworkInterface, responses: &mut VecDeque) { for (&layer, state) in &self.selected_shape_state { let Some(vector) = network_interface.compute_modified_vector(layer) else { continue }; + let colinear_pairs = vector.colinear_pairs(); for &point in &state.selected_points { if let ManipulatorPointId::Anchor(point) = point { for connected in vector.all_connected(point) { - if let Some(&handles) = vector.colinear_manipulators.iter().find(|target| target.contains(&connected)) { + if let Some(&handles) = colinear_pairs.iter().find(|pair| pair.contains(&connected)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } } else if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_manipulators.iter().find(|handles| handles[0] == handle || handles[1] == handle) + && let Some(handles) = vector.colinear_pair_containing(handle) { - let modification_type = VectorModificationType::SetG1Continuous { handles: *handles, enabled: false }; + let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } } @@ -1750,7 +1749,7 @@ impl ShapeState { } // Anchors - for (&id, &point) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (id, point) in vector.anchors() { let point = viewspace.transform_point2(point); if point.distance_squared(pos) <= closest_distance_squared { @@ -1773,6 +1772,7 @@ impl ShapeState { let mut closest_distance_squared: f64 = tolerance * tolerance; let vector = network_interface.compute_modified_vector(layer)?; + let colinear_pairs = vector.colinear_pairs(); for (segment_id, mut segment, start, end) in vector.segment_iter() { let t = segment.nearest(dvec2_to_point(layer_pos), DEFAULT_ACCURACY).t; @@ -1793,10 +1793,10 @@ impl ShapeState { } } - let primary_handle = vector.colinear_manipulators.iter().find(|handles| handles.contains(&HandleId::primary(segment_id))); - let end_handle = vector.colinear_manipulators.iter().find(|handles| handles.contains(&HandleId::end(segment_id))); - let primary_handle = primary_handle.and_then(|&handles| handles.into_iter().find(|handle| handle.segment != segment_id)); - let end_handle = end_handle.and_then(|&handles| handles.into_iter().find(|handle| handle.segment != segment_id)); + let primary_handle = colinear_pairs.iter().copied().find(|handles| handles.contains(&HandleId::primary(segment_id))); + let end_handle = colinear_pairs.iter().copied().find(|handles| handles.contains(&HandleId::end(segment_id))); + let primary_handle = primary_handle.and_then(|handles| handles.into_iter().find(|handle| handle.segment != segment_id)); + let end_handle = end_handle.and_then(|handles| handles.into_iter().find(|handle| handle.segment != segment_id)); closest = Some(ClosestSegment { segment: segment_id, @@ -1831,7 +1831,7 @@ impl ShapeState { if point.as_anchor().is_some() { return PointSelectState::Anchor; } - if point.get_handle_pair(&vector).is_some() { + if vector.handle_pair_of(*point).is_some() { return PointSelectState::HandleWithPair; } } @@ -1848,7 +1848,7 @@ impl ShapeState { if point.as_anchor().is_some() { return false; } - if point.get_handle_pair(&vector).is_some() { + if vector.handle_pair_of(*point).is_some() { return true; } } @@ -1869,9 +1869,9 @@ impl ShapeState { continue; } - if let Some(other_handles) = point.get_all_connected_handles(&vector) { - let Some(anchor) = point.get_anchor_position(&vector) else { continue }; - let Some(orig_handle_pos) = point.get_position(&vector) else { continue }; + if let Some(other_handles) = vector.all_connected_handles_of(*point) { + let Some(anchor) = vector.anchor_position_of(*point) else { continue }; + let Some(orig_handle_pos) = vector.position_of(*point) else { continue }; let Some(v_orig) = (orig_handle_pos - anchor).try_normalize() else { continue }; // Find the next closest handle in the clockwise sense @@ -1879,13 +1879,13 @@ impl ShapeState { // Skip handles with no position or with the same position as the anchor candidates.retain(|&handle| { - let Some(handle) = handle.to_manipulator_point().get_position(&vector) else { return false }; + let Some(handle) = vector.position_of(handle.to_manipulator_point()) else { return false }; (handle - anchor).is_non_zero() }); // Find the next handle let next_handle = candidates.into_iter().min_by(|&handle_a, &handle_b| { - let [Some(angle_a), Some(angle_b)] = [handle_a, handle_b].map(|handle| handle.to_manipulator_point().get_position(&vector).and_then(|pos| v_orig.try_angle_to(pos - anchor))) + let [Some(angle_a), Some(angle_b)] = [handle_a, handle_b].map(|handle| vector.position_of(handle.to_manipulator_point()).and_then(|pos| v_orig.try_angle_to(pos - anchor))) else { error!("invalid handles (e.g. no handle or zero length) should be filtered above"); return core::cmp::Ordering::Equal; @@ -1925,8 +1925,8 @@ impl ShapeState { let Some(vector) = network_interface.compute_modified_vector(layer) else { continue }; for point in self.selected_points().filter(|point| point.as_handle().is_some()) { - let anchor = point.get_anchor(&vector); - match point.get_handle_pair(&vector) { + let anchor = vector.anchor_of(*point); + match vector.handle_pair_of(*point) { Some(handles) => { points_to_select.push((layer, anchor, Some(handles[1].to_manipulator_point()))); } @@ -1961,10 +1961,10 @@ impl ShapeState { // Get the current point and its connected handles let selected_points = state.selected_points.clone(); if let Some(point) = selected_points.iter().next() { - if let Some(anchor) = point.get_anchor(&vector) { + if let Some(anchor) = vector.anchor_of(*point) { state.select_point(ManipulatorPointId::Anchor(anchor)); } - if let Some(handles) = point.get_handle_pair(&vector) { + if let Some(handles) = vector.handle_pair_of(*point) { state.select_point(handles[0].to_manipulator_point()); state.select_point(handles[1].to_manipulator_point()); } @@ -1995,12 +1995,12 @@ impl ShapeState { // Check by comparing the handle positions to the anchor if this manipulator group is a point for point in selected_points { let Some(point_id) = point.as_anchor() else { continue }; - let anchor = point.get_position(&vector)?; + let anchor = vector.position_of(*point)?; let handles = vector.all_connected(point_id); // TODO: Check if this method of finding non-colinear is really required let positions = handles - .filter_map(|handle| handle.to_manipulator_point().get_position(&vector)) + .filter_map(|handle| vector.position_of(handle.to_manipulator_point())) .filter(|&handle| anchor.abs_diff_eq(handle, 1e-5)) .count(); @@ -2010,6 +2010,7 @@ impl ShapeState { if positions != 0 || one_or_more_segment_linear { self.convert_manipulator_handles_to_colinear(&vector, point_id, responses, layer); } else { + let colinear_pairs = vector.colinear_pairs(); for handle in vector.all_connected(point_id) { let Some(path_segment) = vector.segment_from_id(handle.segment) else { continue }; @@ -2022,7 +2023,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Set the manipulator to have non-colinear handles - for &handles in &vector.colinear_manipulators { + for handles in colinear_pairs.iter().copied() { if handles.contains(&HandleId::primary(segment)) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -2035,7 +2036,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Set the manipulator to have non-colinear handles - for &handles in &vector.colinear_manipulators { + for handles in colinear_pairs.iter().copied() { if handles.contains(&handle) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -2093,7 +2094,7 @@ impl ShapeState { (_, SelectionChange::Shrink) => state.deselect_point(point), (ManipulatorPointId::EndHandle(_) | ManipulatorPointId::PrimaryHandle(_), _) => { let handle = point.as_handle().expect("Handle cannot be converted"); - if handle.length(&vector) > 0. { + if vector.handle_length(handle) > 0. { state.select_point(point); } } @@ -2151,15 +2152,6 @@ impl ShapeState { let Some(vector) = vector else { continue }; let transform = network_interface.document_metadata().transform_to_viewport_if_feeds(layer, network_interface); - assert_eq!(vector.segment_domain.ids().len(), vector.start_point().count()); - assert_eq!(vector.segment_domain.ids().len(), vector.end_point().count()); - for start in vector.start_point() { - assert!(vector.point_domain.ids().contains(&start)); - } - for end in vector.end_point() { - assert!(vector.point_domain.ids().contains(&end)); - } - let polygon_bezpath = if let SelectionShape::Lasso(polygon) = selection_shape { if polygon.len() < 2 { return (points_inside, segments_inside); @@ -2237,7 +2229,7 @@ impl ShapeState { } // Checking for selection of anchor points - for (&id, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (id, position) in vector.anchors() { let transformed_position = transform.transform_point2(position); let select = match selection_shape { diff --git a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs index 1ffb4538b0..9c072f8ccd 100644 --- a/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs +++ b/editor/src/messages/tool/common_functionality/shapes/shape_utility.rs @@ -260,7 +260,7 @@ pub fn anchor_overlays(document: &DocumentMessageHandler, overlay_context: &mut overlay_context.outline_vector(&vector, transform); - for (_, &position) in vector.point_domain.ids().iter().zip(vector.point_domain.positions()) { + for (_, position) in vector.anchors() { overlay_context.manipulator_anchor(transform.transform_point2(position), false, None); } } diff --git a/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs b/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs index 54e1ea7dc1..08d22caa88 100644 --- a/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs +++ b/editor/src/messages/tool/common_functionality/snap_session/scene_mirror.rs @@ -130,7 +130,7 @@ fn mirror_layer(document: &DocumentMessageHandler, layer: LayerNodeIdentifier) - let curves_drawn: HashSet<[[i64; 2]; 4]> = drawn_curves.iter().map(rounded_curve).collect(); let role = |drawn: bool| if drawn { GeometryRole::Source } else { GeometryRole::Undrawn }; - anchors.extend(vector.point_domain.iter().map(|(id, position)| { + anchors.extend(vector.anchors().map(|(id, position)| { let position = to_document.transform_point2(position); SceneAnchor { position, diff --git a/editor/src/messages/tool/common_functionality/utility_functions.rs b/editor/src/messages/tool/common_functionality/utility_functions.rs index c70f44b0b2..8192407ece 100644 --- a/editor/src/messages/tool/common_functionality/utility_functions.rs +++ b/editor/src/messages/tool/common_functionality/utility_functions.rs @@ -14,7 +14,7 @@ use graph_craft::document::value::TaggedValue; use graphene_std::renderer::Quad; use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModification, VectorModificationType}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModification, VectorModificationType}; use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape}; /// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable. @@ -49,7 +49,7 @@ fn closest_candidate_point( goal: DVec2, max_distance: f64, layers: impl Iterator, - candidates: impl Fn(&Vector) -> Vec, + candidates: impl Fn(&VectorGeometry) -> Vec, ) -> Option<(LayerNodeIdentifier, PointId, DVec2)> { let mut best = None; let mut best_distance_squared = max_distance * max_distance; @@ -63,7 +63,7 @@ fn closest_candidate_point( let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; for id in candidates(&vector) { - let Some(point) = vector.point_domain.position_from_id(id) else { continue }; + let Some(point) = vector.position_from_id(id) else { continue }; let distance_squared = viewspace.transform_point2(point).distance_squared(goal); if distance_squared < best_distance_squared { @@ -92,16 +92,16 @@ pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageH Quad::from_box([DVec2::ZERO, far]) } -pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector: &Vector, prefer_handle_direction: bool) -> Option { +pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector: &VectorGeometry, prefer_handle_direction: bool) -> Option { let is_start = |point: PointId, segment: SegmentId| vector.segment_start_from_id(segment) == Some(point); - let anchor_position = vector.point_domain.position_from_id(anchor)?; - let end_handle = ManipulatorPointId::EndHandle(segment).get_position(vector); - let start_handle = ManipulatorPointId::PrimaryHandle(segment).get_position(vector); + let anchor_position = vector.position_from_id(anchor)?; + let end_handle = vector.position_of(ManipulatorPointId::EndHandle(segment)); + let start_handle = vector.position_of(ManipulatorPointId::PrimaryHandle(segment)); let start_point = if is_start(anchor, segment) { - vector.segment_end_from_id(segment).and_then(|id| vector.point_domain.position_from_id(id)) + vector.segment_end_from_id(segment).and_then(|id| vector.position_from_id(id)) } else { - vector.segment_start_from_id(segment).and_then(|id| vector.point_domain.position_from_id(id)) + vector.segment_start_from_id(segment).and_then(|id| vector.position_from_id(id)) }; let required_handle = if is_start(anchor, segment) { @@ -119,9 +119,9 @@ pub fn calculate_segment_angle(anchor: PointId, segment: SegmentId, vector: &Vec required_handle.map(|handle| handle - anchor_position).and_then(|vector| DVec2::X.try_angle_to(vector)) } -pub fn adjust_handle_colinearity(handle: HandleId, anchor_position: DVec2, target_control_point: DVec2, vector: &Vector, layer: LayerNodeIdentifier, responses: &mut VecDeque) { +pub fn adjust_handle_colinearity(handle: HandleId, anchor_position: DVec2, target_control_point: DVec2, vector: &VectorGeometry, layer: LayerNodeIdentifier, responses: &mut VecDeque) { let Some(other_handle) = vector.other_colinear_handle(handle) else { return }; - let Some(handle_position) = other_handle.to_manipulator_point().get_position(vector) else { + let Some(handle_position) = vector.position_of(other_handle.to_manipulator_point()) else { return; }; let Some(direction) = (anchor_position - target_control_point).try_normalize() else { return }; @@ -136,12 +136,12 @@ pub fn restore_previous_handle_position( handle: HandleId, original_c: DVec2, anchor_position: DVec2, - vector: &Vector, + vector: &VectorGeometry, layer: LayerNodeIdentifier, responses: &mut VecDeque, ) -> Option { let other_handle = vector.other_colinear_handle(handle)?; - let handle_position = other_handle.to_manipulator_point().get_position(vector)?; + let handle_position = vector.position_of(other_handle.to_manipulator_point())?; let direction = (anchor_position - original_c).try_normalize()?; let old_relative_position = (handle_position - anchor_position).length() * direction; @@ -155,8 +155,16 @@ pub fn restore_previous_handle_position( Some(other_handle) } -pub fn restore_g1_continuity(handle: HandleId, other_handle: HandleId, control_point: DVec2, anchor_position: DVec2, vector: &Vector, layer: LayerNodeIdentifier, responses: &mut VecDeque) { - let Some(handle_position) = other_handle.to_manipulator_point().get_position(vector) else { +pub fn restore_g1_continuity( + handle: HandleId, + other_handle: HandleId, + control_point: DVec2, + anchor_position: DVec2, + vector: &VectorGeometry, + layer: LayerNodeIdentifier, + responses: &mut VecDeque, +) { + let Some(handle_position) = vector.position_of(other_handle.to_manipulator_point()) else { return; }; let Some(direction) = (anchor_position - control_point).try_normalize() else { return }; @@ -173,7 +181,7 @@ pub fn restore_g1_continuity(handle: HandleId, other_handle: HandleId, control_p /// Check whether a point is visible in the current overlay mode. pub fn is_visible_point( manipulator_point_id: ManipulatorPointId, - vector: &Vector, + vector: &VectorGeometry, path_overlay_mode: PathOverlayMode, frontier_handles_for_layer: Option<&HashMap>>, selected_segments: &[SegmentId], @@ -190,14 +198,14 @@ pub fn is_visible_point( } // Either the segment is a part of selected segments or the opposite handle is a part of existing selection - let Some(handle_pair) = manipulator_point_id.get_handle_pair(vector) else { return false }; + let Some(handle_pair) = vector.handle_pair_of(manipulator_point_id) else { return false }; let other_handle = handle_pair[1].to_manipulator_point(); // Return whether the list of selected points contain the other handle selected_points.contains(&other_handle) } (PathOverlayMode::FrontierHandles, false) => { - let Some(anchor) = manipulator_point_id.get_anchor(vector) else { + let Some(anchor) = vector.anchor_of(manipulator_point_id) else { warn!("No anchor for selected handle"); return false; }; diff --git a/editor/src/messages/tool/tool_messages/freehand_tool.rs b/editor/src/messages/tool/tool_messages/freehand_tool.rs index 7751093cfb..31f2c0f4f6 100644 --- a/editor/src/messages/tool/tool_messages/freehand_tool.rs +++ b/editor/src/messages/tool/tool_messages/freehand_tool.rs @@ -441,9 +441,9 @@ mod test_freehand { use crate::messages::tool::tool_messages::freehand_tool::FreehandOptionsUpdate; use crate::test_utils::test_prelude::*; use glam::{DAffine2, DMat2, DVec2}; - use graphene_std::vector::Vector; + use graphene_std::vector::VectorGeometry; - async fn get_vector_and_transform_list(editor: &mut EditorTestUtils) -> Vec<(Vector, DAffine2)> { + async fn get_vector_and_transform_list(editor: &mut EditorTestUtils) -> Vec<(VectorGeometry, DAffine2)> { let document = editor.active_document(); let layers = document.metadata().all_layers(); @@ -460,18 +460,18 @@ mod test_freehand { .collect() } - fn verify_path_points(vector_and_transform_list: &[(Vector, DAffine2)], expected_captured_points: &[DVec2], tolerance: f64) -> Result<(), String> { + fn verify_path_points(vector_and_transform_list: &[(VectorGeometry, DAffine2)], expected_captured_points: &[DVec2], tolerance: f64) -> Result<(), String> { assert_eq!(vector_and_transform_list.len(), 1, "There should be one item of Vector geometry"); let (vector, transform) = vector_and_transform_list .iter() - .find(|(data, _)| !data.point_domain.ids().is_empty()) + .find(|(data, _)| data.anchor_points().next().is_some()) .ok_or("Could not find path data")?; - let point_count = vector.point_domain.ids().len(); - let segment_count = vector.segment_domain.ids().len(); + let point_count = vector.anchor_points().count(); + let segment_count = vector.segment_ids().len(); - let actual_positions: Vec = vector.point_domain.positions().iter().map(|&position| transform.transform_point2(position)).collect(); + let actual_positions: Vec = vector.anchor_positions().iter().map(|&position| transform.transform_point2(position)).collect(); if segment_count != point_count - 1 { return Err(format!("Expected segments to be one less than points, got {segment_count} segments for {point_count} points")); @@ -555,8 +555,8 @@ mod test_freehand { assert!(!initial_vector_and_transform.is_empty(), "No vector geometry found after initial drawing"); let (initial_vector, _) = &initial_vector_and_transform[0]; - let initial_point_count = initial_vector.point_domain.ids().len(); - let initial_segment_count = initial_vector.segment_domain.ids().len(); + let initial_point_count = initial_vector.anchor_points().count(); + let initial_segment_count = initial_vector.segment_ids().len(); let existing_layer_id = { let document = editor.active_document(); @@ -613,8 +613,8 @@ mod test_freehand { assert_eq!(layer_count, 1, "Expected only one layer after drawing with Shift key"); let (final_vector, _) = &final_vector_and_transform[0]; - let final_point_count = final_vector.point_domain.ids().len(); - let final_segment_count = final_vector.segment_domain.ids().len(); + let final_point_count = final_vector.anchor_points().count(); + let final_segment_count = final_vector.segment_ids().len(); assert!( final_point_count > initial_point_count, @@ -704,7 +704,7 @@ mod test_freehand { fn point_and_segment_counts(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> (usize, usize) { let vector = editor.active_document().network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry"); - (vector.point_domain.ids().len(), vector.segment_domain.ids().len()) + (vector.anchor_points().count(), vector.segment_ids().len()) } /// The viewport positions of the layer's anchors, split into the endpoints of its open paths and every other anchor. @@ -714,7 +714,7 @@ mod test_freehand { let transform = document.metadata().transform_to_viewport(layer); let endpoints: Vec<_> = vector.anchor_endpoints().collect(); - let viewport_position = |id| vector.point_domain.position_from_id(id).map(|position| transform.transform_point2(position)); + let viewport_position = |id| vector.position_from_id(id).map(|position| transform.transform_point2(position)); let endpoint_positions = endpoints.iter().filter_map(|&id| viewport_position(id)).collect(); let other_positions = vector.anchor_points().filter(|id| !endpoints.contains(id)).filter_map(viewport_position).collect(); @@ -833,11 +833,7 @@ mod test_freehand { let vector = document.network_interface.compute_modified_vector(layer).expect("Layer should have vector geometry"); let transform = document.metadata().transform_to_viewport(layer); for &pointer_position in &continuation[1..] { - let under_pointer = vector - .point_domain - .positions() - .iter() - .any(|&position| transform.transform_point2(position).distance(pointer_position) < 1.); + let under_pointer = vector.anchor_positions().iter().any(|&position| transform.transform_point2(position).distance(pointer_position) < 1.); assert!(under_pointer, "Expected a point under the pointer at {pointer_position:?}"); } } diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index b9c5d8d800..493f5c61b0 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -23,6 +23,7 @@ use crate::messages::tool::common_functionality::shape_editor::{ use crate::messages::tool::common_functionality::snap_session::{FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView, nudge_translation, snapping_hints}; use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, find_two_param_best_approximate, make_path_editable_is_allowed}; use graphene_std::Color; +use graphene_std::list::List; use graphene_std::renderer::Quad; use graphene_std::transform::ReferencePoint; use graphene_std::uuid::NodeId; @@ -30,7 +31,7 @@ use graphene_std::vector::algorithms::util::pathseg_tangent; use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::misc::pathseg_points; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2, segment_to_handles}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModificationType}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorGeometry, VectorModification, VectorModificationType, WorkingVector}; use kurbo::{DEFAULT_ACCURACY, ParamCurve, ParamCurveNearest, PathSeg, Rect}; use std::vec; @@ -678,8 +679,8 @@ impl PathToolData { SelectionStatus::None => false, SelectionStatus::One(single_selected_point) => { let vector = document.network_interface.compute_modified_vector(single_selected_point.layer).unwrap(); - if single_selected_point.id.get_handle_pair(&vector).is_some() { - let anchor = single_selected_point.id.get_anchor(&vector).expect("Cannot find connected anchor"); + if vector.handle_pair_of(single_selected_point.id).is_some() { + let anchor = vector.anchor_of(single_selected_point.id).expect("Cannot find connected anchor"); vector.all_connected(anchor).count() <= 2 } else { false @@ -835,10 +836,11 @@ impl PathToolData { && let Some(first_handle) = vector.all_connected(point_id).next() { self.alt_clicked_on_anchor = true; + let colinear_pairs = vector.colinear_pairs(); for handle in vector.all_connected(point_id) { let modification_type = handle.set_relative_position(DVec2::ZERO); responses.add(GraphOperationMessage::Vector { layer, modification_type }); - for &handles in &vector.colinear_manipulators { + for &handles in &colinear_pairs { if handles.contains(&handle) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); @@ -857,7 +859,7 @@ impl PathToolData { { let handles = vector .all_connected(point) - .filter(|handle| handle.length(&vector) < 1e-6) + .filter(|handle| vector.handle_length(*handle) < 1e-6) .map(|handle| handle.to_manipulator_point()) .collect::>(); let endpoint = vector.anchor_endpoints().any(|anchor| point == anchor); @@ -964,15 +966,15 @@ impl PathToolData { } for point in state.selected_points() { - let Some(anchor) = point.get_anchor(&vector) else { continue }; + let Some(anchor) = vector.anchor_of(point) else { continue }; moving.anchors.push((layer, anchor)); - let Some([handle1, handle2]) = point.get_handle_pair(&vector) else { continue }; + let Some([handle1, handle2]) = vector.handle_pair_of(point) else { continue }; let Some(handle) = point.as_handle() else { continue }; // Check which handle is selected and which is opposite let opposite = if handle == handle1 { handle2 } else { handle1 }; self.opposite_handle_position = if self.opposite_handle_position.is_none() { - opposite.to_manipulator_point().get_position(&vector) + vector.position_of(opposite.to_manipulator_point()) } else { self.opposite_handle_position }; @@ -998,7 +1000,7 @@ impl PathToolData { let to_document = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface); for point in state.selected_points() { - let Some(position) = point.get_position(&vector) else { continue }; + let Some(position) = vector.position_of(point) else { continue }; let point_start = to_document.transform_point2(position) - slid_so_far; starts.push(point_start); @@ -1104,11 +1106,11 @@ impl PathToolData { }; // Check if handle has a pair (to ignore handles of edges of open paths) - if let Some(handle_pair) = selected_handle_id.get_handle_pair(&vector) { + if let Some(handle_pair) = vector.handle_pair_of(selected_handle_id) { let opposite_handle_length = handle_pair.iter().filter(|&&h| h.to_manipulator_point() != selected_handle_id).find_map(|&h| { - let opp_handle_pos = h.to_manipulator_point().get_position(&vector)?; - let opp_anchor_id = h.to_manipulator_point().get_anchor(&vector)?; - let opp_anchor_pos = vector.point_domain.position_from_id(opp_anchor_id)?; + let opp_handle_pos = vector.position_of(h.to_manipulator_point())?; + let opp_anchor_id = vector.anchor_of(h.to_manipulator_point())?; + let opp_anchor_pos = vector.position_from_id(opp_anchor_id)?; Some((opp_handle_pos - opp_anchor_pos).length()) }); @@ -1141,9 +1143,9 @@ impl PathToolData { let layer_to_document = document.metadata().transform_to_document_if_feeds(*layer, &document.network_interface); let vector = document.network_interface.compute_modified_vector(*layer)?; - let handle_position_local = selected_handle.to_manipulator_point().get_position(&vector)?; - let anchor_id = selected_handle.to_manipulator_point().get_anchor(&vector)?; - let anchor_position_local = vector.point_domain.position_from_id(anchor_id)?; + let handle_position_local = vector.position_of(selected_handle.to_manipulator_point())?; + let anchor_id = vector.anchor_of(selected_handle.to_manipulator_point())?; + let anchor_position_local = vector.position_from_id(anchor_id)?; let handle_position_document = layer_to_document.transform_point2(handle_position_local); let anchor_position_document = layer_to_document.transform_point2(anchor_position_local); @@ -1177,13 +1179,13 @@ impl PathToolData { // If the handle is dragged over one of its adjacent anchors while holding down the Ctrl key, compute the angle based on the tangent formed with the neighboring anchor points. if adjacent_anchor.is_some() && lock_angle && !self.angle_locked { - let anchor = handle_id.get_anchor(&vector); + let anchor = vector.anchor_of(handle_id); let (angle, anchor_position) = calculate_adjacent_anchor_tangent(handle_id, anchor, adjacent_anchor, &vector); let layer_to_document = document.metadata().transform_to_document_if_feeds(*layer, &document.network_interface); - self.adjacent_anchor_offset = handle_id - .get_anchor_position(&vector) + self.adjacent_anchor_offset = vector + .anchor_position_of(handle_id) .and_then(|handle_anchor| anchor_position.map(|adjacent_anchor| layer_to_document.transform_point2(adjacent_anchor) - layer_to_document.transform_point2(handle_anchor))); required_angle = angle; @@ -1229,17 +1231,17 @@ impl PathToolData { handle_angle } - fn get_normalized_tangent(&mut self, point: PointId, segment: SegmentId, vector: &Vector) -> Option { + fn get_normalized_tangent(&mut self, point: PointId, segment: SegmentId, vector: &VectorGeometry) -> Option { let other_point = vector.other_point(segment, point)?; - let position = ManipulatorPointId::Anchor(point).get_position(vector)?; + let position = vector.position_of(ManipulatorPointId::Anchor(point))?; let mut handles = vector.all_connected(other_point); let other_handle = handles.find(|handle| handle.segment == segment)?; - let target_position = if other_handle.length(vector) == 0. { - ManipulatorPointId::Anchor(other_point).get_position(vector)? + let target_position = if vector.handle_length(other_handle) == 0. { + vector.position_of(ManipulatorPointId::Anchor(other_point))? } else { - other_handle.to_manipulator_point().get_position(vector)? + vector.position_of(other_handle.to_manipulator_point())? }; let tangent_vector = target_position - position; @@ -1269,7 +1271,7 @@ impl PathToolData { // Check if that segment exists or it has been removed if let Some(vector_data) = document.network_interface.compute_modified_vector(layer) - && !(vector_data.segment_domain.ids().contains(&segment_id)) + && !(vector_data.segment_ids().contains(&segment_id)) { self.segment = None; } @@ -1346,7 +1348,7 @@ impl PathToolData { }; // Move the anchor to the new position - let Some(current_position) = ManipulatorPointId::Anchor(anchor).get_position(&vector) else { + let Some(current_position) = vector.position_of(ManipulatorPointId::Anchor(anchor)) else { return; }; let delta = new_position - current_position; @@ -1510,7 +1512,7 @@ impl PathToolData { return; }; let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - let Some(point_id) = shape_editor.selected_points().next().unwrap().get_anchor(&vector) else { + let Some(point_id) = vector.anchor_of(*shape_editor.selected_points().next().unwrap()) else { return; }; @@ -1739,7 +1741,7 @@ impl Fsm for PathToolFsmState { } } - // TODO: find the segment ids of which the selected points are a part of + // TODO: find the segment IDs of which the selected points are a part of match tool_options.path_overlay_mode { PathOverlayMode::AllHandles => { @@ -1833,7 +1835,7 @@ impl Fsm for PathToolFsmState { let Some((layer, manipulator_point_id)) = nearest_visible_point_indices else { return }; let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - let Some(position) = manipulator_point_id.get_position(&vector) else { + let Some(position) = vector.position_of(manipulator_point_id) else { error!("No position for hovered point"); return; }; @@ -1960,7 +1962,7 @@ impl Fsm for PathToolFsmState { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; for point in points { - let Some(position) = point.get_position(&vector) else { continue }; + let Some(position) = vector.position_of(point) else { continue }; let transform = document.metadata().transform_to_viewport(layer); let position = transform.transform_point2(position); @@ -2712,16 +2714,13 @@ impl Fsm for PathToolFsmState { // Find points by their positions (with small tolerance for floating point comparison) const POSITION_TOLERANCE: f64 = 1e-6; - let positions = vector.point_domain.positions(); - let point_ids = vector.point_domain.ids(); - let mut start_point_id = None; let mut end_point_id = None; // Get the merged layer's transform to convert local positions to document space let layer_transform = document.metadata().transform_to_document(layer); - for (i, &local_pos) in positions.iter().enumerate() { + for (point_id, local_pos) in vector.anchors() { // Transform the local position to document space for comparison let doc_pos = layer_transform.transform_point2(local_pos); @@ -2729,10 +2728,10 @@ impl Fsm for PathToolFsmState { let end_distance = (doc_pos - end_position).length(); if start_point_id.is_none() && start_distance < POSITION_TOLERANCE { - start_point_id = Some(point_ids[i]); + start_point_id = Some(point_id); } if end_point_id.is_none() && end_distance < POSITION_TOLERANCE { - end_point_id = Some(point_ids[i]); + end_point_id = Some(point_id); } if start_point_id.is_some() && end_point_id.is_some() { break; @@ -2780,7 +2779,7 @@ impl Fsm for PathToolFsmState { // Also get the transform node that is applied on the layer if it exists let transform = document.metadata().transform_to_document(layer); - let mut new_vector = Vector::default(); + let mut new_vector = WorkingVector::default(); let mut selected_points_by_segment = HashSet::new(); old_vector @@ -2792,13 +2791,14 @@ impl Fsm for PathToolFsmState { }); // Add all the selected points - for (point, position) in old_vector.point_domain.iter() { + for (point, position) in old_vector.anchors() { if layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(point)) || selected_points_by_segment.contains(&point) { - new_vector.point_domain.push(point, position); + new_vector.point_ids.push(point); + new_vector.point_positions.push(position); } } - let find_index = |id: PointId| new_vector.point_domain.iter().enumerate().find(|(_, (point_id, _))| *point_id == id).map(|(index, _)| index); + let find_index = |new_vector: &WorkingVector, id: PointId| new_vector.point_ids.iter().position(|&point_id| point_id == id); // Add segments which have selected ends for (segment_id, segment, start, end) in old_vector.segment_iter() { @@ -2807,21 +2807,27 @@ impl Fsm for PathToolFsmState { let segment_selected = layer_selection_state.is_segment_selected(segment_id); if both_ends_selected || segment_selected { - let Some((start_index, end_index)) = find_index(start).zip(find_index(end)) else { - error!("Point does not exist in point domain"); + let Some((start_index, end_index)) = find_index(&new_vector, start).zip(find_index(&new_vector, end)) else { + error!("Point does not exist in the copied selection"); return PathToolFsmState::Ready; }; - new_vector.segment_domain.push(segment_id, start_index, end_index, segment_to_handles(&segment)); + new_vector.segment_ids.push(segment_id); + new_vector.segment_start.push(start_index); + new_vector.segment_end.push(end_index); + new_vector.segment_handles.push(segment_to_handles(&segment)); } } - for handles in old_vector.colinear_manipulators { - if new_vector.segment_domain.ids().contains(&handles[0].segment) && new_vector.segment_domain.ids().contains(&handles[1].segment) { - new_vector.colinear_manipulators.push(handles); + for handles in old_vector.colinear_pairs() { + if new_vector.segment_ids.contains(&handles[0].segment) && new_vector.segment_ids.contains(&handles[1].segment) { + new_vector.colinear.push(handles); } } - buffer.push((layer, new_vector, transform)); + // The clipboard stores a modification that rebuilds the copied selection from nothing + let (mut copied, mut copied_paths) = (Vector::default(), List::new()); + new_vector.reweave(&mut copied, &mut copied_paths); + buffer.push((layer, VectorModification::create_from_vector(&copied, &copied_paths), transform)); } responses.add(ClipboardMessage::WriteItems { @@ -2875,9 +2881,14 @@ impl Fsm for PathToolFsmState { layer }; - // Create new point ids and add those into the existing vector content + // Materialize the copied snapshot so its points and segments can replay with fresh IDs + let (mut pasted_vector, mut pasted_paths) = (Vector::default(), List::new()); + new_vector.apply(&mut pasted_vector, &mut pasted_paths); + let pasted = VectorGeometry::new(pasted_vector, pasted_paths); + + // Create new point IDs and add those into the existing vector content let mut points_map = HashMap::new(); - for (point, position) in new_vector.point_domain.iter() { + for (point, position) in pasted.anchors() { let new_point_id = PointId::generate(); points_map.insert(point, new_point_id); @@ -2886,9 +2897,9 @@ impl Fsm for PathToolFsmState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); } - // Create new segment ids and add the segments into the existing vector content + // Create new segment IDs and add the segments into the existing vector content let mut segments_map = HashMap::new(); - for (segment_id, bezier, start, end) in new_vector.segment_iter() { + for (segment_id, bezier, start, end) in pasted.segment_iter() { let new_segment_id = SegmentId::generate(); segments_map.insert(segment_id, new_segment_id); @@ -2903,7 +2914,7 @@ impl Fsm for PathToolFsmState { } // Set G1 continuity - for handles in new_vector.colinear_manipulators { + for handles in pasted.colinear_pairs() { let to_new_handle = |handle: HandleId| -> HandleId { HandleId { ty: handle.ty, @@ -2973,7 +2984,7 @@ impl Fsm for PathToolFsmState { }); let mut points_map = HashMap::new(); - for (point, position) in old_vector.point_domain.iter() { + for (point, position) in old_vector.anchors() { // TODO: Either the point is selected or it is an endpoint of a selected segment if layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(point)) || selected_points_by_segment.contains(&point) { @@ -3008,7 +3019,7 @@ impl Fsm for PathToolFsmState { } } - for handles in old_vector.colinear_manipulators { + for handles in old_vector.colinear_pairs() { let to_new_handle = |handle: HandleId| -> HandleId { HandleId { ty: handle.ty, @@ -3311,7 +3322,7 @@ fn get_selection_status(network_interface: &NodeNetworkInterface, shape_state: & let Some(&point) = shape_state.selected_points().next() else { return SelectionStatus::None; }; - let Some(local_position) = point.get_position(&vector) else { + let Some(local_position) = vector.position_of(point) else { return SelectionStatus::None; }; @@ -3344,12 +3355,12 @@ fn calculate_lock_angle( shape_state: &mut ShapeState, responses: &mut VecDeque, document: &DocumentMessageHandler, - vector: &Vector, + vector: &VectorGeometry, handle_id: ManipulatorPointId, tangent_to_neighboring_tangents: bool, ) -> Option { - let anchor = handle_id.get_anchor(vector)?; - let anchor_position = vector.point_domain.position_from_id(anchor); + let anchor = vector.anchor_of(handle_id)?; + let anchor_position = vector.position_from_id(anchor); let current_segment = handle_id.get_segment(); let points_connected = vector.connected_count(anchor); @@ -3357,17 +3368,17 @@ fn calculate_lock_angle( if points_connected == 1 { calculate_segment_angle(anchor, segment, vector, false) } else { - let opposite_handle = handle_id - .get_handle_pair(vector) + let opposite_handle = vector + .handle_pair_of(handle_id) .iter() .flatten() .find(|&h| h.to_manipulator_point() != handle_id) .copied() .map(|h| h.to_manipulator_point()); - let opposite_handle_position = opposite_handle.and_then(|h| h.get_position(vector)).filter(|pos| (pos - anchor_position).length() > 1e-6); + let opposite_handle_position = opposite_handle.and_then(|h| vector.position_of(h)).filter(|pos| (pos - anchor_position).length() > 1e-6); if let Some(opposite_pos) = opposite_handle_position { - if !vector.colinear_manipulators.iter().flatten().map(|h| h.to_manipulator_point()).any(|h| h == handle_id) { + if !vector.colinear(handle_id) { shape_state.convert_selected_manipulators_to_colinear_handles(responses, document); tool_data.temporary_colinear_handles = true; } @@ -3398,7 +3409,7 @@ fn calculate_lock_angle( } /// The position of the one unselected anchor joined to `anchor`, if the segment joining them has no handles to bend it as `anchor` moves. -fn unselected_neighbor_joined_straight(anchor: PointId, state: &SelectedLayerState, vector: &Vector) -> Option { +fn unselected_neighbor_joined_straight(anchor: PointId, state: &SelectedLayerState, vector: &VectorGeometry) -> Option { let mut unselected = vector.connected_points(anchor).filter(|&neighbor| !state.is_point_selected(ManipulatorPointId::Anchor(neighbor))); let (Some(neighbor), None) = (unselected.next(), unselected.next()) else { return None }; @@ -3411,7 +3422,7 @@ fn unselected_neighbor_joined_straight(anchor: PointId, state: &SelectedLayerSta return None; } - vector.point_domain.position_from_id(neighbor) + vector.position_from_id(neighbor) } /// The document positions of the selected points, along with both ends of each selected segment. @@ -3427,18 +3438,18 @@ fn selected_positions_in_document(shape_editor: &ShapeState, document: &Document .segment_iter() .filter(|&(segment, ..)| state.is_segment_selected(segment)) .flat_map(|(_, _, start, end)| [start, end]); - let positions = selected_points.filter_map(|point| point.get_position(&vector)); - let positions = positions.chain(segment_ends.filter_map(|point| vector.point_domain.position_from_id(point))); + let positions = selected_points.filter_map(|point| vector.position_of(point)); + let positions = positions.chain(segment_ends.filter_map(|point| vector.position_from_id(point))); positions.map(|position| to_document.transform_point2(position)).collect() }) } -fn check_handle_over_adjacent_anchor(handle_id: ManipulatorPointId, vector: &Vector) -> Option { - let (anchor, handle_position) = handle_id.get_anchor(vector).zip(handle_id.get_position(vector))?; +fn check_handle_over_adjacent_anchor(handle_id: ManipulatorPointId, vector: &VectorGeometry) -> Option { + let (anchor, handle_position) = vector.anchor_of(handle_id).zip(vector.position_of(handle_id))?; let check_if_close = |point_id: &PointId| { - let Some(anchor_position) = vector.point_domain.position_from_id(*point_id) else { + let Some(anchor_position) = vector.position_from_id(*point_id) else { return false; }; (anchor_position - handle_position).length() < 10. @@ -3446,15 +3457,15 @@ fn check_handle_over_adjacent_anchor(handle_id: ManipulatorPointId, vector: &Vec vector.connected_points(anchor).find(check_if_close) } -fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointId, anchor: Option, adjacent_anchor: Option, vector: &Vector) -> (Option, Option) { +fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointId, anchor: Option, adjacent_anchor: Option, vector: &VectorGeometry) -> (Option, Option) { // Early return if no anchor or no adjacent anchors let Some((dragged_handle_anchor, adjacent_anchor)) = anchor.zip(adjacent_anchor) else { return (None, None); }; - let adjacent_anchor_position = vector.point_domain.position_from_id(adjacent_anchor); + let adjacent_anchor_position = vector.position_from_id(adjacent_anchor); - let handles: Vec<_> = vector.all_connected(adjacent_anchor).filter(|handle| handle.length(vector) > 1e-6).collect(); + let handles: Vec<_> = vector.all_connected(adjacent_anchor).filter(|handle| vector.handle_length(*handle) > 1e-6).collect(); match handles.len() { 0 => { @@ -3494,8 +3505,8 @@ fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointI return (None, None); }; - let angle = shared_segment_handle - .get_position(vector) + let angle = vector + .position_of(shared_segment_handle) .zip(adjacent_anchor_position) .and_then(|(handle, anchor)| DVec2::X.try_angle_to(handle - anchor)); @@ -3765,7 +3776,7 @@ mod test_path_tool { let vector = document.network_interface.compute_modified_vector(layer).expect("the path should have a vector"); let to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); - vector.point_domain.positions().iter().map(|&position| to_viewport.transform_point2(position)).collect() + vector.anchor_positions().iter().map(|&position| to_viewport.transform_point2(position)).collect() } fn assert_anchors(editor: &EditorTestUtils, layer: LayerNodeIdentifier, expected: &[DVec2]) { @@ -3881,8 +3892,8 @@ mod test_path_tool { let handle_position = |editor: &EditorTestUtils| { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("the path should have a vector"); - let segment = vector.segment_domain.ids()[0]; - let handle = ManipulatorPointId::EndHandle(segment).get_position(&vector).expect("the segment should have a handle at its end"); + let segment = vector.segment_ids()[0]; + let handle = vector.position_of(ManipulatorPointId::EndHandle(segment)).expect("the segment should have a handle at its end"); document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface).transform_point2(handle) }; let handle = anchor * 2. - dragged_out; @@ -4038,4 +4049,68 @@ mod test_path_tool { "only the Alt-clicked anchor should be selected, not {selected:?}" ); } + + #[tokio::test] + async fn copied_points_paste_back_as_the_same_curves_and_smooth_pairs() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.handle_message(DocumentMessage::DeselectAllLayers).await; + + // Dragging out of the middle anchor with the Pen gives it a smooth pair of handles + let dragged_out = B + DVec2::new(60., 25.); + editor.click_tool(ToolType::Pen, MouseKeys::LEFT, A, ModifierKeys::empty()).await; + editor.move_mouse(B.x, B.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(B.x, B.y, ModifierKeys::empty()).await; + editor.move_mouse(dragged_out.x, dragged_out.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor.left_mouseup(dragged_out.x, dragged_out.y, ModifierKeys::empty()).await; + editor.click_tool(ToolType::Pen, MouseKeys::LEFT, C, ModifierKeys::empty()).await; + editor.press(Key::Enter, ModifierKeys::empty()).await; + + let layer = editor.get_selected_layer().await.expect("the drawn path should be selected"); + let geometry = |editor: &EditorTestUtils| editor.active_document().network_interface.compute_modified_vector(layer).expect("the path should have a vector"); + let original = geometry(&editor); + assert_eq!(original.colinear_pairs().len(), 1, "the dragged-out anchor should be smooth"); + + // Copy every point and paste them back into the same layer + editor.select_tool(ToolType::Path).await; + editor.handle_message(PathToolMessage::SelectAll).await; + let clipboard = editor + .handle_message(ClipboardMessage::CopyLayers) + .await + .into_iter() + .find_map(|message| match message { + FrontendMessage::TriggerClipboardWrite { content } => Some(content), + _ => None, + }) + .expect("copying points should write a payload to the clipboard"); + editor + .handle_message(ClipboardMessage::ReadClipboard { + content: ClipboardContentRaw::Text(clipboard), + }) + .await; + + // Each curve now appears a second time under a new ID + let control_points = |segment: kurbo::PathSeg| match segment { + kurbo::PathSeg::Line(line) => vec![line.p0, line.p1], + kurbo::PathSeg::Quad(quad) => vec![quad.p0, quad.p1, quad.p2], + kurbo::PathSeg::Cubic(cubic) => vec![cubic.p0, cubic.p1, cubic.p2, cubic.p3], + }; + let same_curve = |a: kurbo::PathSeg, b: kurbo::PathSeg| { + let (a, b) = (control_points(a), control_points(b)); + a.len() == b.len() && a.iter().zip(&b).all(|(a, b)| a.distance(*b) < 1e-9) + }; + + let pasted = geometry(&editor); + let original_ids = original.segment_ids(); + let pasted_segments: Vec<_> = pasted.segment_iter().filter(|(id, ..)| !original_ids.contains(id)).map(|(_, segment, ..)| segment).collect(); + assert_eq!(pasted_segments.len(), original_ids.len()); + for (_, segment, ..) in original.segment_iter() { + assert!( + pasted_segments.iter().any(|&pasted| same_curve(pasted, segment)), + "no pasted copy of {segment:?} among {pasted_segments:?}" + ); + } + + assert_eq!(pasted.colinear_pairs().len(), 2, "the pasted copy of the smooth anchor should be smooth too"); + } } diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index 8bee8c725a..9c7d3facc8 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -22,7 +22,7 @@ use graphene_std::Color; use graphene_std::vector::misc::pathseg_points; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; use graphene_std::vector::style::FillChoice; -use graphene_std::vector::{PointId, SegmentId, Vector, VectorModificationType}; +use graphene_std::vector::{PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{BezPath, CubicBez, PathSeg}; #[derive(Default, ExtractField)] @@ -531,7 +531,7 @@ impl PenToolData { } /// Check whether target handle is primary, end, or `self.handle_end` - fn check_end_handle_type(&self, vector: &Vector) -> TargetHandle { + fn check_end_handle_type(&self, vector: &VectorGeometry) -> TargetHandle { match (self.handle_end, self.prior_segment_endpoint, self.prior_segment, self.path_closed) { (Some(_), _, _, false) => TargetHandle::PreviewInHandle, (None, Some(point), Some(segment), false) | (Some(_), Some(point), Some(segment), true) => { @@ -545,7 +545,7 @@ impl PenToolData { } } - fn check_grs_end_handle(&self, vector: &Vector) -> TargetHandle { + fn check_grs_end_handle(&self, vector: &VectorGeometry) -> TargetHandle { let Some(point) = self.latest_point().map(|point| point.id) else { return TargetHandle::None }; let Some(segment) = self.prior_segment else { return TargetHandle::None }; @@ -556,7 +556,7 @@ impl PenToolData { } } - fn get_opposite_handle_type(&self, handle_type: TargetHandle, vector: &Vector) -> TargetHandle { + fn get_opposite_handle_type(&self, handle_type: TargetHandle, vector: &VectorGeometry) -> TargetHandle { match handle_type { TargetHandle::FuturePreviewOutHandle => self.check_end_handle_type(vector), TargetHandle::PreviewInHandle => match (self.path_closed, self.prior_segment_endpoint, self.prior_segment) { @@ -608,10 +608,10 @@ impl PenToolData { } } - fn target_handle_position(&self, handle_type: TargetHandle, vector: &Vector) -> Option { + fn target_handle_position(&self, handle_type: TargetHandle, vector: &VectorGeometry) -> Option { match handle_type { - TargetHandle::PriorOutHandle(segment) => ManipulatorPointId::PrimaryHandle(segment).get_position(vector), - TargetHandle::PriorInHandle(segment) => ManipulatorPointId::EndHandle(segment).get_position(vector), + TargetHandle::PriorOutHandle(segment) => vector.position_of(ManipulatorPointId::PrimaryHandle(segment)), + TargetHandle::PriorInHandle(segment) => vector.position_of(ManipulatorPointId::EndHandle(segment)), TargetHandle::PreviewInHandle => self.handle_end, TargetHandle::FuturePreviewOutHandle => Some(self.next_handle_start), TargetHandle::None => None, @@ -663,7 +663,7 @@ impl PenToolData { let into_merged = self.merging_from.map_or(DAffine2::IDENTITY, |previous| layer_to_document.inverse() * previous); for point in &mut self.latest_points { - let Some(pos) = vector.point_domain.position_from_id(point.id) else { continue }; + let Some(pos) = vector.position_from_id(point.id) else { continue }; point.handle_start = pos + into_merged.transform_vector2(point.handle_start - point.pos); point.pos = pos; } @@ -671,7 +671,7 @@ impl PenToolData { } /// Re-anchors the in-progress preview segment on the current anchor after undo or redo moved it, using the re-evaluated layer transform. - fn resume_preview_from_current_anchor(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, vector: &Vector, responses: &mut VecDeque) { + fn resume_preview_from_current_anchor(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, vector: &VectorGeometry, responses: &mut VecDeque) { // The segments meeting the current anchor are the ones whose handles the overlays show and the angle lock references let connected_segments: Vec = self .latest_point() @@ -757,9 +757,9 @@ impl PenToolData { } } - fn close_path_on_point(&mut self, vector: &Vector, document: &DocumentMessageHandler, id: PointId, transform: &DAffine2) -> bool { + fn close_path_on_point(&mut self, vector: &VectorGeometry, document: &DocumentMessageHandler, id: PointId, transform: &DAffine2) -> bool { for id in vector.anchor_points().filter(|&point| point != id) { - let Some(pos) = vector.point_domain.position_from_id(id) else { continue }; + let Some(pos) = vector.position_from_id(id) else { continue }; let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(self.next_point)); let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2); @@ -815,7 +815,7 @@ impl PenToolData { let start = self.latest_point()?.id; let transform = document.metadata().document_to_viewport * transform; for id in vector.anchor_points().filter(|&point| point != start) { - let Some(pos) = vector.point_domain.position_from_id(id) else { continue }; + let Some(pos) = vector.position_from_id(id) else { continue }; let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point)); let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2); if transformed_distance_between_squared < snap_point_tolerance_squared { @@ -839,12 +839,12 @@ impl PenToolData { && let Some((handles, handle1_pos)) = match self.get_opposite_handle_type(TargetHandle::PreviewInHandle, &vector) { TargetHandle::PriorOutHandle(segment) => { let handles = [HandleId::end(id), HandleId::primary(segment)]; - let handle1_pos = handles[1].to_manipulator_point().get_position(&vector); + let handle1_pos = vector.position_of(handles[1].to_manipulator_point()); handle1_pos.map(|pos| (handles, pos)) } TargetHandle::PriorInHandle(segment) => { let handles = [HandleId::end(id), HandleId::end(segment)]; - let handle1_pos = handles[1].to_manipulator_point().get_position(&vector); + let handle1_pos = vector.position_of(handles[1].to_manipulator_point()); handle1_pos.map(|pos| (handles, pos)) } _ => None, @@ -872,7 +872,7 @@ impl PenToolData { [HandleId::primary(last_segment), HandleId::primary(id)] }; - if let Some(h1) = handles[0].to_manipulator_point().get_position(&vector) { + if let Some(h1) = vector.position_of(handles[0].to_manipulator_point()) { let colinear = is_almost_colinear(last_point.pos, h1, last_point.handle_start); responses.add(GraphOperationMessage::Vector { layer, @@ -894,7 +894,7 @@ impl PenToolData { } /// Snaps the slide of the anchor and its handles while Space is held, and returns how far they move in layer space. - fn space_anchor_handle_snap(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, mouse: DVec2, vector: &Vector) -> Option { + fn space_anchor_handle_snap(&mut self, snap_session: &mut SnapSession, view: SnapView, transform: DAffine2, mouse: DVec2, vector: &VectorGeometry) -> Option { let reference_handle = if self.path_closed { TargetHandle::PreviewInHandle } else { TargetHandle::FuturePreviewOutHandle }; let reference_position = transform.transform_point2(self.target_handle_position(reference_handle, vector)?); @@ -996,7 +996,7 @@ impl PenToolData { Some(PenToolFsmState::DraggingHandle(self.handle_mode)) } - fn move_anchor_and_handles(&mut self, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque, vector: &Vector) { + fn move_anchor_and_handles(&mut self, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque, vector: &VectorGeometry) { if self.handle_end.is_none() && let Some(latest_pt) = self.latest_point_mut() { @@ -1122,7 +1122,7 @@ impl PenToolData { } /// Makes the opposite handle equidistant or locks its length. - fn adjust_handle_length(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &Vector) { + fn adjust_handle_length(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, vector: &VectorGeometry) { let opposite_handle_type = self.get_opposite_handle_type(self.handle_type, vector); match self.handle_mode { HandleMode::ColinearEquidistant => { @@ -1159,7 +1159,7 @@ impl PenToolData { } } - fn apply_colinear_constraint(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, anchor_pos: DVec2, vector: &Vector) { + fn apply_colinear_constraint(&mut self, responses: &mut VecDeque, layer: LayerNodeIdentifier, anchor_pos: DVec2, vector: &VectorGeometry) { let Some(handle) = self.target_handle_position(self.handle_type, vector) else { return }; if (anchor_pos - handle).length() < 1e-6 && self.modifiers.lock_angle { @@ -1193,7 +1193,7 @@ impl PenToolData { if let Some(vector) = document.network_interface.compute_modified_vector(layer) { let transform = document.metadata().document_to_viewport * transform; for point in vector.anchor_points() { - let Some(pos) = vector.point_domain.position_from_id(point) else { continue }; + let Some(pos) = vector.position_from_id(point) else { continue }; let transformed_distance_between_squared = transform.transform_point2(pos).distance_squared(transform.transform_point2(self.next_point)); let snap_point_tolerance_squared = crate::consts::SNAP_POINT_TOLERANCE.powi(2); if transformed_distance_between_squared < snap_point_tolerance_squared { @@ -1367,7 +1367,7 @@ impl PenToolData { /// Perform extension of an existing path fn extend_existing_path(&mut self, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, point: PointId, position: DVec2) { - let vector: Option = document.network_interface.compute_modified_vector(layer); + let vector: Option = document.network_interface.compute_modified_vector(layer); let (handle_start, in_segment) = if let Some(vector) = &vector { vector .segment_iter() @@ -1435,8 +1435,8 @@ impl PenToolData { } } - fn set_lock_angle(&mut self, vector: &Vector, anchor: PointId, segment: Option) { - let anchor_position = vector.point_domain.position_from_id(anchor); + fn set_lock_angle(&mut self, vector: &VectorGeometry, anchor: PointId, segment: Option) { + let anchor_position = vector.position_from_id(anchor); let Some((anchor_position, segment)) = anchor_position.zip(segment) else { self.handle_mode = HandleMode::Free; @@ -1823,7 +1823,7 @@ impl Fsm for PenToolFsmState { && let Some(mut vector) = document.network_interface.compute_modified_vector(layer) { let closest_point = vector.anchor_points().filter(|&id| id != start).find(|&id| { - vector.point_domain.position_from_id(id).is_some_and(|pos| { + vector.position_from_id(id).is_some_and(|pos| { let dist_sq = transform.transform_point2(pos).distance_squared(transform.transform_point2(next_point)); dist_sq < crate::consts::SNAP_POINT_TOLERANCE.powi(2) }) @@ -1841,10 +1841,8 @@ impl Fsm for PenToolFsmState { for path in closed_paths { let segments = path.edges.iter().filter_map(|edge| { vector - .segment_domain - .iter() - .find(|(id, _, _, _)| id == &edge.id) - .map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) }) + .segment_with_pool_endpoints(edge.id) + .map(|(segment, start, end)| if start == edge.start { (segment, start, end) } else { (segment.reverse(), end, start) }) }); if let Some(bezpath) = vector.bezpath_from_segments_ignore_discontinuities(segments) { fill_region.extend(bezpath.elements().iter().copied()); @@ -1970,7 +1968,7 @@ impl Fsm for PenToolFsmState { } (PenToolFsmState::PlacingAnchor, PenToolMessage::Undo) => { let vector = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)); - let anchor_exists = |point: &LastPoint| vector.as_ref().is_some_and(|vector| vector.point_domain.position_from_id(point.id).is_some()); + let anchor_exists = |point: &LastPoint| vector.as_ref().is_some_and(|vector| vector.position_from_id(point.id).is_some()); // Rewind past the anchors the reverted path no longer contains, remembering them so redo can advance back through them while tool_data.point_index > 0 && !tool_data.latest_point().is_some_and(anchor_exists) { @@ -1996,7 +1994,7 @@ impl Fsm for PenToolFsmState { }; // Advance only through the remembered anchors the re-applied step actually brought back - let anchor_exists = |point: &LastPoint| vector.point_domain.position_from_id(point.id).is_some(); + let anchor_exists = |point: &LastPoint| vector.position_from_id(point.id).is_some(); let mut advanced = false; while tool_data.latest_points.get(tool_data.point_index + 1).is_some_and(anchor_exists) { tool_data.point_index += 1; @@ -2238,7 +2236,7 @@ impl Fsm for PenToolFsmState { (PenToolFsmState::DraggingHandle(..), PenToolMessage::Confirm) => { // Confirm to end path if let Some((vector, layer)) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)).zip(layer) { - let single_point_in_layer = vector.point_domain.ids().len() == 1; + let single_point_in_layer = vector.anchor_points().count() == 1; tool_data.finish_placing_handle(snap_session, view, transform, responses); let latest_points = tool_data.point_index == 0; @@ -2290,7 +2288,7 @@ impl Fsm for PenToolFsmState { } (PenToolFsmState::PlacingAnchor, PenToolMessage::Abort) => { let should_delete_layer = if let Some(vector) = layer.and_then(|layer| document.network_interface.compute_modified_vector(layer)) { - vector.point_domain.ids().len() == 1 + vector.anchor_points().count() == 1 } else { false }; @@ -2395,10 +2393,10 @@ mod test_pen_tool { use crate::test_utils::test_prelude::*; use glam::DAffine2; use graphene_std::vector::misc::ManipulatorPointId; - use graphene_std::vector::{SegmentId, Vector}; + use graphene_std::vector::{SegmentId, VectorGeometry}; /// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away. - fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, Vector)> { + fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> { let document = editor.active_document(); let path_identifier = DefinitionIdentifier::Network("Path".into()); let mut path_layers = document @@ -2414,8 +2412,8 @@ mod test_pen_tool { fn assert_path_shape(editor: &EditorTestUtils, points: usize, segments: usize) { let (_, vector) = drawn_path(editor).expect("Expected a drawn path"); - assert_eq!(vector.point_domain.ids().len(), points, "Unexpected point count"); - assert_eq!(vector.segment_domain.ids().len(), segments, "Unexpected segment count"); + assert_eq!(vector.anchor_points().count(), points, "Unexpected point count"); + assert_eq!(vector.segment_ids().len(), segments, "Unexpected segment count"); } /// Asserts the path's anchors sit at the given viewport positions, in placement order, and that each segment joins consecutive anchors. @@ -2423,17 +2421,17 @@ mod test_pen_tool { let (layer, vector) = drawn_path(editor).expect("Expected a drawn path"); let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); - let anchor_ids = vector.point_domain.ids(); + let anchor_ids = vector.anchor_points().collect::>(); assert_eq!(anchor_ids.len(), expected.len(), "Unexpected point count"); for (index, (&id, &expected_position)) in anchor_ids.iter().zip(expected).enumerate() { - let position = layer_to_viewport.transform_point2(vector.point_domain.position_from_id(id).unwrap()); + let position = layer_to_viewport.transform_point2(vector.position_from_id(id).unwrap()); assert!( position.distance(expected_position) < 1e-6, "Anchor {index} is at {position:?} but was expected at {expected_position:?}" ); } - let segment_ids = vector.segment_domain.ids(); + let segment_ids = vector.segment_ids(); assert_eq!(segment_ids.len(), expected.len().saturating_sub(1), "Unexpected segment count"); for (index, &segment) in segment_ids.iter().enumerate() { assert_eq!(vector.segment_start_from_id(segment), Some(anchor_ids[index]), "Segment {index} does not start at anchor {index}"); @@ -2640,7 +2638,7 @@ mod test_pen_tool { fn anchor_positions(editor: &EditorTestUtils) -> Vec { let (layer, vector) = drawn_path(editor).expect("Expected a drawn path"); let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); - vector.point_domain.positions().iter().map(|&position| layer_to_viewport.transform_point2(position)).collect() + vector.anchor_positions().into_iter().map(|position| layer_to_viewport.transform_point2(position)).collect() } async fn set_space_held(editor: &mut EditorTestUtils, held: bool) { @@ -2756,8 +2754,8 @@ mod test_pen_tool { // The last segment runs from C back to A rather than to a new anchor beside it let (_, vector) = drawn_path(&editor).expect("Expected a drawn path"); - let anchors = vector.point_domain.ids(); - let closing = vector.segment_domain.ids()[2]; + let anchors: Vec<_> = vector.anchor_points().collect(); + let closing = vector.segment_ids()[2]; assert_eq!(vector.segment_start_from_id(closing), Some(anchors[2])); assert_eq!(vector.segment_end_from_id(closing), Some(anchors[0])); assert!(anchor_positions(&editor)[0].distance(A) < 1e-6); @@ -2848,16 +2846,13 @@ mod test_pen_tool { let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); let handles = vector - .segment_domain - .ids() - .iter() - .flat_map(|&segment| [ManipulatorPointId::PrimaryHandle(segment), ManipulatorPointId::EndHandle(segment)]) - .filter_map(|handle| handle.get_position(&vector)); + .segment_ids() + .into_iter() + .flat_map(|segment| [ManipulatorPointId::PrimaryHandle(segment), ManipulatorPointId::EndHandle(segment)]) + .filter_map(|handle| vector.position_of(handle)); let mut positions: Vec = vector - .point_domain - .positions() - .iter() - .copied() + .anchor_positions() + .into_iter() .chain(handles) .map(|position| layer_to_viewport.transform_point2(position)) .collect(); @@ -2934,7 +2929,7 @@ mod test_pen_tool { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("The second path should have a vector"); - let first = document.metadata().transform_to_viewport(layer).transform_point2(vector.point_domain.positions()[0]); + let first = document.metadata().transform_to_viewport(layer).transform_point2(vector.anchor_positions()[0]); // Its next anchor has a handle dragged out of it let (anchor, handle) = (DVec2::new(260., 240.), DVec2::new(300., 270.)); @@ -2955,17 +2950,16 @@ mod test_pen_tool { let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer); let leaves_the_anchor = |&segment: &SegmentId| { - let start = vector.segment_start_from_id(segment).and_then(|point| vector.point_domain.position_from_id(point)); + let start = vector.segment_start_from_id(segment).and_then(|point| vector.position_from_id(point)); start.is_some_and(|start| layer_to_viewport.transform_point2(start).distance(anchor) < 1e-6) }; let joining = vector - .segment_domain - .ids() + .segment_ids() .iter() .copied() .find(|segment| leaves_the_anchor(segment)) .expect("A segment should leave the anchor"); - let leaving = ManipulatorPointId::PrimaryHandle(joining).get_position(&vector).expect("The joining segment should have a handle"); + let leaving = vector.position_of(ManipulatorPointId::PrimaryHandle(joining)).expect("The joining segment should have a handle"); let leaving = layer_to_viewport.transform_point2(leaving); assert!(leaving.distance(handle) < 1e-6, "the joining segment's handle is at {leaving}"); } @@ -2997,8 +2991,8 @@ mod test_pen_tool { // The incoming handle stays opposite the outgoing one, which was dragged out from the anchor before it moved let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); - let segment = vector.segment_domain.ids()[0]; - let incoming = ManipulatorPointId::EndHandle(segment).get_position(&vector).expect("The segment should have an incoming handle"); + let segment = vector.segment_ids()[0]; + let incoming = vector.position_of(ManipulatorPointId::EndHandle(segment)).expect("The segment should have an incoming handle"); let incoming = editor.active_document().metadata().transform_to_viewport(layer).transform_point2(incoming); assert!(incoming.distance(corner + anchor - handle) < 1e-6, "the incoming handle is at {incoming}"); } @@ -3028,8 +3022,8 @@ mod test_pen_tool { // The next segment starts with the moved handle click_pen(&mut editor, DVec2::new(450., 400.)).await; let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path"); - let segment = vector.segment_domain.ids()[1]; - let outgoing = ManipulatorPointId::PrimaryHandle(segment).get_position(&vector).expect("The segment should have an outgoing handle"); + let segment = vector.segment_ids()[1]; + let outgoing = vector.position_of(ManipulatorPointId::PrimaryHandle(segment)).expect("The segment should have an outgoing handle"); let outgoing = editor.active_document().metadata().transform_to_viewport(layer).transform_point2(outgoing); assert!(outgoing.distance(handle + travel) < 1e-6, "the handle is at {outgoing} rather than {}", handle + travel); } diff --git a/editor/src/messages/tool/tool_messages/spline_tool.rs b/editor/src/messages/tool/tool_messages/spline_tool.rs index e2674cce35..4b25b369c7 100644 --- a/editor/src/messages/tool/tool_messages/spline_tool.rs +++ b/editor/src/messages/tool/tool_messages/spline_tool.rs @@ -698,15 +698,13 @@ mod test_spline_tool { use crate::test_utils::test_prelude::*; use glam::DAffine2; use graphene_std::vector::PointId; - use graphene_std::vector::Vector; + use graphene_std::vector::VectorGeometry; - fn assert_point_positions(vector: &Vector, layer_to_viewport: DAffine2, expected_points: &[DVec2], epsilon: f64) { + fn assert_point_positions(vector: &VectorGeometry, layer_to_viewport: DAffine2, expected_points: &[DVec2], epsilon: f64) { let points_in_viewport: Vec = vector - .point_domain - .ids() - .iter() - .filter_map(|&point_id| { - let position = vector.point_domain.position_from_id(point_id)?; + .anchor_points() + .filter_map(|point_id| { + let position = vector.position_from_id(point_id)?; Some(layer_to_viewport.transform_point2(position)) }) .collect(); @@ -734,7 +732,7 @@ mod test_spline_tool { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("The spline should have a path"); - assert_eq!(vector.point_domain.ids().len(), expected.len(), "Unexpected point count"); + assert_eq!(vector.anchor_points().count(), expected.len(), "Unexpected point count"); assert_point_positions(&vector, document.metadata().transform_to_viewport(layer), expected, 1e-6); } @@ -771,8 +769,8 @@ mod test_spline_tool { let first_vector = document.network_interface.compute_modified_vector(spline_layer).expect("Vector not found for the spline layer"); // Verify initial spline has correct number of points and segments - let initial_point_count = first_vector.point_domain.ids().len(); - let initial_segment_count = first_vector.segment_domain.ids().len(); + let initial_point_count = first_vector.anchor_points().count(); + let initial_segment_count = first_vector.segment_ids().len(); assert_eq!(initial_point_count, 3, "Expected 3 points in initial spline, found {initial_point_count}"); assert_eq!(initial_segment_count, 2, "Expected 2 segments in initial spline, found {initial_segment_count}"); @@ -780,7 +778,7 @@ mod test_spline_tool { let endpoints: Vec<(PointId, DVec2)> = first_vector .anchor_endpoints() - .filter_map(|point_id| first_vector.point_domain.position_from_id(point_id).map(|pos| (point_id, layer_to_viewport.transform_point2(pos)))) + .filter_map(|point_id| first_vector.position_from_id(point_id).map(|pos| (point_id, layer_to_viewport.transform_point2(pos)))) .collect(); assert_eq!(endpoints.len(), 2, "Expected 2 endpoints in the initial spline"); @@ -805,8 +803,8 @@ mod test_spline_tool { .expect("Vector not found for the extended spline layer"); // Verify extended spline has correct number of points and segments - let extended_point_count = extended_vector.point_domain.ids().len(); - let extended_segment_count = extended_vector.segment_domain.ids().len(); + let extended_point_count = extended_vector.anchor_points().count(); + let extended_segment_count = extended_vector.segment_ids().len(); assert_eq!(extended_point_count, 5, "Expected 5 points in extended spline, found {extended_point_count}"); assert_eq!(extended_segment_count, 4, "Expected 4 segments in extended spline, found {extended_segment_count}"); @@ -997,8 +995,8 @@ mod test_spline_tool { let vector = document.network_interface.compute_modified_vector(spline_layer).expect("Vector not found for the spline layer"); // Verify we have the correct number of points and segments - let point_count = vector.point_domain.ids().len(); - let segment_count = vector.segment_domain.ids().len(); + let point_count = vector.anchor_points().count(); + let segment_count = vector.segment_ids().len(); assert_eq!(point_count, 3, "Expected 3 points in the spline, found {point_count}"); assert_eq!(segment_count, 2, "Expected 2 segments in the spline, found {segment_count}"); diff --git a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs index e2bdff5374..b29847431f 100644 --- a/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs +++ b/editor/src/messages/tool/transform_layer/transform_layer_message_handler.rs @@ -20,7 +20,7 @@ use glam::{DAffine2, DVec2}; use graphene_std::renderer::Quad; use graphene_std::vector::click_target::ClickTargetType; use graphene_std::vector::misc::ManipulatorPointId; -use graphene_std::vector::{Vector, VectorModificationType}; +use graphene_std::vector::{VectorGeometry, VectorModificationType}; use std::f64::consts::{PI, TAU}; const TRANSFORM_GRS_OVERLAY_PROVIDER: OverlayProvider = |context| TransformLayerMessage::Overlays { context }.into(); @@ -184,7 +184,7 @@ impl MessageHandler> for let affected_point_refs = affected_points.iter().collect(); - let get_location = |point: &&ManipulatorPointId| point.get_position(&vector).map(|position| viewspace.transform_point2(position)); + let get_location = |point: &&ManipulatorPointId| vector.position_of(**point).map(|position| viewspace.transform_point2(position)); if let (Some((new_pivot, grab_target)), bounds) = calculate_pivot( document, &affected_point_refs, @@ -480,9 +480,9 @@ impl MessageHandler> for && let [point] = selected_points.as_slice() { if matches!(point, ManipulatorPointId::Anchor(_)) { - if let Some([handle1, handle2]) = point.get_handle_pair(&vector) { - let handle1_length = handle1.length(&vector); - let handle2_length = handle2.length(&vector); + if let Some([handle1, handle2]) = vector.handle_pair_of(**point) { + let handle1_length = vector.handle_length(handle1); + let handle2_length = vector.handle_length(handle2); if (handle1_length == 0. && handle2_length == 0. && !using_select_tool) || (handle1_length == f64::MAX && handle2_length == f64::MAX && !using_select_tool) { // G should work for this point but not R and S @@ -493,7 +493,7 @@ impl MessageHandler> for } } } else { - let handle_length = point.as_handle().map(|handle| handle.length(&vector)); + let handle_length = point.as_handle().map(|handle| vector.handle_length(handle)); if handle_length == Some(0.) { selected.original_transforms.clear(); @@ -800,10 +800,10 @@ impl Snapping { moving.edited.push(layer); for point in points { - if let Some(anchor) = point.get_anchor(&vector) { + if let Some(anchor) = vector.anchor_of(point) { moving.anchors.push((layer, anchor)); } - if let Some(position) = point.get_position(&vector) { + if let Some(position) = vector.position_of(point) { starts.push(to_document.transform_point2(position)); } } @@ -952,7 +952,7 @@ fn snap_again(operation: &mut TransformOperation, snapping: Option<&Snapping>, s fn calculate_pivot( document: &DocumentMessageHandler, selected_points: &Vec<&ManipulatorPointId>, - vector: &Vector, + vector: &VectorGeometry, viewspace: DAffine2, get_location: impl Fn(&ManipulatorPointId) -> Option, gizmo: &mut PivotGizmo, @@ -995,8 +995,8 @@ fn calculate_pivot( ManipulatorPointId::PrimaryHandle(_) | ManipulatorPointId::EndHandle(_) => { // Get the anchor position and transform it to the pivot let (Some(pivot_position), Some(position)) = ( - point.get_anchor_position(vector).map(|anchor_position| viewspace.transform_point2(anchor_position)), - point.get_position(vector), + vector.anchor_position_of(**point).map(|anchor_position| viewspace.transform_point2(anchor_position)), + vector.position_of(**point), ) else { return (None, None); }; @@ -1015,18 +1015,18 @@ fn update_colinear_handles(selected_layers: &[LayerNodeIdentifier], document: &D for &layer in selected_layers { let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; - for [handle1, handle2] in &vector.colinear_manipulators { + for [handle1, handle2] in vector.colinear_pairs() { let manipulator1 = handle1.to_manipulator_point(); let manipulator2 = handle2.to_manipulator_point(); - let Some(anchor_pos) = manipulator1.get_anchor_position(&vector) else { continue }; - let Some(handle1_pos) = manipulator1.get_position(&vector) else { continue }; - let Some(handle2_pos) = manipulator2.get_position(&vector) else { continue }; + let Some(anchor_pos) = vector.anchor_position_of(manipulator1) else { continue }; + let Some(handle1_pos) = vector.position_of(manipulator1) else { continue }; + let Some(handle2_pos) = vector.position_of(manipulator2) else { continue }; // Check if handles are not colinear (not approximately equal to +/- PI) if !is_almost_colinear(anchor_pos, handle1_pos, handle2_pos) { let modification_type = VectorModificationType::SetG1Continuous { - handles: [*handle1, *handle2], + handles: [handle1, handle2], enabled: false, }; @@ -1840,7 +1840,7 @@ mod test_transform_layer { let document = editor.active_document(); let vector = document.network_interface.compute_modified_vector(layer).expect("the path should have a vector"); let to_viewport = document.metadata().transform_to_viewport_if_feeds(layer, &document.network_interface); - let anchors: Vec = vector.point_domain.positions().iter().map(|&position| to_viewport.transform_point2(position)).collect(); + let anchors: Vec = vector.anchor_positions().iter().map(|&position| to_viewport.transform_point2(position)).collect(); assert_eq!(anchors.len(), 2, "unexpected anchors {anchors:?}"); assert!( anchors[0].distance(first) < 1e-6 && anchors[1].distance(DVec2::new(400., 300.)) < 1e-6, diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 50ccce48d4..ecb9ba72d6 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -14,7 +14,7 @@ use graphene_std::memo::IORecord; 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, graphic_types}; +use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes}; use graphene_std::{ATTR_TRANSFORM, Context, Graphic}; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use std::any::Any; @@ -36,7 +36,7 @@ pub struct ExecutionResponse { execution_id: u64, result: Result, responses: VecDeque, - vector_modify: HashMap, + vector_modify: HashMap, /// The resulting value from the temporary inspected during execution inspect_result: Option, } @@ -838,7 +838,8 @@ fn measure_fill_geometry(data: &Arc) -> Option<(DAffine2, if let Some(list) = introspected_output::>(data) { let vector = list.element(0)?; let item_transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0); - let bounds = vector.nonzero_bounding_box(); + let paths = paths_from_list_row_attributes(&list, 0).unwrap_or_else(|| no_paths()); + let bounds = vector.nonzero_bounding_box(paths); let bounding_box_affine = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]); return Some((bounding_box_affine, item_transform)); } diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 8ce1ccea57..26f1307866 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -18,8 +18,8 @@ use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, use graphene_std::raster_types::Raster; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment}; use graphene_std::transform::RenderQuality; -use graphene_std::vector::Vector; use graphene_std::vector::style::RenderMode; +use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes}; use graphene_std::{Artboard, Context, Graphic}; use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::util::wrap_network_in_scope; @@ -54,7 +54,7 @@ pub struct NodeRuntime { // TODO: Remove, it doesn't need to be persisted anymore /// The current renders of the thumbnails for layer nodes. thumbnail_renders: HashMap>, - vector_modify: HashMap, + vector_modify: HashMap, /// Cached surface for Wasm viewport rendering (reused across frames) #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] @@ -432,7 +432,11 @@ impl NodeRuntime { // Vector list: vector modifications else if let Some(io) = introspected_data.downcast_ref::>>() { // Insert the vector modify - self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default()); + let geometry = VectorGeometry::new( + io.output.element(0).cloned().unwrap_or_default(), + paths_from_list_row_attributes(&io.output, 0).cloned().unwrap_or_default(), + ); + self.vector_modify.insert(parent_network_node_id, geometry); } // String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`) else if let Some(io) = introspected_data.downcast_ref::>>() { @@ -455,7 +459,7 @@ impl NodeRuntime { Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &singleton, bounds, responses) } } else if let Some(io) = introspected_data.downcast_ref::>>() { - self.vector_modify.insert(parent_network_node_id, io.output.element().clone()); + self.vector_modify.insert(parent_network_node_id, VectorGeometry::from_item(&io.output)); } else if let Some(io) = introspected_data.downcast_ref::>>() { if update_thumbnails { let singleton = List::new_from_item(io.output.clone()); diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 7cede3af5d..086d632bd1 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -779,8 +779,8 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize } "Vector" | "VectorData" => { let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?; - if let Some(vector) = vector { - let modification = Box::new(VectorModification::create_from_vector(&vector)); + if let Some((vector, paths)) = vector { + let modification = Box::new(VectorModification::create_from_vector(&vector, &paths)); return Ok(MemoHash::new(TaggedValue::VectorModification(modification))); } return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Vector)))); diff --git a/node-graph/libraries/core-types/src/bounds.rs b/node-graph/libraries/core-types/src/bounds.rs index 17af647c10..f4fcd282a0 100644 --- a/node-graph/libraries/core-types/src/bounds.rs +++ b/node-graph/libraries/core-types/src/bounds.rs @@ -1,4 +1,5 @@ use crate::Color; +use crate::list::{Item, List}; use glam::{DAffine2, DVec2}; #[derive(Clone, Copy, Default, Debug, PartialEq)] @@ -20,6 +21,33 @@ pub trait BoundingBox { /// Types with no meaningful contribution (e.g., `Color`) return `Infinite` from both; the runtime substitutes a /// small fallback rectangle at the end if no finite bounds remain after combining. fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox; + + /// The bounds of an item's element, for the thumbnail when `thumbnail` is set. A type with geometry that + /// partly rides its item's attributes overrides this to read them, and the rest defer to the element alone. + fn bounding_box_in_item(item: &Item, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox + where + Self: Sized, + { + let element = item.element(); + if thumbnail { + element.thumbnail_bounding_box(transform, include_stroke) + } else { + element.bounding_box(transform, include_stroke) + } + } + + /// As [`Self::bounding_box_in_item`], for the element at one index of a list. + fn bounding_box_in_list(list: &List, index: usize, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox + where + Self: Sized, + { + let Some(element) = list.element(index) else { return RenderBoundingBox::None }; + if thumbnail { + element.thumbnail_bounding_box(transform, include_stroke) + } else { + element.bounding_box(transform, include_stroke) + } + } } macro_rules! none_impl { diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index d9f75d319a..128f1ff515 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -30,7 +30,7 @@ pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path"; /// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for /// the original child layers after their content has been collapsed. pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers"; -/// Optional `Vector` that overrides the item's own geometry for click-target generation. +/// Optional `BezPath` that overrides the item's own geometry for click-target generation. /// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable /// by clicking anywhere within their bounds, not just the filled letterform. pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target"; @@ -112,11 +112,11 @@ pub const ATTR_PATHS: &str = "paths"; /// holding the path (implicit default `Linear`). pub const ATTR_CURVE_TYPE: &str = "curve_type"; /// Point reference's `bool` tool state marking the tangent pair at this anchor occurrence as smooth, -/// on the `List` inside a `Path` (implicit default `false`). Editing tools keep a smooth pair +/// on the `List` inside a `Path` (implicit default `false`). Editing tools keep a smooth pair /// colinear. Rendering derives continuity from actual tangent geometry and does not read this. pub const ATTR_SMOOTH: &str = "smooth"; /// Item's stable ID for external addressing (modifications, tools, animation), opt-in because indices are -/// the internal addressing: a `PointId` on a `Vector`'s point pool, or a `SegmentId` on the `List` +/// the internal addressing: a `PointId` on a `Vector`'s point pool, or a `SegmentId` on the `List` /// inside a `Path` at the anchor reference the segment departs from. pub const ATTR_ID: &str = "id"; /// Text item's font size in document-space units (`f64`, implicit default `24.`). @@ -1214,8 +1214,8 @@ impl BoundingBox for List { fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { let mut combined_bounds = None; - for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::(ATTR_TRANSFORM)) { - match element.bounding_box(transform * item_transform, include_stroke) { + for (index, item_transform) in self.iter_attribute_values_or_default::(ATTR_TRANSFORM).enumerate() { + match T::bounding_box_in_list(self, index, transform * item_transform, include_stroke, false) { RenderBoundingBox::None => continue, RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite, RenderBoundingBox::Rectangle(bounds) => match combined_bounds { @@ -1236,8 +1236,8 @@ impl BoundingBox for List { let mut combined_bounds = None; let mut any_infinite = false; - for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::(ATTR_TRANSFORM)) { - match element.thumbnail_bounding_box(transform * item_transform, include_stroke) { + for (index, item_transform) in self.iter_attribute_values_or_default::(ATTR_TRANSFORM).enumerate() { + match T::bounding_box_in_list(self, index, transform * item_transform, include_stroke, true) { RenderBoundingBox::None => continue, RenderBoundingBox::Infinite => any_infinite = true, RenderBoundingBox::Rectangle(bounds) => match combined_bounds { @@ -1357,12 +1357,12 @@ impl BoundingBox for Item { /// Computes the element's bounding box, composing the item's transform attribute with the given transform. fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM); - self.element().bounding_box(transform * item_transform, include_stroke) + T::bounding_box_in_item(self, transform * item_transform, include_stroke, false) } fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM); - self.element().thumbnail_bounding_box(transform * item_transform, include_stroke) + T::bounding_box_in_item(self, transform * item_transform, include_stroke, true) } } diff --git a/node-graph/libraries/core-types/src/render_complexity.rs b/node-graph/libraries/core-types/src/render_complexity.rs index b9bbeeb201..5d891b5761 100644 --- a/node-graph/libraries/core-types/src/render_complexity.rs +++ b/node-graph/libraries/core-types/src/render_complexity.rs @@ -6,17 +6,34 @@ pub trait RenderComplexity { fn render_complexity(&self) -> usize { 0 } + + /// The complexity of an item's element. A type with content that partly rides its item's attributes overrides + /// this to read them, and the rest defer to the element alone. + fn render_complexity_in_item(item: &Item) -> usize + where + Self: Sized, + { + item.element().render_complexity() + } + + /// As [`Self::render_complexity_in_item`], for the element at one index of a list. + fn render_complexity_in_list(list: &List, index: usize) -> usize + where + Self: Sized, + { + list.element(index).map_or(0, Self::render_complexity) + } } impl RenderComplexity for Item { fn render_complexity(&self) -> usize { - self.element().render_complexity() + T::render_complexity_in_item(self) } } impl RenderComplexity for List { fn render_complexity(&self) -> usize { - self.iter_element_values().map(|element| element.render_complexity()).fold(0, usize::saturating_add) + (0..self.len()).map(|index| T::render_complexity_in_list(self, index)).fold(0, usize::saturating_add) } } diff --git a/node-graph/libraries/graphene-hash/Cargo.toml b/node-graph/libraries/graphene-hash/Cargo.toml index 92ea4610fe..36c59e8b8c 100644 --- a/node-graph/libraries/graphene-hash/Cargo.toml +++ b/node-graph/libraries/graphene-hash/Cargo.toml @@ -16,9 +16,10 @@ workspace = true [features] default = ["std"] -std = [] +std = ["dep:kurbo"] derive = ["graphene-hash-derive"] [dependencies] graphene-hash-derive = { path = "derive", optional = true } glam = { workspace = true } +kurbo = { workspace = true, optional = true } diff --git a/node-graph/libraries/graphene-hash/src/lib.rs b/node-graph/libraries/graphene-hash/src/lib.rs index 4476ad4fed..00be14c112 100644 --- a/node-graph/libraries/graphene-hash/src/lib.rs +++ b/node-graph/libraries/graphene-hash/src/lib.rs @@ -153,6 +153,44 @@ impl_glam_array! { glam::Quat, glam::DQuat, } +// kurbo path types: hash each element's verb and point coordinates via to_bits(). +#[cfg(feature = "std")] +impl CacheHash for kurbo::Point { + #[inline] + fn cache_hash(&self, state: &mut H) { + self.x.cache_hash(state); + self.y.cache_hash(state); + } +} + +#[cfg(feature = "std")] +impl CacheHash for kurbo::PathEl { + fn cache_hash(&self, state: &mut H) { + core::hash::Hash::hash(&core::mem::discriminant(self), state); + match self { + kurbo::PathEl::MoveTo(point) | kurbo::PathEl::LineTo(point) => point.cache_hash(state), + kurbo::PathEl::QuadTo(handle, point) => { + handle.cache_hash(state); + point.cache_hash(state); + } + kurbo::PathEl::CurveTo(handle_start, handle_end, point) => { + handle_start.cache_hash(state); + handle_end.cache_hash(state); + point.cache_hash(state); + } + kurbo::PathEl::ClosePath => {} + } + } +} + +#[cfg(feature = "std")] +impl CacheHash for kurbo::BezPath { + #[inline] + fn cache_hash(&self, state: &mut H) { + self.elements().cache_hash(state); + } +} + // Generic container impls. impl CacheHash for Option { #[inline] diff --git a/node-graph/libraries/graphic-types/src/graphic.rs b/node-graph/libraries/graphic-types/src/graphic.rs index c6848c0dc1..3768ecdded 100644 --- a/node-graph/libraries/graphic-types/src/graphic.rs +++ b/node-graph/libraries/graphic-types/src/graphic.rs @@ -13,6 +13,7 @@ use dyn_any::DynAny; use glam::{DAffine2, DVec2}; use raster_types::{CPU, GPU, Raster}; pub use vector_types::Vector; +use vector_types::vector::{Path, paths_from_item_attributes, paths_from_list_row_attributes}; use vector_types::{Gradient, GradientSpread}; /// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node. @@ -52,11 +53,6 @@ impl From> for Graphic { } // Vector -impl From for Graphic { - fn from(vector: Vector) -> Self { - Graphic::Vector(Box::new(Item::new_from_element(vector))) - } -} impl From> for Graphic { fn from(vector: Item) -> Self { Graphic::Vector(Box::new(vector)) @@ -771,9 +767,9 @@ fn every_item_has_full_opacity(list: &List) -> bool { } /// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true. -/// Stroke parameters live on the item attribute, out of reach of the element-level impl. -fn vector_bounding_box(vector: &Vector, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> { - let mut bounds = vector.bounding_box_with_transform(composed_transform)?; +/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl. +fn vector_bounding_box(vector: &Vector, paths: Option<&List>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> { + let mut bounds = vector.bounding_box_with_transform(paths?, composed_transform)?; // The full line width (not half) accounts for different styles of stroke caps if include_stroke && let Some(stroke) = appearance.and_then(|appearance| appearance.first_coverage_of(Cover::Stroke)).map(Coverage::stroke_params) { @@ -789,7 +785,13 @@ fn vector_bounding_box(vector: &Vector, composed_transform: DAffine2, appearance pub fn vector_item_bounding_box(item: &Item, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox { let composed_transform = transform * item.attribute_cloned_or_default::(ATTR_TRANSFORM); - match vector_bounding_box(item.element(), composed_transform, item.attribute::(ATTR_APPEARANCE), include_stroke) { + match vector_bounding_box( + item.element(), + paths_from_item_attributes(item), + composed_transform, + item.attribute::(ATTR_APPEARANCE), + include_stroke, + ) { Some(bounds) => RenderBoundingBox::Rectangle(bounds), None => RenderBoundingBox::None, } @@ -804,7 +806,7 @@ pub fn vector_list_bounding_box(list: &List, transform: DAffine2, includ let item_transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, index); let appearance = list.attribute::(ATTR_APPEARANCE, index); - let Some(bounds) = vector_bounding_box(element, transform * item_transform, appearance, include_stroke) else { + let Some(bounds) = vector_bounding_box(element, paths_from_list_row_attributes(list, index), transform * item_transform, appearance, include_stroke) else { continue; }; diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index 9e5b18c6e8..1903291f51 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -22,9 +22,12 @@ pub mod migrations { // TODO: Eventually remove this document upgrade code pub mod legacy { use core_types::Color; + use core_types::list::List; use dyn_any::DynAny; use glam::{DAffine2, DVec2}; - use vector_types::vector::{PointDomain, SegmentDomain, misc::HandleId, style::Stroke}; + use vector_types::vector::misc::{BezierHandles, HandleId}; + use vector_types::vector::style::Stroke; + use vector_types::vector::{Path, PointId, SegmentId, vector_from_legacy_parts}; use vector_types::{GradientRamp, Vector, vector}; #[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)] @@ -102,6 +105,49 @@ pub mod migrations { pub stroke: Option, } + /// The legacy point storage shape, kept only so old documents still deserialize. + #[derive(Default, serde::Deserialize)] + #[cfg_attr(test, derive(serde::Serialize))] + pub(super) struct LegacyPointDomain { + pub id: Vec, + #[serde(alias = "positions")] + pub position: Vec, + } + + /// The legacy segment storage shape, kept only so old documents still deserialize. + #[derive(Default, serde::Deserialize)] + #[cfg_attr(test, derive(serde::Serialize))] + pub(super) struct LegacySegmentDomain { + #[serde(alias = "ids")] + pub id: Vec, + pub start_point: Vec, + pub end_point: Vec, + pub handles: Vec, + } + + /// The legacy `Vector` struct shape, converted into pool storage at load. + #[derive(Default, serde::Deserialize)] + #[cfg_attr(test, derive(serde::Serialize))] + pub(super) struct LegacyVector { + pub colinear_manipulators: Vec<[HandleId; 2]>, + pub point_domain: LegacyPointDomain, + pub segment_domain: LegacySegmentDomain, + } + + impl LegacyVector { + pub(super) fn into_parts(self) -> (Vector, List) { + vector_from_legacy_parts( + self.point_domain.id, + self.point_domain.position, + self.segment_domain.id, + self.segment_domain.start_point, + self.segment_domain.end_point, + self.segment_domain.handles, + self.colinear_manipulators, + ) + } + } + /// Old documents stored a `Vector` flattened with list attributes (`transform`, `alpha_blending`, `upstream_graphic_group`); only the geometry fields are recovered. #[derive(serde::Deserialize)] #[cfg_attr(test, derive(Default, serde::Serialize))] @@ -109,41 +155,43 @@ pub mod migrations { #[allow(dead_code)] pub style: PathStyle, pub colinear_manipulators: Vec<[HandleId; 2]>, - pub point_domain: PointDomain, - pub segment_domain: SegmentDomain, + pub point_domain: LegacyPointDomain, + pub segment_domain: LegacySegmentDomain, } #[derive(serde::Deserialize)] pub(super) struct Table { #[serde(alias = "instances", alias = "instance")] - pub element: Vec, + pub element: Vec, } } // TODO: Eventually remove this document upgrade code - /// Returns the first `Vector` recovered from any of the legacy on-disk shapes (the legacy `VectorData` flat struct, a single `Vector`, or any of the historical `List` variants). - pub fn migrate_to_optional_vector<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + /// Returns the first vector recovered from any of the legacy on-disk shapes (the legacy `VectorData` flat struct, a legacy `Vector` struct, or any of the historical list variants). + pub fn migrate_to_optional_vector<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result)>, D::Error> { use serde::Deserialize; #[derive(serde::Deserialize)] #[serde(untagged)] #[allow(clippy::large_enum_variant)] enum VectorFormat { - // Old vector data must be tried first. Serde would otherwise ignore its `style` field and - // deserialize the missing optional `stroke` field as `None` in the current `Vector`. + // The old flat shape that also held a style. Both this and the legacy `Vector` arm recover the same geometry from it. OldVectorData(legacy::VectorData), - Vector(Vector), + Vector(legacy::LegacyVector), List(legacy::Table), } Ok(match VectorFormat::deserialize(deserializer)? { - VectorFormat::OldVectorData(old) => Some(Vector { - colinear_manipulators: old.colinear_manipulators, - point_domain: old.point_domain, - segment_domain: old.segment_domain, - }), - VectorFormat::Vector(vector) => Some(vector), - VectorFormat::List(list) => list.element.into_iter().next(), + VectorFormat::OldVectorData(old) => { + let vector = legacy::LegacyVector { + colinear_manipulators: old.colinear_manipulators, + point_domain: old.point_domain, + segment_domain: old.segment_domain, + }; + Some(vector.into_parts()) + } + VectorFormat::Vector(vector) => Some(vector.into_parts()), + VectorFormat::List(list) => list.element.into_iter().next().map(legacy::LegacyVector::into_parts), }) } @@ -187,15 +235,15 @@ pub mod migrations { use super::*; use vector_types::vector::style::Stroke; - /// The legacy `style` payload (including its stroke) must still parse so the untagged format - /// disambiguation succeeds, even though the geometry is all that survives. + /// The legacy `style` payload is discarded, leaving only the geometry. #[test] fn recovers_geometry_from_old_vector_data_with_style() { - use core_types::ops::FromAnchorPosition; - let old_vector = legacy::VectorData { style: legacy::PathStyle { stroke: Some(Stroke::new(12.)) }, - point_domain: Vector::from_anchor_position(glam::DVec2::new(3., 4.)).point_domain, + point_domain: legacy::LegacyPointDomain { + id: vec![vector_types::vector::PointId::ZERO], + position: vec![glam::DVec2::new(3., 4.)], + }, ..Default::default() }; @@ -209,25 +257,97 @@ pub mod migrations { .unwrap() .insert("fill".into(), serde_json::to_value(legacy::LegacyFill::default()).unwrap()); - let migrated = migrate_to_optional_vector(value).unwrap().expect("the legacy shape should parse into a vector"); + let (migrated, _paths) = migrate_to_optional_vector(value).unwrap().expect("the legacy shape should parse into a vector"); assert_eq!( - migrated.point_domain.positions(), + migrated.positions().collect::>(), [glam::DVec2::new(3., 4.)], "the legacy geometry should survive alongside the discarded style" ); } #[test] - fn recovers_geometry_from_current_vector_data() { - use core_types::ops::FromAnchorPosition; - - let vector = Vector::from_anchor_position(glam::DVec2::new(3., 4.)); + fn recovers_geometry_from_legacy_vector_struct() { + let vector = legacy::LegacyVector { + point_domain: legacy::LegacyPointDomain { + id: vec![vector_types::vector::PointId::ZERO], + position: vec![glam::DVec2::new(3., 4.)], + }, + ..Default::default() + }; let value = serde_json::to_value(&vector).unwrap(); - let migrated = migrate_to_optional_vector(value).unwrap().unwrap(); + let (migrated, _paths) = migrate_to_optional_vector(value).unwrap().unwrap(); - assert_eq!(migrated.point_domain.positions(), [glam::DVec2::new(3., 4.)]); + assert_eq!(migrated.positions().collect::>(), [glam::DVec2::new(3., 4.)]); + } + + /// The oldest documents named these fields in the plural. + #[test] + fn recovers_geometry_from_plural_field_names() { + let value = serde_json::json!({ + "colinear_manipulators": [], + "point_domain": { "id": [1, 2], "positions": [[3., 4.], [5., 6.]] }, + "segment_domain": { "ids": [7], "start_point": [0], "end_point": [1], "handles": ["Linear"] }, + }); + + let (migrated, paths) = migrate_to_optional_vector(value).unwrap().expect("the plural field names should parse"); + + assert_eq!(migrated.positions().collect::>(), [glam::DVec2::new(3., 4.), glam::DVec2::new(5., 6.)]); + assert_eq!(paths.len(), 1); + } + + /// A closed triangle keeps its IDs, its handles, and the smooth pairs at its anchors, beside a free point. + #[test] + fn keeps_ids_handles_smooth_pairs_and_free_points() { + use glam::DVec2; + use vector_types::kurbo::{CubicBez, Line, PathSeg, QuadBez}; + use vector_types::vector::misc::HandleType; + + let handle = |ty: &str, segment: u64| serde_json::json!({ "ty": ty, "segment": segment }); + let value = serde_json::json!({ + "colinear_manipulators": [[handle("End", 101), handle("Primary", 102)], [handle("End", 103), handle("Primary", 101)]], + "point_domain": { "id": [10, 20, 30, 40], "position": [[0., 0.], [10., 0.], [10., 10.], [99., 99.]] }, + "segment_domain": { + "id": [101, 102, 103], + "start_point": [0, 1, 2], + "end_point": [1, 2, 0], + "handles": [{ "Cubic": { "handle_start": [2., -1.], "handle_end": [8., -1.] } }, { "Quadratic": { "handle": [12., 5.] } }, "Linear"], + }, + }); + + let (vector, paths) = migrate_to_optional_vector(value).unwrap().expect("the legacy vector should parse"); + + // Looked up by ID, since storage order is free to differ from the legacy order + let mut anchors: Vec<(u64, DVec2)> = vector + .anchor_points(&paths) + .filter_map(|point| Some((point.inner(), vector.position(vector.index_of_point_id(point)? as usize)?))) + .collect(); + anchors.sort_by_key(|&(id, _)| id); + assert_eq!(anchors, [(10, DVec2::new(0., 0.)), (20, DVec2::new(10., 0.)), (30, DVec2::new(10., 10.)), (40, DVec2::new(99., 99.))]); + + let mut segments: Vec<(u64, PathSeg, u64, u64)> = vector.segment_iter(&paths).map(|(id, segment, start, end)| (id.inner(), segment, start.inner(), end.inner())).collect(); + segments.sort_by_key(|&(id, ..)| id); + assert_eq!( + segments, + [ + (101, PathSeg::Cubic(CubicBez::new((0., 0.), (2., -1.), (8., -1.), (10., 0.))), 10, 20), + (102, PathSeg::Quad(QuadBez::new((10., 0.), (12., 5.), (10., 10.))), 20, 30), + (103, PathSeg::Line(Line::new((10., 10.), (0., 0.))), 30, 10), + ] + ); + + let mut smooth_pairs: Vec<[(bool, u64); 2]> = vector + .colinear_pairs(&paths) + .into_iter() + .map(|pair| { + let mut sides = pair.map(|handle| (handle.ty == HandleType::Primary, handle.segment.inner())); + sides.sort(); + sides + }) + .collect(); + smooth_pairs.sort(); + assert_eq!(smooth_pairs, [[(false, 101), (true, 102)], [(false, 103), (true, 101)]]); } } } diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 1db2a7a675..14ad6b4b02 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -9,6 +9,7 @@ use core_types::color::Color; use core_types::color::SRGBA8; use core_types::consts::DEFAULT_FONT_SIZE; use core_types::list::ATTR_APPEARANCE; +use core_types::list::ATTR_PATHS; use core_types::list::{Item, List, NodeIdPath}; use core_types::math::quad::Quad; use core_types::render_complexity::RenderComplexity; @@ -28,6 +29,7 @@ use graphic_types::vector_types::gradient::{Gradient, GradientForm}; use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint}; use graphic_types::vector_types::vector::misc::dvec2_to_point; use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, StrokeCap, StrokeJoin}; +use graphic_types::vector_types::vector::{Path, edit_item_geometry, edit_list_row_geometry, no_paths}; use graphic_types::{Appearance, Artboard, Cover, Coverage, FillAndStroke, Graphic, Vector}; use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape, StrokeOpts}; use num_traits::Zero; @@ -702,7 +704,9 @@ pub struct RenderMetadata { /// The Text tool composes this with `transform_to_viewport(layer)` to position its drag cage. pub text_frames: HashMap, pub clip_targets: HashSet, - pub vector_data: HashMap>, + /// Per-layer source geometry as the holder item, carrying the pool element and its paths attribute. + #[cfg_attr(feature = "serde", serde(skip))] + pub vector_data: HashMap>>, /// Per-layer `ATTR_APPEARANCE` item attribute, exposed so message handlers can read it. #[cfg_attr(feature = "serde", serde(skip))] pub appearance_attributes: HashMap>, @@ -1247,7 +1251,9 @@ impl Render for Graphic { let layer = ItemRef::Item(item).layer(); item.element_mut().new_ids_from_hash(layer); } - Graphic::Vector(item) => item.element_mut().vector_new_ids_from_hash(reference.map(|id| id.0).unwrap_or_default()), + Graphic::Vector(item) => { + edit_item_geometry(item, |vector, paths| vector.vector_new_ids_from_hash(paths, reference.map(|id| id.0).unwrap_or_default())); + } Graphic::GraphicList(list) => list.new_ids_from_hash(reference), Graphic::VectorList(list) => list.new_ids_from_hash(reference), _ => (), @@ -1441,6 +1447,7 @@ impl Render for List { /// Emits one vector shape as SVG, with no wrapping group of its own. fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &mut SvgRender, render_params: &RenderParams) { + let paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); @@ -1466,16 +1473,18 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: & let applied_stroke_transform = render_params.alignment_parent_transform.unwrap_or(applied_stroke_transform); let element_transform = set_stroke_transform.map(|stroke_transform| item_transform * stroke_transform.inverse()); let element_transform = element_transform.unwrap_or(DAffine2::IDENTITY); - let layer_bounds = vector.bounding_box().unwrap_or_default(); - let transformed_bounds = vector.bounding_box_with_transform(applied_stroke_transform).unwrap_or_default(); - let stroke_layer_bounds = vector.stroke_inclusive_bounding_box_with_transform(DAffine2::IDENTITY, stroke_params.as_ref()).unwrap_or(layer_bounds); + let layer_bounds = vector.bounding_box(paths).unwrap_or_default(); + let transformed_bounds = vector.bounding_box_with_transform(paths, applied_stroke_transform).unwrap_or_default(); + let stroke_layer_bounds = vector + .stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke_params.as_ref()) + .unwrap_or(layer_bounds); let bounds_matrix = DAffine2::from_scale_angle_translation(layer_bounds[1] - layer_bounds[0], 0., layer_bounds[0]); let stroke_bounds_matrix = DAffine2::from_scale_angle_translation(stroke_layer_bounds[1] - stroke_layer_bounds[0], 0., stroke_layer_bounds[0]); let mut path = String::new(); - for mut bezpath in vector.stroke_bezpath_iter() { + for mut bezpath in vector.stroke_bezpath_iter(paths) { bezpath.apply_affine(Affine::new(applied_stroke_transform.to_cols_array())); path.push_str(bezpath.to_svg().as_str()); } @@ -1486,7 +1495,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: & MaskType::Mask }; - let path_is_closed = vector.stroke_bezpath_iter().all(|path| matches!(path.elements().last(), Some(PathEl::ClosePath))); + let path_is_closed = vector.stroke_bezpath_iter(paths).all(|path| matches!(path.elements().last(), Some(PathEl::ClosePath))); let can_draw_aligned_stroke = path_is_closed && stroke_params.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered()) && stroke_paint.is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent()); @@ -1494,7 +1503,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: & let needs_separate_alignment_fill = can_draw_aligned_stroke && !can_use_paint_order; let override_paint_order = can_draw_aligned_stroke && can_use_paint_order; - let use_face_fill = vector.use_face_fill(); + let use_face_fill = vector.use_face_fill(paths); if needs_separate_alignment_fill && !wants_stroke_below { emit_svg_fill_path( @@ -1516,7 +1525,9 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: & // The mask must draw at full alpha so the SVG ``/`` fully zeroes the path interior. // The wrapping SVG group (above) handles the user-set opacity. - let mut mask_item = Item::new_from_element(cloned_vector).with_attribute(ATTR_TRANSFORM, item_transform); + let mut mask_item = Item::new_from_element(cloned_vector) + .with_attribute(ATTR_PATHS, paths.clone()) + .with_attribute(ATTR_TRANSFORM, item_transform); let black_fill = Graphic::ColorList(List::new_from_element(Color::BLACK)); mask_item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), black_fill)); let vector_item = List::new_from_item(mask_item); @@ -1525,7 +1536,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: & }); if use_face_fill { - for mut face_path in vector.construct_faces() { + for mut face_path in vector.construct_faces(paths) { face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array())); let face_d = face_path.to_svg(); @@ -1691,6 +1702,7 @@ fn render_vector_item_to_vello( paint_render_params: &RenderParams, ) { let Some(element) = item.element() else { return }; + let element_paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.); @@ -1724,10 +1736,10 @@ fn render_vector_item_to_vello( multiplied_transform }; } - let layer_bounds = element.bounding_box().unwrap_or_default(); + let layer_bounds = element.bounding_box(element_paths).unwrap_or_default(); let mut path = kurbo::BezPath::new(); - for mut bezpath in element.stroke_bezpath_iter() { + for mut bezpath in element.stroke_bezpath_iter(element_paths) { bezpath.apply_affine(Affine::new(applied_stroke_transform.to_cols_array())); for element in bezpath { path.push(element); @@ -1748,7 +1760,7 @@ fn render_vector_item_to_vello( let stroke_fully_transparent = stroke_paint.is_none_or(|paint| paint.is_guaranteed_fully_transparent()); let can_draw_aligned_stroke = !stroke_fully_transparent && stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) - && element.stroke_bezpath_iter().all(|p| matches!(p.elements().last(), Some(PathEl::ClosePath))); + && element.stroke_bezpath_iter(element_paths).all(|p| matches!(p.elements().last(), Some(PathEl::ClosePath))); let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32; let needs_blend_layer = opacity < 1. || blend_mode_attr != BlendMode::default(); @@ -1848,10 +1860,10 @@ fn render_vector_item_to_vello( }; }; - let use_face_fill = element.use_face_fill(); + let use_face_fill = element.use_face_fill(element_paths); let do_fill = |scene: &mut Scene, context: &mut RenderContext| { if use_face_fill { - for mut face_path in element.construct_faces() { + for mut face_path in element.construct_faces(element_paths) { face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array())); let mut kurbo_path = kurbo::BezPath::new(); for element in face_path { @@ -1956,12 +1968,14 @@ fn render_vector_item_to_vello( // The mask must draw at full alpha so `SrcOut` fully zeroes the path interior. // The outer opacity/blend layer (above) handles the user-set opacity. - let mut mask_item = Item::new_from_element(cloned_element).with_attribute(ATTR_TRANSFORM, item_transform); + let mut mask_item = Item::new_from_element(cloned_element) + .with_attribute(ATTR_PATHS, element_paths.clone()) + .with_attribute(ATTR_TRANSFORM, item_transform); let black_fill = Graphic::ColorList(List::new_from_element(Color::BLACK)); mask_item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), black_fill)); let vector_list = List::new_from_item(mask_item); - let bounds = element.bounding_box_with_transform(multiplied_transform).unwrap_or(layer_bounds); + let bounds = element.bounding_box_with_transform(element_paths, multiplied_transform).unwrap_or(layer_bounds); // This branch is gated on `can_draw_aligned_stroke`, which already requires every subpath is closed let inflation = stroke.map_or(0., |stroke| stroke.max_aabb_inflation(true)); let (largest_scale, _) = singular_values(applied_stroke_transform); @@ -2061,18 +2075,20 @@ fn collect_vector_items_metadata<'a>( DAffine2::IDENTITY }; - // Use click-target override if the item provides one (e.g. 'Text' node's per-glyph bboxes) - let click_target_vector = item.attribute::(ATTR_EDITOR_CLICK_TARGET).unwrap_or(source); - + let source_paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let item_relative_transform = reference_inverse * transform; + // Use click-target override if the item provides one (e.g. 'Text' node's per-glyph bboxes) let mut click_targets_unwrapped = Vec::new(); - extend_targets_from_vector(&mut click_targets_unwrapped, appearance, click_target_vector, item_relative_transform); + match item.attribute::(ATTR_EDITOR_CLICK_TARGET) { + Some(override_path) => extend_targets_from_bezpaths(&mut click_targets_unwrapped, appearance, split_bezpath_contours(override_path), item_relative_transform), + None => extend_targets_from_vector(&mut click_targets_unwrapped, appearance, source, source_paths, item_relative_transform), + } accumulated_click_targets.entry(element_id).or_default().extend(click_targets_unwrapped.into_iter().map(Arc::new)); // Outlines always use source geometry so the visual outline reflects actual letterforms let mut outlines_unwrapped = Vec::new(); - extend_targets_from_vector(&mut outlines_unwrapped, appearance, source, item_relative_transform); + extend_targets_from_vector(&mut outlines_unwrapped, appearance, source, source_paths, item_relative_transform); accumulated_outlines.entry(element_id).or_default().extend(outlines_unwrapped.into_iter().map(Arc::new)); // Source geometry (not the click-target override) so editing tools work on letterforms. @@ -2080,7 +2096,7 @@ fn collect_vector_items_metadata<'a>( // Only item 0 is recorded since editing tools can only target a single item currently. // If that item has no paint attribute, none is recorded. if let std::collections::hash_map::Entry::Vacant(e) = metadata.vector_data.entry(element_id) { - e.insert(Arc::new(source.clone())); + e.insert(Arc::new(Item::new_from_element(source.clone()).with_attribute(ATTR_PATHS, source_paths.clone()))); if let Some(appearance) = appearance { metadata.appearance_attributes.insert(element_id, Arc::new(appearance.clone())); @@ -2126,22 +2142,25 @@ fn collect_vector_items_metadata<'a>( /// Collects one vector item's click target into the caller's list, baked through the item's transform. fn add_vector_item_click_targets(item: ItemRef<'_, Vector>, click_targets: &mut Vec, inherited_appearance: Option<&Appearance>) { let Some(source) = item.element() else { return }; + let source_paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let appearance = Appearance::cascade(item.attribute::(ATTR_APPEARANCE), inherited_appearance); // Use click-target override geometry if the item provides one (e.g. 'Text' node's per-glyph bounding boxes) - let vector = item.attribute::(ATTR_EDITOR_CLICK_TARGET).unwrap_or(source); - - extend_targets_from_vector(click_targets, appearance, vector, transform); + match item.attribute::(ATTR_EDITOR_CLICK_TARGET) { + Some(override_path) => extend_targets_from_bezpaths(click_targets, appearance, split_bezpath_contours(override_path), transform), + None => extend_targets_from_vector(click_targets, appearance, source, source_paths, transform), + } } /// Like [`add_vector_item_click_targets`] but on source geometry only, ignoring `editor:click_target`, so outlines reflect actual letterforms. fn add_vector_item_outline_targets(item: ItemRef<'_, Vector>, outlines: &mut Vec, inherited_appearance: Option<&Appearance>) { let Some(source) = item.element() else { return }; + let source_paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let appearance = Appearance::cascade(item.attribute::(ATTR_APPEARANCE), inherited_appearance); - extend_targets_from_vector(outlines, appearance, source, transform); + extend_targets_from_vector(outlines, appearance, source, source_paths, transform); } impl Render for List { @@ -2202,19 +2221,28 @@ impl Render for List { } fn new_ids_from_hash(&mut self, reference: Option) { - for vector in self.iter_element_values_mut() { - vector.vector_new_ids_from_hash(reference.map(|id| id.0).unwrap_or_default()); + for index in 0..self.len() { + edit_list_row_geometry(self, index, |vector, paths| vector.vector_new_ids_from_hash(paths, reference.map(|id| id.0).unwrap_or_default())); } } } -/// Build one multi-contour `Path` (nonzero fill rule, so holes like the inside of an "O" work +/// Build one multi-contour `BezPath` (nonzero fill rule, so holes like the inside of an "O" work /// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append. -fn extend_targets_from_vector(targets: &mut Vec, appearance: Option<&Appearance>, geometry: &Vector, transform: DAffine2) { +fn extend_targets_from_vector(targets: &mut Vec, appearance: Option<&Appearance>, geometry: &Vector, geometry_paths: &List, transform: DAffine2) { + let bezpaths: Vec = geometry.stroke_bezpath_iter(geometry_paths).filter(|bezpath| !bezpath.elements().is_empty()).collect(); + extend_targets_from_bezpaths(targets, appearance, bezpaths, transform); + + for click_target in extend_free_point_targets(geometry, geometry_paths, transform) { + targets.push(click_target); + } +} + +/// The contour half of [`extend_targets_from_vector`], also serving `editor:click_target` overrides. +fn extend_targets_from_bezpaths(targets: &mut Vec, appearance: Option<&Appearance>, mut bezpaths: Vec, transform: DAffine2) { // A coverage whose paint is `Graphic::None` exists but paints nothing, so it does not close subpaths for hit testing let filled = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill)); - let mut bezpaths: Vec = geometry.stroke_bezpath_iter().filter(|bezpath| !bezpath.elements().is_empty()).collect(); let all_contours_closed = bezpaths.iter().all(|bezpath| matches!(bezpath.elements().last(), Some(PathEl::ClosePath))); // Inside/Outside-aligned strokes reach `weight` from the centerline rather than `weight / 2` per side, @@ -2246,25 +2274,35 @@ fn extend_targets_from_vector(targets: &mut Vec, appearance: Option click_target.apply_transform(transform); targets.push(click_target); } - - for click_target in extend_free_point_targets(geometry, transform) { - targets.push(click_target); - } } -fn extend_free_point_targets(vector: &Vector, transform: DAffine2) -> impl Iterator + '_ { - // Mark every point index touched by a segment endpoint in one `O(points + segments)` pass, avoiding a per-point `any_connected` scan - let mut connected = vec![false; vector.point_domain.len()]; - for &point_index in vector.segment_domain.start_point().iter().chain(vector.segment_domain.end_point()) { - connected[point_index] = true; +/// Splits a compound bezpath into its contours, so per-contour closing behaves as with source geometry. +fn split_bezpath_contours(bezpath: &BezPath) -> Vec { + let mut contours = Vec::new(); + + for &element in bezpath.elements() { + if matches!(element, PathEl::MoveTo(_)) || contours.is_empty() { + contours.push(BezPath::new()); + } + if let Some(contour) = contours.last_mut() { + contour.push(element); + } } - vector.point_domain.ids().iter().enumerate().filter_map(move |(point_index, &point_id)| { - if connected[point_index] { + contours +} + +fn extend_free_point_targets<'a>(vector: &'a Vector, geometry_paths: &List, transform: DAffine2) -> impl Iterator + 'a { + // A pool point that no path references is a free point, since handles and anchors are all referenced + let connectivity = vector.connectivity(geometry_paths); + + (0..vector.point_count() as u32).filter_map(move |point_index| { + if connectivity.is_referenced(point_index) { return None; } - let anchor = vector.point_domain.position_from_id(point_id).unwrap_or_default(); + let point_id = vector.point_id_at(point_index).unwrap_or_default(); + let anchor = vector.position(point_index as usize).unwrap_or_default(); let mut click_target = ClickTarget::new_with_free_point(FreePoint::new(point_id, anchor)); click_target.apply_transform(transform); Some(click_target) diff --git a/node-graph/libraries/vector-types/src/vector/addressing.rs b/node-graph/libraries/vector-types/src/vector/addressing.rs index a78719c368..7481e3d4c6 100644 --- a/node-graph/libraries/vector-types/src/vector/addressing.rs +++ b/node-graph/libraries/vector-types/src/vector/addressing.rs @@ -51,10 +51,10 @@ pub fn span_of_segment_id(paths: &List, segment: SegmentId) -> Option, span: Span) -> Option<(u32, u32)> { let path = paths.element(span.path as usize)?; let curve_type = curve_type_at(paths, span.path as usize); - let start = path.0.element(span.start_reference(curve_type))?; - let end = path.0.element(span.end_reference(curve_type))?; + let start = path.reference(span.start_reference(curve_type))?; + let end = path.reference(span.end_reference(curve_type))?; - Some((*start, *end)) + Some((start, end)) } /// The pool point a handle of the given span occupies, absent on a linear span that has no handles. @@ -68,7 +68,7 @@ pub fn handle_point(paths: &List, span: Span, primary: bool) -> Option, point: PointId) -> Option { pool.iter_attribute_values::(ATTR_ID)?.position(|&id| id == point).map(|index| index as u32) } -/// The spans meeting at a pool point, each paired with whether the point is where that span ends. +/// The spans meeting at a pool point in stored span order, each paired with whether the point is where that span ends. pub fn spans_at(pool_index: u32, paths: &List, connectivity: &Connectivity) -> Vec<(Span, bool)> { let mut found = Vec::new(); @@ -94,17 +94,8 @@ pub fn spans_at(pool_index: u32, paths: &List, connectivity: &Connectivity continue; } - // An anchor departs the span starting at it and arrives on the one before it + // An anchor arrives on the span before it and departs the one starting at it let anchor = reference.index as usize / curve_type.stride(); - if anchor < path.segment_count(curve_type) { - found.push(( - Span { - path: reference.path, - index: anchor as u32, - }, - false, - )); - } if let Some(previous) = anchor.checked_sub(1) { found.push(( Span { @@ -114,6 +105,15 @@ pub fn spans_at(pool_index: u32, paths: &List, connectivity: &Connectivity true, )); } + if anchor < path.segment_count(curve_type) { + found.push(( + Span { + path: reference.path, + index: anchor as u32, + }, + false, + )); + } } found @@ -137,10 +137,13 @@ pub fn end_connected(pool_index: u32, paths: &List, connectivity: &Connect .collect() } -/// The handles of every segment meeting the given pool point, naming the side that faces it. +/// The handles of every segment meeting the given pool point, naming the side that faces it, with departing segments first. pub fn all_connected(pool_index: u32, paths: &List, connectivity: &Connectivity) -> Vec { - spans_at(pool_index, paths, connectivity) + let (arriving, departing): (Vec<_>, Vec<_>) = spans_at(pool_index, paths, connectivity).into_iter().partition(|&(_, arriving)| arriving); + + departing .into_iter() + .chain(arriving) .filter_map(|(span, arriving)| { let segment = segment_id_of(paths, span)?; Some(if arriving { HandleId::end(segment) } else { HandleId::primary(segment) }) @@ -163,7 +166,7 @@ mod tests { let mut paths = List::new(); for &(curve_type, references) in specs { - let mut path = Path(references.iter().map(|&reference| Item::new_from_element(reference)).collect()); + let mut path = Path::from_references(references.iter().copied()); // Name each span on the anchor it departs from for span in 0..path.segment_count(curve_type) { @@ -217,6 +220,24 @@ mod tests { assert_eq!(all_connected(1, &paths, &connectivity).len(), 2); } + // The tools take the first connected handle, so it must not depend on whether the anchor welds two paths or sits along one + #[test] + fn connected_handles_lead_with_departing_segments() { + let paths = paths_of(&[(CurveType::Linear, &[0, 1]), (CurveType::Cubic, &[1, 2, 3, 4, 5, 6, 7])]); + let connectivity = Connectivity::build(8, &paths); + let segment = |path, index| segment_id_of(&paths, Span { path, index }).expect("every span was named"); + + let welded = all_connected(1, &paths, &connectivity); + assert_eq!(welded, [HandleId::primary(segment(1, 0)), HandleId::end(segment(0, 0))]); + + let along_path = all_connected(4, &paths, &connectivity); + assert_eq!(along_path, [HandleId::primary(segment(1, 1)), HandleId::end(segment(1, 0))]); + + // The spans themselves stay in stored order + let spans = spans_at(4, &paths, &connectivity); + assert_eq!(spans, [(Span { path: 1, index: 0 }, true), (Span { path: 1, index: 1 }, false)]); + } + #[test] fn point_ids_resolve_both_ways() { let pool = pool(4); diff --git a/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs b/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs index e4cf8f25a5..3bed3916cf 100644 --- a/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs +++ b/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs @@ -1,4 +1,7 @@ -use crate::vector::{PointDomain, PointId, SegmentDomain, SegmentId, Vector}; +use crate::vector::flatten::WorkingVector; +use crate::vector::path::Path; +use crate::vector::{PointId, SegmentId, Vector}; +use core_types::list::List; use glam::{DAffine2, DVec2}; use petgraph::graph::{EdgeIndex, NodeIndex, UnGraph}; use petgraph::prelude::UnGraphMap; @@ -7,20 +10,22 @@ use rustc_hash::FxHashSet; pub trait MergeByDistanceExt { /// Collapse all points with edges shorter than the specified distance - fn merge_by_distance_topological(&mut self, distance: f64); - fn merge_by_distance_spatial(&mut self, transform: DAffine2, distance: f64); + fn merge_by_distance_topological(&mut self, paths: &mut List, distance: f64); + fn merge_by_distance_spatial(&mut self, paths: &mut List, transform: DAffine2, distance: f64); } impl MergeByDistanceExt for Vector { - fn merge_by_distance_topological(&mut self, distance: f64) { - // Treat self as an undirected graph - let indices = VectorIndex::build_from(self); + fn merge_by_distance_topological(&mut self, paths: &mut List, distance: f64) { + let mut working = WorkingVector::flatten(self, paths); + + // Treat the working form as an undirected graph + let indices = VectorIndex::build_from(&working); // TODO: We lose information on the winding order by using an undirected graph. Switch to a directed graph and fix the algorithm to handle that. // Graph containing only short edges, referencing the data graph let mut short_edges = UnGraphMap::new(); - for segment_id in self.segment_ids().iter().copied() { + for segment_id in working.segment_ids.iter().copied() { let length = indices.segment_chord_length(segment_id); if length < distance { let [start, end] = indices.segment_ends(segment_id); @@ -39,7 +44,7 @@ impl MergeByDistanceExt for Vector { let average_position = collapse .iter() .map(|collapse_set| { - let sum: DVec2 = collapse_set.iter().map(|&id| indices.point_position(id, self)).sum(); + let sum: DVec2 = collapse_set.iter().map(|&id| indices.point_position(id, &working)).sum(); sum / collapse_set.len() as f64 }) .collect::>(); @@ -49,11 +54,13 @@ impl MergeByDistanceExt for Vector { let mut segments_to_delete = FxHashSet::default(); for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) { // Remove any segments where both endpoints are in the collapse set - segments_to_delete.extend(self.segment_domain.iter().filter_map(|(id, start_offset, end_offset, _)| { - let start = self.point_domain.ids()[start_offset]; - let end = self.point_domain.ids()[end_offset]; - if collapse_set.contains(&start) && collapse_set.contains(&end) { Some(id) } else { None } - })); + for segment_index in 0..working.segment_ids.len() { + let start = working.point_ids[working.segment_start[segment_index]]; + let end = working.point_ids[working.segment_end[segment_index]]; + if collapse_set.contains(&start) && collapse_set.contains(&end) { + segments_to_delete.insert(working.segment_ids[segment_index]); + } + } // Delete all points but the first, set its position to the average, and update segments let first_id = collapse_set.iter().copied().next().unwrap(); @@ -61,52 +68,77 @@ impl MergeByDistanceExt for Vector { let first_offset = indices.point_to_offset[&first_id]; // Look for segments with endpoints in `collapse_set` and replace them with the point we are collapsing to - for (_, start_offset, end_offset, handles) in self.segment_domain.iter_mut() { - let start_id = self.point_domain.ids()[*start_offset]; - let end_id = self.point_domain.ids()[*end_offset]; + for segment_index in 0..working.segment_ids.len() { + let start_id = working.point_ids[working.segment_start[segment_index]]; + let end_id = working.point_ids[working.segment_end[segment_index]]; // Update Bezier handles for moved points if start_id == first_id { - let point_position = self.point_domain.position[*start_offset]; - handles.move_start(average_pos - point_position); + let point_position = working.point_positions[working.segment_start[segment_index]]; + working.segment_handles[segment_index].move_start(average_pos - point_position); } if end_id == first_id { - let point_position = self.point_domain.position[*end_offset]; - handles.move_end(average_pos - point_position); + let point_position = working.point_positions[working.segment_end[segment_index]]; + working.segment_handles[segment_index].move_end(average_pos - point_position); } // Replace removed points with the collapsed point if collapse_set.contains(&start_id) { - let point_position = self.point_domain.position[*start_offset]; - *start_offset = first_offset; - handles.move_start(average_pos - point_position); + let point_position = working.point_positions[working.segment_start[segment_index]]; + working.segment_start[segment_index] = first_offset; + working.segment_handles[segment_index].move_start(average_pos - point_position); } if collapse_set.contains(&end_id) { - let point_position = self.point_domain.position[*end_offset]; - *end_offset = first_offset; - handles.move_end(average_pos - point_position); + let point_position = working.point_positions[working.segment_end[segment_index]]; + working.segment_end[segment_index] = first_offset; + working.segment_handles[segment_index].move_end(average_pos - point_position); } } // Update the position of the collapsed point - self.point_domain.position[first_offset] = average_pos; + working.point_positions[first_offset] = average_pos; points_to_delete.extend(collapse_set) } - self.segment_domain.retain(|id| !segments_to_delete.contains(id), usize::MAX); - self.point_domain.retain(&mut self.segment_domain, |id| !points_to_delete.contains(id)); + // Drop the collapsed segments, then the merged-away points, remapping segment endpoints + let keep_segment: Vec = working.segment_ids.iter().map(|id| !segments_to_delete.contains(id)).collect(); + retain_by(&mut working.segment_ids, &keep_segment); + retain_by(&mut working.segment_start, &keep_segment); + retain_by(&mut working.segment_end, &keep_segment); + retain_by(&mut working.segment_handles, &keep_segment); + + let mut point_map = Vec::with_capacity(working.point_ids.len()); + let mut new_index = 0; + let keep_point: Vec = working + .point_ids + .iter() + .map(|id| { + let keep = !points_to_delete.contains(id); + point_map.push(if keep { new_index } else { usize::MAX }); + new_index += usize::from(keep); + keep + }) + .collect(); + retain_by(&mut working.point_ids, &keep_point); + retain_by(&mut working.point_positions, &keep_point); + for index in working.segment_start.iter_mut().chain(working.segment_end.iter_mut()) { + *index = point_map.get(*index).copied().unwrap_or(usize::MAX); + } + + working.reweave(self, paths); } - fn merge_by_distance_spatial(&mut self, transform: DAffine2, distance: f64) { - let point_count = self.point_domain.positions().len(); + fn merge_by_distance_spatial(&mut self, paths: &mut List, transform: DAffine2, distance: f64) { + let working = WorkingVector::flatten(self, paths); + let point_count = working.point_positions.len(); // Find min x and y for grid cell normalization let mut min_x = f64::MAX; let mut min_y = f64::MAX; // Calculate mins without collecting all positions - for &pos in self.point_domain.positions() { + for &pos in &working.point_positions { let transformed_pos = transform.transform_point2(pos); min_x = min_x.min(transformed_pos.x); min_y = min_y.min(transformed_pos.y); @@ -118,7 +150,7 @@ impl MergeByDistanceExt for Vector { // Add points to grid cells without collecting all positions first for i in 0..point_count { - let pos = transform.transform_point2(self.point_domain.positions()[i]); + let pos = transform.transform_point2(working.point_positions[i]); let grid_x = ((pos.x - min_x) / distance).floor() as i32; let grid_y = ((pos.y - min_y) / distance).floor() as i32; @@ -137,7 +169,7 @@ impl MergeByDistanceExt for Vector { continue; } - let pos_i = transform.transform_point2(self.point_domain.positions()[i]); + let pos_i = transform.transform_point2(working.point_positions[i]); let grid_x = ((pos_i.x - min_x) / distance).floor() as i32; let grid_y = ((pos_i.y - min_y) / distance).floor() as i32; @@ -151,7 +183,7 @@ impl MergeByDistanceExt for Vector { if let Some(indices) = grid.get(&neighbor_cell) { for &j in indices { if j > i && point_index_map[j].is_none() { - let pos_j = transform.transform_point2(self.point_domain.positions()[j]); + let pos_j = transform.transform_point2(working.point_positions[j]); if pos_i.distance(pos_j) <= distance { group.push(j); } @@ -164,7 +196,7 @@ impl MergeByDistanceExt for Vector { // Create merged point - calculate positions as needed let merged_position = group .iter() - .map(|&idx| transform.transform_point2(self.point_domain.positions()[idx])) + .map(|&idx| transform.transform_point2(working.point_positions[idx])) .fold(DVec2::ZERO, |sum, pos| sum + pos) / group.len() as f64; @@ -172,7 +204,7 @@ impl MergeByDistanceExt for Vector { let merged_index = merged_positions.len(); merged_positions.push(merged_position); - merged_indices.push(self.point_domain.ids()[group[0]]); + merged_indices.push(working.point_ids[group[0]]); // Update mapping for all points in the group for &idx in &group { @@ -180,43 +212,43 @@ impl MergeByDistanceExt for Vector { } } - // Create new point domain with merged points - let mut new_point_domain = PointDomain::new(); - for (idx, pos) in merged_indices.into_iter().zip(merged_positions) { - new_point_domain.push(idx, pos); - } + // Build the merged working form, skipping segments with endpoints that collapsed together + let mut merged = WorkingVector { + point_ids: merged_indices, + point_positions: merged_positions, + colinear: working.colinear, + ..Default::default() + }; - // Update segment domain - let mut new_segment_domain = SegmentDomain::new(); - for segment_idx in 0..self.segment_domain.ids().len() { - let id = self.segment_domain.ids()[segment_idx]; - let start = self.segment_domain.start_point()[segment_idx]; - let end = self.segment_domain.end_point()[segment_idx]; - let handles = self.segment_domain.handles()[segment_idx]; + for segment_index in 0..working.segment_ids.len() { + let new_start = point_index_map[working.segment_start[segment_index]].unwrap(); + let new_end = point_index_map[working.segment_end[segment_index]].unwrap(); - // Get new indices for start and end points - let new_start = point_index_map[start].unwrap(); - let new_end = point_index_map[end].unwrap(); - - // Skip segments where start and end points were merged if new_start != new_end { - new_segment_domain.push(id, new_start, new_end, handles); + merged.segment_ids.push(working.segment_ids[segment_index]); + merged.segment_start.push(new_start); + merged.segment_end.push(new_end); + merged.segment_handles.push(working.segment_handles[segment_index]); } } - // Create new vector geometry - self.point_domain = new_point_domain; - self.segment_domain = new_segment_domain; + merged.reweave(self, paths); } } -/// All the fixed fields of a point from the point domain. +/// Keeps only the elements flagged true, in order. +fn retain_by(values: &mut Vec, keep: &[bool]) { + let mut flags = keep.iter(); + values.retain(|_| *flags.next().unwrap_or(&false)); +} + +/// All the fixed fields of a point from the working form. pub(crate) struct Point { pub id: PointId, pub position: DVec2, } -/// Useful indexes to speed up various operations on [`Vector`]. +/// Useful indexes to speed up various operations on the flattened working form. /// /// Important: It is the user's responsibility to ensure the indexes remain valid after mutations to the data. pub(crate) struct VectorIndex { @@ -231,23 +263,23 @@ pub(crate) struct VectorIndex { } impl VectorIndex { - /// Construct a [`VectorIndex`] by building indexes from the given [`Vector`]. Takes `O(n)` time. - fn build_from(data: &Vector) -> Self { - let point_to_offset = data.point_domain.ids().iter().copied().enumerate().map(|(a, b)| (b, a)).collect::>(); + /// Construct a [`VectorIndex`] by building indexes from the given working form. Takes `O(n)` time. + fn build_from(working: &WorkingVector) -> Self { + let point_to_offset = working.point_ids.iter().copied().enumerate().map(|(a, b)| (b, a)).collect::>(); let mut point_to_node = FxHashMap::default(); let mut segment_to_edge = FxHashMap::default(); let mut graph = UnGraph::new_undirected(); - for (point_id, position) in data.point_domain.iter() { + for (&point_id, &position) in working.point_ids.iter().zip(&working.point_positions) { let idx = graph.add_node(Point { id: point_id, position }); point_to_node.insert(point_id, idx); } - for (segment_id, start_offset, end_offset, ..) in data.segment_domain.iter() { - let start_id = data.point_domain.ids()[start_offset]; - let end_id = data.point_domain.ids()[end_offset]; + for (segment_index, &segment_id) in working.segment_ids.iter().enumerate() { + let start_id = working.point_ids[working.segment_start[segment_index]]; + let end_id = working.point_ids[working.segment_end[segment_index]]; let edge = graph.add_edge(point_to_node[&start_id], point_to_node[&end_id], ()); segment_to_edge.insert(segment_id, edge); @@ -290,8 +322,8 @@ impl VectorIndex { /// # Panics /// /// Will panic if `id` isn't in the data. - fn point_position(&self, id: PointId, data: &Vector) -> DVec2 { + fn point_position(&self, id: PointId, working: &WorkingVector) -> DVec2 { let offset = self.point_to_offset[&id]; - data.point_domain.positions()[offset] + working.point_positions[offset] } } diff --git a/node-graph/libraries/vector-types/src/vector/connectivity.rs b/node-graph/libraries/vector-types/src/vector/connectivity.rs index bcd42d3c90..1848b70deb 100644 --- a/node-graph/libraries/vector-types/src/vector/connectivity.rs +++ b/node-graph/libraries/vector-types/src/vector/connectivity.rs @@ -24,7 +24,7 @@ impl Connectivity { pub fn build(point_count: usize, paths: &List) -> Self { let mut starts = vec![0_u32; point_count + 1]; for path in paths.iter_element_values() { - for &point in path.0.iter_element_values() { + for point in path.references() { if let Some(count) = (point as usize).checked_add(1).and_then(|slot| starts.get_mut(slot)) { *count += 1; } @@ -39,7 +39,7 @@ impl Connectivity { let mut cursors = starts[..point_count].to_vec(); let mut references = vec![Reference::default(); starts[point_count] as usize]; for (path_index, path) in paths.iter_element_values().enumerate() { - for (reference_index, &point) in path.0.iter_element_values().enumerate() { + for (reference_index, point) in path.references().enumerate() { let Some(cursor) = cursors.get_mut(point as usize) else { continue }; references[*cursor as usize] = Reference { path: path_index as u32, @@ -94,7 +94,7 @@ mod tests { let mut paths = List::new(); for &(curve_type, references) in specs { - let path = Path(references.iter().map(|&reference| Item::new_from_element(reference)).collect()); + let path = Path::from_references(references.iter().copied()); paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); } diff --git a/node-graph/libraries/vector-types/src/vector/contour.rs b/node-graph/libraries/vector-types/src/vector/contour.rs index cbcf5648f3..c3be65e84b 100644 --- a/node-graph/libraries/vector-types/src/vector/contour.rs +++ b/node-graph/libraries/vector-types/src/vector/contour.rs @@ -106,7 +106,7 @@ pub fn subpaths(point_count: usize, paths: &List) -> Vec { let stride = curve_type.stride(); for span in 0..path.segment_count(curve_type) { - let references = (span * stride..=(span + 1) * stride).map(|index| path.0.element(index).copied()); + let references = (span * stride..=(span + 1) * stride).map(|index| path.reference(index)); let Some(references) = references.collect::>>() else { continue }; // A span naming a point outside the pool cannot be drawn, so it takes no part in the walk @@ -213,10 +213,7 @@ mod tests { /// Linear paths over a pool of the given size, one path per list of references. fn linear(point_count: usize, paths: &[&[u32]]) -> (List, List) { let pool = (0..point_count).map(|index| Item::new_from_element(DVec2::new(index as f64, (index * index) as f64))).collect(); - let paths = paths - .iter() - .map(|references| Item::new_from_element(Path(references.iter().copied().map(Item::new_from_element).collect()))) - .collect(); + let paths = paths.iter().map(|references| Item::new_from_element(Path::from_references(references.iter().copied()))).collect(); (pool, paths) } @@ -229,8 +226,8 @@ mod tests { let mut anchors = vec![subpath.entry]; for step in &subpath.steps { let path = paths.element(step.path as usize).expect("the step names a path"); - let (start, end) = (path.0.element(step.span as usize), path.0.element(step.span as usize + 1)); - anchors.push(*if step.reversed { start } else { end }.expect("the span has both ends")); + let (start, end) = (path.reference(step.span as usize), path.reference(step.span as usize + 1)); + anchors.push(if step.reversed { start } else { end }.expect("the span has both ends")); } if subpath.closed { anchors.pop(); diff --git a/node-graph/libraries/vector-types/src/vector/flatten.rs b/node-graph/libraries/vector-types/src/vector/flatten.rs new file mode 100644 index 0000000000..be20579b22 --- /dev/null +++ b/node-graph/libraries/vector-types/src/vector/flatten.rs @@ -0,0 +1,352 @@ +use super::addressing; +use super::misc::{BezierHandles, HandleId, HandleType, segment_to_handles}; +use super::path::{CurveType, Path, curve_type_at, push_path}; +use super::vector_attributes::{PointId, SegmentId}; +use super::vector_types::Vector; +use core_types::list::{ATTR_ID, Item, List}; +use glam::DVec2; +use std::collections::HashMap; + +/// One path under construction: its curve type, the pool references it weaves, and the IDs of the spans between them. +type Run = (CurveType, Vec, Vec); + +/// The legacy flat form that modifications and merge passes are expressed against: anchors with IDs, +/// segments with IDs and absolute handles, and G1 pairs. Callers flatten storage into this, edit it, +/// and weave it back. +#[derive(Default)] +pub struct WorkingVector { + pub point_ids: Vec, + pub point_positions: Vec, + pub segment_ids: Vec, + pub segment_start: Vec, + pub segment_end: Vec, + pub segment_handles: Vec, + pub colinear: Vec<[HandleId; 2]>, +} + +impl WorkingVector { + /// Reads the pool and paths into the working form, one working point per anchor or free point. + pub fn flatten(vector: &Vector, paths: &List) -> Self { + let mut working = Self::default(); + let connectivity = vector.connectivity(paths); + + let mut pool_to_working = vec![None; vector.point_count()]; + for (index, slot) in pool_to_working.iter_mut().enumerate() { + if !vector.is_handle_point(paths, &connectivity, index as u32) { + *slot = Some(working.point_ids.len()); + working.point_ids.push(vector.point_id_at(index as u32).unwrap_or_default()); + working.point_positions.push(vector.position(index).unwrap_or_default()); + } + } + + // One pass so a span that fails to resolve leaves every array at the same length + for span in addressing::spans(paths) { + let Some(path) = paths.element(span.path as usize) else { continue }; + let Some(segment) = path.segment(&vector.0, curve_type_at(paths, span.path as usize), span.index as usize) else { + continue; + }; + let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; + let working_point = |pool_index: u32| pool_to_working.get(pool_index as usize).copied().flatten(); + let (Some(start), Some(end)) = (working_point(start), working_point(end)) else { continue }; + + working.segment_ids.push(addressing::segment_id_of(paths, span).unwrap_or_default()); + working.segment_handles.push(segment_to_handles(&segment)); + working.segment_start.push(start); + working.segment_end.push(end); + } + + working.colinear = vector.colinear_pairs(paths); + + working + } + + /// Weaves the working form back into a pool and paths, gathering consecutive segments that meet head to tail into one path. + pub fn reweave(self, vector: &mut Vector, paths: &mut List) { + *vector = Vector::default(); + *paths = List::new(); + + for (index, (&id, &position)) in self.point_ids.iter().zip(&self.point_positions).enumerate() { + vector.0.push(Item::new_from_element(position)); + vector.0.set_attribute(ATTR_ID, index, id); + } + let anchor_count = vector.0.len(); + + let mut runs: Vec = Vec::new(); + let mut segment_anchors = HashMap::new(); + + let ends = self.segment_start.iter().zip(&self.segment_end); + for ((&id, (&start, &end)), handles) in self.segment_ids.iter().zip(ends).zip(&self.segment_handles) { + if start >= anchor_count || end >= anchor_count { + continue; + } + + let (curve_type, handle_positions) = match *handles { + BezierHandles::Linear => (CurveType::Linear, Vec::new()), + BezierHandles::Quadratic { handle } => (CurveType::Quadratic, vec![handle]), + BezierHandles::Cubic { handle_start, handle_end } => (CurveType::Cubic, vec![handle_start, handle_end]), + }; + + // Runs stay in segment order, since the order spans are woven in decides how subpaths are walked. + // A run carries on through a junction and gives way only once it has closed. + let continues_run = runs + .last() + .is_some_and(|(run_curve_type, references, _)| *run_curve_type == curve_type && references.last() == Some(&(start as u32)) && references.first() != references.last()); + if !continues_run { + runs.push((curve_type, vec![start as u32], Vec::new())); + } + + let Some((_, references, ids)) = runs.last_mut() else { continue }; + for position in handle_positions { + references.push(vector.0.len() as u32); + vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, PointId::UNNAMED)); + } + references.push(end as u32); + ids.push(id); + + segment_anchors.insert(id, (start as u32, end as u32)); + } + + for (curve_type, references, ids) in runs { + push_path(paths, curve_type, references, ids); + } + + // G1 pairs narrow to the smooth flag on the anchor both handles face, and other pairings are dropped + let anchor = |handle: HandleId| { + let &(start, end) = segment_anchors.get(&handle.segment)?; + Some(if handle.ty == HandleType::Primary { start } else { end }) + }; + let smooth_anchors: Vec = self + .colinear + .into_iter() + .filter_map(|[first, second]| anchor(first).zip(anchor(second))) + .filter_map(|(first, second)| (first == second).then_some(first)) + .collect(); + + vector.set_smooth_at_indices(paths, smooth_anchors, true); + } + + pub fn resolve_id(&self, id: PointId) -> Option { + self.point_ids.iter().position(|&check_id| check_id == id) + } +} + +// TODO: Eventually remove this document upgrade code +/// Builds storage from the legacy flat arrays: anchors with IDs and positions, segments with IDs, +/// endpoint indices, and absolute handles, plus G1 pairs. Used by document migration. +pub fn vector_from_legacy_parts( + point_ids: Vec, + point_positions: Vec, + segment_ids: Vec, + segment_start: Vec, + segment_end: Vec, + segment_handles: Vec, + colinear: Vec<[HandleId; 2]>, +) -> (Vector, List) { + let working = WorkingVector { + point_ids, + point_positions, + segment_ids, + segment_start, + segment_end, + segment_handles, + colinear, + }; + + let (mut vector, mut paths) = (Vector::default(), List::new()); + working.reweave(&mut vector, &mut paths); + + (vector, paths) +} + +#[cfg(test)] +mod tests { + use super::*; + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID}; + + fn working(points: usize, segments: &[(usize, usize, BezierHandles)]) -> WorkingVector { + WorkingVector { + point_ids: (0..points).map(|_| PointId::generate()).collect(), + point_positions: (0..points).map(|index| DVec2::new(index as f64, 0.)).collect(), + segment_ids: segments.iter().map(|_| SegmentId::generate()).collect(), + segment_start: segments.iter().map(|&(start, ..)| start).collect(), + segment_end: segments.iter().map(|&(_, end, _)| end).collect(), + segment_handles: segments.iter().map(|(.., handles)| *handles).collect(), + colinear: Vec::new(), + } + } + + fn woven(working: WorkingVector) -> (Vector, List) { + let (mut vector, mut paths) = (Vector::default(), List::new()); + working.reweave(&mut vector, &mut paths); + + (vector, paths) + } + + fn references(paths: &List, index: usize) -> Vec { + paths.element(index).expect("the path was woven").references().collect() + } + + // Four sides that meet head to tail become one closed path, its last reference naming its first + #[test] + fn reweave_gathers_a_rectangle_into_one_path() { + let sides = [ + (0, 1, BezierHandles::Linear), + (1, 2, BezierHandles::Linear), + (2, 3, BezierHandles::Linear), + (3, 0, BezierHandles::Linear), + ]; + let (_, paths) = woven(working(4, &sides)); + + assert_eq!(paths.len(), 1); + assert_eq!(references(&paths, 0), vec![0, 1, 2, 3, 0]); + + let rectangle = paths.element(0).expect("the run became a path"); + assert!(rectangle.is_closed()); + assert_eq!(rectangle.segment_count(CurveType::Linear), 4); + } + + // A run carries on through a junction, and the third segment leaving that anchor starts its own path + #[test] + fn reweave_carries_a_run_through_a_junction() { + let spokes = [(0, 1, BezierHandles::Linear), (1, 2, BezierHandles::Linear), (1, 3, BezierHandles::Linear)]; + let (_, paths) = woven(working(4, &spokes)); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), vec![0, 1, 2]); + assert_eq!(references(&paths, 1), vec![1, 3]); + } + + // Two loops meeting at one anchor stay apart, since a run gives way once it has closed + #[test] + fn reweave_keeps_loops_meeting_at_an_anchor_apart() { + let lobes = [ + (0, 1, BezierHandles::Linear), + (1, 0, BezierHandles::Linear), + (0, 2, BezierHandles::Linear), + (2, 0, BezierHandles::Linear), + ]; + let (_, paths) = woven(working(3, &lobes)); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), vec![0, 1, 0]); + assert_eq!(references(&paths, 1), vec![0, 2, 0]); + } + + // One path weaves one stride, so a curve following a line starts its own + #[test] + fn reweave_breaks_a_run_at_a_verb_change() { + let handles = BezierHandles::Cubic { + handle_start: DVec2::new(1., 1.), + handle_end: DVec2::new(2., 1.), + }; + let (_, paths) = woven(working(3, &[(0, 1, BezierHandles::Linear), (1, 2, handles)])); + + assert_eq!(paths.len(), 2); + assert_eq!(curve_type_at(&paths, 0), CurveType::Linear); + assert_eq!(curve_type_at(&paths, 1), CurveType::Cubic); + } + + // Consecutive curves weave into one path, each span's handles filling the references between its anchors + #[test] + fn reweave_gathers_cubic_handles_into_one_path() { + let handles = |offset: f64| BezierHandles::Cubic { + handle_start: DVec2::new(offset, 1.), + handle_end: DVec2::new(offset + 1., 1.), + }; + let (vector, paths) = woven(working(3, &[(0, 1, handles(0.)), (1, 2, handles(2.))])); + + assert_eq!(paths.len(), 1); + assert_eq!(references(&paths, 0), vec![0, 3, 4, 1, 5, 6, 2]); + assert_eq!(vector.point_count(), 7); + assert_eq!(paths.element(0).expect("the run became a path").segment_count(CurveType::Cubic), 2); + } + + // Beveling appends its corner segments after the sides, which keep that order and still walk as one closed contour + #[test] + fn reweave_keeps_segments_appended_out_of_order_in_order() { + let sides = [(0, 1), (2, 3), (4, 5), (6, 7)]; + let corners = [(1, 2), (3, 4), (5, 6), (7, 0)]; + let segments: Vec<_> = sides.into_iter().chain(corners).map(|(start, end)| (start, end, BezierHandles::Linear)).collect(); + + let (vector, paths) = woven(working(8, &segments)); + + assert_eq!(paths.len(), 8); + assert_eq!(references(&paths, 3), vec![6, 7]); + assert_eq!(references(&paths, 4), vec![1, 2]); + + let contours: Vec<_> = vector.stroke_bezpath_iter(&paths).collect(); + assert_eq!(contours.len(), 1); + assert_eq!(contours[0].elements().len(), 10); + } + + // Separate shapes stay where they were, so nothing downstream sees geometry shuffle + #[test] + fn reweave_keeps_untouched_shapes_in_order() { + let triangle = [(0, 1), (1, 2), (2, 0)]; + let open_pair = [(3, 4), (4, 5)]; + let segments: Vec<_> = triangle.into_iter().chain(open_pair).map(|(start, end)| (start, end, BezierHandles::Linear)).collect(); + + let (_, paths) = woven(working(6, &segments)); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), vec![0, 1, 2, 0]); + assert_eq!(references(&paths, 1), vec![3, 4, 5]); + } + + // A span naming a point the pool does not have drops out of every array at once, keeping them aligned + #[test] + fn flatten_drops_an_unresolvable_span_from_every_array() { + let mut vector = Vector::default(); + for index in 0..2 { + vector.0.push(Item::new_from_element(DVec2::new(index as f64, 0.)).with_attribute(ATTR_ID, PointId::generate())); + } + + let mut path = Path::from_references([99, 0, 1]); + let drawn = SegmentId::generate(); + path.0.set_attribute(ATTR_ID, 0, SegmentId::generate()); + path.0.set_attribute(ATTR_ID, 1, drawn); + + let mut paths = List::new(); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + + let working = WorkingVector::flatten(&vector, &paths); + assert_eq!(working.segment_ids, vec![drawn]); + assert_eq!(working.segment_start, vec![0]); + assert_eq!(working.segment_end, vec![1]); + } + + // A segment naming a point the pool lacks is dropped, leaving the run around it woven as one path + #[test] + fn unresolvable_segment_leaves_the_run_intact() { + let mut working = working(3, &[(0, 1, BezierHandles::Linear), (1, 2, BezierHandles::Linear)]); + working.segment_ids.push(SegmentId::generate()); + working.segment_start.push(1); + working.segment_end.push(99); + working.segment_handles.push(BezierHandles::Linear); + + let (_, paths) = woven(working); + assert_eq!(paths.len(), 1); + assert_eq!(references(&paths, 0), [0, 1, 2]); + } + + // Gathering runs stays invisible to the bridge: the same segments come back in the same order + #[test] + fn reweave_round_trips_through_flatten() { + let sides = [ + (0, 1, BezierHandles::Linear), + (1, 2, BezierHandles::Linear), + (2, 3, BezierHandles::Linear), + (3, 0, BezierHandles::Linear), + ]; + let original = working(4, &sides); + let (point_ids, segment_ids) = (original.point_ids.clone(), original.segment_ids.clone()); + + let (vector, paths) = woven(original); + let round_tripped = WorkingVector::flatten(&vector, &paths); + + assert_eq!(round_tripped.point_ids, point_ids); + assert_eq!(round_tripped.segment_ids, segment_ids); + assert_eq!(round_tripped.segment_start, vec![0, 1, 2, 3]); + assert_eq!(round_tripped.segment_end, vec![1, 2, 3, 0]); + } +} diff --git a/node-graph/libraries/vector-types/src/vector/geometry.rs b/node-graph/libraries/vector-types/src/vector/geometry.rs new file mode 100644 index 0000000000..7685be903d --- /dev/null +++ b/node-graph/libraries/vector-types/src/vector/geometry.rs @@ -0,0 +1,254 @@ +use super::misc::{HandleId, ManipulatorGroup, ManipulatorPointId}; +use super::path::{Path, paths_from_item_attributes}; +use super::vector_attributes::{FoundSubpath, PointId, SegmentId}; +use super::vector_types::Vector; +use core_types::list::{ATTR_PATHS, Item, List}; +use glam::{DAffine2, DVec2}; +use kurbo::{BezPath, PathSeg, Rect}; + +/// A vector element bundled with its paths, so editor-side callers can query geometry without +/// threading the holder's paths attribute through every call. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct VectorGeometry { + pub vector: Vector, + pub paths: List, +} + +impl VectorGeometry { + pub fn new(vector: Vector, paths: List) -> Self { + Self { vector, paths } + } + + /// Clones a holder item's element and paths attribute into one bundle. + pub fn from_item(item: &Item) -> Self { + Self { + vector: item.element().clone(), + paths: paths_from_item_attributes(item).cloned().unwrap_or_default(), + } + } + + /// Rebuilds a holder item carrying this bundle's element and paths. + pub fn into_item(self) -> Item { + Item::new_from_element(self.vector).with_attribute(ATTR_PATHS, self.paths) + } + + pub fn point_count(&self) -> usize { + self.vector.point_count() + } + + pub fn position(&self, index: usize) -> Option { + self.vector.position(index) + } + + pub fn positions(&self) -> impl Iterator + '_ { + self.vector.positions() + } + + pub fn point_id_at(&self, index: u32) -> Option { + self.vector.point_id_at(index) + } + + pub fn index_of_point_id(&self, point: PointId) -> Option { + self.vector.index_of_point_id(point) + } + + /// The position of the pool point a point ID names. + pub fn position_from_id(&self, point: PointId) -> Option { + self.vector.index_of_point_id(point).and_then(|index| self.vector.position(index as usize)) + } + + pub fn anchor_positions(&self) -> Vec { + self.vector.anchor_positions(&self.paths) + } + + pub fn anchor_points(&self) -> impl Iterator { + self.vector.anchor_points(&self.paths) + } + + pub fn anchor_endpoints(&self) -> impl Iterator { + self.vector.anchor_endpoints(&self.paths) + } + + /// The ID and position of every anchor and free point, found in one pass over the paths. + pub fn anchors(&self) -> impl Iterator + '_ { + let anchor_indices = self.vector.anchor_indices(&self.paths); + anchor_indices + .into_iter() + .filter_map(|index| Some((self.vector.point_id_at(index as u32)?, self.vector.position(index)?))) + } + + /// The ID and position of each pool point that no path references, found in one pass over the paths. + pub fn free_points(&self) -> impl Iterator + '_ { + let connectivity = self.vector.connectivity(&self.paths); + (0..self.vector.point_count() as u32) + .filter(move |&index| !connectivity.is_referenced(index)) + .filter_map(|index| Some((self.vector.point_id_at(index)?, self.vector.position(index as usize)?))) + } + + pub fn segment_iter(&self) -> impl Iterator + '_ { + self.vector.segment_iter(&self.paths) + } + + pub fn segment_ids(&self) -> Vec { + self.vector.segment_ids(&self.paths) + } + + pub fn segment_from_id(&self, id: SegmentId) -> Option { + self.vector.segment_from_id(&self.paths, id) + } + + pub fn segment_points_from_id(&self, id: SegmentId) -> Option<(PointId, PointId, PathSeg)> { + self.vector.segment_points_from_id(&self.paths, id) + } + + pub fn segment_with_pool_endpoints(&self, id: SegmentId) -> Option<(PathSeg, usize, usize)> { + self.vector.segment_with_pool_endpoints(&self.paths, id) + } + + /// Appends a lone segment between two existing points. See [`Vector::push`]. + pub fn push(&mut self, id: SegmentId, start: PointId, end: PointId, handles: (Option, Option)) { + self.vector.push(&mut self.paths, id, start, end, handles); + } + + pub fn segment_start_from_id(&self, segment: SegmentId) -> Option { + self.vector.segment_start_from_id(&self.paths, segment) + } + + pub fn segment_end_from_id(&self, segment: SegmentId) -> Option { + self.vector.segment_end_from_id(&self.paths, segment) + } + + pub fn start_point(&self) -> impl Iterator + '_ { + self.vector.start_point(&self.paths) + } + + pub fn end_point(&self) -> impl Iterator + '_ { + self.vector.end_point(&self.paths) + } + + pub fn other_point(&self, segment: SegmentId, current: PointId) -> Option { + self.vector.other_point(&self.paths, segment, current) + } + + pub fn stroke_bezpath_iter(&self) -> impl Iterator { + self.vector.stroke_bezpath_iter(&self.paths) + } + + pub fn stroke_manipulator_groups(&self) -> impl Iterator, bool)> { + self.vector.stroke_manipulator_groups(&self.paths) + } + + pub fn bounding_box(&self) -> Option<[DVec2; 2]> { + self.vector.bounding_box(&self.paths) + } + + pub fn bounding_box_rect(&self) -> Option { + self.vector.bounding_box_rect(&self.paths) + } + + pub fn bounding_box_with_transform(&self, transform: DAffine2) -> Option<[DVec2; 2]> { + self.vector.bounding_box_with_transform(&self.paths, transform) + } + + pub fn nonzero_bounding_box(&self) -> [DVec2; 2] { + self.vector.nonzero_bounding_box(&self.paths) + } + + pub fn stroke_inclusive_bounding_box_with_transform(&self, transform: DAffine2, stroke: Option<&super::style::Stroke>) -> Option<[DVec2; 2]> { + self.vector.stroke_inclusive_bounding_box_with_transform(&self.paths, transform, stroke) + } + + pub fn check_point_inside_shape(&self, transform: DAffine2, point: DVec2) -> bool { + self.vector.check_point_inside_shape(&self.paths, transform, point) + } + + pub fn start_connected(&self, point: PointId) -> impl Iterator { + self.vector.start_connected(&self.paths, point) + } + + pub fn end_connected(&self, point: PointId) -> impl Iterator { + self.vector.end_connected(&self.paths, point) + } + + pub fn all_connected(&self, point: PointId) -> impl Iterator { + self.vector.all_connected(&self.paths, point) + } + + pub fn connected_count(&self, point: PointId) -> usize { + self.vector.connected_count(&self.paths, point) + } + + pub fn any_connected(&self, point: PointId) -> bool { + self.vector.any_connected(&self.paths, point) + } + + pub fn connected_points(&self, current: PointId) -> impl Iterator { + self.vector.connected_points(&self.paths, current) + } + + pub fn connected_linear_segments(&self, point_id: PointId) -> usize { + self.vector.connected_linear_segments(&self.paths, point_id) + } + + pub fn colinear(&self, point: ManipulatorPointId) -> bool { + self.vector.colinear(&self.paths, point) + } + + pub fn other_colinear_handle(&self, handle: HandleId) -> Option { + self.vector.other_colinear_handle(&self.paths, handle) + } + + pub fn colinear_pairs(&self) -> Vec<[HandleId; 2]> { + self.vector.colinear_pairs(&self.paths) + } + + pub fn colinear_pair_containing(&self, handle: HandleId) -> Option<[HandleId; 2]> { + self.vector.colinear_pair_containing(&self.paths, handle) + } + + pub fn adjacent_segment(&self, manipulator_id: &ManipulatorPointId) -> Option<(PointId, SegmentId)> { + self.vector.adjacent_segment(&self.paths, manipulator_id) + } + + pub fn auto_join_paths(&self) -> Vec { + self.vector.auto_join_paths(&self.paths) + } + + pub fn bezpath_from_segments_ignore_discontinuities(&self, segments: impl Iterator) -> Option { + self.vector.bezpath_from_segments_ignore_discontinuities(segments) + } + + pub fn point_tangent(&self, point_index: usize) -> Option { + self.vector.point_tangent(&self.paths, point_index) + } + + /// The manipulator's position in layer space. See [`ManipulatorPointId::get_position`]. + pub fn position_of(&self, point: ManipulatorPointId) -> Option { + point.get_position(&self.vector, &self.paths) + } + + /// The position of the anchor the manipulator sits on or belongs to. + pub fn anchor_position_of(&self, point: ManipulatorPointId) -> Option { + point.get_anchor_position(&self.vector, &self.paths) + } + + /// The anchor the manipulator sits on or belongs to. + pub fn anchor_of(&self, point: ManipulatorPointId) -> Option { + point.get_anchor(&self.vector, &self.paths) + } + + /// The manipulator's handle pair. See [`ManipulatorPointId::get_handle_pair`]. + pub fn handle_pair_of(&self, point: ManipulatorPointId) -> Option<[HandleId; 2]> { + point.get_handle_pair(&self.vector, &self.paths) + } + + /// All handles connected to the manipulator's anchor, excluding itself when it is a handle. + pub fn all_connected_handles_of(&self, point: ManipulatorPointId) -> Option> { + point.get_all_connected_handles(&self.vector, &self.paths) + } + + /// The handle's length from its anchor. See [`HandleId::length`]. + pub fn handle_length(&self, handle: HandleId) -> f64 { + handle.length(&self.vector, &self.paths) + } +} diff --git a/node-graph/libraries/vector-types/src/vector/misc.rs b/node-graph/libraries/vector-types/src/vector/misc.rs index 7cbdc30746..43e84b7f38 100644 --- a/node-graph/libraries/vector-types/src/vector/misc.rs +++ b/node-graph/libraries/vector-types/src/vector/misc.rs @@ -1,5 +1,6 @@ use super::PointId; use super::algorithms::consts::MAX_COINCIDENT_POINT_DISTANCE; +use super::path::Path; use crate::vector::{SegmentId, Vector}; use core_types::list::{Item, List}; use dyn_any::DynAny; @@ -413,37 +414,39 @@ pub enum ManipulatorPointId { impl ManipulatorPointId { /// Attempt to retrieve the manipulator position in layer space (no transformation applied). #[must_use] - #[track_caller] - pub fn get_position(&self, vector: &Vector) -> Option { + pub fn get_position(&self, vector: &Vector, paths: &List) -> Option { match self { - ManipulatorPointId::Anchor(id) => vector.point_domain.position_from_id(*id), - ManipulatorPointId::PrimaryHandle(id) => vector.segment_from_id(*id).and_then(|segment| segment_to_handles(&segment).start()), - ManipulatorPointId::EndHandle(id) => vector.segment_from_id(*id).and_then(|segment| segment_to_handles(&segment).end()), + ManipulatorPointId::Anchor(id) => vector.index_of_point_id(*id).and_then(|index| vector.position(index as usize)), + ManipulatorPointId::PrimaryHandle(id) => vector.segment_from_id(paths, *id).and_then(|segment| segment_to_handles(&segment).start()), + ManipulatorPointId::EndHandle(id) => vector.segment_from_id(paths, *id).and_then(|segment| segment_to_handles(&segment).end()), } } - pub fn get_anchor_position(&self, vector: &Vector) -> Option { + pub fn get_anchor_position(&self, vector: &Vector, paths: &List) -> Option { match self { - ManipulatorPointId::EndHandle(_) | ManipulatorPointId::PrimaryHandle(_) => self.get_anchor(vector).and_then(|id| vector.point_domain.position_from_id(id)), - _ => self.get_position(vector), + ManipulatorPointId::EndHandle(_) | ManipulatorPointId::PrimaryHandle(_) => self + .get_anchor(vector, paths) + .and_then(|id| vector.index_of_point_id(id)) + .and_then(|index| vector.position(index as usize)), + _ => self.get_position(vector, paths), } } /// Attempt to get a pair of handles. For an anchor this is the first two handles connected. For a handle it is self and the first opposing handle. #[must_use] - pub fn get_handle_pair(self, vector: &Vector) -> Option<[HandleId; 2]> { + pub fn get_handle_pair(self, vector: &Vector, paths: &List) -> Option<[HandleId; 2]> { match self { - ManipulatorPointId::Anchor(point) => vector.all_connected(point).take(2).collect::>().try_into().ok(), + ManipulatorPointId::Anchor(point) => vector.all_connected(paths, point).take(2).collect::>().try_into().ok(), ManipulatorPointId::PrimaryHandle(segment) => { - let point = vector.segment_domain.segment_start_from_id(segment)?; + let point = vector.segment_start_from_id(paths, segment)?; let current = HandleId::primary(segment); - let other = vector.segment_domain.all_connected(point).find(|&value| value != current); + let other = vector.all_connected(paths, point).find(|&value| value != current); other.map(|other| [current, other]) } ManipulatorPointId::EndHandle(segment) => { - let point = vector.segment_domain.segment_end_from_id(segment)?; + let point = vector.segment_end_from_id(paths, segment)?; let current = HandleId::end(segment); - let other = vector.segment_domain.all_connected(point).find(|&value| value != current); + let other = vector.all_connected(paths, point).find(|&value| value != current); other.map(|other| [current, other]) } } @@ -452,22 +455,22 @@ impl ManipulatorPointId { /// Finds all the connected handles of a point. /// For an anchor it is all the connected handles. /// For a handle it is all the handles connected to its corresponding anchor other than the current handle. - pub fn get_all_connected_handles(self, vector: &Vector) -> Option> { + pub fn get_all_connected_handles(self, vector: &Vector, paths: &List) -> Option> { match self { ManipulatorPointId::Anchor(point) => { - let connected = vector.all_connected(point).collect::>(); + let connected = vector.all_connected(paths, point).collect::>(); Some(connected) } ManipulatorPointId::PrimaryHandle(segment) => { - let point = vector.segment_domain.segment_start_from_id(segment)?; + let point = vector.segment_start_from_id(paths, segment)?; let current = HandleId::primary(segment); - let connected = vector.segment_domain.all_connected(point).filter(|&value| value != current).collect::>(); + let connected = vector.all_connected(paths, point).filter(|&value| value != current).collect::>(); Some(connected) } ManipulatorPointId::EndHandle(segment) => { - let point = vector.segment_domain.segment_end_from_id(segment)?; + let point = vector.segment_end_from_id(paths, segment)?; let current = HandleId::end(segment); - let connected = vector.segment_domain.all_connected(point).filter(|&value| value != current).collect::>(); + let connected = vector.all_connected(paths, point).filter(|&value| value != current).collect::>(); Some(connected) } } @@ -475,11 +478,11 @@ impl ManipulatorPointId { /// Attempt to find the closest anchor. If self is already an anchor then it is just self. If it is a start or end handle, then the start or end point is chosen. #[must_use] - pub fn get_anchor(self, vector: &Vector) -> Option { + pub fn get_anchor(self, vector: &Vector, paths: &List) -> Option { match self { ManipulatorPointId::Anchor(point) => Some(point), - ManipulatorPointId::PrimaryHandle(segment) => vector.segment_start_from_id(segment), - ManipulatorPointId::EndHandle(segment) => vector.segment_end_from_id(segment), + ManipulatorPointId::PrimaryHandle(segment) => vector.segment_start_from_id(paths, segment), + ManipulatorPointId::EndHandle(segment) => vector.segment_end_from_id(paths, segment), } } @@ -561,12 +564,12 @@ impl HandleId { } /// Calculate the magnitude of the handle from the anchor. - pub fn length(self, vector: &Vector) -> f64 { - let Some(anchor_position) = self.to_manipulator_point().get_anchor_position(vector) else { + pub fn length(self, vector: &Vector, paths: &List) -> f64 { + let Some(anchor_position) = self.to_manipulator_point().get_anchor_position(vector, paths) else { // TODO: This was previously an unwrap which was encountered, so this is a temporary way to avoid a crash return 0.; }; - let handle_position = self.to_manipulator_point().get_position(vector); + let handle_position = self.to_manipulator_point().get_position(vector, paths); handle_position.map(|pos| (pos - anchor_position).length()).unwrap_or(f64::MAX) } diff --git a/node-graph/libraries/vector-types/src/vector/mod.rs b/node-graph/libraries/vector-types/src/vector/mod.rs index e290c269b0..c6eac68241 100644 --- a/node-graph/libraries/vector-types/src/vector/mod.rs +++ b/node-graph/libraries/vector-types/src/vector/mod.rs @@ -3,6 +3,8 @@ pub mod algorithms; pub mod click_target; mod connectivity; mod contour; +mod flatten; +mod geometry; pub mod misc; mod path; pub mod reference_point; @@ -14,6 +16,8 @@ mod vector_types; pub use addressing::*; pub use connectivity::*; pub use contour::*; +pub use flatten::{WorkingVector, vector_from_legacy_parts}; +pub use geometry::VectorGeometry; pub use path::*; pub use reference_point::*; pub use vector_attributes::*; diff --git a/node-graph/libraries/vector-types/src/vector/path.rs b/node-graph/libraries/vector-types/src/vector/path.rs index 4227f610ae..00c546fa97 100644 --- a/node-graph/libraries/vector-types/src/vector/path.rs +++ b/node-graph/libraries/vector-types/src/vector/path.rs @@ -1,6 +1,7 @@ use super::algorithms::consts::CLOSE_POINT_TOLERANCE; use super::misc::{dvec2_to_point, point_to_dvec2}; -use core_types::list::{ATTR_CURVE_TYPE, ATTR_PATHS, Item, List}; +use super::vector_attributes::SegmentId; +use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List}; use glam::DVec2; use graphene_hash::CacheHash; use kurbo::{BezPath, CubicBez, Line, PathEl, PathSeg, Point, QuadBez}; @@ -41,10 +42,27 @@ impl std::fmt::Display for CurveType { /// One connected stroke of geometry: an ordered list of references (indices into the owning `Vector`'s point pool) /// woven in its curve type's stride order. Welding is two paths, or two ends of one path, referencing the same anchor. /// Per-reference data such as `ATTR_SMOOTH` rides this list's attributes. +/// +/// References are stored as `i64`, the integer type the data model standardizes on, and read back as `u32` pool indices. #[derive(Clone, Debug, Default, PartialEq, CacheHash)] -pub struct Path(pub List); +pub struct Path(pub List); impl Path { + /// Builds a path from pool indices, with no per-reference attributes. + pub fn from_references(references: impl IntoIterator) -> Self { + Self(references.into_iter().map(|reference| Item::new_from_element(i64::from(reference))).collect()) + } + + /// The pool index named by the reference at `index`, or `None` if out of bounds. + pub fn reference(&self, index: usize) -> Option { + self.0.element(index).map(|&reference| reference as u32) + } + + /// The pool indices named by each reference, in weave order. + pub fn references(&self) -> impl ExactSizeIterator + '_ { + self.0.iter_element_values().map(|&reference| reference as u32) + } + /// Whether this path is closed, indicated by its first and last references naming the same pool point. pub fn is_closed(&self) -> bool { let len = self.0.len(); @@ -63,7 +81,7 @@ impl Path { /// The pool position named by the reference at `index`, or `None` if either lookup falls out of bounds. pub fn position(&self, pool: &List, index: usize) -> Option { - pool.element(*self.0.element(index)? as usize).copied() + pool.element(self.reference(index)? as usize).copied() } /// The segment at `index`, resolved against the point pool. @@ -77,6 +95,55 @@ impl Path { CurveType::Cubic => PathSeg::Cubic(CubicBez::new(point(0)?, point(1)?, point(2)?, point(3)?)), }) } + + /// A copy of the spans in `start_span..end_span`, keeping both boundary anchors so the pieces stay welded. + pub fn clone_span_range(&self, curve_type: CurveType, start_span: usize, end_span: usize) -> Path { + let stride = curve_type.stride(); + let first_reference = start_span * stride; + let last_reference = (end_span * stride).min(self.0.len().saturating_sub(1)); + + let mut piece = Path((first_reference..=last_reference).filter_map(|index| self.0.clone_item(index)).collect()); + + // The final anchor's cell may hold the ID of a span outside the piece, which its own piece keeps + let last_index = piece.0.len().saturating_sub(1); + if piece.0.attribute::(ATTR_ID, last_index).is_some() { + piece.0.set_attribute(ATTR_ID, last_index, SegmentId::default()); + } + + piece + } + + /// Reverses the path in place, so the weave walks its references in the opposite direction. + /// Per-reference attributes travel with their references, and each span's ID moves to the anchor it now departs from. + pub fn reverse(&mut self, curve_type: CurveType) { + let stride = curve_type.stride(); + let count = self.segment_count(curve_type); + let ids: Vec> = (0..count).map(|span| self.0.attribute::(ATTR_ID, span * stride).copied()).collect(); + + self.0 = (0..self.0.len()).rev().filter_map(|index| self.0.clone_item(index)).collect(); + + // Span k of the reversed path walks old span (count - 1 - k) backwards, so it takes over that span's ID + for span in 0..count { + if let Some(id) = ids[count - 1 - span] { + self.0.set_attribute(ATTR_ID, span * stride, id); + } + } + if count > 0 && self.0.attribute::(ATTR_ID, count * stride).is_some() { + self.0.set_attribute(ATTR_ID, count * stride, SegmentId::default()); + } + } +} + +/// Appends one path weaving the given references in the curve type's stride, naming its spans with the given IDs in order. +pub fn push_path(paths: &mut List, curve_type: CurveType, references: impl IntoIterator, ids: impl IntoIterator) { + let mut path = Path::from_references(references); + + let span_count = path.segment_count(curve_type); + for (span, id) in ids.into_iter().enumerate().take(span_count) { + path.0.set_attribute(ATTR_ID, span * curve_type.stride(), id); + } + + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); } /// Appends a segment to a bezpath already positioned at that segment's start point. @@ -98,6 +165,12 @@ pub fn paths_from_list_row_attributes(list: &List, index: usize) -> Option list.attribute(ATTR_PATHS, index) } +/// The empty weave, standing in for a pool with a holder that carries no paths. +pub fn no_paths() -> &'static List { + static EMPTY: std::sync::LazyLock> = std::sync::LazyLock::new(List::new); + &EMPTY +} + /// The curve type the path at `index` weaves in. pub fn curve_type_at(paths: &List, index: usize) -> CurveType { paths.attribute_cloned_or_default(ATTR_CURVE_TYPE, index) @@ -229,7 +302,7 @@ impl PathWeaver { } for (curve_type, references) in self.woven { - let path = Path(references.into_iter().map(Item::new_from_element).collect()); + let path = Path::from_references(references); paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); } } @@ -264,7 +337,7 @@ mod tests { } fn path(references: &[u32]) -> Path { - Path(references.iter().map(|&reference| Item::new_from_element(reference)).collect()) + Path::from_references(references.iter().copied()) } #[test] diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index 16fb9a092c..7a799d0e7b 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -1,12 +1,15 @@ -use crate::vector::misc::{BezierHandles, HandleId, ManipulatorGroup, Tangent, dvec2_to_point}; +use crate::vector::addressing::{self, Span}; +use crate::vector::contour::subpaths; +use crate::vector::misc::{ManipulatorGroup, Tangent, point_to_dvec2, segment_to_handles}; +use crate::vector::path::{Path, append_segment, curve_type_at}; use crate::vector::vector_types::Vector; +use core_types::list::{Item, List}; use dyn_any::DynAny; use fixedbitset::FixedBitSet; -use glam::{DAffine2, DVec2}; -use kurbo::{CubicBez, Line, ParamCurve, PathSeg, QuadBez}; -use std::collections::{HashMap, HashSet}; +use glam::DVec2; +use kurbo::{ParamCurve, PathSeg}; +use std::collections::HashSet; use std::hash::{Hash, Hasher}; -use std::iter::zip; /// A simple macro for creating strongly typed ids (to avoid confusion when passing around ids). macro_rules! create_ids { @@ -38,7 +41,7 @@ macro_rules! create_ids { self.0 } - /// Adds one to the current value and returns the old value. Note that the ids are not going to be unique unless you use the largest id. + /// Adds one to the current value and returns it. pub fn next_id(&mut self) -> Self { self.0 += 1; *self @@ -50,6 +53,11 @@ macro_rules! create_ids { create_ids! { PointId, SegmentId } +impl PointId { + /// The filler naming nothing, carried by pool points that are handles rather than anchors. + pub const UNNAMED: PointId = PointId(u64::MAX); +} + /// A no-op hasher that allows writing u64s (the id type). #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct NoHash(Option); @@ -63,7 +71,7 @@ impl Hasher for NoHash { } fn write_u64(&mut self, i: u64) { debug_assert!(self.0.is_none()); - self.0 = Some(i) + self.0 = Some(i); } } @@ -78,475 +86,51 @@ impl std::hash::BuildHasher for NoHashBuilder { } } -#[derive(Clone, Debug, Default, PartialEq, graphene_hash::CacheHash, DynAny)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -/// Stores data which is per-point. Each point is merely a position and can be used in a point cloud or to for a bézier path. In future this will be extendable at runtime with custom attributes. -pub struct PointDomain { - id: Vec, - #[cfg_attr(feature = "serde", serde(alias = "positions"))] - pub(crate) position: Vec, +/// A flat view of every resolvable span as an edge of the segment graph, so graph algorithms can +/// address segments by one index. Rebuilt on demand rather than stored. +pub(crate) struct SegmentGraph { + pub spans: Vec, + pub ids: Vec, + pub start_point: Vec, + pub end_point: Vec, + pub segments: Vec, + pub point_count: usize, } -impl PointDomain { - pub const fn new() -> Self { - Self { id: Vec::new(), position: Vec::new() } - } +impl SegmentGraph { + pub fn new(vector: &Vector, paths: &List) -> Self { + let mut graph = Self { + spans: Vec::new(), + ids: Vec::new(), + start_point: Vec::new(), + end_point: Vec::new(), + segments: Vec::new(), + point_count: vector.point_count(), + }; - #[inline(always)] - pub fn reserve(&mut self, additional: usize) { - self.id.reserve(additional); - self.position.reserve(additional); - } + for span in addressing::spans(paths) { + let Some(path) = paths.element(span.path as usize) else { continue }; + let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; + let Some(segment) = path.segment(&vector.0, curve_type_at(paths, span.path as usize), span.index as usize) else { + continue; + }; - pub(crate) fn retain(&mut self, segment_domain: &mut SegmentDomain, f: impl Fn(&PointId) -> bool) { - let mut keep = self.id.iter().map(&f); - self.position.retain(|_| keep.next().unwrap_or_default()); - - // TODO(TrueDoctor): Consider using a prefix sum to avoid this Vec allocation (https://github.com/GraphiteEditor/Graphite/pull/1949#discussion_r1741711562) - let mut id_map = Vec::with_capacity(self.ids().len()); - let mut new_index = 0; - for id in self.ids() { - if f(id) { - id_map.push(new_index); - new_index += 1; - } else { - // A placeholder for invalid IDs. This is checked after the segment domain is modified. - id_map.push(usize::MAX); - } + graph.spans.push(span); + graph.ids.push(addressing::segment_id_of(paths, span).unwrap_or_default()); + graph.start_point.push(start as usize); + graph.end_point.push(end as usize); + graph.segments.push(segment); } - let update_index = |index: &mut usize| *index = id_map[*index]; - segment_domain.start_point.iter_mut().for_each(update_index); - segment_domain.end_point.iter_mut().for_each(update_index); - - self.id.retain(f); - } - - pub fn push(&mut self, id: PointId, position: DVec2) { - #[cfg(debug_assertions)] - if self.id.contains(&id) { - warn!("Tried to push a duplicate point to a point domain"); - return; - } - - self.push_unchecked(id, position); - } - - #[inline(always)] - pub fn push_unchecked(&mut self, id: PointId, position: DVec2) { - self.id.push(id); - self.position.push(position); - } - - pub fn positions(&self) -> &[DVec2] { - &self.position - } - - pub fn positions_mut(&mut self) -> impl Iterator { - self.id.iter().copied().zip(self.position.iter_mut()) - } - - pub fn set_position(&mut self, index: usize, position: DVec2) { - self.position[index] = position; - } - - pub fn ids(&self) -> &[PointId] { - &self.id - } - - pub fn next_id(&self) -> PointId { - self.ids().iter().copied().max_by(|a, b| a.0.cmp(&b.0)).map(|mut id| id.next_id()).unwrap_or(PointId::ZERO) - } - - #[track_caller] - pub fn position_from_id(&self, id: PointId) -> Option { - let pos = self.resolve_id(id).map(|index| self.position[index]); - if pos.is_none() { - warn!("Resolving pos of invalid id"); - } - pos - } - - pub fn resolve_id(&self, id: PointId) -> Option { - self.id.iter().position(|&check_id| check_id == id) - } - - pub(crate) fn concat(&mut self, other: &Self, transform: DAffine2, id_map: &IdMap) { - self.id.extend(other.id.iter().map(|id| *id_map.point_map.get(id).unwrap_or(id))); - self.position.extend(other.position.iter().map(|&pos| transform.transform_point2(pos))); - } - - pub(crate) fn map_ids(&mut self, id_map: &IdMap) { - self.id.iter_mut().for_each(|id| *id = *id_map.point_map.get(id).unwrap_or(id)); - } - - pub(crate) fn transform(&mut self, transform: DAffine2) { - for pos in &mut self.position { - *pos = transform.transform_point2(*pos); - } + graph } pub fn len(&self) -> usize { - self.id.len() + self.spans.len() } - pub fn is_empty(&self) -> bool { - self.id.is_empty() - } - - /// Iterate over point IDs and positions - pub fn iter(&self) -> impl Iterator + '_ { - self.ids().iter().copied().zip(self.positions().iter().copied()) - } -} - -#[derive(Clone, Debug, Default, PartialEq, graphene_hash::CacheHash, DynAny)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -/// Stores data which is per-segment. A segment is a bézier curve between two end points. In future this will be extendable at runtime with custom attributes. -pub struct SegmentDomain { - #[cfg_attr(feature = "serde", serde(alias = "ids"))] - id: Vec, - start_point: Vec, - end_point: Vec, - handles: Vec, -} - -impl SegmentDomain { - pub const fn new() -> Self { - Self { - id: Vec::new(), - start_point: Vec::new(), - end_point: Vec::new(), - handles: Vec::new(), - } - } - - #[inline(always)] - pub fn reserve(&mut self, additional: usize) { - self.id.reserve(additional); - self.start_point.reserve(additional); - self.end_point.reserve(additional); - self.handles.reserve(additional); - } - - pub(crate) fn retain(&mut self, f: impl Fn(&SegmentId) -> bool, points_length: usize) { - let additional_delete_ids = self - .id - .iter() - .zip(&self.start_point) - .zip(&self.end_point) - .filter(|((_, start), end)| **start >= points_length || **end >= points_length) - .map(|x| *x.0.0) - .collect::>(); - - let can_delete = || { - let f = &f; - let mut delete_iter = additional_delete_ids.iter().peekable(); - move |id| { - if delete_iter.peek() == Some(&id) { - delete_iter.next(); - false - } else { - f(id) - } - } - }; - - let mut keep = self.id.iter().map(can_delete()); - self.start_point.retain(|_| keep.next().unwrap_or_default()); - let mut keep = self.id.iter().map(can_delete()); - self.end_point.retain(|_| keep.next().unwrap_or_default()); - let mut keep = self.id.iter().map(can_delete()); - self.handles.retain(|_| keep.next().unwrap_or_default()); - - let mut delete_iter = additional_delete_ids.iter().peekable(); - self.id.retain(move |id| { - if delete_iter.peek() == Some(&id) { - delete_iter.next(); - false - } else { - f(id) - } - }); - } - - pub fn ids(&self) -> &[SegmentId] { - &self.id - } - - pub fn next_id(&self) -> SegmentId { - self.ids().iter().copied().max_by(|a, b| a.0.cmp(&b.0)).map(|mut id| id.next_id()).unwrap_or(SegmentId::ZERO) - } - - pub fn start_point(&self) -> &[usize] { - &self.start_point - } - - pub fn end_point(&self) -> &[usize] { - &self.end_point - } - - pub fn set_start_point(&mut self, segment_index: usize, new: usize) { - self.start_point[segment_index] = new; - } - - pub fn set_end_point(&mut self, segment_index: usize, new: usize) { - self.end_point[segment_index] = new; - } - - pub fn set_handles(&mut self, segment_index: usize, new: BezierHandles) { - self.handles[segment_index] = new; - } - - pub fn handles(&self) -> &[BezierHandles] { - &self.handles - } - - pub fn push(&mut self, id: SegmentId, start: usize, end: usize, handles: BezierHandles) { - #[cfg(debug_assertions)] - if self.id.contains(&id) { - warn!("Tried to push a duplicate segment to a segment domain"); - return; - } - - self.push_unchecked(id, start, end, handles); - } - - #[inline(always)] - pub fn push_unchecked(&mut self, id: SegmentId, start: usize, end: usize, handles: BezierHandles) { - self.id.push(id); - self.start_point.push(start); - self.end_point.push(end); - self.handles.push(handles); - } - - pub(crate) fn start_point_mut(&mut self) -> impl Iterator { - self.id.iter().copied().zip(self.start_point.iter_mut()) - } - - pub(crate) fn end_point_mut(&mut self) -> impl Iterator { - self.id.iter().copied().zip(self.end_point.iter_mut()) - } - - pub(crate) fn handles_mut(&mut self) -> impl Iterator { - let nested = self.id.iter().zip(&mut self.handles).zip(&self.start_point).zip(&self.end_point); - nested.map(|(((&a, b), &c), &d)| (a, b, c, d)) - } - - pub fn handles_and_points_mut(&mut self) -> impl Iterator { - let nested = self.handles.iter_mut().zip(&mut self.start_point).zip(&mut self.end_point); - nested.map(|((a, b), c)| (a, b, c)) - } - - pub(crate) fn segment_start_from_id(&self, segment: SegmentId) -> Option { - self.id_to_index(segment).and_then(|index| self.start_point.get(index)).copied() - } - - pub(crate) fn segment_end_from_id(&self, segment: SegmentId) -> Option { - self.id_to_index(segment).and_then(|index| self.end_point.get(index)).copied() - } - - /// Returns an array for the start and end points of a segment. - pub(crate) fn points_from_id(&self, segment: SegmentId) -> Option<[usize; 2]> { - self.segment_start_from_id(segment).and_then(|start| self.segment_end_from_id(segment).map(|end| [start, end])) - } - - /// Attempts to find another point in the segment that is not the one passed in. - pub(crate) fn other_point(&self, segment: SegmentId, current: usize) -> Option { - self.points_from_id(segment).and_then(|points| points.into_iter().find(|&point| point != current)) - } - - /// Gets all points connected to the current one but not including the current one. - pub(crate) fn connected_points(&self, current: usize) -> impl Iterator + '_ { - self.start_point.iter().zip(&self.end_point).filter_map(move |(&a, &b)| match (a == current, b == current) { - (true, false) => Some(b), - (false, true) => Some(a), - _ => None, - }) - } - - /// Get index from ID by linear search. Takes `O(n)` time. - fn id_to_index(&self, id: SegmentId) -> Option { - debug_assert_eq!(self.id.len(), self.handles.len()); - debug_assert_eq!(self.id.len(), self.start_point.len()); - debug_assert_eq!(self.id.len(), self.end_point.len()); - self.id.iter().position(|&check_id| check_id == id) - } - - pub(crate) fn concat(&mut self, other: &Self, transform: DAffine2, id_map: &IdMap) { - self.id.extend(other.id.iter().map(|id| *id_map.segment_map.get(id).unwrap_or(id))); - self.start_point.extend(other.start_point.iter().map(|&index| id_map.point_offset + index)); - self.end_point.extend(other.end_point.iter().map(|&index| id_map.point_offset + index)); - self.handles.extend(other.handles.iter().map(|handles| handles.apply_transformation(|p| transform.transform_point2(p)))); - } - - pub(crate) fn map_ids(&mut self, id_map: &IdMap) { - self.id.iter_mut().for_each(|id| *id = *id_map.segment_map.get(id).unwrap_or(id)); - } - - pub(crate) fn transform(&mut self, transform: DAffine2) { - for handles in &mut self.handles { - *handles = handles.apply_transformation(|p| transform.transform_point2(p)); - } - } - - /// Enumerate all segments that start at the point. - pub(crate) fn start_connected(&self, point: usize) -> impl Iterator + '_ { - self.start_point.iter().zip(&self.id).filter(move |&(&found_point, _)| found_point == point).map(|(_, &seg)| seg) - } - - /// Enumerate all segments that end at the point. - pub(crate) fn end_connected(&self, point: usize) -> impl Iterator + '_ { - self.end_point.iter().zip(&self.id).filter(move |&(&found_point, _)| found_point == point).map(|(_, &seg)| seg) - } - - /// Enumerate all segments that start or end at a point, converting them to [`HandleId`s]. Note that the handles may not exist e.g. for a linear segment. - pub(crate) fn all_connected(&self, point: usize) -> impl Iterator + '_ { - self.start_connected(point).map(HandleId::primary).chain(self.end_connected(point).map(HandleId::end)) - } - - /// Enumerate the number of segments connected to a point. If a segment starts and ends at a point then it is counted twice. - pub(crate) fn connected_count(&self, point: usize) -> usize { - self.all_connected(point).count() - } - - /// Enumerate the number of segments connected to a point. If a segment starts and ends at a point then it is counted twice. - pub(crate) fn any_connected(&self, point: usize) -> bool { - self.all_connected(point).next().is_some() - } - - /// Computes the direction-of-travel tangent at one endpoint of a segment. - /// Uses the "first distinct control point" pattern: iterates through the Bezier control points - /// from the anchor outward, returning the direction to the first one that differs in position. - /// This handles zero-length handles by finding the tangent direction in the limit. - /// Returns `DVec2::ZERO` if all control points coincide (fully degenerate segment). - fn segment_tangent_at_endpoint(&self, segment_index: usize, positions: &[DVec2], at_start: bool) -> DVec2 { - let anchor_start = positions[self.start_point[segment_index]]; - let anchor_end = positions[self.end_point[segment_index]]; - - // Build ordered control points for this segment - let (points, count) = match self.handles[segment_index] { - BezierHandles::Linear => ([anchor_start, anchor_end, DVec2::ZERO, DVec2::ZERO], 2), - BezierHandles::Quadratic { handle } => ([anchor_start, handle, anchor_end, DVec2::ZERO], 3), - BezierHandles::Cubic { handle_start, handle_end } => ([anchor_start, handle_start, handle_end, anchor_end], 4), - }; - - let not_near = |a: DVec2, b: DVec2| a.distance_squared(b) > f64::EPSILON * 1e3; - - if at_start { - let anchor = points[0]; - points[1..count].iter().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| point - anchor) - } else { - let anchor = points[count - 1]; - points[..count - 1].iter().rev().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| anchor - point) - } - } - - /// Computes the average tangent direction at a point based on its 1 or 2 connected segments. - /// Returns `None` for points with 0 or 3+ connections (ambiguous or undefined tangent), - /// or if the tangent is degenerate (all control points coincide). - pub fn point_tangent(&self, point_index: usize, positions: &[DVec2]) -> Option { - // Collect connected segments with their relationship to this point (at_start flag) - let mut connections: [(usize, bool); 2] = [(0, false); 2]; - let mut connection_count = 0; - - for (segment_index, (&start, &end)) in self.start_point.iter().zip(&self.end_point).enumerate() { - // Self-loop segments count as two connections (outgoing and incoming) - let is_start = start == point_index; - let is_end = end == point_index; - - if !is_start && !is_end { - continue; - } - - if is_start { - if connection_count >= 2 { - return None; - } - connections[connection_count] = (segment_index, true); - connection_count += 1; - } - if is_end { - if connection_count >= 2 { - return None; - } - connections[connection_count] = (segment_index, false); - connection_count += 1; - } - } - - if connection_count == 0 { - return None; - } - - // Compute the direction-of-travel tangent for the first connection - let (segment_index, at_start) = connections[0]; - let tangent1 = self.segment_tangent_at_endpoint(segment_index, positions, at_start).try_normalize(); - - if connection_count == 1 { - return tangent1; - } - - // Compute the direction-of-travel tangent for the second connection - let (segment_index, at_start) = connections[1]; - let tangent2 = self.segment_tangent_at_endpoint(segment_index, positions, at_start).try_normalize(); - - // Average the two normalized tangents - let average = tangent1? + tangent2?; - - // If the tangents are nearly opposite (straight-through), use t1 directly - if average.length_squared() < (f64::EPSILON * 1e3).powi(2) { - return tangent1; - } - - average.try_normalize() - } - - /// Iterates over segments in the domain. - /// - /// Tuple is: (id, start point, end point, handles) - pub fn iter(&self) -> impl Iterator + '_ { - let ids = self.id.iter().copied(); - let start_point = self.start_point.iter().copied(); - let end_point = self.end_point.iter().copied(); - let handles = self.handles.iter().copied(); - zip(ids, zip(start_point, zip(end_point, handles))).map(|(id, (start_point, (end_point, handles)))| (id, start_point, end_point, handles)) - } - - /// Iterates over segments in the domain, mutably. - /// - /// Tuple is: (id, start point, end point, handles) - pub(crate) fn iter_mut(&mut self) -> impl Iterator + '_ { - let ids = self.id.iter_mut(); - let start_point = self.start_point.iter_mut(); - let end_point = self.end_point.iter_mut(); - let handles = self.handles.iter_mut(); - zip(ids, zip(start_point, zip(end_point, handles))).map(|(id, (start_point, (end_point, handles)))| (id, start_point, end_point, handles)) - } - - pub fn pair_handles_and_points_mut_by_index(&mut self, index1: usize, index2: usize) -> (&mut BezierHandles, &mut usize, &mut usize, &mut BezierHandles, &mut usize, &mut usize) { - // Use split_at_mut to avoid multiple mutable borrows of the same slice - let (handles_first, handles_second) = self.handles.split_at_mut(index2.max(index1)); - let (start_first, start_second) = self.start_point.split_at_mut(index2.max(index1)); - let (end_first, end_second) = self.end_point.split_at_mut(index2.max(index1)); - - let (h1, h2) = if index1 < index2 { - (&mut handles_first[index1], &mut handles_second[0]) - } else { - (&mut handles_second[0], &mut handles_first[index2]) - }; - let (sp1, sp2) = if index1 < index2 { - (&mut start_first[index1], &mut start_second[0]) - } else { - (&mut start_second[0], &mut start_first[index2]) - }; - let (ep1, ep2) = if index1 < index2 { - (&mut end_first[index1], &mut end_second[0]) - } else { - (&mut end_second[0], &mut end_first[index2]) - }; - - (h1, sp1, ep1, h2, sp2, ep2) + fn segment(&self, index: usize, reversed: bool) -> PathSeg { + if reversed { self.segments[index].reverse() } else { self.segments[index] } } } @@ -715,221 +299,227 @@ impl Faces { } } -impl Vector { - /// Construct a [`kurbo::PathSeg`] by resolving the points from their ids. - fn path_segment_from_index(&self, start: usize, end: usize, handles: BezierHandles) -> PathSeg { - let start = dvec2_to_point(self.point_domain.positions()[start]); - let end = dvec2_to_point(self.point_domain.positions()[end]); - - match handles { - BezierHandles::Linear => PathSeg::Line(Line::new(start, end)), - BezierHandles::Quadratic { handle } => PathSeg::Quad(QuadBez::new(start, dvec2_to_point(handle), end)), - BezierHandles::Cubic { handle_start, handle_end } => PathSeg::Cubic(CubicBez::new(start, dvec2_to_point(handle_start), dvec2_to_point(handle_end), end)), - } - } - - /// Tries to convert a segment with the specified id to a [`PathSeg`], returning None if the id is invalid. - pub fn segment_from_id(&self, id: SegmentId) -> Option { - self.segment_points_from_id(id).map(|(_, _, segment)| segment) - } - - /// Tries to convert a segment with the specified id to the start and end points and a [`PathSeg`], returning None if the id is invalid. - pub fn segment_points_from_id(&self, id: SegmentId) -> Option<(PointId, PointId, PathSeg)> { - Some(self.segment_points_from_index(self.segment_domain.id_to_index(id)?)) - } - - /// Converts a segment with the specified index to the start and end points and a [`PathSeg`]. - pub fn segment_points_from_index(&self, index: usize) -> (PointId, PointId, PathSeg) { - let start = self.segment_domain.start_point[index]; - let end = self.segment_domain.end_point[index]; - let start_id = self.point_domain.ids()[start]; - let end_id = self.point_domain.ids()[end]; - (start_id, end_id, self.path_segment_from_index(start, end, self.segment_domain.handles[index])) - } - - /// Iterator over all of the [`PathSeg`]s following the order that they are stored in the segment domain, skipping invalid segments. - pub fn segment_iter(&self) -> impl Iterator { - let to_segment = |(((&handles, &id), &start), &end)| (id, self.path_segment_from_index(start, end, handles), self.point_domain.ids()[start], self.point_domain.ids()[end]); - - self.segment_domain - .handles - .iter() - .zip(&self.segment_domain.id) - .zip(self.segment_domain.start_point()) - .zip(self.segment_domain.end_point()) - .map(to_segment) - } - - pub fn auto_join_paths(&self) -> Vec { - let segments = self.segment_domain.iter().map(|(id, start, end, _)| HalfEdge::new(id, start, end, false)); - - let mut paths: Vec = Vec::new(); - let mut current_path: Option<&mut FoundSubpath> = None; - let mut previous: Option<(usize, usize)> = None; - - // First pass. Generates subpaths from continuous segments. - for seg_ref in segments { - let (start, end) = (seg_ref.start, seg_ref.end); - - if previous.is_some_and(|(_, prev_end)| start == prev_end) { - if let Some(path) = current_path.as_mut() { - path.push(seg_ref); - } - } else { - paths.push(FoundSubpath::from_segment(seg_ref)); - current_path = paths.last_mut(); - } - - previous = Some((start, end)); - } - - // Second pass. Try to join paths together. - let mut joined_paths = Vec::new(); - - loop { - let mut prev_index: Option = None; - let original_len = paths.len(); - - for current in paths.into_iter() { - // If there's no previous subpath, start a new one - if prev_index.is_none() { - joined_paths.push(current); - prev_index = Some(joined_paths.len() - 1); - continue; - } - - let prev = &mut joined_paths[prev_index.unwrap()]; - - // Compare segment connections - let (prev_first, prev_last) = prev.endpoints().unwrap(); - let (cur_first, cur_last) = current.endpoints().unwrap(); - - // Join paths if the endpoints connect - if prev_last.end == cur_first.start { - prev.edges.extend(current.edges.into_iter().map(|s| s.normalize_direction())); - } else if prev_first.start == cur_last.end { - prev.edges.splice(0..0, current.edges.into_iter().rev().map(|s| s.normalize_direction())); - } else if prev_last.end == cur_last.end { - prev.edges.extend(current.edges.into_iter().rev().map(|s| s.reversed().normalize_direction())); - } else if prev_first.start == cur_first.start { - prev.edges.splice(0..0, current.edges.into_iter().map(|s| s.reversed().normalize_direction())); - } else { - // If not connected, start a new subpath - joined_paths.push(current); - prev_index = Some(joined_paths.len() - 1); - } - } - - // If no paths were joined in this pass, we're done - if joined_paths.len() == original_len { - return joined_paths; - } - - // Repeat pass with newly joined paths - paths = joined_paths; - joined_paths = Vec::new(); - } - } - - /// Construct a [`kurbo::BezPath`] from an iterator of segments with (handles, start point, end point) independently of discontinuities. - pub fn bezpath_from_segments_ignore_discontinuities(&self, segments: impl Iterator) -> Option { - let mut first_point = None; - let mut manipulators_list = Vec::new(); - let mut last: Option<(usize, BezierHandles)> = None; - - for (handle, start, end) in segments { - first_point = Some(first_point.unwrap_or(start)); - - manipulators_list.push(ManipulatorGroup { - anchor: self.point_domain.positions()[start], - in_handle: last.and_then(|(_, handle)| handle.end()), - out_handle: handle.start(), - id: self.point_domain.ids()[start], - }); - - last = Some((end, handle)); - } - - let closed = manipulators_list.len() > 1 && last.map(|(point, _)| point) == first_point; - - if let Some((end, last_handle)) = last { - if closed { - manipulators_list[0].in_handle = last_handle.end(); - } else { - manipulators_list.push(ManipulatorGroup { - anchor: self.point_domain.positions()[end], - in_handle: last_handle.end(), - out_handle: None, - id: self.point_domain.ids()[end], - }); - } - } - - Some(crate::vector::misc::bezpath_from_manipulator_groups(&manipulators_list, closed)) - } - - pub fn build_stroke_path_iter(&self) -> StrokePathIter<'_> { - let mut points = vec![StrokePathIterPointMetadata::default(); self.point_domain.ids().len()]; - for (segment_index, (&start, &end)) in self.segment_domain.start_point.iter().zip(&self.segment_domain.end_point).enumerate() { - points[start].set(StrokePathIterPointSegmentMetadata::new(segment_index, false)); - points[end].set(StrokePathIterPointSegmentMetadata::new(segment_index, true)); - } - - StrokePathIter { - vector: self, - points, - skip: 0, - done_one: false, - } - } - - /// Construct and return an iterator of `(Vec, bool)` for each stroke. - /// The boolean in the tuple indicates if the path is closed. - pub fn stroke_manipulator_groups(&self) -> impl Iterator, bool)> { - self.build_stroke_path_iter() - } - - /// Construct a [`kurbo::BezPath`] curve for stroke. - pub fn stroke_bezpath_iter(&self) -> impl Iterator { - self.build_stroke_path_iter() - .map(|(manipulators_list, closed)| crate::vector::misc::bezpath_from_manipulator_groups(&manipulators_list, closed)) - } - - pub fn transform(&mut self, transform: DAffine2) { - self.point_domain.transform(transform); - self.segment_domain.transform(transform); - } - - pub fn vector_new_ids_from_hash(&mut self, node_id: u64) { - let point_map = self.point_domain.ids().iter().map(|&old| (old, old.generate_from_hash(node_id))).collect::>(); - let segment_map = self.segment_domain.ids().iter().map(|&old| (old, old.generate_from_hash(node_id))).collect::>(); - - let id_map = IdMap { - point_offset: self.point_domain.ids().len(), - point_map, - segment_map, +impl SegmentGraph { + /// Computes the direction-of-travel tangent at one endpoint of a segment. + /// Uses the "first distinct control point" pattern: iterates through the Bezier control points + /// from the anchor outward, returning the direction to the first one that differs in position. + /// This handles zero-length handles by finding the tangent direction in the limit. + /// Returns `DVec2::ZERO` if all control points coincide (fully degenerate segment). + fn segment_tangent_at_endpoint(&self, segment_index: usize, at_start: bool) -> DVec2 { + let (points, count) = match self.segments[segment_index] { + PathSeg::Line(line) => ([point_to_dvec2(line.p0), point_to_dvec2(line.p1), DVec2::ZERO, DVec2::ZERO], 2), + PathSeg::Quad(quad) => ([point_to_dvec2(quad.p0), point_to_dvec2(quad.p1), point_to_dvec2(quad.p2), DVec2::ZERO], 3), + PathSeg::Cubic(cubic) => ([point_to_dvec2(cubic.p0), point_to_dvec2(cubic.p1), point_to_dvec2(cubic.p2), point_to_dvec2(cubic.p3)], 4), }; - self.point_domain.map_ids(&id_map); - self.segment_domain.map_ids(&id_map); + let not_near = |a: DVec2, b: DVec2| a.distance_squared(b) > f64::EPSILON * 1e3; + + if at_start { + let anchor = points[0]; + points[1..count].iter().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| point - anchor) + } else { + let anchor = points[count - 1]; + points[..count - 1].iter().rev().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| anchor - point) + } } - pub fn is_branching(&self) -> bool { - // Tally segment endpoints per point in one `O(points + segments)` pass, short-circuiting once any point exceeds two - let mut connected_count = vec![0_u8; self.point_domain.len()]; - for &point_index in self.segment_domain.start_point().iter().chain(self.segment_domain.end_point()) { - connected_count[point_index] += 1; - if connected_count[point_index] > 2 { - return true; + /// Computes the average tangent direction at a point based on its 1 or 2 connected segments. + /// Returns `None` for points with 0 or 3+ connections (ambiguous or undefined tangent), + /// or if the tangent is degenerate (all control points coincide). + pub fn point_tangent(&self, point_index: usize) -> Option { + // Collect connected segments with their relationship to this point (at_start flag) + let mut connections: [(usize, bool); 2] = [(0, false); 2]; + let mut connection_count = 0; + + for (segment_index, (&start, &end)) in self.start_point.iter().zip(&self.end_point).enumerate() { + // Self-loop segments count as two connections (outgoing and incoming) + let is_start = start == point_index; + let is_end = end == point_index; + + if !is_start && !is_end { + continue; + } + + if is_start { + if connection_count >= 2 { + return None; + } + connections[connection_count] = (segment_index, true); + connection_count += 1; + } + if is_end { + if connection_count >= 2 { + return None; + } + connections[connection_count] = (segment_index, false); + connection_count += 1; } } - false + + if connection_count == 0 { + return None; + } + + // Compute the direction-of-travel tangent for the first connection + let (segment_index, at_start) = connections[0]; + let tangent1 = self.segment_tangent_at_endpoint(segment_index, at_start).try_normalize(); + + if connection_count == 1 { + return tangent1; + } + + // Compute the direction-of-travel tangent for the second connection + let (segment_index, at_start) = connections[1]; + let tangent2 = self.segment_tangent_at_endpoint(segment_index, at_start).try_normalize(); + + // Average the two normalized tangents + let average = tangent1? + tangent2?; + + // If the tangents are nearly opposite (straight-through), use t1 directly + if average.length_squared() < (f64::EPSILON * 1e3).powi(2) { + return tangent1; + } + + average.try_normalize() } - /// Determines if face-by-face fill rendering should be used. Branching vectors are meshes, whose - /// bounded faces are found and filled individually rather than filling the stroke path directly. - pub fn use_face_fill(&self) -> bool { - self.is_branching() + /// Walks every face orbit of the segment graph and traces each one's path and signed area. + fn face_orbits(&self) -> FaceOrbits { + let mut adjacency: Vec> = vec![Vec::new(); self.point_count]; + for (segment_index, (&start, &end)) in self.start_point.iter().zip(&self.end_point).enumerate() { + adjacency[start].push(FaceSide { segment_index, reversed: false }); + adjacency[end].push(FaceSide { segment_index, reversed: true }); + } + + for neighbors in &mut adjacency { + neighbors.sort_by(|a, b| { + let angle = [a, b].map(|side| { + let tangent = self.segment(side.segment_index, side.reversed).tangent_at_start(); + tangent.y.atan2(tangent.x) + }); + angle[0].partial_cmp(&angle[1]).unwrap_or(std::cmp::Ordering::Equal) + }) + } + + let mut faces: Faces = Faces::new(); + let mut seen = FaceSideSet::new(self.len()); + + for segment_index in 0..self.len() { + for &reversed in &[false, true] { + let side = FaceSide { segment_index, reversed }; + if seen.contains(side) { + continue; + } + if self.construct_face(&adjacency, side, &mut faces, &mut seen).is_none() { + // Undo `seen` markings for sides added during this failed face construction, + // so they remain available for future face constructions starting from different sides. + if let Some(&last_start) = faces.face_start.last() { + for &failed_side in &faces.sides[last_start..] { + seen.remove(failed_side); + } + } + faces.backtrack(); + } + } + } + + let mut paths = Vec::with_capacity(faces.face_start.len()); + let mut areas = Vec::with_capacity(faces.face_start.len()); + let mut side_to_orbit = vec![usize::MAX; self.len() * 2]; + for orbit_index in 0..faces.face_start.len() { + let start = faces.face_start[orbit_index]; + let end = faces.face_start.get(orbit_index + 1).copied().unwrap_or(faces.sides.len()); + let sides = &faces.sides[start..end]; + + for side in sides { + side_to_orbit[FaceSideSet::index_of(side)] = orbit_index; + } + let path = self.face_path(sides); + areas.push(kurbo::Shape::area(&path)); + paths.push(path); + } + + FaceOrbits { faces, paths, areas, side_to_orbit } + } + + /// Computes each point's degree in the two-core: the graph left after iteratively stripping dead-end segments. + /// Returns the degrees and which segments were pruned as spurs. + fn two_core(&self) -> (Vec, Vec, Vec>) { + let segment_count = self.len(); + let point_count = self.point_count; + + let mut degree = vec![0_usize; point_count]; + let mut adjacency: Vec> = vec![Vec::new(); point_count]; + for (segment_index, (&start, &end)) in self.start_point.iter().zip(&self.end_point).enumerate() { + degree[start] += 1; + degree[end] += 1; + adjacency[start].push(segment_index); + adjacency[end].push(segment_index); + } + + let mut pruned = vec![false; segment_count]; + let mut leaf_points: Vec = (0..point_count).filter(|&point| degree[point] == 1).collect(); + while let Some(point) = leaf_points.pop() { + if degree[point] != 1 { + continue; + } + let Some(&segment_index) = adjacency[point].iter().find(|&&segment_index| !pruned[segment_index]) else { + continue; + }; + + pruned[segment_index] = true; + for endpoint in [self.start_point[segment_index], self.end_point[segment_index]] { + degree[endpoint] -= 1; + if degree[endpoint] == 1 { + leaf_points.push(endpoint); + } + } + } + + (degree, pruned, adjacency) + } + + /// Traces one face orbit's sides into a path, reversing each segment walked against its drawn direction. + fn face_path(&self, sides: &[FaceSide]) -> kurbo::BezPath { + let mut path = kurbo::BezPath::new(); + let Some(first_side) = sides.first() else { return path }; + + path.move_to(self.segment(first_side.segment_index, first_side.reversed).start()); + for side in sides { + append_segment(&mut path, self.segment(side.segment_index, side.reversed)); + } + + path + } + + fn construct_face(&self, adjacency: &[Vec], first: FaceSide, faces: &mut Faces, seen: &mut FaceSideSet) -> Option<()> { + faces.start_new_face(); + let max_iterations = self.len() * 2; + let mut side = first; + for _iteration in 1..max_iterations { + if seen.contains(side) { + return None; + } + seen.insert(side); + faces.add_side(side); + let next_vertex = if side.reversed { + self.start_point[side.segment_index] + } else { + self.end_point[side.segment_index] + }; + let neighbors = &adjacency[next_vertex]; + let side_index = neighbors.iter().position(|s| { + FaceSide { + segment_index: s.segment_index, + reversed: !s.reversed, + } == side + })?; + side = neighbors[(side_index + 1) % neighbors.len()]; + if side == first { + return Some(()); + } + } + None } /// Returns the fillable faces of the segment graph: bounded regions, skipping the unbounded @@ -967,7 +557,7 @@ impl Vector { // contour was drawn as one unit. Walls shared among several faces are mesh and stay filled. let is_standalone_loop = non_spur_sides .iter() - .all(|side| core_degree[self.segment_domain.start_point[side.segment_index]] == 2 && core_degree[self.segment_domain.end_point[side.segment_index]] == 2); + .all(|side| core_degree[self.start_point[side.segment_index]] == 2 && core_degree[self.end_point[side.segment_index]] == 2); let mut mirror_orbits = non_spur_sides.iter().map(|side| orbits.side_to_orbit[FaceSideSet::index_of(&side.mirrored())]); let first_mirror_orbit = mirror_orbits.next().unwrap_or(usize::MAX); let surrounded_by_one_face = first_mirror_orbit != usize::MAX && orbits.areas[first_mirror_orbit] <= 0. && mirror_orbits.all(|orbit| orbit == first_mirror_orbit); @@ -994,176 +584,214 @@ impl Vector { kept_faces.into_iter().map(|(path, _)| path).collect() } +} - /// Walks every face orbit of the segment graph and traces each one's path and signed area. - fn face_orbits(&self) -> FaceOrbits { - let mut adjacency: Vec> = vec![Vec::new(); self.point_domain.len()]; - for (segment_index, (&start, &end)) in self.segment_domain.start_point.iter().zip(&self.segment_domain.end_point).enumerate() { - adjacency[start].push(FaceSide { segment_index, reversed: false }); - adjacency[end].push(FaceSide { segment_index, reversed: true }); +impl Vector { + /// Whether any point has more than two segment ends meeting at it, making the vector a mesh. + pub fn is_branching(&self, paths: &List) -> bool { + let connectivity = self.connectivity(paths); + (0..self.point_count() as u32).any(|point| connectivity.spokes(point, paths) > 2) + } + + /// Determines if face-by-face fill rendering should be used. Branching vectors are meshes, whose + /// bounded faces are found and filled individually rather than filling the stroke path directly. + pub fn use_face_fill(&self, paths: &List) -> bool { + self.is_branching(paths) + } + + /// Returns the fillable faces of the segment graph, one closed path per bounded face. + pub fn construct_faces(&self, paths: &List) -> Vec { + SegmentGraph::new(self, paths).construct_faces() + } + + /// Computes the average tangent direction at a point based on its 1 or 2 connected segments. + pub fn point_tangent(&self, paths: &List, point_index: usize) -> Option { + SegmentGraph::new(self, paths).point_tangent(point_index) + } + + /// Every segment's stable ID, in span order. + pub fn segment_ids(&self, paths: &List) -> Vec { + addressing::spans(paths).map(|span| addressing::segment_id_of(paths, span).unwrap_or_default()).collect() + } + + pub fn auto_join_paths(&self, paths: &List) -> Vec { + let graph = SegmentGraph::new(self, paths); + let segments = (0..graph.len()).map(|index| HalfEdge::new(graph.ids[index], graph.start_point[index], graph.end_point[index], false)); + + let mut found: Vec = Vec::new(); + let mut current_path: Option<&mut FoundSubpath> = None; + let mut previous: Option<(usize, usize)> = None; + + // First pass. Generates subpaths from continuous segments. + for seg_ref in segments { + let (start, end) = (seg_ref.start, seg_ref.end); + + if previous.is_some_and(|(_, prev_end)| start == prev_end) { + if let Some(path) = current_path.as_mut() { + path.push(seg_ref); + } + } else { + found.push(FoundSubpath::from_segment(seg_ref)); + current_path = found.last_mut(); + } + + previous = Some((start, end)); } - for neighbors in &mut adjacency { - neighbors.sort_by(|a, b| { - let angle = [a, b].map(|side| { - let curve = self.path_segment_from_index( - self.segment_domain.start_point[side.segment_index], - self.segment_domain.end_point[side.segment_index], - self.segment_domain.handles[side.segment_index], - ); - let curve = if side.reversed { curve.reverse() } else { curve }; - let tangent = curve.tangent_at_start(); - tangent.y.atan2(tangent.x) - }); - angle[0].partial_cmp(&angle[1]).unwrap_or(std::cmp::Ordering::Equal) - }) - } + // Second pass. Try to join paths together. + let mut paths_to_join = found; + let mut joined_paths = Vec::new(); - let mut faces: Faces = Faces::new(); - let mut seen = FaceSideSet::new(self.segment_domain.id.len()); + loop { + let mut prev_index: Option = None; + let original_len = paths_to_join.len(); - for segment_index in 0..self.segment_domain.id.len() { - for &reversed in &[false, true] { - let side = FaceSide { segment_index, reversed }; - if seen.contains(side) { + for current in paths_to_join.into_iter() { + // If there's no previous subpath, start a new one + if prev_index.is_none() { + joined_paths.push(current); + prev_index = Some(joined_paths.len() - 1); continue; } - if self.construct_face(&adjacency, side, &mut faces, &mut seen).is_none() { - // Undo `seen` markings for sides added during this failed face construction, - // so they remain available for future face constructions starting from different sides. - if let Some(&last_start) = faces.face_start.last() { - for &failed_side in &faces.sides[last_start..] { - seen.remove(failed_side); - } - } - faces.backtrack(); + + let prev = &mut joined_paths[prev_index.unwrap()]; + + // Compare segment connections + let (prev_first, prev_last) = prev.endpoints().unwrap(); + let (cur_first, cur_last) = current.endpoints().unwrap(); + + // Join paths if the endpoints connect + if prev_last.end == cur_first.start { + prev.edges.extend(current.edges.into_iter().map(|s| s.normalize_direction())); + } else if prev_first.start == cur_last.end { + prev.edges.splice(0..0, current.edges.into_iter().rev().map(|s| s.normalize_direction())); + } else if prev_last.end == cur_last.end { + prev.edges.extend(current.edges.into_iter().rev().map(|s| s.reversed().normalize_direction())); + } else if prev_first.start == cur_first.start { + prev.edges.splice(0..0, current.edges.into_iter().map(|s| s.reversed().normalize_direction())); + } else { + // If not connected, start a new subpath + joined_paths.push(current); + prev_index = Some(joined_paths.len() - 1); } } - } - let mut paths = Vec::with_capacity(faces.face_start.len()); - let mut areas = Vec::with_capacity(faces.face_start.len()); - let mut side_to_orbit = vec![usize::MAX; self.segment_domain.id.len() * 2]; - for orbit_index in 0..faces.face_start.len() { - let start = faces.face_start[orbit_index]; - let end = faces.face_start.get(orbit_index + 1).copied().unwrap_or(faces.sides.len()); - let sides = &faces.sides[start..end]; - - for side in sides { - side_to_orbit[FaceSideSet::index_of(side)] = orbit_index; + // If no paths were joined in this pass, we're done + if joined_paths.len() == original_len { + return joined_paths; } - let path = self.face_path(sides); - areas.push(kurbo::Shape::area(&path)); - paths.push(path); - } - FaceOrbits { faces, paths, areas, side_to_orbit } + // Repeat pass with newly joined paths + paths_to_join = joined_paths; + joined_paths = Vec::new(); + } } - /// Computes each point's degree in the two-core: the graph left after iteratively stripping dead-end segments. - /// Returns the degrees and which segments were pruned as spurs. - fn two_core(&self) -> (Vec, Vec, Vec>) { - let segment_count = self.segment_domain.id.len(); - let point_count = self.point_domain.len(); - - let mut degree = vec![0_usize; point_count]; - let mut adjacency: Vec> = vec![Vec::new(); point_count]; - for (segment_index, (&start, &end)) in self.segment_domain.start_point.iter().zip(&self.segment_domain.end_point).enumerate() { - degree[start] += 1; - degree[end] += 1; - adjacency[start].push(segment_index); - adjacency[end].push(segment_index); - } - - let mut pruned = vec![false; segment_count]; - let mut leaf_points: Vec = (0..point_count).filter(|&point| degree[point] == 1).collect(); - while let Some(point) = leaf_points.pop() { - if degree[point] != 1 { - continue; - } - let Some(&segment_index) = adjacency[point].iter().find(|&&segment_index| !pruned[segment_index]) else { - continue; - }; - - pruned[segment_index] = true; - for endpoint in [self.segment_domain.start_point[segment_index], self.segment_domain.end_point[segment_index]] { - degree[endpoint] -= 1; - if degree[endpoint] == 1 { - leaf_points.push(endpoint); - } - } - } - - (degree, pruned, adjacency) - } - - /// Traces one face orbit's sides into a path, reversing each segment walked against its drawn direction. - fn face_path(&self, sides: &[FaceSide]) -> kurbo::BezPath { - let mut path = kurbo::BezPath::new(); - let Some(first_side) = sides.first() else { return path }; - - let get_point = |point: usize| dvec2_to_point(self.point_domain.positions()[point]); - let start_point_index = if first_side.reversed { - self.segment_domain.end_point[first_side.segment_index] - } else { - self.segment_domain.start_point[first_side.segment_index] + /// Construct a [`kurbo::BezPath`] from an iterator of segments with (segment, start point, end point) independently of discontinuities. + pub fn bezpath_from_segments_ignore_discontinuities(&self, segments: impl Iterator) -> Option { + let handle = |segment: PathSeg, from_start: bool| { + let handles = segment_to_handles(&segment); + if from_start { handles.start() } else { handles.end() } }; - path.move_to(get_point(start_point_index)); - for side in sides { - let (handle, end_index) = match side.reversed { - false => (self.segment_domain.handles[side.segment_index], self.segment_domain.end_point[side.segment_index]), - true => (self.segment_domain.handles[side.segment_index].reversed(), self.segment_domain.start_point[side.segment_index]), - }; - let path_element = match handle { - BezierHandles::Linear => kurbo::PathEl::LineTo(get_point(end_index)), - BezierHandles::Quadratic { handle } => kurbo::PathEl::QuadTo(dvec2_to_point(handle), get_point(end_index)), - BezierHandles::Cubic { handle_start, handle_end } => kurbo::PathEl::CurveTo(dvec2_to_point(handle_start), dvec2_to_point(handle_end), get_point(end_index)), - }; - path.push(path_element); + let mut first_point = None; + let mut manipulators_list = Vec::new(); + let mut last: Option<(usize, PathSeg)> = None; + + for (segment, start, end) in segments { + first_point = Some(first_point.unwrap_or(start)); + + manipulators_list.push(ManipulatorGroup { + anchor: self.position(start)?, + in_handle: last.and_then(|(_, segment)| handle(segment, false)), + out_handle: handle(segment, true), + id: self.point_id_at(start as u32).unwrap_or_default(), + }); + + last = Some((end, segment)); } - path + let closed = manipulators_list.len() > 1 && last.map(|(point, _)| point) == first_point; + + if let Some((end, last_segment)) = last { + if closed { + manipulators_list[0].in_handle = handle(last_segment, false); + } else { + manipulators_list.push(ManipulatorGroup { + anchor: self.position(end)?, + in_handle: handle(last_segment, false), + out_handle: None, + id: self.point_id_at(end as u32).unwrap_or_default(), + }); + } + } + + Some(crate::vector::misc::bezpath_from_manipulator_groups(&manipulators_list, closed)) } - fn construct_face(&self, adjacency: &[Vec], first: FaceSide, faces: &mut Faces, seen: &mut FaceSideSet) -> Option<()> { - faces.start_new_face(); - let max_iterations = self.segment_domain.id.len() * 2; - let mut side = first; - for _iteration in 1..max_iterations { - if seen.contains(side) { - return None; + /// Construct and return an iterator of `(Vec, bool)` for each stroke. + /// The boolean in the tuple indicates if the path is closed. + /// The groups pair index-for-index with the contours emission, both walking the same subpaths. + pub fn stroke_manipulator_groups(&self, paths: &List) -> impl Iterator, bool)> { + let mut groups = Vec::new(); + + for subpath in subpaths(self.point_count(), paths) { + let mut manipulators_list: Vec = Vec::new(); + let mut in_handle: Option = None; + + for step in &subpath.steps { + let span = Span { path: step.path, index: step.span }; + let Some(path) = paths.element(step.path as usize) else { continue }; + let Some(segment) = path.segment(&self.0, curve_type_at(paths, step.path as usize), step.span as usize) else { + continue; + }; + let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; + + // A quadratic's one handle leaves its anchor whichever way the span is crossed + let handles = segment_to_handles(&segment); + let handles = if step.reversed { handles.reversed() } else { handles }; + let anchor = if step.reversed { end } else { start }; + + manipulators_list.push(ManipulatorGroup { + anchor: point_to_dvec2(if step.reversed { segment.end() } else { segment.start() }), + in_handle, + out_handle: handles.start(), + id: self.point_id_at(anchor).unwrap_or_default(), + }); + + in_handle = handles.end(); } - seen.insert(side); - faces.add_side(side); - let next_vertex = if side.reversed { - self.segment_domain.start_point[side.segment_index] - } else { - self.segment_domain.end_point[side.segment_index] - }; - let neighbors = &adjacency[next_vertex]; - let side_index = neighbors.iter().position(|s| { - FaceSide { - segment_index: s.segment_index, - reversed: !s.reversed, - } == side - })?; - side = neighbors[(side_index + 1) % neighbors.len()]; - if side == first { - return Some(()); + + if subpath.closed { + if let Some(first) = manipulators_list.first_mut() { + first.in_handle = in_handle; + } + } else if let Some(position) = self.position(subpath.exit as usize) { + manipulators_list.push(ManipulatorGroup { + anchor: position, + in_handle, + out_handle: None, + id: self.point_id_at(subpath.exit).unwrap_or_default(), + }); + } + + if !manipulators_list.is_empty() { + groups.push((manipulators_list, subpath.closed)); } } - None + + groups.into_iter() } /// Normalizes the winding direction of every simple closed loop so nesting depth alone decides fill: /// loops at even depth wind positive and loops nested inside them wind negative, regardless of the direction they happened /// to be drawn in. Loops passing through branch points, and open runs including dead-end spurs, are left untouched. - pub fn normalize_winding_directions(&mut self) { - let segment_count = self.segment_domain.id.len(); + pub fn normalize_winding_directions(&mut self, paths: &mut List) { + let graph = SegmentGraph::new(self, paths); + let segment_count = graph.len(); // Strip dead-end spurs first so a spur hanging off a loop doesn't disguise it - let (degree, pruned, adjacency) = self.two_core(); + let (degree, pruned, adjacency) = graph.two_core(); // Walk out each simple loop: a chain of surviving segments passing only through degree-2 points. // Chains that reach a branch point are mesh or welded structure and keep their drawn directions. @@ -1173,8 +801,8 @@ impl Vector { if visited[first_segment] { continue; } - let start = self.segment_domain.start_point[first_segment]; - let end = self.segment_domain.end_point[first_segment]; + let start = graph.start_point[first_segment]; + let end = graph.end_point[first_segment]; if degree[start] != 2 || degree[end] != 2 { visited[first_segment] = true; continue; @@ -1196,12 +824,8 @@ impl Vector { break; }; - let walked_reversed = self.segment_domain.end_point[next_segment] == current_point; - current_point = if walked_reversed { - self.segment_domain.start_point[next_segment] - } else { - self.segment_domain.end_point[next_segment] - }; + let walked_reversed = graph.end_point[next_segment] == current_point; + current_point = if walked_reversed { graph.start_point[next_segment] } else { graph.end_point[next_segment] }; loop_sides.push((next_segment, walked_reversed)); } @@ -1219,24 +843,9 @@ impl Vector { .map(|loop_sides| { let mut path = kurbo::BezPath::new(); let (first_segment, first_reversed) = loop_sides[0]; - let start_point = if first_reversed { - self.segment_domain.end_point[first_segment] - } else { - self.segment_domain.start_point[first_segment] - }; - path.move_to(dvec2_to_point(self.point_domain.positions()[start_point])); + path.move_to(graph.segment(first_segment, first_reversed).start()); for &(segment_index, walked_reversed) in loop_sides { - let (handle, end_index) = match walked_reversed { - false => (self.segment_domain.handles[segment_index], self.segment_domain.end_point[segment_index]), - true => (self.segment_domain.handles[segment_index].reversed(), self.segment_domain.start_point[segment_index]), - }; - let end = dvec2_to_point(self.point_domain.positions()[end_index]); - let path_element = match handle { - BezierHandles::Linear => kurbo::PathEl::LineTo(end), - BezierHandles::Quadratic { handle } => kurbo::PathEl::QuadTo(dvec2_to_point(handle), end), - BezierHandles::Cubic { handle_start, handle_end } => kurbo::PathEl::CurveTo(dvec2_to_point(handle_start), dvec2_to_point(handle_end), end), - }; - path.push(path_element); + append_segment(&mut path, graph.segment(segment_index, walked_reversed)); } path.close_path(); path @@ -1246,7 +855,7 @@ impl Vector { // Nesting depth counts the bounded face regions covering each loop, so containment still registers when the // surrounding contour is branching mesh structure rather than a simple loop. The bounding box check keeps // the containment tests from being `O(loops × faces × segments)` on many-loop paths like converted text. - let orbits = self.face_orbits(); + let orbits = graph.face_orbits(); let bounded_orbits: Vec<(&kurbo::BezPath, kurbo::Rect, HashSet)> = (0..orbits.face_count()) .filter(|&orbit_index| orbits.areas[orbit_index] <= 0.) .map(|orbit_index| { @@ -1256,7 +865,8 @@ impl Vector { }) .collect(); - // Reverse the segments of each loop whose drawn winding disagrees with its nesting parity + // Collect the loops drawn with a winding that disagrees with their nesting parity + let mut reversals: Vec<&Vec<(usize, bool)>> = Vec::new(); for (loop_index, loop_sides) in loops.iter().enumerate() { // A segment midpoint is a safe winding sample, as in `construct_faces` let Some(first_segment) = loop_paths[loop_index].segments().next() else { continue }; @@ -1270,159 +880,158 @@ impl Vector { let area = kurbo::Shape::area(&loop_paths[loop_index]); let wants_positive = depth % 2 == 0; if area != 0. && (area > 0.) != wants_positive { - for &(segment_index, _) in loop_sides { - let segment_domain = &mut self.segment_domain; - std::mem::swap(&mut segment_domain.start_point[segment_index], &mut segment_domain.end_point[segment_index]); - segment_domain.handles[segment_index] = segment_domain.handles[segment_index].reversed(); - } - } - } - } -} - -#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] -struct StrokePathIterPointSegmentMetadata { - segment_index: usize, - start_from_end: bool, -} - -impl StrokePathIterPointSegmentMetadata { - #[must_use] - const fn new(segment_index: usize, start_from_end: bool) -> Self { - Self { segment_index, start_from_end } - } - #[must_use] - const fn flipped(&self) -> Self { - Self { - segment_index: self.segment_index, - start_from_end: !self.start_from_end, - } - } -} - -#[derive(Clone, Default)] -struct StrokePathIterPointMetadata(tinyvec::TinyVec<[StrokePathIterPointSegmentMetadata; 2]>); - -impl StrokePathIterPointMetadata { - fn set(&mut self, value: StrokePathIterPointSegmentMetadata) { - self.0.insert(0, value); - } - #[must_use] - fn connected(&self) -> usize { - self.0.len() - } - #[must_use] - fn take_first(&mut self) -> Option { - self.0.pop() - } - fn take_eq(&mut self, target: StrokePathIterPointSegmentMetadata) -> bool { - let has_taken = self.0.contains(&target); - self.0.retain(|value| *value != target); - has_taken - } -} - -#[derive(Clone)] -pub struct StrokePathIter<'a> { - vector: &'a Vector, - points: Vec, - skip: usize, - done_one: bool, -} - -impl Iterator for StrokePathIter<'_> { - type Item = (Vec, bool); - - fn next(&mut self) -> Option { - let mut current_start = None; - // First iterate over the single connected points - if !self.done_one { - current_start = self.points.iter().enumerate().skip(self.skip).find(|(_, val)| val.connected() == 1); - self.done_one = current_start.is_none(); - self.skip = current_start.map_or(0, |(index, _)| index + 1); - } - - // If we've already done the single connected, then go through looking at multi connected - if current_start.is_none() { - current_start = self.points.iter().enumerate().skip(self.skip).find(|(_, val)| val.connected() > 0); - self.skip = current_start.map_or(self.points.len(), |(index, _)| index); - } - - // If there is no starting point, exit - let current_start = current_start?.0; - - // There will always be at least one segment connected to this one - let mut point_index = current_start; - let mut manipulators_list = Vec::new(); - let mut in_handle = None; - let mut closed = false; - loop { - let Some(val) = self.points[point_index].take_first() else { - // Dead end - manipulators_list.push(ManipulatorGroup { - anchor: self.vector.point_domain.positions()[point_index], - in_handle, - out_handle: None, - id: self.vector.point_domain.ids()[point_index], - }); - - break; - }; - - let mut handles = self.vector.segment_domain.handles()[val.segment_index]; - if val.start_from_end { - handles = handles.reversed(); - } - let next_point_index = if val.start_from_end { - self.vector.segment_domain.start_point()[val.segment_index] - } else { - self.vector.segment_domain.end_point()[val.segment_index] - }; - manipulators_list.push(ManipulatorGroup { - anchor: self.vector.point_domain.positions()[point_index], - in_handle, - out_handle: handles.start(), - id: self.vector.point_domain.ids()[point_index], - }); - - in_handle = handles.end(); - - point_index = next_point_index; - self.points[next_point_index].take_eq(val.flipped()); - if next_point_index == current_start { - closed = true; - manipulators_list[0].in_handle = in_handle; - break; + reversals.push(loop_sides); } } - Some((manipulators_list, closed)) + let reversed: HashSet<(u32, u32)> = reversals + .into_iter() + .flatten() + .map(|&(segment_index, _)| (graph.spans[segment_index].path, graph.spans[segment_index].index)) + .collect(); + if !reversed.is_empty() { + *paths = reverse_spans_in_place(paths, &reversed); + } } } -/// Represents the conversion of IDs used when concatenating vector paths with conflicting IDs. -pub(crate) struct IdMap { - pub point_offset: usize, - pub point_map: HashMap, - pub segment_map: HashMap, +/// Reweaves the paths with the given `(path, span)` pairs reversed. Each reversed span keeps its place in span +/// order, which decides how subpaths are walked, so it becomes a path of its own among the pieces left around it. +fn reverse_spans_in_place(paths: &List, reversed: &HashSet<(u32, u32)>) -> List { + let mut rewoven = List::new(); + + for path_index in 0..paths.len() { + let Some(template) = paths.clone_item(path_index) else { continue }; + let curve_type = curve_type_at(paths, path_index); + let span_count = template.element().segment_count(curve_type); + let is_reversed = |span: usize| reversed.contains(&(path_index as u32, span as u32)); + + if !(0..span_count).any(is_reversed) { + rewoven.push(template); + continue; + } + + let path = template.element(); + let mut push_piece = |piece: Path| rewoven.push(Item::from_parts(piece, template.attributes().clone())); + + let mut kept_from = 0; + for span in (0..span_count).filter(|&span| is_reversed(span)) { + if kept_from < span { + push_piece(path.clone_span_range(curve_type, kept_from, span)); + } + + let mut flipped = path.clone_span_range(curve_type, span, span + 1); + flipped.reverse(curve_type); + push_piece(flipped); + + kept_from = span + 1; + } + if kept_from < span_count { + push_piece(path.clone_span_range(curve_type, kept_from, span_count)); + } + } + + rewoven } #[cfg(test)] mod tests { use super::*; + use crate::vector::path::CurveType; + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, Item}; use kurbo::Shape; - fn build_vector(points: &[DVec2], segments: &[(usize, usize)]) -> Vector { + fn build_vector(points: &[DVec2], segments: &[(usize, usize)]) -> (Vector, List) { let mut vector = Vector::default(); let mut point_id = PointId::ZERO; - for &position in points { - vector.point_domain.push(point_id.next_id(), position); + for (index, &position) in points.iter().enumerate() { + vector.0.push(Item::new_from_element(position)); + vector.0.set_attribute(ATTR_ID, index, point_id.next_id()); } + + let mut paths = List::new(); let mut segment_id = SegmentId::ZERO; for &(start, end) in segments { - vector.segment_domain.push(segment_id.next_id(), start, end, BezierHandles::Linear); + let mut path = Path::from_references([start as u32, end as u32]); + path.0.set_attribute(ATTR_ID, 0, segment_id.next_id()); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); } - vector + + (vector, paths) + } + + // A morph pairs manipulators by position, so a loop's walk is fixed: from its lowest anchor, along the earliest span there + #[test] + fn a_closed_loop_walks_from_its_lowest_anchor_along_its_earliest_span() { + let (vector, mut paths) = build_vector(&[DVec2::new(0., 10.), DVec2::new(0., 0.), DVec2::new(10., 0.)], &[]); + + // The loop weaves 1 to 2 to 0 and back, so the earliest span at anchor 0 arrives there and is crossed backwards + let mut path = Path::from_references([1, 2, 0, 1]); + let mut segment_id = SegmentId::ZERO; + for span in 0..3 { + path.0.set_attribute(ATTR_ID, span, segment_id.next_id()); + } + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + + let (manipulators, closed) = vector.stroke_manipulator_groups(&paths).next().expect("the loop is one subpath"); + assert!(closed); + let anchors: Vec = manipulators.iter().map(|manipulator| manipulator.anchor).collect(); + assert_eq!(anchors, vec![DVec2::new(0., 10.), DVec2::new(10., 0.), DVec2::new(0., 0.)]); + } + + /// Manipulator groups and contours are two views of the same walk, so they must agree on order and + /// geometry. Click targets, the snapper's point recovery, and outline stitching all rely on it. + #[test] + fn manipulator_groups_and_contours_agree() { + use crate::vector::misc::bezpath_from_manipulator_groups; + use crate::vector::path::pool_and_paths_from_bezpath; + + // A closed contour woven before an open one, so path order alone would emit them the other way around + let mut source = kurbo::BezPath::new(); + source.move_to((0., 0.)); + source.line_to((10., 0.)); + source.line_to((10., 10.)); + source.close_path(); + source.move_to((20., 20.)); + source.line_to((30., 20.)); + source.curve_to((35., 25.), (35., 30.), (30., 35.)); + + let (pool, paths) = pool_and_paths_from_bezpath(&source); + let vector = Vector(pool); + + let groups: Vec<_> = vector.stroke_manipulator_groups(&paths).collect(); + let contours = vector.stroke_bezpath_iter(&paths).collect::>(); + assert_eq!(groups.len(), 2); + assert_eq!(contours.len(), 2); + + // Open runs lead, and each group re-emits its own contour + assert!(!groups[0].1, "the open run should be emitted first"); + assert!(groups[1].1, "the closed loop should follow"); + for (index, (manipulators, closed)) in groups.iter().enumerate() { + let rebuilt = bezpath_from_manipulator_groups(manipulators, *closed); + assert_eq!(rebuilt.elements(), contours[index].elements(), "group {index} should describe contour {index}"); + } + } + + /// Two paths welded head to head, so the subpath must walk the second one backward and still + /// emit anchors and geometry in travel order. + #[test] + fn subpath_walks_a_welded_path_backward() { + use crate::vector::misc::bezpath_from_manipulator_groups; + + let points = [DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(20., 0.)]; + let (vector, paths) = build_vector(&points, &[(0, 1), (2, 1)]); + + let contours = vector.stroke_bezpath_iter(&paths).collect::>(); + assert_eq!(contours.len(), 1, "the shared endpoint welds both paths into one contour"); + + let groups: Vec<_> = vector.stroke_manipulator_groups(&paths).collect(); + assert_eq!(groups.len(), 1); + let (manipulators, closed) = &groups[0]; + assert!(!closed); + assert_eq!(manipulators.iter().map(|group| group.anchor).collect::>(), points.to_vec()); + + assert_eq!(bezpath_from_manipulator_groups(manipulators, *closed).elements(), contours[0].elements()); } /// Square wound positively with a reverse-wound triangle welded to its corner: @@ -1438,10 +1047,10 @@ mod tests { DVec2::new(4., 2.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 4), (4, 5), (5, 0)]; - let vector = build_vector(&points, &segments); - assert!(vector.is_branching()); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.is_branching(&paths)); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 1); assert_ne!(faces[0].winding(kurbo::Point::new(8., 8.)), 0, "the region around the triangle should be filled"); assert_eq!(faces[0].winding(kurbo::Point::new(1.5, 1.5)), 0, "the reverse-wound triangle interior should stay empty"); @@ -1459,9 +1068,9 @@ mod tests { DVec2::new(4., 2.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 5), (5, 4), (4, 0)]; - let vector = build_vector(&points, &segments); + let (vector, paths) = build_vector(&points, &segments); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 2); assert!( faces.iter().any(|face| face.winding(kurbo::Point::new(1.5, 1.5)) != 0), @@ -1485,10 +1094,10 @@ mod tests { DVec2::new(0., 5.), ]; let segments = [(0, 4), (1, 4), (1, 5), (2, 5), (2, 6), (3, 6), (3, 7), (0, 7), (4, 5), (5, 6), (6, 7), (4, 7)]; - let vector = build_vector(&points, &segments); - assert!(vector.use_face_fill()); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.use_face_fill(&paths)); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 5); assert!(faces.iter().any(|face| face.winding(kurbo::Point::new(5., 5.)) != 0), "the center diamond cell should be filled"); assert!(faces.iter().any(|face| face.winding(kurbo::Point::new(1., 1.)) != 0), "the corner cells should be filled"); @@ -1510,10 +1119,10 @@ mod tests { DVec2::new(1., 5.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 8)]; - let vector = build_vector(&points, &segments); - assert!(vector.is_branching()); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.is_branching(&paths)); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 1); assert_ne!(faces[0].winding(kurbo::Point::new(1., 1.)), 0, "the ring around the hole should be filled"); assert_eq!(faces[0].winding(kurbo::Point::new(5., 5.)), 0, "the reverse-wound hole should stay empty"); @@ -1534,10 +1143,10 @@ mod tests { DVec2::new(1., 5.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 4), (0, 7)]; - let vector = build_vector(&points, &segments); - assert!(vector.is_branching()); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.is_branching(&paths)); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 1); assert_ne!(faces[0].winding(kurbo::Point::new(1., 1.)), 0, "the region around the hole should be filled"); assert_eq!(faces[0].winding(kurbo::Point::new(5., 7.5)), 0, "the snapped hole should stay empty"); @@ -1556,10 +1165,10 @@ mod tests { DVec2::new(20., 10.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (3, 4), (4, 5), (5, 2)]; - let vector = build_vector(&points, &segments); - assert!(vector.is_branching()); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.is_branching(&paths)); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 2); assert!(faces.iter().any(|face| face.winding(kurbo::Point::new(5., 5.)) != 0), "the reverse-drawn left cell should be filled"); assert!(faces.iter().any(|face| face.winding(kurbo::Point::new(15., 5.)) != 0), "the right cell should be filled"); @@ -1571,11 +1180,11 @@ mod tests { fn fully_enclosed_reverse_drawn_mesh_cell_still_fills() { let points = [DVec2::new(4., 3.), DVec2::new(6., 3.), DVec2::new(5., 5.), DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(5., 10.)]; let segments = [(0, 2), (2, 1), (1, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)]; - let vector = build_vector(&points, &segments); - assert!(vector.is_branching()); - assert!(drawn_signed_area(&vector, 0..3) < 0.); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.is_branching(&paths)); + assert!(drawn_signed_area(&vector, &paths, 0..3) < 0.); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 4); assert!(faces.iter().any(|face| face.winding(kurbo::Point::new(5., 4.)) != 0), "the enclosed hub cell should be filled"); } @@ -1595,11 +1204,11 @@ mod tests { DVec2::new(7., 3.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4)]; - let vector = build_vector(&points, &segments); - assert!(vector.is_branching()); - assert!(drawn_signed_area(&vector, 4..8) < 0.); + let (vector, paths) = build_vector(&points, &segments); + assert!(vector.is_branching(&paths)); + assert!(drawn_signed_area(&vector, &paths, 4..8) < 0.); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 1); assert_ne!(faces[0].winding(kurbo::Point::new(8., 5.)), 0, "the ring should be filled"); assert_eq!(faces[0].winding(kurbo::Point::new(5., 5.)), 0, "the bridged hole should stay empty"); @@ -1620,13 +1229,13 @@ mod tests { DVec2::new(3., 1.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (4, 5), (5, 6), (6, 7), (7, 4)]; - let mut vector = build_vector(&points, &segments); - assert!(drawn_signed_area(&vector, 5..9) < 0.); + let (mut vector, mut paths) = build_vector(&points, &segments); + assert!(drawn_signed_area(&vector, &paths, 5..9) < 0.); - vector.normalize_winding_directions(); - assert!(drawn_signed_area(&vector, 5..9) < 0., "normalization must not flip a hole nested under mesh structure"); + vector.normalize_winding_directions(&mut paths); + assert!(drawn_signed_area(&vector, &paths, 5..9) < 0., "normalization must not flip a hole nested under mesh structure"); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert_eq!(faces.len(), 2); assert!(faces.iter().all(|face| face.winding(kurbo::Point::new(2., 2.)) == 0), "the hole should stay empty"); assert!(faces.iter().any(|face| face.winding(kurbo::Point::new(0.5, 0.5)) != 0), "the triangle around the hole should be filled"); @@ -1639,19 +1248,20 @@ mod tests { fn spur_does_not_rescue_a_negative_space_loop() { let points = [DVec2::new(0., 0.), DVec2::new(0., 10.), DVec2::new(10., 10.), DVec2::new(10., 0.), DVec2::new(5., 5.)]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 4)]; - let vector = build_vector(&points, &segments); + let (vector, paths) = build_vector(&points, &segments); - let faces = vector.construct_faces(); + let faces = vector.construct_faces(&paths); assert!(faces.is_empty(), "a reverse-wound loop with an interior spur should produce no filled faces"); } /// Shoelace sum over the drawn direction of a range of line segments, so tests can read the /// stored winding directly rather than through a path walker that may pick its own direction. - fn drawn_signed_area(vector: &Vector, segment_range: std::ops::Range) -> f64 { + fn drawn_signed_area(vector: &Vector, paths: &List, segment_range: std::ops::Range) -> f64 { + let graph = SegmentGraph::new(vector, paths); segment_range .map(|segment_index| { - let start = vector.point_domain.positions()[vector.segment_domain.start_point()[segment_index]]; - let end = vector.point_domain.positions()[vector.segment_domain.end_point()[segment_index]]; + let start = vector.position(graph.start_point[segment_index]).unwrap(); + let end = vector.position(graph.end_point[segment_index]).unwrap(); start.perp_dot(end) }) .sum::() @@ -1661,11 +1271,11 @@ mod tests { #[test] fn normalization_flips_a_reverse_wound_loop() { let points = [DVec2::new(0., 0.), DVec2::new(0., 10.), DVec2::new(10., 10.), DVec2::new(10., 0.)]; - let mut vector = build_vector(&points, &[(0, 1), (1, 2), (2, 3), (3, 0)]); - assert!(drawn_signed_area(&vector, 0..4) < 0.); - vector.normalize_winding_directions(); + let (mut vector, mut paths) = build_vector(&points, &[(0, 1), (1, 2), (2, 3), (3, 0)]); + assert!(drawn_signed_area(&vector, &paths, 0..4) < 0.); + vector.normalize_winding_directions(&mut paths); - assert!(drawn_signed_area(&vector, 0..4) > 0., "a lone loop should wind positively after normalization"); + assert!(drawn_signed_area(&vector, &paths, 0..4) > 0., "a lone loop should wind positively after normalization"); } #[test] @@ -1681,11 +1291,11 @@ mod tests { DVec2::new(3., 7.), ]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4)]; - let mut vector = build_vector(&points, &segments); - vector.normalize_winding_directions(); + let (mut vector, mut paths) = build_vector(&points, &segments); + vector.normalize_winding_directions(&mut paths); - assert!(drawn_signed_area(&vector, 0..4) > 0., "the outer loop should wind positively"); - assert!(drawn_signed_area(&vector, 4..8) < 0., "the nested loop should wind negatively"); + assert!(drawn_signed_area(&vector, &paths, 0..4) > 0., "the outer loop should wind positively"); + assert!(drawn_signed_area(&vector, &paths, 4..8) < 0., "the nested loop should wind negatively"); } /// Loops passing through a branch point are welded or mesh structure whose drawn winding is meaningful, @@ -1694,14 +1304,15 @@ mod tests { fn normalization_leaves_branching_structure_untouched() { let points = [DVec2::new(0., 0.), DVec2::new(4., 0.), DVec2::new(2., 3.), DVec2::new(-4., 0.), DVec2::new(-2., -3.)]; let segments = [(0, 1), (1, 2), (2, 0), (0, 3), (3, 4), (4, 0)]; - let mut vector = build_vector(&points, &segments); + let (mut vector, mut paths) = build_vector(&points, &segments); - let starts_before = vector.segment_domain.start_point().to_vec(); - let ends_before = vector.segment_domain.end_point().to_vec(); - vector.normalize_winding_directions(); + let before = SegmentGraph::new(&vector, &paths); + let (starts_before, ends_before) = (before.start_point.clone(), before.end_point.clone()); + vector.normalize_winding_directions(&mut paths); - assert_eq!(vector.segment_domain.start_point(), starts_before.as_slice()); - assert_eq!(vector.segment_domain.end_point(), ends_before.as_slice()); + let after = SegmentGraph::new(&vector, &paths); + assert_eq!(after.start_point, starts_before); + assert_eq!(after.end_point, ends_before); } /// Pruning dead-end spurs first lets the loop they hang off still be found and flipped, @@ -1710,11 +1321,54 @@ mod tests { fn normalization_flips_a_loop_with_a_spur_attached() { let points = [DVec2::new(0., 0.), DVec2::new(0., 10.), DVec2::new(10., 10.), DVec2::new(10., 0.), DVec2::new(5., 5.)]; let segments = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 4)]; - let mut vector = build_vector(&points, &segments); - vector.normalize_winding_directions(); + let (mut vector, mut paths) = build_vector(&points, &segments); + vector.normalize_winding_directions(&mut paths); - assert_eq!(vector.segment_domain.start_point()[0], 1, "the reverse-wound loop should be flipped"); - assert_eq!(vector.segment_domain.start_point()[4], 0, "the spur should keep its drawn direction"); - assert_eq!(vector.segment_domain.end_point()[4], 4); + assert!(drawn_signed_area(&vector, &paths, 0..4) > 0., "the reverse-wound loop should be flipped"); + let graph = SegmentGraph::new(&vector, &paths); + let spur = graph.spans.iter().position(|span| span.path == 4).expect("the spur keeps its own path"); + assert_eq!((graph.start_point[spur], graph.end_point[spur]), (0, 4), "the spur should keep its drawn direction"); + } + + /// A loop covering only the middle spans of one longer path splits that path so just the loop reverses. + #[test] + fn normalization_splits_a_path_to_flip_its_inner_loop() { + let points = [ + DVec2::new(-5., 0.), + DVec2::new(0., 0.), + DVec2::new(0., 10.), + DVec2::new(10., 10.), + DVec2::new(10., 0.), + DVec2::new(15., 0.), + ]; + let mut path = Path::from_references([0, 1, 2, 3, 4, 1, 5]); + let mut segment_id = SegmentId::ZERO; + for span in 0..6 { + path.0.set_attribute(ATTR_ID, span, segment_id.next_id()); + } + + let mut vector = Vector::default(); + let mut point_id = PointId::ZERO; + for (index, &position) in points.iter().enumerate() { + vector.0.push(Item::new_from_element(position)); + vector.0.set_attribute(ATTR_ID, index, point_id.next_id()); + } + let mut paths = List::new(); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + + vector.normalize_winding_directions(&mut paths); + + // The reverse-wound inner loop (1 -> 2 -> 3 -> 4 -> 1) flips while both spur spans keep their direction + let graph = SegmentGraph::new(&vector, &paths); + let loop_area = (0..graph.len()) + .filter(|&index| graph.start_point[index] != 0 && graph.end_point[index] != 0 && graph.start_point[index] != 5 && graph.end_point[index] != 5) + .map(|index| { + let start = vector.position(graph.start_point[index]).unwrap(); + let end = vector.position(graph.end_point[index]).unwrap(); + start.perp_dot(end) + }) + .sum::() + / 2.; + assert!(loop_area > 0., "the inner loop should wind positively after normalization"); } } diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index 1fedf925ce..b90388f901 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -1,11 +1,11 @@ use super::*; -use crate::vector::algorithms::consts::CLOSE_POINT_TOLERANCE; -use crate::vector::misc::BezierHandles; -use crate::vector::misc::{HandleId, HandleType, point_to_dvec2, segment_to_handles}; +use crate::vector::flatten::WorkingVector; +use crate::vector::misc::{BezierHandles, HandleId, HandleType}; +use crate::vector::path::Path; +use core_types::list::List; use core_types::uuid::generate_uuid; use dyn_any::DynAny; use glam::DVec2; -use kurbo::{BezPath, ParamCurve, PathEl, Point}; use serde::de::{SeqAccess, Visitor}; use serde::ser::SerializeSeq; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -14,7 +14,7 @@ use std::fmt; use std::hash::BuildHasher; use std::hash::Hash; -/// Represents a procedural change to the [`PointDomain`] in [`Vector`]. +/// Represents a procedural change to the points of a [`Vector`]. #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub(crate) struct PointModification { @@ -26,25 +26,47 @@ pub(crate) struct PointModification { } impl PointModification { - /// Apply this modification to the specified [`PointDomain`]. - pub fn apply(&self, point_domain: &mut PointDomain, segment_domain: &mut SegmentDomain) { - point_domain.retain(segment_domain, |id| !self.remove.contains(id)); + /// Apply this modification to the working form's points. + fn apply(&self, working: &mut WorkingVector) { + // Remove points, remapping segment endpoints and leaving out-of-range markers on segments + // that referenced a removed point, for the segment pass to delete + let mut id_map = Vec::with_capacity(working.point_ids.len()); + let mut new_index = 0; + for id in &working.point_ids { + if !self.remove.contains(id) { + id_map.push(new_index); + new_index += 1; + } else { + id_map.push(usize::MAX); + } + } + let update_index = |index: &mut usize| { + if *index < id_map.len() { + *index = id_map[*index]; + } + }; + working.segment_start.iter_mut().for_each(update_index); + working.segment_end.iter_mut().for_each(update_index); - for (index, (id, position)) in point_domain.positions_mut().enumerate() { - let Some(&delta) = self.delta.get(&id) else { continue }; + let mut keep = working.point_ids.iter().map(|id| !self.remove.contains(id)); + working.point_positions.retain(|_| keep.next().unwrap_or_default()); + working.point_ids.retain(|id| !self.remove.contains(id)); + + for (index, id) in working.point_ids.iter().enumerate() { + let Some(&delta) = self.delta.get(id) else { continue }; if !delta.is_finite() { warn!("Invalid delta when applying a point modification"); continue; } - *position += delta; + working.point_positions[index] += delta; - for (_, handles, start, end) in segment_domain.handles_mut() { - if start == index { - handles.move_start(delta); + for segment_index in 0..working.segment_ids.len() { + if working.segment_start[segment_index] == index { + working.segment_handles[segment_index].move_start(delta); } - if end == index { - handles.move_end(delta); + if working.segment_end[segment_index] == index { + working.segment_handles[segment_index].move_end(delta); } } } @@ -56,16 +78,23 @@ impl PointModification { continue; } - point_domain.push(add_id, position); + #[cfg(debug_assertions)] + if working.point_ids.contains(&add_id) { + warn!("Tried to push a duplicate point to the working form"); + continue; + } + + working.point_ids.push(add_id); + working.point_positions.push(position); } } - /// Create a new modification that will convert an empty [`Vector`] into the target [`Vector`]. - pub fn create_from_vector(vector: &Vector) -> Self { + /// Create a new modification that will convert an empty [`Vector`] into the target working form. + fn create_from_working(working: &WorkingVector) -> Self { Self { - add: vector.point_domain.ids().to_vec(), + add: working.point_ids.clone(), remove: HashSet::new(), - delta: vector.point_domain.ids().iter().copied().zip(vector.point_domain.positions().iter().cloned()).collect(), + delta: working.point_ids.iter().copied().zip(working.point_positions.iter().copied()).collect(), } } @@ -81,7 +110,7 @@ impl PointModification { } } -/// Represents a procedural change to the [`SegmentDomain`] in [`Vector`]. +/// Represents a procedural change to the segments of a [`Vector`]. #[derive(Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub(crate) struct SegmentModification { @@ -99,44 +128,52 @@ pub(crate) struct SegmentModification { } impl SegmentModification { - /// Apply this modification to the specified [`SegmentDomain`]. - pub fn apply(&self, segment_domain: &mut SegmentDomain, point_domain: &PointDomain) { - segment_domain.retain(|id| !self.remove.contains(id), point_domain.ids().len()); + /// Apply this modification to the working form's segments. + fn apply(&self, working: &mut WorkingVector) { + // Remove the deleted segments, plus any segment left referencing a removed point + let point_count = working.point_ids.len(); + let keep: Vec = (0..working.segment_ids.len()) + .map(|index| !self.remove.contains(&working.segment_ids[index]) && working.segment_start[index] < point_count && working.segment_end[index] < point_count) + .collect(); + let mut keep_iter = keep.iter(); + working.segment_start.retain(|_| *keep_iter.next().unwrap_or(&false)); + let mut keep_iter = keep.iter(); + working.segment_end.retain(|_| *keep_iter.next().unwrap_or(&false)); + let mut keep_iter = keep.iter(); + working.segment_handles.retain(|_| *keep_iter.next().unwrap_or(&false)); + let mut keep_iter = keep.iter(); + working.segment_ids.retain(|_| *keep_iter.next().unwrap_or(&false)); - for (id, point) in segment_domain.start_point_mut() { - let Some(&new) = self.start_point.get(&id) else { continue }; - let Some(index) = point_domain.resolve_id(new) else { - warn!("Invalid start ID when applying a segment modification"); - continue; - }; - - *point = index; + for (index, id) in working.segment_ids.iter().enumerate() { + if let Some(&new) = self.start_point.get(id) { + match working.resolve_id(new) { + Some(point) => working.segment_start[index] = point, + None => warn!("Invalid start ID when applying a segment modification"), + } + } + if let Some(&new) = self.end_point.get(id) { + match working.resolve_id(new) { + Some(point) => working.segment_end[index] = point, + None => warn!("Invalid end ID when applying a segment modification"), + } + } } - for (id, point) in segment_domain.end_point_mut() { - let Some(&new) = self.end_point.get(&id) else { continue }; - let Some(index) = point_domain.resolve_id(new) else { - warn!("Invalid end ID when applying a segment modification"); - continue; - }; - - *point = index; - } - - for (id, handles, start, end) in segment_domain.handles_mut() { - let Some(&start) = point_domain.positions().get(start) else { continue }; - let Some(&end) = point_domain.positions().get(end) else { continue }; + for (index, id) in working.segment_ids.iter().enumerate() { + let Some(&start) = working.point_positions.get(working.segment_start[index]) else { continue }; + let Some(&end) = working.point_positions.get(working.segment_end[index]) else { continue }; // Compute the actual start and end position based on the offset from the anchor - let start = self.handle_primary.get(&id).copied().map(|handle| handle.map(|handle| handle + start)); - let end = self.handle_end.get(&id).copied().map(|handle| handle.map(|handle| handle + end)); + let new_start = self.handle_primary.get(id).copied().map(|handle| handle.map(|handle| handle + start)); + let new_end = self.handle_end.get(id).copied().map(|handle| handle.map(|handle| handle + end)); - if !start.unwrap_or_default().is_none_or(|start| start.is_finite()) || !end.unwrap_or_default().is_none_or(|end| end.is_finite()) { + if !new_start.unwrap_or_default().is_none_or(|start| start.is_finite()) || !new_end.unwrap_or_default().is_none_or(|end| end.is_finite()) { warn!("Invalid handles when applying a segment modification"); continue; } - match (start, end) { + let handles = &mut working.segment_handles[index]; + match (new_start, new_end) { // The new handles are fully specified by the modification (Some(Some(handle_start)), Some(Some(handle_end))) => *handles = BezierHandles::Cubic { handle_start, handle_end }, (Some(Some(handle)), Some(None)) | (Some(None), Some(Some(handle))) => *handles = BezierHandles::Quadratic { handle }, @@ -172,17 +209,17 @@ impl SegmentModification { let Some(&handle_start) = self.handle_primary.get(&add_id) else { continue }; let Some(&handle_end) = self.handle_end.get(&add_id) else { continue }; - let Some(start_index) = point_domain.resolve_id(start) else { + let Some(start_index) = working.resolve_id(start) else { warn!("invalid start id: {start:#?}"); continue; }; - let Some(end_index) = point_domain.resolve_id(end) else { + let Some(end_index) = working.resolve_id(end) else { warn!("invalid end id: {end:#?}"); continue; }; - let start_position = point_domain.positions()[start_index]; - let end_position = point_domain.positions()[end_index]; + let start_position = working.point_positions[start_index]; + let end_position = working.point_positions[end_index]; let handles = match (handle_start, handle_end) { (Some(handle_start), Some(handle_end)) => BezierHandles::Cubic { handle_start: handle_start + start_position, @@ -197,34 +234,35 @@ impl SegmentModification { continue; } - segment_domain.push(add_id, start_index, end_index, handles); + working.segment_ids.push(add_id); + working.segment_start.push(start_index); + working.segment_end.push(end_index); + working.segment_handles.push(handles); } - assert!( - segment_domain.start_point().iter().all(|&index| index < point_domain.ids().len()), - "index should be in range {segment_domain:#?}" - ); - assert!( - segment_domain.end_point().iter().all(|&index| index < point_domain.ids().len()), - "index should be in range {segment_domain:#?}" - ); + assert!(working.segment_start.iter().all(|&index| index < working.point_ids.len()), "index should be in range"); + assert!(working.segment_end.iter().all(|&index| index < working.point_ids.len()), "index should be in range"); } - /// Create a new modification that will convert an empty [`Vector`] into the target [`Vector`]. - pub fn create_from_vector(vector: &Vector) -> Self { - let point_id = |(&segment, &index)| (segment, vector.point_domain.ids()[index]); + /// Create a new modification that will convert an empty [`Vector`] into the target working form. + fn create_from_working(working: &WorkingVector) -> Self { + let point_id = |(&segment, &index): (&SegmentId, &usize)| (segment, working.point_ids[index]); Self { - add: vector.segment_domain.ids().to_vec(), + add: working.segment_ids.clone(), remove: HashSet::new(), - start_point: vector.segment_domain.ids().iter().zip(vector.segment_domain.start_point()).map(point_id).collect(), - end_point: vector.segment_domain.ids().iter().zip(vector.segment_domain.end_point()).map(point_id).collect(), - handle_primary: vector - .segment_iter() - .map(|(id, segment, _, _)| (id, segment_to_handles(&segment).start().map(|handle| handle - point_to_dvec2(segment.start())))) + start_point: working.segment_ids.iter().zip(&working.segment_start).map(point_id).collect(), + end_point: working.segment_ids.iter().zip(&working.segment_end).map(point_id).collect(), + handle_primary: working + .segment_ids + .iter() + .enumerate() + .map(|(index, &id)| (id, working.segment_handles[index].start().map(|handle| handle - working.point_positions[working.segment_start[index]]))) .collect(), - handle_end: vector - .segment_iter() - .map(|(id, segment, _, _)| (id, segment_to_handles(&segment).end().map(|handle| handle - point_to_dvec2(segment.end())))) + handle_end: working + .segment_ids + .iter() + .enumerate() + .map(|(index, &id)| (id, working.segment_handles[index].end().map(|handle| handle - working.point_positions[working.segment_end[index]]))) .collect(), } } @@ -390,21 +428,34 @@ impl VectorModification { if lines.is_empty() { "None".to_string() } else { lines.join("\n") } } - /// Apply this modification to the specified [`Vector`]. - pub fn apply(&self, vector: &mut Vector) { - self.points.apply(&mut vector.point_domain, &mut vector.segment_domain); - self.segments.apply(&mut vector.segment_domain, &vector.point_domain); + /// Whether this modification changes nothing at all. + pub fn is_empty(&self) -> bool { + self.points == PointModification::default() && self.segments == SegmentModification::default() && self.add_g1_continuous.is_empty() && self.remove_g1_continuous.is_empty() + } - let valid = |val: &[HandleId; 2]| vector.segment_domain.ids().contains(&val[0].segment) && vector.segment_domain.ids().contains(&val[1].segment); - vector - .colinear_manipulators + /// Apply this modification to the specified [`Vector`] and its paths. + pub fn apply(&self, vector: &mut Vector, paths: &mut List) { + // An untouched vector keeps its incoming path structure instead of being flattened and rewoven + if self.is_empty() { + return; + } + + let mut working = WorkingVector::flatten(vector, paths); + self.points.apply(&mut working); + self.segments.apply(&mut working); + + let valid = |val: &[HandleId; 2]| working.segment_ids.contains(&val[0].segment) && working.segment_ids.contains(&val[1].segment); + working + .colinear .retain(|val| !self.remove_g1_continuous.contains(val) && !self.remove_g1_continuous.contains(&[val[1], val[0]]) && valid(val)); for handles in &self.add_g1_continuous { - if !vector.colinear_manipulators.iter().any(|test| test == handles || test == &[handles[1], handles[0]]) && valid(handles) { - vector.colinear_manipulators.push(*handles); + if !working.colinear.iter().any(|test| test == handles || test == &[handles[1], handles[0]]) && valid(handles) { + working.colinear.push(*handles); } } + + working.reweave(vector, paths); } /// Add a [`VectorModificationType`] to this modification. @@ -469,11 +520,12 @@ impl VectorModification { } /// Create a new modification that will convert an empty [`Vector`] into the target [`Vector`]. - pub fn create_from_vector(vector: &Vector) -> Self { + pub fn create_from_vector(vector: &Vector, paths: &List) -> Self { + let working = WorkingVector::flatten(vector, paths); Self { - points: PointModification::create_from_vector(vector), - segments: SegmentModification::create_from_vector(vector), - add_g1_continuous: vector.colinear_manipulators.iter().copied().collect(), + points: PointModification::create_from_working(&working), + segments: SegmentModification::create_from_working(&working), + add_g1_continuous: working.colinear.iter().copied().collect(), remove_g1_continuous: HashSet::new(), } } @@ -588,147 +640,6 @@ where deserializer.deserialize_seq(visitor) } -pub(crate) struct AppendBezpath<'a> { - first_point: Option, - last_point: Option, - first_point_index: Option, - last_point_index: Option, - point_id: PointId, - segment_id: SegmentId, - vector: &'a mut Vector, -} - -impl<'a> AppendBezpath<'a> { - fn new(vector: &'a mut Vector) -> Self { - Self { - first_point: None, - last_point: None, - first_point_index: None, - last_point_index: None, - point_id: vector.point_domain.next_id(), - segment_id: vector.segment_domain.next_id(), - vector, - } - } - - fn append_segment_and_close_path(&mut self, point: Point, handle: BezierHandles) { - // A path's final point may return to approximately (but not bit-exactly) its start before closing, e.g. a contour - // produced by Kurbo's path offsetting. Treat a near-coincident final point as already on the start so we don't - // introduce a redundant duplicate anchor and a zero-length closing segment. - let endpoints_coincide = (self.first_point.unwrap() - point).hypot2() <= CLOSE_POINT_TOLERANCE * CLOSE_POINT_TOLERANCE; - let handle = if !endpoints_coincide { - // If the first point is not the same as the last point of the path then we append the segment - // with given handle and point and then close the path with linear handle. - self.append_segment(point, handle); - BezierHandles::Linear - } else { - // if the endpoints are the same then we close the path with given handle. - handle - }; - - // Create a new segment. - let next_segment_id = self.segment_id.next_id(); - self.vector - .segment_domain - .push(next_segment_id, self.last_point_index.unwrap(), self.first_point_index.unwrap(), handle); - } - - fn append_segment(&mut self, end_point: Point, handle: BezierHandles) { - // Append the point. - let next_point_index = self.vector.point_domain.ids().len(); - let next_point_id = self.point_id.next_id(); - - self.vector.point_domain.push(next_point_id, point_to_dvec2(end_point)); - - // Append the segment. - let next_segment_id = self.segment_id.next_id(); - self.vector.segment_domain.push(next_segment_id, self.last_point_index.unwrap(), next_point_index, handle); - - // Update the states. - self.last_point = Some(end_point); - self.last_point_index = Some(next_point_index); - } - - fn append_first_point(&mut self, point: Point) { - self.first_point = Some(point); - self.last_point = Some(point); - - // Append the first point. - let next_point_index = self.vector.point_domain.ids().len(); - self.vector.point_domain.push(self.point_id.next_id(), point_to_dvec2(point)); - - // Update the state. - self.first_point_index = Some(next_point_index); - self.last_point_index = Some(next_point_index); - } - - fn reset(&mut self) { - self.first_point = None; - self.last_point = None; - self.first_point_index = None; - self.last_point_index = None; - } - - pub fn append_bezpath(vector: &'a mut Vector, bezpath: BezPath) { - let mut this = Self::new(vector); - let mut elements = bezpath.elements().iter().peekable(); - - while let Some(element) = elements.next() { - let close_path = elements.peek().is_some_and(|elm| **elm == PathEl::ClosePath); - - match *element { - PathEl::MoveTo(point) => { - // Clear any segment state left by a preceding open contour so its segments don't leak into this contour's region - this.reset(); - this.append_first_point(point); - } - PathEl::LineTo(point) => { - let handle = BezierHandles::Linear; - if close_path { - this.append_segment_and_close_path(point, handle); - } else { - this.append_segment(point, handle); - } - } - PathEl::QuadTo(point, point1) => { - let handle = BezierHandles::Quadratic { handle: point_to_dvec2(point) }; - if close_path { - this.append_segment_and_close_path(point1, handle); - } else { - this.append_segment(point1, handle); - } - } - PathEl::CurveTo(point, point1, point2) => { - let handle = BezierHandles::Cubic { - handle_start: point_to_dvec2(point), - handle_end: point_to_dvec2(point1), - }; - - if close_path { - this.append_segment_and_close_path(point2, handle); - } else { - this.append_segment(point2, handle); - } - } - PathEl::ClosePath => { - // Already handled using `append_segment_and_close_path()` hence we reset state and continue. - this.reset(); - } - } - } - } -} - -pub trait VectorExt { - fn append_bezpath(&mut self, bezpath: BezPath); -} - -impl VectorExt for Vector { - fn append_bezpath(&mut self, bezpath: BezPath) { - AppendBezpath::append_bezpath(self, bezpath); - } -} - pub trait HandleExt { /// Set the handle's position relative to the anchor which is the start anchor for the primary handle and end anchor for the end handle. #[must_use] @@ -750,18 +661,33 @@ mod tests { use super::*; use crate::vector::algorithms::shapes::{ellipse_bezpath, rectangle_bezpath}; - use kurbo::{PathSeg, QuadBez}; + use kurbo::{BezPath, PathSeg, Point, QuadBez}; + + fn anchor_id(vector: &Vector, paths: &List, anchor_index: usize) -> PointId { + vector.anchor_points(paths).nth(anchor_index).expect("anchor exists") + } + + fn anchor_position(vector: &Vector, paths: &List, anchor_index: usize) -> DVec2 { + let id = anchor_id(vector, paths, anchor_index); + vector.position(vector.index_of_point_id(id).unwrap() as usize).unwrap() + } #[test] fn modify_new() { - let mut vector = Vector::from_bezpath(ellipse_bezpath(DVec2::ZERO, DVec2::ONE)); - vector.append_bezpath(rectangle_bezpath(DVec2::NEG_ONE, DVec2::ZERO)); + let (mut vector, mut paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::ZERO, DVec2::ONE)); + vector.append_bezpath(&mut paths, &rectangle_bezpath(DVec2::NEG_ONE, DVec2::ZERO)); - let modify = VectorModification::create_from_vector(&vector); + let modify = VectorModification::create_from_vector(&vector, &paths); - let mut new = Vector::default(); - modify.apply(&mut new); - assert_eq!(vector, new); + let (mut new, mut new_paths) = (Vector::default(), List::new()); + modify.apply(&mut new, &mut new_paths); + + assert_eq!( + vector.segment_iter(&paths).collect::>(), + new.segment_iter(&new_paths).collect::>(), + "replaying the capture should rebuild every segment" + ); + assert_eq!(vector.anchor_points(&paths).collect::>(), new.anchor_points(&new_paths).collect::>()); } #[test] @@ -771,34 +697,34 @@ mod tests { open_quads.quad_to(Point::new(5., 10.), Point::new(10., 0.)); open_quads.quad_to(Point::new(15., 10.), Point::new(20., 0.)); - let mut vector = Vector::from_bezpath(ellipse_bezpath(DVec2::ZERO, DVec2::ONE)); - vector.append_bezpath(rectangle_bezpath(DVec2::NEG_ONE, DVec2::ZERO)); - vector.append_bezpath(open_quads); + let (mut vector, mut paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::ZERO, DVec2::ONE)); + vector.append_bezpath(&mut paths, &rectangle_bezpath(DVec2::NEG_ONE, DVec2::ZERO)); + vector.append_bezpath(&mut paths, &open_quads); - let mut modify_new = VectorModification::create_from_vector(&vector); + let mut modify_new = VectorModification::create_from_vector(&vector, &paths); let mut modify_original = VectorModification::default(); for modification in [&mut modify_new, &mut modify_original] { - let point = vector.point_domain.ids()[0]; + let point = anchor_id(&vector, &paths, 0); modification.modify(&VectorModificationType::ApplyPointDelta { point, delta: DVec2::X * 0.5 }); - let point = vector.point_domain.ids()[9]; + let point = anchor_id(&vector, &paths, 9); modification.modify(&VectorModificationType::ApplyPointDelta { point, delta: DVec2::X }); } - let mut new = Vector::default(); - modify_new.apply(&mut new); + let (mut new, mut new_paths) = (Vector::default(), List::new()); + modify_new.apply(&mut new, &mut new_paths); - modify_original.apply(&mut vector); + modify_original.apply(&mut vector, &mut paths); - assert_eq!(vector, new); - assert_eq!(vector.point_domain.positions()[0], DVec2::X); - assert_eq!(vector.point_domain.positions()[9], DVec2::new(11., 0.)); + assert_eq!(vector.segment_iter(&paths).collect::>(), new.segment_iter(&new_paths).collect::>()); + assert_eq!(anchor_position(&vector, &paths, 0), DVec2::X); + assert_eq!(anchor_position(&vector, &paths, 9), DVec2::new(11., 0.)); assert_eq!( - vector.segment_iter().nth(8).unwrap().1, + vector.segment_iter(&paths).nth(8).unwrap().1, PathSeg::Quad(QuadBez::new(Point::new(0., 0.), Point::new(5., 10.), Point::new(11., 0.))) ); assert_eq!( - vector.segment_iter().nth(9).unwrap().1, + vector.segment_iter(&paths).nth(9).unwrap().1, PathSeg::Quad(QuadBez::new(Point::new(11., 0.), Point::new(16., 10.), Point::new(20., 0.))) ); } diff --git a/node-graph/libraries/vector-types/src/vector/vector_types.rs b/node-graph/libraries/vector-types/src/vector/vector_types.rs index 62367f05b6..86f51aa7b9 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_types.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_types.rs @@ -1,55 +1,29 @@ -use super::misc::dvec2_to_point; +use super::addressing; +use super::connectivity::Connectivity; +use super::contour::{contours, subpaths}; +use super::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; +use super::path::{CurveType, Path, append_bezpath, curve_type_at, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path}; use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin}; -use super::vector_attributes::*; -use crate::vector::misc::{BezierHandles, ManipulatorGroup}; -use crate::vector::misc::{HandleId, ManipulatorPointId}; -use crate::vector::vector_modification::VectorExt; +use super::vector_attributes::{PointId, SegmentId}; use core_types::bounds::{BoundingBox, RenderBoundingBox}; +use core_types::list::{ATTR_ID, ATTR_PATHS, ATTR_SMOOTH, Item, List}; use core_types::render_complexity::RenderComplexity; -use dyn_any::StaticType; +use dyn_any::DynAny; use glam::{DAffine2, DVec2}; -use kurbo::{Affine, BezPath, Rect, Shape}; -use std::collections::HashMap; +use kurbo::{Affine, BezPath, PathSeg, Rect, Shape}; -/// Represents vector graphics data, composed of Bézier curves in a path or mesh arrangement. -#[derive(Clone, Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Vector { - /// A list of all manipulator groups (referenced in `subpaths`) that have colinear handles (where they're locked at 180° angles from one another). - /// This gets read in `graph_operation_message_handler.rs` by calling `inputs.as_mut_slice()` (search for the string `"Shape does not have both `subpath` and `colinear_manipulators` inputs"` to find it). - pub colinear_manipulators: Vec<[HandleId; 2]>, - - pub point_domain: PointDomain, - pub segment_domain: SegmentDomain, -} -unsafe impl StaticType for Vector { - type Static = Self; -} - -impl Default for Vector { - fn default() -> Self { - Self { - colinear_manipulators: Vec::new(), - point_domain: PointDomain::new(), - segment_domain: SegmentDomain::new(), - } - } -} - -impl graphene_hash::CacheHash for Vector { - fn cache_hash(&self, state: &mut H) { - self.point_domain.cache_hash(state); - self.segment_domain.cache_hash(state); - self.colinear_manipulators.cache_hash(state); - } -} +/// Vector graphics: a pool of control points, anchors and handles alike, that paths weave into curves and meshes. +/// The weave rides the holder as a `List` under `ATTR_PATHS`, and per-point data such as the stable `ATTR_ID` rides this pool's own attributes. +#[derive(Clone, Debug, Default, PartialEq, graphene_hash::CacheHash, DynAny)] +pub struct Vector(pub List); impl core_types::ops::FromAnchorPosition for Vector { fn from_anchor_position(position: DVec2) -> Self { - let mut point_domain = PointDomain::new(); - point_domain.push(PointId::ZERO, position); + let mut pool = List::new_from_element(position); + // A lone anchor is named zero, the ID stored document edits address it by + pool.set_attribute(ATTR_ID, 0, PointId::ZERO); - Self { point_domain, ..Default::default() } + Self(pool) } } @@ -60,129 +34,246 @@ impl From for Vector { } } +// Handles are pool points, so transforming the pool carries the whole geometry impl core_types::transform::BakeTransform for Vector { - fn bake_transform(&mut self, transform: &glam::DAffine2) { - for (_, point) in self.point_domain.positions_mut() { - *point = transform.transform_point2(*point); - } - self.segment_domain.transform(*transform); + fn bake_transform(&mut self, transform: &DAffine2) { + self.transform(*transform); } } impl Vector { - /// Add a path of manipulator groups to this vector path. - pub fn append_manipulator_groups(&mut self, manipulator_groups: &[ManipulatorGroup], closed: bool, preserve_id: bool) { - let mut point_id = self.point_domain.next_id(); + /// The number of points in the pool, counting anchors and handles alike. + pub fn point_count(&self) -> usize { + self.0.len() + } - let handles = |a: &ManipulatorGroup, b: &ManipulatorGroup| match (a.out_handle, b.in_handle) { - (None, None) => BezierHandles::Linear, - (Some(handle), None) | (None, Some(handle)) => BezierHandles::Quadratic { handle }, - (Some(handle_start), Some(handle_end)) => BezierHandles::Cubic { handle_start, handle_end }, - }; - let mut segment_id = self.segment_domain.next_id(); - let mut last_point = None; - let mut first_point = None; + /// The pool position at the given index. + pub fn position(&self, index: usize) -> Option { + self.0.element(index).copied() + } - // Construct a bezier segment from the two manipulators on the subpath. - for pair in manipulator_groups.windows(2) { - let start = last_point.unwrap_or_else(|| { - let id = if preserve_id && !self.point_domain.ids().contains(&pair[0].id) { - pair[0].id - } else { - point_id.next_id() - }; - self.point_domain.push(id, pair[0].anchor); - self.point_domain.ids().len() - 1 - }); - first_point = Some(first_point.unwrap_or(start)); - let end = if preserve_id && !self.point_domain.ids().contains(&pair[1].id) { - pair[1].id + /// Every pool position in index order. + pub fn positions(&self) -> impl Iterator + '_ { + self.0.iter_element_values().copied() + } + + /// The stored ID of the pool point at the given index, `PointId::UNNAMED` for a handle. + pub fn point_id_at(&self, index: u32) -> Option { + addressing::point_id_at(&self.0, index) + } + + /// The pool index a point ID names, by scanning the ID attribute in O(points). + pub fn index_of_point_id(&self, point: PointId) -> Option { + if point == PointId::UNNAMED { + return None; + } + + addressing::index_of_point_id(&self.0, point) + } + + /// Applies an affine transform to every pool point. + pub fn transform(&mut self, transform: DAffine2) { + for position in self.0.iter_element_values_mut() { + *position = transform.transform_point2(*position); + } + } + + /// The reverse index answering which paths meet at each pool point, built in O(points + references). + pub fn connectivity(&self, paths: &List) -> Connectivity { + Connectivity::build(self.0.len(), paths) + } +} + +/// The ID continuing the pool's point ID sequence. +fn next_point_id(pool: &List) -> PointId { + let ids = pool.iter_attribute_values::(ATTR_ID); + ids.and_then(|ids| ids.copied().filter(|id| *id != PointId::UNNAMED).max()) + .map(|mut id| id.next_id()) + .unwrap_or(PointId::ZERO) +} + +/// The ID continuing the paths' segment ID sequence. +fn next_segment_id(paths: &List) -> SegmentId { + let ids = paths + .iter_element_values() + .filter_map(|path| path.0.iter_attribute_values::(ATTR_ID)) + .flatten() + .copied() + .max(); + + ids.map(|mut id| id.next_id()).unwrap_or(SegmentId::ZERO) +} + +impl Vector { + /// Names the anchors and spans appended since the given watermarks, continuing the ID sequences. + /// Handles take `PointId::UNNAMED`. + fn stamp_appended_ids(&mut self, paths: &mut List, first_new_point: usize, first_new_path: usize) { + let mut point_id = next_point_id(&self.0); + let mut segment_id = next_segment_id(paths); + + // Pool order is traversal order, so anchors and free points take IDs in the order they were drawn + let connectivity = Connectivity::build(self.0.len(), paths); + for index in first_new_point..self.0.len() { + let id = if self.is_handle_point(paths, &connectivity, index as u32) { + PointId::UNNAMED } else { point_id.next_id() }; - let end_index = self.point_domain.ids().len(); - self.point_domain.push(end, pair[1].anchor); - - let id = segment_id.next_id(); - self.segment_domain.push(id, start, end_index, handles(&pair[0], &pair[1])); - - last_point = Some(end_index); + self.0.set_attribute(ATTR_ID, index, id); } - if closed && let (Some(last), Some(first), Some(first_id), Some(last_id)) = (manipulator_groups.last(), manipulator_groups.first(), first_point, last_point) { - let id = segment_id.next_id(); - self.segment_domain.push(id, last_id, first_id, handles(last, first)); + for path_index in first_new_path..paths.len() { + let curve_type = curve_type_at(paths, path_index); + let Some(path) = paths.element_mut(path_index) else { continue }; + + for span in 0..path.segment_count(curve_type) { + path.0.set_attribute(ATTR_ID, span * curve_type.stride(), segment_id.next_id()); + } } } - /// Construct some new vector path from a single [`BezPath`] with an identity transform and black fill. - pub fn from_bezpath(bezpath: BezPath) -> Self { - let mut vector = Self::default(); - vector.append_bezpath(bezpath); - vector + /// Weaves a bezpath's contours onto this pool and the given paths, naming the new anchors and spans. + pub fn append_bezpath(&mut self, paths: &mut List, bezpath: &BezPath) { + let (first_new_point, first_new_path) = (self.0.len(), paths.len()); + append_bezpath(&mut self.0, paths, bezpath); + self.stamp_appended_ids(paths, first_new_point, first_new_path); } - /// Compute the bounding boxes of the bezpaths without any transform - pub fn bounding_box_rect(&self) -> Option { - self.bounding_box_with_transform_rect(DAffine2::IDENTITY) + /// Builds a fresh pool and paths from a single bezpath. + pub fn from_bezpath(bezpath: &BezPath) -> (Self, List) { + let (mut vector, mut paths) = (Self::default(), List::new()); + vector.append_bezpath(&mut paths, bezpath); + + (vector, paths) } - pub fn close_subpaths(&mut self) { - let segments_to_add: Vec<_> = self - .build_stroke_path_iter() - .filter(|(_, closed)| !closed) - .filter_map(|(manipulator_groups, _)| { - let (first, last) = manipulator_groups.first().zip(manipulator_groups.last())?; - let (start, end) = self.point_domain.resolve_id(first.id).zip(self.point_domain.resolve_id(last.id))?; - Some((start, end)) - }) - .collect(); + /// Builds a holder item from a single bezpath, its paths riding the item's attributes. + pub fn item_from_bezpath(bezpath: &BezPath) -> Item { + let (vector, paths) = Self::from_bezpath(bezpath); - for (start, end) in segments_to_add { - let segment_id = self.segment_domain.next_id().next_id(); - self.segment_domain.push(segment_id, start, end, BezierHandles::Linear); + Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths) + } +} + +impl Vector { + /// Every segment in span order as `(id, segment, start point ID, end point ID)`. + pub fn segment_iter<'a>(&'a self, paths: &'a List) -> impl Iterator + 'a { + addressing::spans(paths).filter_map(|span| { + let path = paths.element(span.path as usize)?; + let segment = path.segment(&self.0, curve_type_at(paths, span.path as usize), span.index as usize)?; + let id = addressing::segment_id_of(paths, span).unwrap_or_default(); + let (start, end) = addressing::span_endpoints(paths, span)?; + + Some((id, segment, self.point_id_at(start).unwrap_or_default(), self.point_id_at(end).unwrap_or_default())) + }) + } + + /// The segment a segment ID names, resolved against the pool. + pub fn segment_from_id(&self, paths: &List, id: SegmentId) -> Option { + let span = addressing::span_of_segment_id(paths, id)?; + paths.element(span.path as usize)?.segment(&self.0, curve_type_at(paths, span.path as usize), span.index as usize) + } + + /// The endpoints and geometry of the segment a segment ID names. + pub fn segment_points_from_id(&self, paths: &List, id: SegmentId) -> Option<(PointId, PointId, PathSeg)> { + let span = addressing::span_of_segment_id(paths, id)?; + let (start, end) = addressing::span_endpoints(paths, span)?; + let segment = paths.element(span.path as usize)?.segment(&self.0, curve_type_at(paths, span.path as usize), span.index as usize)?; + + Some((self.point_id_at(start).unwrap_or_default(), self.point_id_at(end).unwrap_or_default(), segment)) + } + + /// The segment a segment ID names, paired with the pool indices of its endpoints. + pub fn segment_with_pool_endpoints(&self, paths: &List, id: SegmentId) -> Option<(PathSeg, usize, usize)> { + let span = addressing::span_of_segment_id(paths, id)?; + let (start, end) = addressing::span_endpoints(paths, span)?; + let segment = paths.element(span.path as usize)?.segment(&self.0, curve_type_at(paths, span.path as usize), span.index as usize)?; + + Some((segment, start as usize, end as usize)) + } + + /// The ID of the point the segment starts at. + pub fn segment_start_from_id(&self, paths: &List, segment: SegmentId) -> Option { + let span = addressing::span_of_segment_id(paths, segment)?; + self.point_id_at(addressing::span_endpoints(paths, span)?.0) + } + + /// The ID of the point the segment ends at. + pub fn segment_end_from_id(&self, paths: &List, segment: SegmentId) -> Option { + let span = addressing::span_of_segment_id(paths, segment)?; + self.point_id_at(addressing::span_endpoints(paths, span)?.1) + } + + /// Each segment's start point ID, in span order. + pub fn start_point<'a>(&'a self, paths: &'a List) -> impl Iterator + 'a { + addressing::spans(paths).filter_map(|span| self.point_id_at(addressing::span_endpoints(paths, span)?.0)) + } + + /// Each segment's end point ID, in span order. + pub fn end_point<'a>(&'a self, paths: &'a List) -> impl Iterator + 'a { + addressing::spans(paths).filter_map(|span| self.point_id_at(addressing::span_endpoints(paths, span)?.1)) + } + + /// The point at the segment's other end from the given one. + pub fn other_point(&self, paths: &List, segment: SegmentId, current: PointId) -> Option { + let (start, end, _) = self.segment_points_from_id(paths, segment)?; + + match current { + _ if start == end => None, + point if point == start => Some(end), + point if point == end => Some(start), + _ => None, } } - /// Compute the bounding boxes of the subpaths without any transform - pub fn bounding_box(&self) -> Option<[DVec2; 2]> { - self.bounding_box_with_transform_rect(DAffine2::IDENTITY) + /// Emits the assembled contours, one bezpath per subpath walked. + pub fn stroke_bezpath_iter(&self, paths: &List) -> impl Iterator { + contours(&self.0, paths).into_iter() + } +} + +impl Vector { + /// Compute the bounding box of the contours without any transform. + pub fn bounding_box(&self, paths: &List) -> Option<[DVec2; 2]> { + self.bounding_box_with_transform(paths, DAffine2::IDENTITY) + } + + /// Compute the bounding box of the contours without any transform. + pub fn bounding_box_rect(&self, paths: &List) -> Option { + self.bounding_box_with_transform_rect(paths, DAffine2::IDENTITY) + } + + /// Compute the bounding box of the contours with the specified transform. + pub fn bounding_box_with_transform(&self, paths: &List, transform: DAffine2) -> Option<[DVec2; 2]> { + self.bounding_box_with_transform_rect(paths, transform) .map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)]) } - /// Compute the bounding boxes of the subpaths with the specified transform - pub fn bounding_box_with_transform(&self, transform: DAffine2) -> Option<[DVec2; 2]> { - self.bounding_box_with_transform_rect(transform) - .map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)]) - } - - /// Compute the bounding boxes of the bezpaths with the specified transform - fn bounding_box_with_transform_rect(&self, transform: DAffine2) -> Option { - let combine = |r1: Rect, r2: Rect| r1.union(r2); - self.stroke_bezpath_iter() + fn bounding_box_with_transform_rect(&self, paths: &List, transform: DAffine2) -> Option { + self.stroke_bezpath_iter(paths) .map(|mut bezpath| { bezpath.apply_affine(Affine::new(transform.to_cols_array())); bezpath.bounding_box() }) - .reduce(combine) + .reduce(|r1, r2| r1.union(r2)) } /// Tight bounding box in the supplied transform space, including the actual rendered stroke geometry - /// (caps, joins, miter extensions, dashes). Runs `kurbo::stroke` on each subpath and unions the + /// (caps, joins, miter extensions, dashes). Runs `kurbo::stroke` on each contour and unions the /// resulting fills' bounding boxes. /// - /// Kurbo doesn't natively support stroke alignment — that's a renderer-side compositing trick that + /// Kurbo doesn't natively support stroke alignment, a renderer-side compositing trick that /// only applies to closed paths. For closed paths with non-Center align, we use the `effective_width` /// identity (`Inside` = 0, `Outside` = 2×weight): the renderer masks half of a centered double-width /// stroke, so its AABB matches the unmasked centered stroke's. For open paths the renderer always /// draws a centered `weight`-wide stroke regardless of the align attribute, so we mirror that here. - pub fn stroke_inclusive_bounding_box_with_transform(&self, transform: DAffine2, stroke: Option<&Stroke>) -> Option<[DVec2; 2]> { - let path_bounds = self.bounding_box_with_transform(transform); + pub fn stroke_inclusive_bounding_box_with_transform(&self, paths: &List, transform: DAffine2, stroke: Option<&Stroke>) -> Option<[DVec2; 2]> { + let path_bounds = self.bounding_box_with_transform(paths, transform); let Some(stroke) = stroke else { return path_bounds }; - // Stroke alignment is only honored by the renderer when every subpath is closed; open paths fall + // Stroke alignment is only honored by the renderer when every contour is closed; open paths fall // back to drawing a Center-aligned `weight`-wide stroke. Match that behavior to keep bounds in sync. - let aligned_renders = stroke.align != StrokeAlign::Center && self.stroke_bezpath_iter().all(|path| matches!(path.elements().last(), Some(kurbo::PathEl::ClosePath))); + let aligned_renders = stroke.align != StrokeAlign::Center && self.stroke_bezpath_iter(paths).all(|path| matches!(path.elements().last(), Some(kurbo::PathEl::ClosePath))); let kurbo_width = if aligned_renders { stroke.effective_width() } else { stroke.weight }; // `Inside`-aligned strokes never expand beyond the path bounds; a zero-weight stroke is invisible if kurbo_width <= 0. { @@ -206,7 +297,7 @@ impl Vector { .with_dashes(stroke.dash_offset, stroke.dash_lengths.clone()) .with_miter_limit(stroke.join_miter_limit); let stroke_options = kurbo::StrokeOpts::default(); - // Same tolerance as `solidify_stroke` — balanced between performance and curve accuracy + // Same tolerance as `solidify_stroke`, balanced between performance and curve accuracy const STROKE_TOLERANCE: f64 = 0.25; let stroke_local = Affine::new(stroke.transform.to_cols_array()); @@ -214,7 +305,7 @@ impl Vector { let final_transform = Affine::new(transform.to_cols_array()); let stroke_bounds = self - .stroke_bezpath_iter() + .stroke_bezpath_iter(paths) .map(|mut bezpath| { // Match `solidify_stroke`'s pre/post-stroke transform pair so non-uniform `stroke.transform` // (e.g. resisting layer scale) is applied while kurbo strokes, then undone before placing the @@ -230,7 +321,7 @@ impl Vector { .reduce(|a, b| a.union(b)) .map(|rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)]); - // Union with the path bounds in case a degenerate subpath (e.g. a single point) produced no stroke geometry + // Union with the path bounds in case a degenerate contour (e.g. a single point) produced no stroke geometry match (path_bounds, stroke_bounds) { (Some([min_a, max_a]), Some([min_b, max_b])) => Some([min_a.min(min_b), max_a.max(max_b)]), (Some(b), None) | (None, Some(b)) => Some(b), @@ -241,8 +332,8 @@ impl Vector { /// Calculate the corners of the bounding box but with a nonzero size. /// /// If the layer bounds are `0` in either axis then they are changed to be `1`. - pub fn nonzero_bounding_box(&self) -> [DVec2; 2] { - let [bounds_min, mut bounds_max] = self.bounding_box().unwrap_or_default(); + pub fn nonzero_bounding_box(&self, paths: &List) -> [DVec2; 2] { + let [bounds_min, mut bounds_max] = self.bounding_box(paths).unwrap_or_default(); let bounds_size = bounds_max - bounds_min; if bounds_size.x < 1e-10 { @@ -255,97 +346,10 @@ impl Vector { [bounds_min, bounds_max] } - pub fn start_point(&self) -> impl Iterator + '_ { - self.segment_domain.start_point().iter().map(|&index| self.point_domain.ids()[index]) - } - - pub fn end_point(&self) -> impl Iterator + '_ { - self.segment_domain.end_point().iter().map(|&index| self.point_domain.ids()[index]) - } - - pub fn push(&mut self, id: SegmentId, start: PointId, end: PointId, handles: (Option, Option)) { - let [Some(start), Some(end)] = [start, end].map(|id| self.point_domain.resolve_id(id)) else { - return; - }; - let handles = match handles { - (None, None) => BezierHandles::Linear, - (None, Some(handle)) | (Some(handle), None) => BezierHandles::Quadratic { handle }, - (Some(handle_start), Some(handle_end)) => BezierHandles::Cubic { handle_start, handle_end }, - }; - self.segment_domain.push(id, start, end, handles) - } - - pub fn handles_mut(&mut self) -> impl Iterator { - self.segment_domain - .handles_mut() - .map(|(id, handles, start, end)| (id, handles, self.point_domain.ids()[start], self.point_domain.ids()[end])) - } - - pub fn segment_start_from_id(&self, segment: SegmentId) -> Option { - self.segment_domain.segment_start_from_id(segment).map(|index| self.point_domain.ids()[index]) - } - - pub fn segment_end_from_id(&self, segment: SegmentId) -> Option { - self.segment_domain.segment_end_from_id(segment).map(|index| self.point_domain.ids()[index]) - } - - /// Attempts to find another point in the segment that is not the one passed in. - pub fn other_point(&self, segment: SegmentId, current: PointId) -> Option { - let index = self.point_domain.resolve_id(current); - index.and_then(|index| self.segment_domain.other_point(segment, index)).map(|index| self.point_domain.ids()[index]) - } - - /// Gets all points connected to the current one but not including the current one. - pub fn connected_points(&self, current: PointId) -> impl Iterator + '_ { - let index = [self.point_domain.resolve_id(current)].into_iter().flatten(); - index.flat_map(|index| self.segment_domain.connected_points(index).map(|index| self.point_domain.ids()[index])) - } - - /// Returns the number of linear segments connected to the given point. - pub fn connected_linear_segments(&self, point_id: PointId) -> usize { - self.segment_iter() - .filter(|(_, segment, start, end)| (*start == point_id || *end == point_id) && matches!(segment, kurbo::PathSeg::Line(_))) - .count() - } - - /// Get an array slice of all segment IDs. - pub fn segment_ids(&self) -> &[SegmentId] { - self.segment_domain.ids() - } - - /// Enumerate all segments that start at the point. - pub fn start_connected(&self, point: PointId) -> impl Iterator + '_ { - let index = [self.point_domain.resolve_id(point)].into_iter().flatten(); - index.flat_map(|index| self.segment_domain.start_connected(index)) - } - - /// Enumerate all segments that end at the point. - pub fn end_connected(&self, point: PointId) -> impl Iterator + '_ { - let index = [self.point_domain.resolve_id(point)].into_iter().flatten(); - index.flat_map(|index| self.segment_domain.end_connected(index)) - } - - /// Enumerate all segments that start or end at a point, converting them to [`HandleId`s]. Note that the handles may not exist e.g. for a linear segment. - pub fn all_connected(&self, point: PointId) -> impl Iterator + '_ { - let index = [self.point_domain.resolve_id(point)].into_iter().flatten(); - index.flat_map(|index| self.segment_domain.all_connected(index)) - } - - /// Enumerate the number of segments connected to a point. If a segment starts and ends at a point then it is counted twice. - pub fn connected_count(&self, point: PointId) -> usize { - self.point_domain.resolve_id(point).map_or(0, |point| self.segment_domain.connected_count(point)) - } - - /// Enumerate the number of segments connected to a point. If a segment starts and ends at a point then it is counted twice. - pub fn any_connected(&self, point: PointId) -> bool { - self.point_domain.resolve_id(point).is_some_and(|point| self.segment_domain.any_connected(point)) - } - - pub fn check_point_inside_shape(&self, transform: DAffine2, point: DVec2) -> bool { + pub fn check_point_inside_shape(&self, paths: &List, transform: DAffine2, point: DVec2) -> bool { let number = self - .stroke_bezpath_iter() + .stroke_bezpath_iter(paths) .map(|mut bezpath| { - // TODO: apply transform to points instead of modifying the paths bezpath.apply_affine(Affine::new(transform.to_cols_array())); bezpath.close_path(); let bbox = bezpath.bounding_box(); @@ -358,110 +362,427 @@ impl Vector { // Non-zero fill rule number != 0 } +} - /// Iterator over all anchor points. - pub fn anchor_points(&self) -> impl Iterator + '_ { - self.point_domain.ids().iter().copied() +impl Vector { + /// Whether the pool point at the given index is a handle, referenced only between anchors. + pub(crate) fn is_handle_point(&self, paths: &List, connectivity: &Connectivity, index: u32) -> bool { + let references = connectivity.references(index); + + !references.is_empty() + && references + .iter() + .all(|reference| !matches!(paths.element(reference.path as usize), Some(path) if path.is_anchor_reference(reference.index as usize, curve_type_at(paths, reference.path as usize)))) } - /// Anchor points at the ends of open subpaths. These are points with exactly one connection by a segment to another anchor. - pub fn anchor_endpoints(&self) -> impl Iterator + '_ { - // O(points + segments): tally every point's connections in a single pass - let mut connected_counts = vec![0_usize; self.point_domain.ids().len()]; - for &point_index in self.segment_domain.start_point().iter().chain(self.segment_domain.end_point()) { - if let Some(count) = connected_counts.get_mut(point_index) { - *count += 1; + /// The pool indices of all anchor points and free points in pool order, skipping handles. + pub fn anchor_indices(&self, paths: &List) -> Vec { + let connectivity = self.connectivity(paths); + (0..self.0.len() as u32) + .filter(|&index| !self.is_handle_point(paths, &connectivity, index)) + .map(|index| index as usize) + .collect() + } + + /// The positions of all anchor points and free points in pool order, skipping handles. + pub fn anchor_positions(&self, paths: &List) -> Vec { + self.anchor_indices(paths).into_iter().filter_map(|index| self.position(index)).collect() + } + + /// Iterator over the IDs of all anchor points and free points, skipping handles. + pub fn anchor_points(&self, paths: &List) -> impl Iterator { + let connectivity = self.connectivity(paths); + let anchors: Vec<_> = (0..self.0.len() as u32) + .filter(|&index| !self.is_handle_point(paths, &connectivity, index)) + .filter_map(|index| self.point_id_at(index)) + .collect(); + + anchors.into_iter() + } + + /// Anchor points at the ends of open chains, where exactly one segment end meets the point. + pub fn anchor_endpoints(&self, paths: &List) -> impl Iterator { + let connectivity = self.connectivity(paths); + let endpoints: Vec<_> = (0..self.0.len() as u32) + .filter(|&index| connectivity.spokes(index, paths) == 1) + .filter_map(|index| self.point_id_at(index)) + .collect(); + + endpoints.into_iter() + } + + // Each per-point query below builds its own connectivity index, O(points + references) with two allocations. + // Callers looping over many points should hoist `connectivity()` and use `addressing` directly. + + /// Enumerate all segments that start at the point. + pub fn start_connected(&self, paths: &List, point: PointId) -> impl Iterator { + let connected = self + .index_of_point_id(point) + .map(|index| addressing::start_connected(index, paths, &self.connectivity(paths))) + .unwrap_or_default(); + + connected.into_iter() + } + + /// Enumerate all segments that end at the point. + pub fn end_connected(&self, paths: &List, point: PointId) -> impl Iterator { + let connected = self + .index_of_point_id(point) + .map(|index| addressing::end_connected(index, paths, &self.connectivity(paths))) + .unwrap_or_default(); + + connected.into_iter() + } + + /// Enumerate all segments that start or end at a point, converting them to [`HandleId`]s. Note that the handles may not exist e.g. for a linear segment. + pub fn all_connected(&self, paths: &List, point: PointId) -> impl Iterator { + let connected = self + .index_of_point_id(point) + .map(|index| addressing::all_connected(index, paths, &self.connectivity(paths))) + .unwrap_or_default(); + + connected.into_iter() + } + + /// The number of segment ends meeting at a point. A segment that starts and ends there is counted twice. + pub fn connected_count(&self, paths: &List, point: PointId) -> usize { + let Some(index) = self.index_of_point_id(point) else { return 0 }; + + self.connectivity(paths).spokes(index, paths) + } + + /// Whether any segment starts or ends at the point. + pub fn any_connected(&self, paths: &List, point: PointId) -> bool { + self.connected_count(paths, point) > 0 + } + + /// Gets all points connected to the current one but not including the current one. + pub fn connected_points(&self, paths: &List, current: PointId) -> impl Iterator { + let mut found = Vec::new(); + if let Some(index) = self.index_of_point_id(current) { + for (span, arriving) in addressing::spans_at(index, paths, &self.connectivity(paths)) { + let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; + if start == end { + continue; + } + + let other = if arriving { start } else { end }; + if let Some(id) = self.point_id_at(other) { + found.push(id); + } } } - self.anchor_points().zip(connected_counts).filter(|&(_, count)| count == 1).map(|(id, _)| id) + found.into_iter() } - /// Computes if all the connected handles are colinear for an anchor, or if that handle is colinear for a handle. - pub fn colinear(&self, point: ManipulatorPointId) -> bool { - let has_handle = |target| self.colinear_manipulators.iter().flatten().any(|&handle| handle == target); - match point { - ManipulatorPointId::Anchor(id) => { - self.start_connected(id).all(|segment| has_handle(HandleId::primary(segment))) && self.end_connected(id).all(|segment| has_handle(HandleId::end(segment))) - } - ManipulatorPointId::PrimaryHandle(segment) => has_handle(HandleId::primary(segment)), - ManipulatorPointId::EndHandle(segment) => has_handle(HandleId::end(segment)), - } - } - - pub fn other_colinear_handle(&self, handle: HandleId) -> Option { - let pair = self.colinear_manipulators.iter().find(|pair| pair.contains(&handle))?; - let other = pair.iter().copied().find(|&val| val != handle)?; - if handle.to_manipulator_point().get_anchor(self) == other.to_manipulator_point().get_anchor(self) { - Some(other) - } else { - None - } - } - - pub fn adjacent_segment(&self, manipulator_id: &ManipulatorPointId) -> Option<(PointId, SegmentId)> { - match manipulator_id { - ManipulatorPointId::PrimaryHandle(segment_id) => { - // For start handle, find segments ending at our start point - let (start_point_id, _, _) = self.segment_points_from_id(*segment_id)?; - let start_index = self.point_domain.resolve_id(start_point_id)?; - - self.segment_domain.end_connected(start_index).find(|&id| id != *segment_id).map(|id| (start_point_id, id)).or(self - .segment_domain - .start_connected(start_index) - .find(|&id| id != *segment_id) - .map(|id| (start_point_id, id))) - } - ManipulatorPointId::EndHandle(segment_id) => { - // For end handle, find segments starting at our end point - let (_, end_point_id, _) = self.segment_points_from_id(*segment_id)?; - let end_index = self.point_domain.resolve_id(end_point_id)?; - - self.segment_domain.start_connected(end_index).find(|&id| id != *segment_id).map(|id| (end_point_id, id)).or(self - .segment_domain - .end_connected(end_index) - .find(|&id| id != *segment_id) - .map(|id| (end_point_id, id))) - } - ManipulatorPointId::Anchor(_) => None, - } - } - - pub fn concat(&mut self, additional: &Self, transform_of_additional: DAffine2, collision_hash_seed: u64) { - let point_map = additional - .point_domain - .ids() - .iter() - .filter(|id| self.point_domain.ids().contains(id)) - .map(|&old| (old, old.generate_from_hash(collision_hash_seed))) - .collect::>(); - - let segment_map = additional - .segment_domain - .ids() - .iter() - .filter(|id| self.segment_domain.ids().contains(id)) - .map(|&old| (old, old.generate_from_hash(collision_hash_seed))) - .collect::>(); - - let id_map = IdMap { - point_offset: self.point_domain.ids().len(), - point_map, - segment_map, - }; - - self.point_domain.concat(&additional.point_domain, transform_of_additional, &id_map); - self.segment_domain.concat(&additional.segment_domain, transform_of_additional, &id_map); - - self.colinear_manipulators.extend(additional.colinear_manipulators.iter().copied()); + /// Returns the number of linear segments connected to the given point. + pub fn connected_linear_segments(&self, paths: &List, point_id: PointId) -> usize { + self.segment_iter(paths) + .filter(|(_, segment, start, end)| (*start == point_id || *end == point_id) && matches!(segment, PathSeg::Line(_))) + .count() } } -// The element sees only geometry; stroke inflation is applied at the row level by `vector_list_bounding_box` -// in graphic-types, which can read the appearance attribute the stroke parameters live on. +impl Vector { + /// Whether the junction at the given anchor keeps its tangent pair smooth, read from any of its occurrences. + fn smooth_at_anchor_index(&self, paths: &List, connectivity: &Connectivity, index: u32) -> bool { + connectivity.references(index).iter().any(|reference| { + let Some(path) = paths.element(reference.path as usize) else { return false }; + if !path.is_anchor_reference(reference.index as usize, curve_type_at(paths, reference.path as usize)) { + return false; + } + + path.0.attribute::(ATTR_SMOOTH, reference.index as usize).copied().unwrap_or_default() + }) + } + + /// Whether the anchor at the given pool index forms a smooth tangent pair, which needs exactly two + /// segment ends meeting there. A junction has no unambiguous pair to keep smooth. + fn pairs_smoothly(&self, paths: &List, connectivity: &Connectivity, index: u32) -> bool { + self.smooth_at_anchor_index(paths, connectivity, index) && connectivity.spokes(index, paths) == 2 + } + + /// Whether the anchor (or the handle's anchor) keeps a smooth tangent pair, which needs exactly two segment ends meeting there. + pub fn colinear(&self, paths: &List, point: ManipulatorPointId) -> bool { + let connectivity = self.connectivity(paths); + let handle_anchor_smooth = |segment: SegmentId, at_start: bool| { + let Some(span) = addressing::span_of_segment_id(paths, segment) else { return false }; + let Some((start, end)) = addressing::span_endpoints(paths, span) else { return false }; + + self.pairs_smoothly(paths, &connectivity, if at_start { start } else { end }) + }; + + match point { + ManipulatorPointId::Anchor(id) => match self.index_of_point_id(id) { + Some(index) => self.pairs_smoothly(paths, &connectivity, index), + None => false, + }, + ManipulatorPointId::PrimaryHandle(segment) => handle_anchor_smooth(segment, true), + ManipulatorPointId::EndHandle(segment) => handle_anchor_smooth(segment, false), + } + } + + /// Every G1 pair: the two facing handles at each smooth anchor where exactly two segment ends meet. + pub fn colinear_pairs(&self, paths: &List) -> Vec<[HandleId; 2]> { + let connectivity = self.connectivity(paths); + let mut pairs = Vec::new(); + + for index in 0..self.point_count() as u32 { + if connectivity.spokes(index, paths) != 2 || !self.smooth_at_anchor_index(paths, &connectivity, index) { + continue; + } + + let handles: Vec = addressing::spans_at(index, paths, &connectivity) + .into_iter() + .filter_map(|(span, arriving)| { + let segment = addressing::segment_id_of(paths, span)?; + Some(if arriving { HandleId::end(segment) } else { HandleId::primary(segment) }) + }) + .collect(); + if let [first, second] = handles.as_slice() { + pairs.push([*first, *second]); + } + } + + pairs + } + + /// The G1 pair the given handle belongs to, ordered with that handle first. + pub fn colinear_pair_containing(&self, paths: &List, handle: HandleId) -> Option<[HandleId; 2]> { + self.other_colinear_handle(paths, handle).map(|other| [handle, other]) + } + + /// The handle paired with the given one across their shared smooth anchor, where exactly two segment ends meet. + pub fn other_colinear_handle(&self, paths: &List, handle: HandleId) -> Option { + let span = addressing::span_of_segment_id(paths, handle.segment)?; + let (start, end) = addressing::span_endpoints(paths, span)?; + let anchor = if handle.ty == super::misc::HandleType::Primary { start } else { end }; + + let connectivity = self.connectivity(paths); + if !self.pairs_smoothly(paths, &connectivity, anchor) { + return None; + } + + addressing::spans_at(anchor, paths, &connectivity) + .into_iter() + .filter(|&(other, arriving)| (other, arriving) != (span, handle.ty != super::misc::HandleType::Primary)) + .find_map(|(other, arriving)| { + let segment = addressing::segment_id_of(paths, other)?; + Some(if arriving { HandleId::end(segment) } else { HandleId::primary(segment) }) + }) + } + + /// Sets whether the junction at the given anchor keeps its tangent pair smooth, written to every occurrence. + pub fn set_smooth(&mut self, paths: &mut List, point: PointId, smooth: bool) { + let Some(index) = self.index_of_point_id(point) else { return }; + + self.set_smooth_at_indices(paths, [index], smooth); + } + + /// Sets the smooth flag on many anchors at once, finding them in one pass over the pool's IDs. + pub fn set_smooth_points(&mut self, paths: &mut List, points: impl IntoIterator, smooth: bool) { + let points: std::collections::HashSet = points.into_iter().collect(); + let indices: Vec = (0..self.0.len() as u32).filter(|&index| self.point_id_at(index).is_some_and(|id| points.contains(&id))).collect(); + + self.set_smooth_at_indices(paths, indices, smooth); + } + + /// Sets the smooth flag on many anchors at once, reading one connectivity rather than one per anchor. + pub(crate) fn set_smooth_at_indices(&mut self, paths: &mut List, indices: impl IntoIterator, smooth: bool) { + let mut indices = indices.into_iter().peekable(); + if indices.peek().is_none() { + return; + } + + let connectivity = self.connectivity(paths); + for index in indices { + for reference in connectivity.references(index) { + let curve_type = curve_type_at(paths, reference.path as usize); + let Some(path) = paths.element_mut(reference.path as usize) else { continue }; + if path.is_anchor_reference(reference.index as usize, curve_type) { + path.0.set_attribute(ATTR_SMOOTH, reference.index as usize, smooth); + } + } + } + } + + /// The neighboring segment sharing the anchor the given handle sits on. + pub fn adjacent_segment(&self, paths: &List, manipulator_id: &ManipulatorPointId) -> Option<(PointId, SegmentId)> { + let (segment_id, at_start) = match manipulator_id { + ManipulatorPointId::PrimaryHandle(segment_id) => (*segment_id, true), + ManipulatorPointId::EndHandle(segment_id) => (*segment_id, false), + ManipulatorPointId::Anchor(_) => return None, + }; + + let span = addressing::span_of_segment_id(paths, segment_id)?; + let (start, end) = addressing::span_endpoints(paths, span)?; + let anchor = if at_start { start } else { end }; + let anchor_id = self.point_id_at(anchor)?; + + // Prefer the segment meeting this one head-on, since a smooth tangent pairs across the anchor + let occurrences = addressing::spans_at(anchor, paths, &self.connectivity(paths)); + let other = |wanted_arriving: bool| { + occurrences.iter().find_map(|&(other, arriving)| { + let id = addressing::segment_id_of(paths, other)?; + (id != segment_id && arriving == wanted_arriving).then_some(id) + }) + }; + + other(at_start).or_else(|| other(!at_start)).map(|id| (anchor_id, id)) + } +} + +impl Vector { + /// Appends a lone segment between two existing points, its handles becoming new unnamed pool points. + pub fn push(&mut self, paths: &mut List, id: SegmentId, start: PointId, end: PointId, handles: (Option, Option)) { + let [Some(start), Some(end)] = [start, end].map(|point| self.index_of_point_id(point)) else { + return; + }; + + let (curve_type, handle_positions) = match handles { + (None, None) => (CurveType::Linear, Vec::new()), + (None, Some(handle)) | (Some(handle), None) => (CurveType::Quadratic, vec![handle]), + (Some(handle_start), Some(handle_end)) => (CurveType::Cubic, vec![handle_start, handle_end]), + }; + + let mut references = vec![start]; + for position in handle_positions { + references.push(self.0.len() as u32); + self.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, PointId::UNNAMED)); + } + references.push(end); + + push_path(paths, curve_type, references, [id]); + } + + /// Welds every open subpath shut with a linear segment from its first point to its last. + pub fn close_subpaths(&mut self, paths: &mut List) { + let closures: Vec<_> = subpaths(self.point_count(), paths) + .into_iter() + .filter(|subpath| !subpath.closed) + .map(|subpath| (subpath.entry, subpath.exit)) + .collect(); + + for (entry, exit) in closures { + let mut base = next_segment_id(paths); + let id = base.next_id(); + + push_path(paths, CurveType::Linear, [entry, exit], [id]); + } + } + + /// Appends another vector's points and paths, remapping IDs that collide with this vector's. + pub fn concat(&mut self, paths: &mut List, additional: &Self, additional_paths: &List, transform_of_additional: DAffine2, collision_hash_seed: u64) { + let offset = self.0.len() as u32; + + // Remap colliding stable IDs so both sides stay addressable after the merge + let own_point_ids: std::collections::HashSet<_> = self.0.iter_attribute_values::(ATTR_ID).into_iter().flatten().copied().collect(); + let own_segment_ids: std::collections::HashSet<_> = paths + .iter_element_values() + .filter_map(|path| path.0.iter_attribute_values::(ATTR_ID)) + .flatten() + .copied() + .collect(); + + for index in 0..additional.0.len() { + let Some(&position) = additional.0.element(index) else { continue }; + let mut item = Item::new_from_element(transform_of_additional.transform_point2(position)); + + if let Some(&id) = additional.0.attribute::(ATTR_ID, index) { + let id = if id != PointId::UNNAMED && own_point_ids.contains(&id) { + id.generate_from_hash(collision_hash_seed) + } else { + id + }; + item.set_attribute(ATTR_ID, id); + } + + self.0.push(item); + } + + for index in 0..additional_paths.len() { + let Some(mut item) = additional_paths.clone_item(index) else { continue }; + + let path = item.element_mut(); + for reference in path.0.iter_element_values_mut() { + *reference += i64::from(offset); + } + if let Some(ids) = path.0.iter_attribute_values_mut::(ATTR_ID) { + for id in ids { + if *id != SegmentId::ZERO && own_segment_ids.contains(id) { + *id = id.generate_from_hash(collision_hash_seed); + } + } + } + + paths.push(item); + } + } + + /// Rewrites every stable ID deterministically from the given hash, so instanced copies stay distinct. + pub fn vector_new_ids_from_hash(&mut self, paths: &mut List, node_id: u64) { + if let Some(ids) = self.0.iter_attribute_values_mut::(ATTR_ID) { + for id in ids.filter(|id| **id != PointId::UNNAMED) { + *id = id.generate_from_hash(node_id); + } + } + + for index in 0..paths.len() { + let Some(path) = paths.element_mut(index) else { continue }; + if let Some(ids) = path.0.iter_attribute_values_mut::(ATTR_ID) { + for id in ids.filter(|id| **id != SegmentId::ZERO) { + *id = id.generate_from_hash(node_id); + } + } + } + } +} + +/// Edits a holder item's pool and paths together, taking the paths attribute out and restoring it. +pub fn edit_item_geometry(item: &mut Item, edit: impl FnOnce(&mut Vector, &mut List) -> R) -> R { + let mut paths = item.remove_attribute::>(ATTR_PATHS).unwrap_or_default(); + let result = edit(item.element_mut(), &mut paths); + item.set_attribute(ATTR_PATHS, paths); + + result +} + +/// Edits one list row's pool and paths together, writing the paths attribute back afterwards. +pub fn edit_list_row_geometry(list: &mut List, index: usize, edit: impl FnOnce(&mut Vector, &mut List) -> R) -> Option { + let mut paths = list.attribute::>(ATTR_PATHS, index).cloned().unwrap_or_default(); + let result = edit(list.element_mut(index)?, &mut paths); + list.set_attribute(ATTR_PATHS, index, paths); + + Some(result) +} + +// Alone, the element sees only its own pool, and the pool's control points always contain the drawn geometry. impl BoundingBox for Vector { + fn bounding_box_in_item(item: &Item, transform: DAffine2, _include_stroke: bool, _thumbnail: bool) -> RenderBoundingBox { + let paths = paths_from_item_attributes(item).unwrap_or_else(|| no_paths()); + item.element() + .bounding_box_with_transform(paths, transform) + .map_or(RenderBoundingBox::None, RenderBoundingBox::Rectangle) + } + + fn bounding_box_in_list(list: &List, index: usize, transform: DAffine2, _include_stroke: bool, _thumbnail: bool) -> RenderBoundingBox { + let Some(vector) = list.element(index) else { return RenderBoundingBox::None }; + let paths = paths_from_list_row_attributes(list, index).unwrap_or_else(|| no_paths()); + vector.bounding_box_with_transform(paths, transform).map_or(RenderBoundingBox::None, RenderBoundingBox::Rectangle) + } + fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox { - match self.bounding_box_with_transform(transform) { + let mut bounds: Option<[DVec2; 2]> = None; + for position in self.positions() { + let position = transform.transform_point2(position); + bounds = Some(match bounds { + Some([min, max]) => [min.min(position), max.max(position)], + None => [position, position], + }); + } + + match bounds { Some(bounds) => RenderBoundingBox::Rectangle(bounds), None => RenderBoundingBox::None, } @@ -473,19 +794,29 @@ impl BoundingBox for Vector { } impl RenderComplexity for Vector { - fn render_complexity(&self) -> usize { - self.segment_domain.ids().len() + fn render_complexity_in_item(item: &Item) -> usize { + segment_count(paths_from_item_attributes(item)) + } + + fn render_complexity_in_list(list: &List, index: usize) -> usize { + segment_count(paths_from_list_row_attributes(list, index)) } } -// Note: BoundingBox for List is handled by blanket impl in gcore +/// How many segments the paths draw, which is what their vector costs to render. +fn segment_count(paths: Option<&List>) -> usize { + let Some(paths) = paths else { return 0 }; + + paths.iter_element_values().enumerate().map(|(index, path)| path.segment_count(curve_type_at(paths, index))).sum() +} + +// Note: BoundingBox for List is handled by blanket impl in core-types #[cfg(test)] mod tests { - use crate::vector::algorithms::shapes::ellipse_bezpath; - use kurbo::{CubicBez, PathSeg, Point}; - use super::*; + use crate::vector::algorithms::shapes::ellipse_bezpath; + use kurbo::{CubicBez, PathEl, Point}; fn open_curve_bezpath() -> BezPath { let mut bezpath = BezPath::new(); @@ -494,17 +825,62 @@ mod tests { bezpath } + fn lone_anchor(position: DVec2) -> Vector { + ::from_anchor_position(position) + } + + // A layer is too dense for a thumbnail by the segments it draws, whatever handles those bring to the pool + #[test] + fn render_complexity_counts_segments() { + let (vector, paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::NEG_ONE, DVec2::ONE)); + assert_eq!(vector.0.len(), 12); + + let item = Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths); + assert_eq!(item.render_complexity(), 4); + assert_eq!(List::new_from_item(item).render_complexity(), 4); + } + + // A lone anchor is named zero and only the later collisions are renamed, so stored edits keyed on zero still land + #[test] + fn lone_anchor_is_named_zero_and_collisions_rename_from_it() { + let (mut vector, mut paths) = (lone_anchor(DVec2::ZERO), List::new()); + assert_eq!(vector.point_id_at(0), Some(PointId::ZERO)); + + vector.concat(&mut paths, &lone_anchor(DVec2::X), &List::new(), DAffine2::IDENTITY, 7); + vector.concat(&mut paths, &lone_anchor(DVec2::Y), &List::new(), DAffine2::IDENTITY, 8); + + assert_eq!(vector.point_id_at(0), Some(PointId::ZERO)); + assert_eq!(vector.point_id_at(1), Some(PointId::ZERO.generate_from_hash(7))); + assert_eq!(vector.point_id_at(2), Some(PointId::ZERO.generate_from_hash(8))); + assert_eq!(vector.index_of_point_id(PointId::ZERO), Some(0)); + } + + // Handles carry the unnamed filler, so a zero-named anchor behind them is still the one found by ID + #[test] + fn handles_do_not_shadow_a_zero_named_anchor() { + let (mut vector, mut paths) = Vector::from_bezpath(&open_curve_bezpath()); + assert_eq!(vector.point_id_at(1), Some(PointId::UNNAMED)); + assert_eq!(vector.point_id_at(2), Some(PointId::UNNAMED)); + + vector.concat(&mut paths, &lone_anchor(DVec2::new(5., 5.)), &List::new(), DAffine2::IDENTITY, 1); + + let index = vector.index_of_point_id(PointId::ZERO).unwrap(); + assert_eq!(vector.position(index as usize), Some(DVec2::new(5., 5.))); + assert!(vector.anchor_indices(&paths).contains(&(index as usize))); + assert_eq!(next_point_id(&vector.0).inner(), 3); + } + #[test] fn construct_closed_path() { let circle = ellipse_bezpath(DVec2::NEG_ONE, DVec2::ONE); - let vector = Vector::from_bezpath(circle.clone()); - assert_eq!(vector.point_domain.ids().len(), 4); + let (vector, paths) = Vector::from_bezpath(&circle); + assert_eq!(vector.anchor_points(&paths).count(), 4); - let segments = vector.segment_iter().map(|(_, bezier, _, _)| bezier).collect::>(); + let segments = vector.segment_iter(&paths).map(|(_, segment, _, _)| segment).collect::>(); assert_eq!(segments.len(), 4); assert!(segments.iter().all(|&segment| circle.segments().any(|original| original == segment))); - let generated = vector.stroke_bezpath_iter().collect::>(); + let generated = vector.stroke_bezpath_iter(&paths).collect::>(); assert_eq!(generated.len(), 1); assert_eq!(generated[0].elements(), circle.elements()); } @@ -512,19 +888,11 @@ mod tests { #[test] fn construct_open_path() { let curve = open_curve_bezpath(); - let vector = Vector::from_bezpath(curve.clone()); - assert_eq!(vector.point_domain.ids().len(), 2); + let (vector, paths) = Vector::from_bezpath(&curve); + assert_eq!(vector.anchor_points(&paths).count(), 2); - let segments = vector.segment_iter().map(|(_, bezier, _, _)| bezier).collect::>(); + let segments = vector.segment_iter(&paths).map(|(_, segment, _, _)| segment).collect::>(); assert_eq!(segments, vec![PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(-1., -1.), Point::new(1., 1.), Point::new(1., 0.)))]); - - let generated = vector.stroke_manipulator_groups().collect::>(); - assert_eq!(generated.len(), 1); - let (groups, closed) = &generated[0]; - assert!(!closed); - assert_eq!(groups.len(), 2); - assert_eq!((groups[0].anchor, groups[0].in_handle, groups[0].out_handle), (DVec2::ZERO, None, Some(DVec2::new(-1., -1.)))); - assert_eq!((groups[1].anchor, groups[1].in_handle, groups[1].out_handle), (DVec2::new(1., 0.), Some(DVec2::new(1., 1.)), None)); } #[test] @@ -532,30 +900,69 @@ mod tests { let curve = open_curve_bezpath(); let circle = ellipse_bezpath(DVec2::NEG_ONE, DVec2::ONE); - let mut vector = Vector::from_bezpath(curve.clone()); - vector.append_bezpath(circle.clone()); - assert_eq!(vector.point_domain.ids().len(), 6); + let (mut vector, mut paths) = Vector::from_bezpath(&curve); + vector.append_bezpath(&mut paths, &circle); + assert_eq!(vector.anchor_points(&paths).count(), 6); - let segments = vector.segment_iter().map(|(_, bezier, _, _)| bezier).collect::>(); + let segments = vector.segment_iter(&paths).map(|(_, segment, _, _)| segment).collect::>(); assert_eq!(segments.len(), 5); assert!(segments.iter().all(|&segment| circle.segments().chain(curve.segments()).any(|original| original == segment))); - let generated = vector.stroke_bezpath_iter().collect::>(); + let generated = vector.stroke_bezpath_iter(&paths).collect::>(); assert_eq!(generated.len(), 2); assert_eq!(generated[0].elements(), curve.elements()); assert_eq!(generated[1].elements(), circle.elements()); } - // Verifies the `DVec2 -> List` conversion that replaced the former "Vec2 to Point" node yields a path - // with exactly one anchor point at the given position and no segments + // Stored modifications name these exact IDs, so regeneration must reproduce them: anchors count up from one while handles stay unnamed + #[test] + fn appended_ids_stay_reproducible_for_stored_documents() { + let curve = open_curve_bezpath(); + let (mut vector, mut paths) = Vector::from_bezpath(&curve); + + let point_id = |vector: &Vector, index| vector.point_id_at(index).map(|id| id.inner()); + assert_eq!(point_id(&vector, 0), Some(1)); + assert_eq!(vector.point_id_at(1), Some(PointId::UNNAMED), "handles are unnamed"); + assert_eq!(vector.point_id_at(2), Some(PointId::UNNAMED)); + assert_eq!(point_id(&vector, 3), Some(2)); + + let segment_ids: Vec<_> = vector.segment_iter(&paths).map(|(id, ..)| id.inner()).collect(); + assert_eq!(segment_ids, vec![1]); + + // A second append rescans for the maximum and skips one value + vector.append_bezpath(&mut paths, &open_curve_bezpath()); + assert_eq!(point_id(&vector, 4), Some(4)); + assert_eq!(point_id(&vector, 7), Some(5)); + } + + // A lone anchor position builds one named pool point #[test] fn anchor_position_builds_single_point_path() { use core_types::ops::FromAnchorPosition; let vector = Vector::from_anchor_position(DVec2::new(3., 4.)); - assert_eq!(vector.point_domain.positions(), [DVec2::new(3., 4.)]); - assert_eq!(vector.point_domain.ids(), [PointId::ZERO], "expected the anchor position to be assigned the default PointId::ZERO",); - assert!(vector.segment_domain.ids().is_empty()); + assert_eq!(vector.positions().collect::>(), [DVec2::new(3., 4.)]); + assert_eq!(vector.point_id_at(0), Some(PointId::ZERO), "the anchor keeps the zero ID stored edits address it by"); + assert_eq!(vector.point_count(), 1); + } + + // An open subpath welds shut with one linear closing segment, and a second call leaves it alone + #[test] + fn close_subpaths_welds_open_subpaths() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.line_to((10., 10.)); + + let (mut vector, mut paths) = Vector::from_bezpath(&bezpath); + assert_eq!(paths.len(), 1); + + vector.close_subpaths(&mut paths); + assert_eq!(paths.len(), 2); + assert!(vector.stroke_bezpath_iter(&paths).all(|contour| matches!(contour.elements().last(), Some(PathEl::ClosePath)))); + + vector.close_subpaths(&mut paths); + assert_eq!(paths.len(), 2); } } diff --git a/node-graph/nodes/graphic/src/graphic.rs b/node-graph/nodes/graphic/src/graphic.rs index b9b3832b01..dbc95140e7 100644 --- a/node-graph/nodes/graphic/src/graphic.rs +++ b/node-graph/nodes/graphic/src/graphic.rs @@ -459,7 +459,7 @@ async fn mirror( // The mirror reference may be based on the bounding box if an explicit reference point is chosen let item_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); - let RenderBoundingBox::Rectangle(bounding_box) = content.element().bounding_box(item_transform, false) else { + let RenderBoundingBox::Rectangle(bounding_box) = content.bounding_box(DAffine2::IDENTITY, false) else { return List::new_from_item(content); }; diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index 4090049bd1..e75853f9a6 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -32,6 +32,7 @@ pub mod vector { pub use vector_types::vector::algorithms; pub use vector_types::vector::click_target; pub use vector_types::vector::misc::HandleId; + pub use vector_types::vector::{CurveType, Path, VectorGeometry, WorkingVector, no_paths, paths_from_item_attributes, paths_from_list_row_attributes}; pub use vector_types::vector::{PointId, SegmentId}; pub use vector_types::vector::{deserialize_hashmap, serialize_hashmap, serialize_hashmap_as_sorted_object}; diff --git a/node-graph/nodes/path-bool/src/lib.rs b/node-graph/nodes/path-bool/src/lib.rs index 49b4828a79..70c4216ddf 100644 --- a/node-graph/nodes/path-bool/src/lib.rs +++ b/node-graph/nodes/path-bool/src/lib.rs @@ -1,10 +1,11 @@ +use core_types::list::ATTR_PATHS; use core_types::list::{ATTR_APPEARANCE, Item, List, NodeIdPath}; use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Ctx}; use glam::DAffine2; use graphic_types::Appearance; use graphic_types::graphic::bake_paint_transforms; -use graphic_types::vector_types::vector::VectorExt; use graphic_types::vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt; +use graphic_types::vector_types::vector::{Path, no_paths, paths_from_list_row_attributes}; use graphic_types::{Graphic, Vector}; use linesweeper::topology::Topology; use linesweeper::{BinaryOp, FillRule, binary_op}; @@ -59,7 +60,9 @@ async fn boolean_operation( // Clean up the boolean operation result by merging duplicated points let merge_transform: DAffine2 = result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0); - result_vector_list.element_mut(0).unwrap().merge_by_distance_spatial(merge_transform, 0.0001); + let mut result_paths = result_vector_list.attribute::>(ATTR_PATHS, 0).cloned().unwrap_or_default(); + result_vector_list.element_mut(0).unwrap().merge_by_distance_spatial(&mut result_paths, merge_transform, 0.0001); + result_vector_list.set_attribute(ATTR_PATHS, 0, result_paths); } result_vector_list.into_iter().next().unwrap_or_default() @@ -145,6 +148,8 @@ fn boolean_operation_on_vector_list(vector: &List, boolean_operation: Bo let copy_from_transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index); // The boolean op bakes input transforms into the output geometry, so the result item carries no transform of its own attributes.insert(ATTR_TRANSFORM, DAffine2::IDENTITY); + // The result weaves its own paths rather than inheriting the operand's + attributes.remove::>(ATTR_PATHS); bake_paint_transforms(&mut attributes, copy_from_transform); @@ -155,21 +160,25 @@ fn boolean_operation_on_vector_list(vector: &List, boolean_operation: Bo for index in 0..vector.len() { let element = vector.element(index).unwrap(); - paths.push(to_bez_path(element, vector.attribute_cloned_or_default(ATTR_TRANSFORM, index))); + let element_paths = paths_from_list_row_attributes(vector, index).unwrap_or_else(|| no_paths()); + paths.push(to_bez_path(element, element_paths, vector.attribute_cloned_or_default(ATTR_TRANSFORM, index))); } let top = match Topology::::from_paths(paths.iter().enumerate().map(|(idx, path)| (path, (idx, paths.len()))), EPSILON) { Ok(top) => top, Err(e) => { log::error!("Boolean operation failed while building topology: {e}"); + row.set_attribute(ATTR_PATHS, List::::new()); list.push(row); return list; } }; let contours = top.contours(|winding| winding.is_inside(boolean_operation)); + let mut result_paths = List::new(); for contour in contours.contours() { - row.element_mut().append_bezpath(closed(contour.path.clone())); + row.element_mut().append_bezpath(&mut result_paths, &closed(contour.path.clone())); } + row.set_attribute(ATTR_PATHS, result_paths); list.push(row); list @@ -301,11 +310,11 @@ fn closed(mut path: BezPath) -> BezPath { path } -fn to_bez_path(vector: &Vector, transform: DAffine2) -> BezPath { +fn to_bez_path(vector: &Vector, element_paths: &List, transform: DAffine2) -> BezPath { let transform = Affine::new(transform.to_cols_array()); let mut path = BezPath::new(); - for subpath in vector.stroke_bezpath_iter() { + for subpath in vector.stroke_bezpath_iter(element_paths) { let mut first = true; for segment in closed(subpath).segments() { diff --git a/node-graph/nodes/repeat/src/repeat_nodes.rs b/node-graph/nodes/repeat/src/repeat_nodes.rs index ce387dfd0d..29bec64cee 100644 --- a/node-graph/nodes/repeat/src/repeat_nodes.rs +++ b/node-graph/nodes/repeat/src/repeat_nodes.rs @@ -6,6 +6,7 @@ use glam::{DAffine2, DVec2}; use graphic_types::{Artboard, Graphic, Vector}; use raster_types::{CPU, GPU, Raster}; use vector_types::Gradient; +use vector_types::vector::{no_paths, paths_from_list_row_attributes}; #[node_macro::node(category("Repeat"), icon("NodeRepeat"))] async fn repeat( @@ -212,7 +213,9 @@ async fn repeat_on_points( } }; - let range = points_element.point_domain.positions().iter().enumerate(); + let paths = paths_from_list_row_attributes(&points, points_index).unwrap_or_else(|| no_paths()); + let positions = points_element.anchor_positions(paths); + let range = positions.iter().enumerate(); if reverse { for (index, &point) in range.rev() { iteration(index, point).await; @@ -242,10 +245,16 @@ mod test { use std::future::Future; use std::pin::Pin; use vector_nodes::generator_nodes::RectangleNode; + use vector_types::vector::Path; use vector_types::vector::misc::BoxCorners; fn vector_node_from_bezpath(bezpath: BezPath) -> List { - List::new_from_element(Vector::from_bezpath(bezpath)) + List::new_from_item(Vector::item_from_bezpath(&bezpath)) + } + + /// The paths riding the row, so geometry queries can resolve against them. + fn row_paths(list: &List, index: usize) -> &List { + paths_from_list_row_attributes(list, index).unwrap_or_else(|| no_paths()) } #[derive(Clone)] @@ -314,7 +323,7 @@ mod test { let bounds = generated .element(index) .unwrap() - .bounding_box_with_transform(generated.attribute_cloned_or_default(ATTR_TRANSFORM, index)) + .bounding_box_with_transform(row_paths(&generated, index), generated.attribute_cloned_or_default(ATTR_TRANSFORM, index)) .unwrap(); assert!(position.abs_diff_eq((bounds[0] + bounds[1]) / 2., 1e-10)); assert_eq!((bounds[1] - bounds[0]).x, position.y); @@ -336,8 +345,9 @@ mod test { .await; let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); let vector = vector_list.element(0).unwrap(); - assert_eq!(vector.stroke_manipulator_groups().count(), 3); - for (index, (manipulator_groups, _)) in vector.stroke_manipulator_groups().enumerate() { + let paths = row_paths(&vector_list, 0); + assert_eq!(vector.stroke_manipulator_groups(paths).count(), 3); + for (index, (manipulator_groups, _)) in vector.stroke_manipulator_groups(paths).enumerate() { assert!((manipulator_groups[0].anchor - direction * index as f64 / (count - 1) as f64).length() < 1e-5); } } @@ -355,9 +365,10 @@ mod test { .await; let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); let vector = vector_list.element(0).unwrap(); - assert_eq!(vector.stroke_manipulator_groups().count(), 1); + let paths = row_paths(&vector_list, 0); + assert_eq!(vector.stroke_manipulator_groups(paths).count(), 1); - let (manipulator_groups, _) = vector.stroke_manipulator_groups().next().unwrap(); + let (manipulator_groups, _) = vector.stroke_manipulator_groups(paths).next().unwrap(); let anchor = manipulator_groups[0].anchor; assert!(anchor.length() < 1e-5, "Expected the single copy to be untransformed, found anchor {anchor}"); } @@ -377,8 +388,9 @@ mod test { .await; let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); let vector = vector_list.element(0).unwrap(); - assert_eq!(vector.stroke_manipulator_groups().count(), 8); - for (index, (manipulator_groups, _)) in vector.stroke_manipulator_groups().enumerate() { + let paths = row_paths(&vector_list, 0); + assert_eq!(vector.stroke_manipulator_groups(paths).count(), 8); + for (index, (manipulator_groups, _)) in vector.stroke_manipulator_groups(paths).enumerate() { assert!((manipulator_groups[0].anchor - direction * index as f64 / (count - 1) as f64).length() < 1e-5); } } @@ -396,9 +408,10 @@ mod test { .await; let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); let vector = vector_list.element(0).unwrap(); - assert_eq!(vector.stroke_manipulator_groups().count(), 8); + let paths = row_paths(&vector_list, 0); + assert_eq!(vector.stroke_manipulator_groups(paths).count(), 8); - for (index, (manipulator_groups, _)) in vector.stroke_manipulator_groups().enumerate() { + for (index, (manipulator_groups, _)) in vector.stroke_manipulator_groups(paths).enumerate() { let expected_angle = (index as f64 + 1.) * 45.; let center = (manipulator_groups[0].anchor + manipulator_groups[2].anchor) / 2.; diff --git a/node-graph/nodes/text/src/path_builder.rs b/node-graph/nodes/text/src/path_builder.rs index 906d955be2..cd0720d603 100644 --- a/node-graph/nodes/text/src/path_builder.rs +++ b/node-graph/nodes/text/src/path_builder.rs @@ -8,13 +8,18 @@ use skrifa::outline::{DrawSettings, OutlinePen}; use skrifa::raw::FontRef as ReadFontsRef; use skrifa::{MetadataProvider, OutlineGlyph}; use vector_types::kurbo::{Affine, BezPath, Point, Rect, Shape}; -use vector_types::vector::{Vector, VectorExt}; +use vector_types::vector::{Path, Vector}; pub struct PathBuilder { origin: DVec2, /// Contours of the glyph currently being drawn, accumulated as a single path. glyph_bezpath: BezPath, pub vector_list: List, + /// Whether each glyph becomes its own list item rather than merging into one vector. + per_glyph_items: bool, + /// The single accumulated vector and its paths in merged mode, written to item 0 in `finalize()`. + merged_vector: Vector, + merged_paths: List, /// Per-glyph AABBs collected in single-item mode, published as `ATTR_EDITOR_CLICK_TARGET` in `finalize()`. merged_click_target_bboxes: Vec<[DVec2; 2]>, /// Per-glyph baselines, parallel to `merged_click_target_bboxes`. Groups glyphs by line for the widening pass. @@ -34,6 +39,9 @@ impl PathBuilder { Self { glyph_bezpath: BezPath::new(), vector_list: if per_glyph_items { List::new() } else { List::new_from_element(Vector::default()) }, + per_glyph_items, + merged_vector: Vector::default(), + merged_paths: List::new(), merged_click_target_bboxes: Vec::new(), merged_click_target_baselines: Vec::new(), per_glyph_bboxes: Vec::new(), @@ -78,7 +86,7 @@ impl PathBuilder { // back to the layer-local frame origin, regardless of which glyph survived let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -glyph_offset); - let item = Item::new_from_element(Vector::from_bezpath(core::mem::take(&mut self.glyph_bezpath))) + let item = Vector::item_from_bezpath(&core::mem::take(&mut self.glyph_bezpath)) .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(glyph_offset)) .with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local); self.vector_list.push(item); @@ -86,8 +94,7 @@ impl PathBuilder { // Defer click target creation to `finalize()` where adjacent AABBs get widened self.per_glyph_bboxes.push(glyph_bbox); } else { - // Unwrapping here is ok because `self.vector_list` is initialized with a single `List` item - self.vector_list.element_mut(0).unwrap().append_bezpath(core::mem::take(&mut self.glyph_bezpath)); + self.merged_vector.append_bezpath(&mut self.merged_paths, &core::mem::take(&mut self.glyph_bezpath)); if let Some(bbox) = glyph_bbox { self.merged_click_target_bboxes.push(bbox); @@ -157,6 +164,15 @@ impl PathBuilder { } pub fn finalize(mut self) -> List { + // Merged mode accumulated into side fields, which item 0 takes over here + if !self.per_glyph_items + && let Some(element) = self.vector_list.element_mut(0) + { + *element = core::mem::take(&mut self.merged_vector); + let paths = core::mem::take(&mut self.merged_paths); + self.vector_list.set_attribute(core_types::list::ATTR_PATHS, 0, paths); + } + // Empty list = all glyphs clipped by height. Create a placeholder with the same item-0 // transform a populated list would have so `local_transforms` stays stable mid-drag. // TODO: Remove this hack and move the attribute up to the parent return value when is done. @@ -190,11 +206,11 @@ impl PathBuilder { for (entry, widened) in entries.iter().zip(layer_bboxes.iter()) { let glyph_local = [widened[0] - entry.1, widened[1] - entry.1]; let rect = rectangle_bezpath(glyph_local[0], glyph_local[1]); - self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, entry.0, Vector::from_bezpath(rect)); + self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, entry.0, rect); } } - // Glyph separation off: widen the accumulated AABBs and bundle as one override `Vector` + // Glyph separation off: widen the accumulated AABBs and bundle as one override `BezPath` if !self.merged_click_target_bboxes.is_empty() { let mut bboxes = self.merged_click_target_bboxes; widen_horizontal_gaps(&mut bboxes, &self.merged_click_target_baselines); @@ -203,7 +219,7 @@ impl PathBuilder { for [min, max] in &bboxes { widened_bezpath.extend(rectangle_bezpath(*min, *max)); } - self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, 0, Vector::from_bezpath(widened_bezpath)); + self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, 0, widened_bezpath); } // Fill in text frame for items that don't have one yet (single-item mode, where item 0 = identity) diff --git a/node-graph/nodes/vector/src/generator_nodes.rs b/node-graph/nodes/vector/src/generator_nodes.rs index 18349b0f70..48010419c9 100644 --- a/node-graph/nodes/vector/src/generator_nodes.rs +++ b/node-graph/nodes/vector/src/generator_nodes.rs @@ -1,14 +1,14 @@ -use core_types::list::{Item, List}; +use crate::vector_nodes::{push_working_point, push_working_segment}; +use core_types::list::{ATTR_PATHS, Item, List}; use core_types::{CacheHash, Ctx}; use dyn_any::DynAny; use glam::DVec2; use graphic_types::Vector; -use vector_types::vector::VectorExt; use vector_types::vector::algorithms::shapes; use vector_types::vector::misc::BezierHandles; +use vector_types::vector::misc::SpiralType; use vector_types::vector::misc::{ArcType, BoxCorners, GridType}; -use vector_types::vector::misc::{HandleId, SpiralType}; -use vector_types::vector::{PointId, SegmentId}; +use vector_types::vector::{Path, PointId, SegmentId, WorkingVector}; /// Generates a circle shape with a chosen radius. #[node_macro::node(category("Vector: Shape"), icon("NodeCircle"))] @@ -20,7 +20,7 @@ fn circle( radius: Item, ) -> Item { let radius = radius.element().abs(); - Item::new_from_element(Vector::from_bezpath(shapes::ellipse_bezpath(DVec2::splat(-radius), DVec2::splat(radius)))) + Vector::item_from_bezpath(&shapes::ellipse_bezpath(DVec2::splat(-radius), DVec2::splat(radius))) } /// Generates an arc shape forming a portion of a circle which may be open, closed, or a pie slice. @@ -43,12 +43,12 @@ fn arc( arc_type: Item, ) -> Item { let (radius, start_angle, sweep_angle, arc_type) = (*radius.element(), *start_angle.element(), *sweep_angle.element(), arc_type.into_element()); - Item::new_from_element(Vector::from_bezpath(shapes::arc_bezpath( + Vector::item_from_bezpath(&shapes::arc_bezpath( radius, start_angle / 360. * std::f64::consts::TAU, sweep_angle / 360. * std::f64::consts::TAU, arc_type, - ))) + )) } /// Generates a spiral shape that winds from an inner to an outer radius. @@ -78,14 +78,14 @@ fn spiral( *outer_radius.element(), *angular_resolution.element(), ); - Item::new_from_element(Vector::from_bezpath(shapes::spiral_bezpath( + Vector::item_from_bezpath(&shapes::spiral_bezpath( inner_radius, outer_radius, turns, start_angle.to_radians(), angular_resolution.to_radians(), spiral_type.into_element(), - ))) + )) } /// Generates an ellipse shape (an oval or stretched circle) with the chosen radii. @@ -104,16 +104,15 @@ fn ellipse( let corner1 = -radius; let corner2 = radius; - let mut ellipse = Vector::from_bezpath(shapes::ellipse_bezpath(corner1, corner2)); + let (mut ellipse, mut paths) = Vector::from_bezpath(&shapes::ellipse_bezpath(corner1, corner2)); - let len = ellipse.segment_domain.ids().len(); - for i in 0..len { - ellipse - .colinear_manipulators - .push([HandleId::end(ellipse.segment_domain.ids()[i]), HandleId::primary(ellipse.segment_domain.ids()[(i + 1) % len])]); + // Each junction between consecutive segments keeps its tangent pair smooth + for segment in ellipse.segment_ids(&paths) { + let Some(anchor) = ellipse.segment_end_from_id(&paths, segment) else { continue }; + ellipse.set_smooth(&mut paths, anchor, true); } - Item::new_from_element(ellipse) + Item::new_from_element(ellipse).with_attribute(ATTR_PATHS, paths) } /// Generates a rectangle shape with the chosen width and height. It may also have rounded corners if desired. @@ -152,7 +151,7 @@ fn rectangle( radii }; - Item::new_from_element(Vector::from_bezpath(shapes::rounded_rectangle_bezpath(size / -2., size / 2., radii))) + Vector::item_from_bezpath(&shapes::rounded_rectangle_bezpath(size / -2., size / 2., radii)) } /// Builds a set of four corner values, such as a rectangle's corner radii, from a list of one, two, three, or four values. @@ -179,7 +178,7 @@ fn regular_polygon( radius: Item, ) -> Item { let points = *sides.element() as u64; - Item::new_from_element(Vector::from_bezpath(shapes::regular_polygon_bezpath(DVec2::ZERO, points, *radius.element()))) + Vector::item_from_bezpath(&shapes::regular_polygon_bezpath(DVec2::ZERO, points, *radius.element())) } /// Generates an n-pointed star shape with inner and outer points at chosen radii from the center. @@ -198,7 +197,7 @@ fn star( radius_2: Item, ) -> Item { let points = *sides.element() as u64; - Item::new_from_element(Vector::from_bezpath(shapes::star_polygon_bezpath(DVec2::ZERO, points, *radius_1.element(), *radius_2.element()))) + Vector::item_from_bezpath(&shapes::star_polygon_bezpath(DVec2::ZERO, points, *radius_1.element(), *radius_2.element())) } #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] @@ -244,24 +243,24 @@ fn qr_code( }; let Ok(qr_code) = qrcodegen::QrCode::encode_text(&text, ecc) else { - return Item::new_from_element(Vector::default()); + return Item::new_from_element(Vector::default()).with_attribute(ATTR_PATHS, List::::new()); }; - let mut vector = match individual_squares { + let (mut vector, paths) = match individual_squares { true => { - let mut vector = Vector::default(); + let (mut vector, mut paths) = (Vector::default(), List::new()); let dimension = qr_code.size() as usize; for y in 0..dimension { for x in 0..dimension { if qr_code.get_module(x as i32, y as i32) { let corner1 = DVec2::new(x as f64, y as f64); - vector.append_bezpath(shapes::rectangle_bezpath(corner1, corner1 + DVec2::splat(1.))); + vector.append_bezpath(&mut paths, &shapes::rectangle_bezpath(corner1, corner1 + DVec2::splat(1.))); } } } - vector + (vector, paths) } false => crate::merge_qr_squares::merge_qr_squares(&qr_code), }; @@ -270,7 +269,7 @@ fn qr_code( vector.transform(glam::DAffine2::from_scale(DVec2::splat(size / qr_code.size() as f64))); } - Item::new_from_element(vector) + Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths) } /// Generates an arrow from the origin to the chosen coordinate. @@ -295,7 +294,7 @@ fn arrow( head_length: Item, ) -> Item { let (arrow_to, shaft_width, head_width, head_length) = (*arrow_to.element(), *shaft_width.element(), *head_width.element(), *head_length.element()); - Item::new_from_element(Vector::from_bezpath(shapes::arrow_bezpath(DVec2::ZERO, arrow_to, shaft_width, head_width, head_length))) + Vector::item_from_bezpath(&shapes::arrow_bezpath(DVec2::ZERO, arrow_to, shaft_width, head_width, head_length)) } #[node_macro::node(category("Vector: Shape"), icon("NodeLine"))] @@ -306,7 +305,7 @@ fn line( #[default(100., 100.)] line_to: Item, ) -> Item { - Item::new_from_element(Vector::from_bezpath(shapes::line_bezpath(DVec2::ZERO, *line_to.element()))) + Vector::item_from_bezpath(&shapes::line_bezpath(DVec2::ZERO, *line_to.element())) } trait GridSpacing { @@ -379,25 +378,24 @@ fn grid( cells.push(vec![position(x, y), position(x + 1, y), position(x + 1, y + 1), position(x, y + 1)]); } } - let mut vector = Vector::default(); - crate::vector_nodes::replace_with_polygons(&mut vector, cells, connect_cells); - return Item::new_from_element(vector); + let (mut vector, mut paths) = (Vector::default(), List::new()); + crate::vector_nodes::replace_with_polygons(&mut vector, &mut paths, cells, connect_cells); + return Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths); } - let mut vector = Vector::default(); + let mut working = WorkingVector::default(); let mut segment_id = SegmentId::ZERO; let mut point_id = PointId::ZERO; for y in 0..rows { for x in 0..columns { // Add the current point to the grid. - let current_index = vector.point_domain.ids().len(); - vector.point_domain.push(point_id.next_id(), position(x, y)); + let current_index = push_working_point(&mut working, point_id.next_id(), position(x, y)); // Helper function to connect points with line segments. let mut push_segment = |to_index: Option| { if let Some(other_index) = to_index { - vector.segment_domain.push(segment_id.next_id(), other_index, current_index, BezierHandles::Linear); + push_working_segment(&mut working, segment_id.next_id(), other_index, current_index, BezierHandles::Linear); } }; @@ -418,7 +416,10 @@ fn grid( } } - Item::new_from_element(vector) + let (mut vector, mut paths) = (Vector::default(), List::new()); + working.reweave(&mut vector, &mut paths); + + Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths) } #[cfg(test)] @@ -426,6 +427,7 @@ mod tests { use super::*; use kurbo::ParamCurve; use vector_types::vector::misc::point_to_dvec2; + use vector_types::vector::paths_from_item_attributes; fn item(value: T) -> Item { Item::new_from_element(value) @@ -439,9 +441,10 @@ mod tests { // Works properly let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_i64), item(5_i64), item((30., 30.).into()), item(true)); - assert_eq!(grid.element().point_domain.ids().len(), 5 * 5); - assert_eq!(grid.element().segment_iter().count(), 4 * 5 + 4 * 9); - for (_, segment, _, _) in grid.element().segment_iter() { + let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + assert_eq!(grid.element().anchor_points(&paths).count(), 5 * 5); + assert_eq!(grid.element().segment_iter(&paths).count(), 4 * 5 + 4 * 9); + for (_, segment, _, _) in grid.element().segment_iter(&paths) { assert!(matches!(segment, kurbo::PathSeg::Line(_))); let span = point_to_dvec2(segment.start()) - point_to_dvec2(segment.end()); assert!((span.length() - 10.).abs() < 1e-5, "Length of {} should be 10", span.length()); @@ -451,9 +454,10 @@ mod tests { #[test] fn skew_isometric_grid_test() { let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_i64), item(5_i64), item((40., 30.).into()), item(true)); - assert_eq!(grid.element().point_domain.ids().len(), 5 * 5); - assert_eq!(grid.element().segment_iter().count(), 4 * 5 + 4 * 9); - for (_, segment, _, _) in grid.element().segment_iter() { + let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + assert_eq!(grid.element().anchor_points(&paths).count(), 5 * 5); + assert_eq!(grid.element().segment_iter(&paths).count(), 4 * 5 + 4 * 9); + for (_, segment, _, _) in grid.element().segment_iter(&paths) { assert!(matches!(segment, kurbo::PathSeg::Line(_))); let vector = point_to_dvec2(segment.start()) - point_to_dvec2(segment.end()); let angle = (vector.angle_to(DVec2::X).to_degrees() + 180.) % 180.; @@ -465,13 +469,14 @@ mod tests { fn grid_disconnected_cells_test() { // A 3x3 rectangular grid has a 2x2 arrangement of cells, each its own closed quad subpath. let grid = grid((), (), item(GridType::Rectangular), item(10.), item(3_i64), item(3_i64), item((30., 30.).into()), item(false)); + let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); let vector = grid.element(); - assert_eq!(vector.stroke_manipulator_groups().filter(|(_, closed)| *closed).count(), 4); - assert_eq!(vector.point_domain.ids().len(), 4 * 4); - assert_eq!(vector.segment_domain.ids().len(), 4 * 4); + assert_eq!(vector.stroke_manipulator_groups(&paths).filter(|(_, closed)| *closed).count(), 4); + assert_eq!(vector.anchor_points(&paths).count(), 4 * 4); + assert_eq!(vector.segment_ids(&paths).len(), 4 * 4); // Each cell winds counter-clockwise (positive signed area), matching the shape generators. - for (group, closed) in vector.stroke_manipulator_groups() { + for (group, closed) in vector.stroke_manipulator_groups(&paths) { assert!(closed); let anchors: Vec = group.iter().map(|g| g.anchor).collect(); let signed_area: f64 = (0..anchors.len()).map(|i| anchors[i].perp_dot(anchors[(i + 1) % anchors.len()])).sum::() / 2.; @@ -490,7 +495,8 @@ mod tests { item(QRCodeErrorCorrectionLevel::Low), item(true), ); - assert!(!qr.element().point_domain.ids().is_empty()); - assert!(!qr.element().segment_domain.ids().is_empty()); + let paths = paths_from_item_attributes(&qr).cloned().unwrap_or_default(); + assert!(qr.element().anchor_points(&paths).count() > 0); + assert!(!qr.element().segment_ids(&paths).is_empty()); } } diff --git a/node-graph/nodes/vector/src/merge_qr_squares.rs b/node-graph/nodes/vector/src/merge_qr_squares.rs index c14f6fe9a0..ee02a93426 100644 --- a/node-graph/nodes/vector/src/merge_qr_squares.rs +++ b/node-graph/nodes/vector/src/merge_qr_squares.rs @@ -1,11 +1,13 @@ +use core_types::list::List; use glam::DVec2; use graphic_types::Vector; use std::collections::VecDeque; -use vector_types::vector::VectorExt; +use vector_types::vector::Path; use vector_types::vector::algorithms::shapes; -pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> Vector { +pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> (Vector, List) { let mut vector = Vector::default(); + let mut paths = List::new(); let size = qr_code.size() as usize; @@ -107,7 +109,7 @@ pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> Vector { } if !simplified.is_empty() { - vector.append_bezpath(shapes::polyline_bezpath(simplified, true)); + vector.append_bezpath(&mut paths, &shapes::polyline_bezpath(simplified, true)); } } } @@ -121,5 +123,5 @@ pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> Vector { } } - vector + (vector, paths) } diff --git a/node-graph/nodes/vector/src/vector_modification_nodes.rs b/node-graph/nodes/vector/src/vector_modification_nodes.rs index b4467fb180..8c201ca64c 100644 --- a/node-graph/nodes/vector/src/vector_modification_nodes.rs +++ b/node-graph/nodes/vector/src/vector_modification_nodes.rs @@ -4,20 +4,24 @@ use core_types::uuid::NodeId; use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx}; use glam::{DAffine2, DVec2}; use graphic_types::Vector; -use vector_types::vector::VectorModification; +use vector_types::kurbo::BezPath; +use vector_types::vector::{VectorModification, edit_item_geometry}; /// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments. #[node_macro::node(category(""))] async fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item>, node_path: Item) -> Item { let mut vector = vector; - modification.into_element().apply(vector.element_mut()); + let modification = modification.into_element(); + edit_item_geometry(&mut vector, |element, paths| { + modification.apply(element, paths); - // Users draw subpaths in arbitrary winding directions, so normalize them here rather than - // letting the drawn direction decide fill insideness downstream - vector.element_mut().normalize_winding_directions(); + // Users draw subpaths in arbitrary winding directions, so normalize them here rather than + // letting the drawn direction decide fill insideness downstream + element.normalize_winding_directions(paths); + }); // Drop the stale click-target override so hit testing uses the geometry the user is now editing - vector.remove_attribute::(ATTR_EDITOR_CLICK_TARGET); + vector.remove_attribute::(ATTR_EDITOR_CLICK_TARGET); // Set the path to the encapsulating subgraph (drop our own trailing entry from `node_path`), // matching the `path_of_subgraph` proto so editor tools can route data back to the parent layer. diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index 1c43b43fc6..a7bc75d1f7 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -3,7 +3,7 @@ use core::f64::consts::{PI, TAU}; use core::hash::{Hash, Hasher}; use core_types::blending::BlendMode; use core_types::bounds::{BoundingBox, RenderBoundingBox}; -use core_types::list::{ATTR_APPEARANCE, Item, ItemAttributeValues, List, ListDyn, NodeIdPath}; +use core_types::list::{ATTR_APPEARANCE, ATTR_ID, ATTR_PATHS, Item, ItemAttributeValues, List, ListDyn, NodeIdPath}; use core_types::transform::{Footprint, Transform}; use core_types::uuid::NodeId; use core_types::{ @@ -29,11 +29,45 @@ use vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt; use vector_types::vector::algorithms::offset_bezpath::offset_bezpath; use vector_types::vector::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_first_handle_open}; use vector_types::vector::misc::{ - BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, HandleId, InterpolationDistribution, ManipulatorGroup, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, Tangent, + BezierHandles, CentroidType, ExtrudeJoiningAlgorithm, InterpolationDistribution, ManipulatorGroup, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, Tangent, bezpath_from_manipulator_groups, dvec2_to_point, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles, }; use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin}; -use vector_types::vector::{PointDomain, PointId, SegmentDomain, SegmentId, VectorExt}; +use vector_types::vector::{Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, no_paths, paths_from_item_attributes, paths_from_list_row_attributes}; + +/// Appends one point to the working form, returning the index that names it. +pub(crate) fn push_working_point(working: &mut WorkingVector, id: PointId, position: DVec2) -> usize { + let index = working.point_ids.len(); + working.point_ids.push(id); + working.point_positions.push(position); + + index +} + +/// Appends one segment to the working form, running between two of its point indices. +pub(crate) fn push_working_segment(working: &mut WorkingVector, id: SegmentId, start: usize, end: usize, handles: BezierHandles) { + working.segment_ids.push(id); + working.segment_start.push(start); + working.segment_end.push(end); + working.segment_handles.push(handles); +} + +/// The ID continuing the working form's point sequence. +fn next_working_point_id(working: &WorkingVector) -> PointId { + working + .point_ids + .iter() + .copied() + .filter(|&id| id != PointId::UNNAMED) + .max() + .map(|mut id| id.next_id()) + .unwrap_or(PointId::ZERO) +} + +/// The ID continuing the working form's segment sequence. +fn next_working_segment_id(working: &WorkingVector) -> SegmentId { + working.segment_ids.iter().copied().max().map(|mut id| id.next_id()).unwrap_or(SegmentId::ZERO) +} /// Implemented for `List` types that contain vector items reachable via mutable access. /// Used by the whole-collection Assign Colors node so it can apply to either `List` or `List`. @@ -87,28 +121,32 @@ impl VectorListIterMut for List { /// Element-level analog of [`VectorListIterMut`] for the element-wise fill and stroke nodes, operating on a /// single `Item` or `Item`. trait VectorItemMut { - fn for_each_vector_mut(&mut self, f: impl FnMut(&mut Vector, DAffine2)); + fn for_each_vector_mut(&mut self, f: impl FnMut(&mut Vector, &List, DAffine2)); } impl VectorItemMut for Item { - fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, DAffine2)) { + fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, &List, DAffine2)) { + let paths = paths_from_item_attributes(self).cloned().unwrap_or_default(); let transform = self.attribute_cloned_or_default::(ATTR_TRANSFORM); - f(self.element_mut(), transform); + f(self.element_mut(), &paths, transform); } } impl VectorItemMut for Item { - fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, DAffine2)) { + fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, &List, DAffine2)) { match self.element_mut() { Graphic::Vector(item) => { + let paths = paths_from_item_attributes(item).cloned().unwrap_or_default(); let transform = item.attribute_cloned_or_default::(ATTR_TRANSFORM); - f(item.element_mut(), transform); + f(item.element_mut(), &paths, transform); } element => { let Some(vector_list) = element.as_vector_list_mut() else { return }; - let (elements, transforms) = vector_list.element_and_attribute_slices_mut::(ATTR_TRANSFORM); - for (vector, transform) in elements.iter_mut().zip(transforms.iter()) { - f(vector, *transform); + for index in 0..vector_list.len() { + let paths = paths_from_list_row_attributes(vector_list, index).cloned().unwrap_or_default(); + let transform = vector_list.attribute_cloned_or_default::(ATTR_TRANSFORM, index); + let Some(vector) = vector_list.element_mut(index) else { continue }; + f(vector, &paths, transform); } } } @@ -120,8 +158,8 @@ impl VectorItemMut for Item { trait MapVectorItems: Sized { fn map_vector_items(content: Item, f: impl FnMut(Item) -> Item) -> Item; - /// Mutable access to each reachable vector at once, for callers that must await between elements. - fn vector_elements_mut(content: &mut Item) -> Vec<&mut Vector>; + /// Mutable access to each reachable vector at once, each paired with a copy of its paths, for callers that must await between elements. + fn vector_elements_mut(content: &mut Item) -> Vec<(&mut Vector, List)>; } impl MapVectorItems for Vector { @@ -129,8 +167,10 @@ impl MapVectorItems for Vector { f(content) } - fn vector_elements_mut(content: &mut Item) -> Vec<&mut Vector> { - vec![content.element_mut()] + fn vector_elements_mut(content: &mut Item) -> Vec<(&mut Vector, List)> { + let paths = paths_from_item_attributes(content).cloned().unwrap_or_default(); + + vec![(content.element_mut(), paths)] } } @@ -153,12 +193,18 @@ impl MapVectorItems for Graphic { content } - fn vector_elements_mut(content: &mut Item) -> Vec<&mut Vector> { - fn collect<'a>(graphic: &'a mut Graphic, elements: &mut Vec<&'a mut Vector>) { + fn vector_elements_mut(content: &mut Item) -> Vec<(&mut Vector, List)> { + fn collect<'a>(graphic: &'a mut Graphic, elements: &mut Vec<(&'a mut Vector, List)>) { match graphic { - Graphic::VectorList(list) => elements.extend(list.iter_element_values_mut()), + Graphic::VectorList(list) => { + let paths: Vec> = (0..list.len()).map(|index| paths_from_list_row_attributes(list, index).cloned().unwrap_or_default()).collect(); + elements.extend(list.iter_element_values_mut().zip(paths)); + } Graphic::GraphicList(list) => list.iter_element_values_mut().for_each(|nested| collect(nested, elements)), - Graphic::Vector(item) => elements.push(item.element_mut()), + Graphic::Vector(item) => { + let paths = paths_from_item_attributes(&**item).cloned().unwrap_or_default(); + elements.push((item.element_mut(), paths)); + } Graphic::Graphic(item) => collect(item.element_mut(), elements), _ => {} } @@ -342,8 +388,8 @@ where } let mut bounds: Option<[DVec2; 2]> = None; - content.for_each_vector_mut(|vector, _| { - if let Some([min, max]) = vector.bounding_box() { + content.for_each_vector_mut(|vector, vector_paths, _| { + if let Some([min, max]) = vector.bounding_box(vector_paths) { bounds = Some(match bounds { Some([bmin, bmax]) => [bmin.min(min), bmax.max(max)], None => [min, max], @@ -522,7 +568,8 @@ async fn copy_to_points( let do_rotation = random_rotation.abs() > 1e-6; let points_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM); - for &point in row.element().point_domain.positions() { + let row_paths = paths_from_item_attributes(&row).cloned().unwrap_or_default(); + for point in row.element().anchor_positions(&row_paths) { let translation = points_transform.transform_point2(point); let rotation = if do_rotation { @@ -588,30 +635,32 @@ async fn round_corners( let (radius, roundness, edge_length_limit, min_angle_threshold) = (*radius.element(), *roundness.element(), *edge_length_limit.element(), *min_angle_threshold.element()); let source_transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); let source_transform_inverse = source_transform.inverse(); - let (source, attributes) = source.into_parts(); + let source_paths = paths_from_item_attributes(&source).cloned().unwrap_or_default(); + let (source, mut attributes) = source.into_parts(); // Flip the roundness to help with user intuition let roundness = 1. - roundness; // Convert 0-100 to 0-0.5 let edge_length_limit = edge_length_limit * 0.005; - let mut result = Vector::default(); + let (mut result, mut result_paths) = (Vector::default(), List::new()); - for bezpath in source.stroke_bezpath_iter() { + for bezpath in source.stroke_bezpath_iter(&source_paths) { // The radius is measured after the transform, so scaling the layer doesn't scale its rounding let mut document_bezpath = bezpath.clone(); document_bezpath.apply_affine(Affine::new(source_transform.to_cols_array())); // A subpath without corners to round passes through as it was let Some(mut rounded_subpath) = round_subpath_corners(&document_bezpath, radius, roundness, edge_length_limit, min_angle_threshold.to_radians()) else { - result.append_bezpath(bezpath); + result.append_bezpath(&mut result_paths, &bezpath); continue; }; rounded_subpath.apply_affine(Affine::new(source_transform_inverse.to_cols_array())); - result.append_bezpath(rounded_subpath); + result.append_bezpath(&mut result_paths, &rounded_subpath); } + attributes.insert(ATTR_PATHS, result_paths); Item::from_parts(result, attributes) }) } @@ -730,9 +779,9 @@ fn merge_by_distance( match algorithm { MergeByDistanceAlgorithm::Spatial => { let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); - content.element_mut().merge_by_distance_spatial(transform, distance); + edit_item_geometry(&mut content, |vector, paths| vector.merge_by_distance_spatial(paths, transform, distance)); } - MergeByDistanceAlgorithm::Topological => content.element_mut().merge_by_distance_topological(distance), + MergeByDistanceAlgorithm::Topological => edit_item_geometry(&mut content, |vector, paths| vector.merge_by_distance_topological(paths, distance)), } content @@ -740,10 +789,13 @@ fn merge_by_distance( } pub mod extrude_algorithms { + use super::{next_working_point_id, next_working_segment_id, push_working_point, push_working_segment}; + use core_types::list::List; use glam::DVec2; use kurbo::{ParamCurve, ParamCurveDeriv}; use vector_types::vector::misc::BezierHandles; - use vector_types::vector::misc::ExtrudeJoiningAlgorithm; + use vector_types::vector::misc::{ExtrudeJoiningAlgorithm, handles_to_segment}; + use vector_types::vector::{Path, WorkingVector}; /// Convert [`kurbo::CubicBez`] to [`vector_types::vector::misc::BezierHandles`]. fn cubic_to_handles(cubic_bez: kurbo::CubicBez) -> BezierHandles { @@ -769,14 +821,16 @@ pub mod extrude_algorithms { } /// Split so segments no longer have tangents on both sides of the direction vector. - fn split(vector: &mut graphic_types::Vector, direction: DVec2) { - let segment_count = vector.segment_domain.ids().len(); - let mut next_point = vector.point_domain.next_id(); - let mut next_segment = vector.segment_domain.next_id(); + fn split(working: &mut WorkingVector, direction: DVec2) { + let segment_count = working.segment_ids.len(); + let mut next_point = next_working_point_id(working); + let mut next_segment = next_working_segment_id(working); for segment_index in 0..segment_count { - let (_, _, segment) = vector.segment_points_from_index(segment_index); - let mut start_index = vector.segment_domain.start_point()[segment_index]; + let start = working.point_positions[working.segment_start[segment_index]]; + let end = working.point_positions[working.segment_end[segment_index]]; + let segment = handles_to_segment(start, working.segment_handles[segment_index], end); + let mut start_index = working.segment_start[segment_index]; let pathseg = segment.to_cubic(); let mut start_t = 0.; @@ -786,11 +840,10 @@ pub mod extrude_algorithms { let middle_point = next_point.next_id(); let start_segment = next_segment.next_id(); - let middle_point_index = vector.point_domain.len(); - vector.point_domain.push(middle_point, DVec2::new(first.end().x, first.end().y)); - vector.segment_domain.push(start_segment, start_index, middle_point_index, first_handles); - vector.segment_domain.set_start_point(segment_index, middle_point_index); - vector.segment_domain.set_handles(segment_index, second_handles); + let middle_point_index = push_working_point(working, middle_point, DVec2::new(first.end().x, first.end().y)); + push_working_segment(working, start_segment, start_index, middle_point_index, first_handles); + working.segment_start[segment_index] = middle_point_index; + working.segment_handles[segment_index] = second_handles; start_t = split_t; start_index = middle_point_index; @@ -799,27 +852,26 @@ pub mod extrude_algorithms { } /// Copy all segments with the offset of `direction`. - fn offset_copy_all_segments(vector: &mut graphic_types::Vector, direction: DVec2) { - let points_count = vector.point_domain.ids().len(); - let mut next_point = vector.point_domain.next_id(); + fn offset_copy_all_segments(working: &mut WorkingVector, direction: DVec2) { + let points_count = working.point_ids.len(); + let mut next_point = next_working_point_id(working); for index in 0..points_count { - vector.point_domain.push(next_point.next_id(), vector.point_domain.positions()[index] + direction); + let position = working.point_positions[index] + direction; + push_working_point(working, next_point.next_id(), position); } - let segment_count = vector.segment_domain.ids().len(); - let mut next_segment = vector.segment_domain.next_id(); + let segment_count = working.segment_ids.len(); + let mut next_segment = next_working_segment_id(working); for index in 0..segment_count { - vector.segment_domain.push( - next_segment.next_id(), - vector.segment_domain.start_point()[index] + points_count, - vector.segment_domain.end_point()[index] + points_count, - vector.segment_domain.handles()[index].apply_transformation(|x| x + direction), - ); + let (start, end) = (working.segment_start[index] + points_count, working.segment_end[index] + points_count); + let handles = working.segment_handles[index].apply_transformation(|x| x + direction); + + push_working_segment(working, next_segment.next_id(), start, end, handles); } } /// Join points from the original to the copied that are on opposite sides of the direction. - fn join_extrema_edges(vector: &mut graphic_types::Vector, direction: DVec2) { + fn join_extrema_edges(working: &mut WorkingVector, direction: DVec2) { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] enum Found { #[default] @@ -841,13 +893,13 @@ pub mod extrude_algorithms { } } - let first_half_points = vector.point_domain.len() / 2; + let first_half_points = working.point_ids.len() / 2; let mut points = vec![Found::None; first_half_points]; - let first_half_segments = vector.segment_domain.ids().len() / 2; + let first_half_segments = working.segment_ids.len() / 2; for segment_id in 0..first_half_segments { - let index = [vector.segment_domain.start_point()[segment_id], vector.segment_domain.end_point()[segment_id]]; - let position = index.map(|index| vector.point_domain.positions()[index]); + let index = [working.segment_start[segment_id], working.segment_end[segment_id]]; + let position = index.map(|index| working.point_positions[index]); if position[0].abs_diff_eq(position[1], 1e-6) { continue; // Skip zero length segments @@ -857,35 +909,39 @@ pub mod extrude_algorithms { points[index[1]].update(direction.perp_dot(position[0] - position[1])); } - let mut next_segment = vector.segment_domain.next_id(); + let mut next_segment = next_working_segment_id(working); for (index, &point) in points.iter().enumerate().take(first_half_points) { // Extrema are single connected points or points with both positive and negative values if !matches!(point, Found::Both | Found::Positive | Found::Negative) { continue; } - vector.segment_domain.push(next_segment.next_id(), index, index + first_half_points, BezierHandles::Linear); + push_working_segment(working, next_segment.next_id(), index, index + first_half_points, BezierHandles::Linear); } } /// Join all points from the original to the copied. - fn join_all(vector: &mut graphic_types::Vector) { - let mut next_segment = vector.segment_domain.next_id(); - let first_half = vector.point_domain.len() / 2; + fn join_all(working: &mut WorkingVector) { + let mut next_segment = next_working_segment_id(working); + let first_half = working.point_ids.len() / 2; for index in 0..first_half { - vector.segment_domain.push(next_segment.next_id(), index, index + first_half, BezierHandles::Linear); + push_working_segment(working, next_segment.next_id(), index, index + first_half, BezierHandles::Linear); } } - pub fn extrude(vector: &mut graphic_types::Vector, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) { - split(vector, direction); - offset_copy_all_segments(vector, direction); + pub fn extrude(vector: &mut graphic_types::Vector, paths: &mut List, direction: DVec2, joining_algorithm: ExtrudeJoiningAlgorithm) { + let mut working = WorkingVector::flatten(vector, paths); + + split(&mut working, direction); + offset_copy_all_segments(&mut working, direction); match joining_algorithm { - ExtrudeJoiningAlgorithm::Extrema => join_extrema_edges(vector, direction), - ExtrudeJoiningAlgorithm::All => join_all(vector), + ExtrudeJoiningAlgorithm::Extrema => join_extrema_edges(&mut working, direction), + ExtrudeJoiningAlgorithm::All => join_all(&mut working), ExtrudeJoiningAlgorithm::None => {} } + + working.reweave(vector, paths); } #[cfg(test)] @@ -914,10 +970,11 @@ pub mod extrude_algorithms { #[test] fn split_vector() { let curve = kurbo::PathSeg::Cubic(kurbo::CubicBez::new((0., 0.), (100., -10.), (100., 110.), (0., 100.))); - let mut vector = graphic_types::Vector::from_bezpath(kurbo::BezPath::from_path_segments([curve].into_iter())); - super::split(&mut vector, DVec2::X); - assert_eq!(vector.segment_ids().len(), 3); - assert_eq!(vector.point_domain.ids().len(), 4); + let (vector, paths) = graphic_types::Vector::from_bezpath(&kurbo::BezPath::from_path_segments([curve].into_iter())); + let mut working = super::WorkingVector::flatten(&vector, &paths); + super::split(&mut working, DVec2::X); + assert_eq!(working.segment_ids.len(), 3); + assert_eq!(working.point_ids.len(), 4); } } } @@ -928,7 +985,7 @@ async fn extrude(_: impl Ctx, #[implementations(G let mut source = source; let (direction, joining_algorithm) = (*direction.element(), *joining_algorithm.element()); - extrude_algorithms::extrude(source.element_mut(), direction, joining_algorithm); + edit_item_geometry(&mut source, |vector, paths| extrude_algorithms::extrude(vector, paths, direction, joining_algorithm)); source }) } @@ -936,20 +993,22 @@ async fn extrude(_: impl Ctx, #[implementations(G #[node_macro::node(category("Vector: Modifier"), icon("NodeBoxWarp"), path(core_types::vector))] async fn box_warp(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item, #[expose] rectangle: Item) -> Item { let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM); + let target_paths = paths_from_item_attributes(&rectangle).cloned().unwrap_or_default(); let target = rectangle.into_element(); V::map_vector_items(content, |content| { let mut row = content; { let transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM); + let paths = paths_from_item_attributes(&row).cloned().unwrap_or_default(); let vector = std::mem::take(row.element_mut()); // Get the bounding box of the source vector geometry - let source_bbox = vector.bounding_box_with_transform(transform).unwrap_or([DVec2::ZERO, DVec2::ONE]); + let source_bbox = vector.bounding_box_with_transform(&paths, transform).unwrap_or([DVec2::ZERO, DVec2::ONE]); // Extract first 4 points from target shape to form the quadrilateral // Apply the target's transform to get points in world space - let target_points: Vec = target.point_domain.positions().iter().map(|&p| target_transform.transform_point2(p)).take(4).collect(); + let target_points: Vec = target.anchor_positions(&target_paths).iter().map(|&p| target_transform.transform_point2(p)).take(4).collect(); // If we have fewer than 4 points, use the corners of the source bounding box // This handles the degenerative case @@ -971,8 +1030,8 @@ async fn box_warp(_: impl Ctx, #[implementations( // Precompute source bounding box size for normalization let source_size = source_bbox[1] - source_bbox[0]; - // Transform points - for (_, position) in result.point_domain.positions_mut() { + // Transform points, handles included since they are pool points too + for position in result.0.iter_element_values_mut() { // Get the point in world space let world_pos = transform.transform_point2(*position); @@ -983,20 +1042,6 @@ async fn box_warp(_: impl Ctx, #[implementations( *position = bilinear_interpolate(t, &dst_corners); } - // Transform handles in bezier curves - for (_, handles, _, _) in result.handles_mut() { - *handles = handles.apply_transformation(|pos| { - // Get the handle in world space - let world_pos = transform.transform_point2(pos); - - // Normalize coordinates within the source bounding box - let t = ((world_pos - source_bbox[0]) / source_size).clamp(DVec2::ZERO, DVec2::ONE); - - // Apply bilinear interpolation - bilinear_interpolate(t, &dst_corners) - }); - } - // Reset the transform since we've applied it directly to the points *row.element_mut() = result; row.set_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY); @@ -1156,11 +1201,21 @@ async fn auto_tangents( let (spread, preserve_existing) = (*spread.element(), *preserve_existing.element()); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); - let (source, attributes) = source.into_parts(); + let source_paths = paths_from_item_attributes(&source).cloned().unwrap_or_default(); + let (source, mut attributes) = source.into_parts(); - let mut result = Vector::default(); + let (mut result, mut result_paths) = (Vector::default(), List::new()); - for (mut manipulators_list, is_closed) in source.stroke_manipulator_groups() { + // Each auto-tangented anchor is found as the end of its incoming segment, counted across all subpaths + let mut segment_offset = 0; + let mut smooth_segment_ends = Vec::new(); + let segments_after = |paths: &List, first_path: usize| -> usize { + (first_path..paths.len()) + .filter_map(|index| Some(paths.element(index)?.segment_count(curve_type_at(paths, index)))) + .sum() + }; + + for (mut manipulators_list, is_closed) in source.stroke_manipulator_groups(&source_paths) { for manipulator in &mut manipulators_list { manipulator.anchor = transform.transform_point2(manipulator.anchor); manipulator.in_handle = manipulator.in_handle.map(|handle| transform.transform_point2(handle)); @@ -1169,7 +1224,12 @@ async fn auto_tangents( if manipulators_list.len() < 2 { // Not enough points for softening or handle removal - result.append_manipulator_groups(&manipulators_list, is_closed, true); + let mut unchanged = bezpath_from_manipulator_groups(&manipulators_list, is_closed); + unchanged.apply_affine(Affine::new(transform.inverse().to_cols_array())); + + let first_path = result_paths.len(); + result.append_bezpath(&mut result_paths, &unchanged); + segment_offset += segments_after(&result_paths, first_path); continue; } @@ -1261,32 +1321,36 @@ async fn auto_tangents( auto_tangented[i] = true; } - // Record segment count before appending so we can find the new segment IDs - let segment_offset = result.segment_domain.ids().len(); - let mut softened_bezpath = bezpath_from_manipulator_groups(&new_manipulators_list, is_closed); softened_bezpath.apply_affine(Affine::new(transform.inverse().to_cols_array())); - result.append_bezpath(softened_bezpath); + + let first_path = result_paths.len(); + result.append_bezpath(&mut result_paths, &softened_bezpath); + let appended_segments = segments_after(&result_paths, first_path); // Mark auto-tangented points as having colinear handles - let segment_ids = result.segment_domain.ids(); let num_manipulators = new_manipulators_list.len(); for (i, _) in auto_tangented.iter().enumerate().filter(|&(_, &tangented)| tangented) { - // For interior point i, the incoming segment is segment_offset + (i - 1) and outgoing is segment_offset + i. - // For closed paths, point 0's incoming segment is the last one (segment_offset + num_manipulators - 1). - // For open paths, endpoints are never auto-tangented (the `is_endpoint` check above ensures that), - // so `i == 0` and `i == num_manipulators - 1` only occur here when the path is closed - let in_segment_index = if i == 0 { segment_offset + num_manipulators - 1 } else { segment_offset + i - 1 }; - let out_segment_index = if i == num_manipulators - 1 { segment_offset } else { segment_offset + i }; + // For interior point i, the incoming segment is (i - 1) and the outgoing one is i, counted within this subpath. + // For closed paths, point 0's incoming segment is the last one. For open paths, endpoints are never + // auto-tangented (the `is_endpoint` check above ensures that), so `i == 0` and the last `i` only occur when closed. + let in_segment = if i == 0 { num_manipulators - 1 } else { i - 1 }; + let out_segment = if i == num_manipulators - 1 { 0 } else { i }; - if in_segment_index < segment_ids.len() && out_segment_index < segment_ids.len() { - result - .colinear_manipulators - .push([HandleId::end(segment_ids[in_segment_index]), HandleId::primary(segment_ids[out_segment_index])]); + if in_segment < appended_segments && out_segment < appended_segments { + smooth_segment_ends.push(segment_offset + in_segment); } } + + segment_offset += appended_segments; } + // O(segments + points) in one pass each, rather than a connectivity build per anchor + let segment_ends: Vec = result.segment_iter(&result_paths).map(|(_, _, _, end)| end).collect(); + let smooth_anchors = smooth_segment_ends.into_iter().filter_map(|index| segment_ends.get(index).copied()); + result.set_smooth_points(&mut result_paths, smooth_anchors, true); + + attributes.insert(ATTR_PATHS, result_paths); Item::from_parts(result, attributes) }) } @@ -1295,26 +1359,25 @@ async fn auto_tangents( async fn bounding_box(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { V::map_vector_items(content, |content| { let mut content = content; - let result = content + let paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let (result, result_paths) = content .element() - .bounding_box_rect() - .map(|bbox| { - let mut vector = Vector::default(); - vector.append_bezpath(bbox.to_path(DEFAULT_ACCURACY)); - vector - }) + .bounding_box_rect(&paths) + .map(|bbox| Vector::from_bezpath(&bbox.to_path(DEFAULT_ACCURACY))) .unwrap_or_default(); *content.element_mut() = result; + content.set_attribute(ATTR_PATHS, result_paths); content }) } #[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector))] async fn dimensions(_: impl Ctx, content: Item) -> Item { + let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let dimensions = content .element() - .bounding_box_with_transform(content.attribute_cloned_or_default(ATTR_TRANSFORM)) + .bounding_box_with_transform(paths, content.attribute_cloned_or_default(ATTR_TRANSFORM)) .map(|[top_left, bottom_right]| bottom_right - top_left) .unwrap_or_default(); @@ -1337,10 +1400,10 @@ fn points_to_vector( let mut vector = Vector::default(); let mut next_point = PointId::ZERO; for &position in points.iter_element_values() { - vector.point_domain.push(next_point.next_id(), position); + vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, next_point.next_id())); } - Item::new_from_element(vector) + Item::new_from_element(vector).with_attribute(ATTR_PATHS, List::::new()) } /// Creates a polyline from a series of vector points, replacing any existing segments that may already exist. @@ -1350,24 +1413,30 @@ async fn points_to_polyline(_: impl Ctx, #[implem V::map_vector_items(points, |points| { let mut points = points; - let vector = points.element_mut(); - let mut segment_domain = SegmentDomain::new(); - let mut next_id = SegmentId::ZERO; + edit_item_geometry(&mut points, |vector, paths| { + let flattened = WorkingVector::flatten(vector, paths); + let mut working = WorkingVector { + point_ids: flattened.point_ids, + point_positions: flattened.point_positions, + ..Default::default() + }; + let mut next_id = SegmentId::ZERO; - let points_count = vector.point_domain.ids().len(); + let points_count = working.point_ids.len(); - if points_count >= 2 { - (0..points_count - 1).for_each(|i| { - segment_domain.push(next_id.next_id(), i, i + 1, BezierHandles::Linear); - }); + if points_count >= 2 { + (0..points_count - 1).for_each(|i| { + push_working_segment(&mut working, next_id.next_id(), i, i + 1, BezierHandles::Linear); + }); - if closed && points_count != 2 { - segment_domain.push(next_id.next_id(), points_count - 1, 0, BezierHandles::Linear); + if closed && points_count != 2 { + push_working_segment(&mut working, next_id.next_id(), points_count - 1, 0, BezierHandles::Linear); + } } - } - vector.segment_domain = segment_domain; + working.reweave(vector, paths); + }); points }) @@ -1389,11 +1458,16 @@ async fn relax_points( let mut source = source; let iterations = *iterations.element(); - let vector = source.element_mut(); - let relaxed = crate::voronoi::relax_sites(vector.point_domain.positions(), iterations); - for ((_, position), new_position) in vector.point_domain.positions_mut().zip(relaxed) { - *position = new_position; - } + edit_item_geometry(&mut source, |vector, paths| { + let indices = vector.anchor_indices(paths); + let sites: Vec = indices.iter().filter_map(|&index| vector.position(index)).collect(); + + for (&index, new_position) in indices.iter().zip(crate::voronoi::relax_sites(&sites, iterations)) { + if let Some(position) = vector.0.element_mut(index) { + *position = new_position; + } + } + }); source }) @@ -1408,12 +1482,13 @@ async fn voronoi_cells(_: impl Ctx, #[implementat let mut source = source; let connect_cells = *connect_cells.element(); - let vector = source.element_mut(); - let sites = vector.point_domain.positions().to_vec(); - let cells = crate::voronoi::voronoi_cells(&sites); - if !cells.is_empty() { - replace_with_polygons(vector, cells, connect_cells); - } + edit_item_geometry(&mut source, |vector, paths| { + let sites = vector.anchor_positions(paths); + let cells = crate::voronoi::voronoi_cells(&sites); + if !cells.is_empty() { + replace_with_polygons(vector, paths, cells, connect_cells); + } + }); source }) @@ -1428,15 +1503,16 @@ async fn triangulate(_: impl Ctx, #[implementatio let mut source = source; let connect_cells = *connect_cells.element(); - let vector = source.element_mut(); - let sites = vector.point_domain.positions().to_vec(); - let triangles = crate::voronoi::delaunay_triangles(&sites); - if !triangles.is_empty() { - // `delaunator` emits triangle vertices clockwise; reverse to `[a, c, b]` so triangles wind counter-clockwise to - // match the Voronoi cells and the rest of the framework's fill winding. - let polygons = triangles.iter().map(|&[a, b, c]| vec![sites[a], sites[c], sites[b]]).collect(); - replace_with_polygons(vector, polygons, connect_cells); - } + edit_item_geometry(&mut source, |vector, paths| { + let sites = vector.anchor_positions(paths); + let triangles = crate::voronoi::delaunay_triangles(&sites); + if !triangles.is_empty() { + // `delaunator` emits triangle vertices clockwise; reverse to `[a, c, b]` so triangles wind counter-clockwise to + // match the Voronoi cells and the rest of the framework's fill winding. + let polygons = triangles.iter().map(|&[a, b, c]| vec![sites[a], sites[c], sites[b]]).collect(); + replace_with_polygons(vector, paths, polygons, connect_cells); + } + }); source }) @@ -1446,9 +1522,8 @@ async fn triangulate(_: impl Ctx, #[implementatio /// /// Without `connect_cells`, each polygon becomes its own closed subpath. /// With it, coincident vertices are welded and each shared edge is emitted once, producing a connected mesh. -pub(crate) fn replace_with_polygons(vector: &mut Vector, polygons: Vec>, connect_cells: bool) { - let mut point_domain = PointDomain::new(); - let mut segment_domain = SegmentDomain::new(); +pub(crate) fn replace_with_polygons(vector: &mut Vector, paths: &mut List, polygons: Vec>, connect_cells: bool) { + let mut working = WorkingVector::default(); let mut next_point = PointId::ZERO; let mut next_segment = SegmentId::ZERO; @@ -1458,16 +1533,14 @@ pub(crate) fn replace_with_polygons(vector: &mut Vector, polygons: Vec index, + None => { + let index = push_working_point(&mut working, next_point.next_id(), position); + vertex_lookup.insert(key, index); + index + } + } }) .collect(); @@ -1505,14 +1581,13 @@ pub(crate) fn replace_with_polygons(vector: &mut Vector, polygons: Vec( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let transform = Affine::new(transform_attribute.to_cols_array()); + let source_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); let vector = std::mem::take(content.element_mut()); - let bezpaths = vector.stroke_bezpath_iter(); - let mut result = Vector::default(); + let bezpaths = vector.stroke_bezpath_iter(&source_paths).collect::>(); + let (mut result, mut result_paths) = (Vector::default(), List::new()); // Perform operation on all subpaths in this shape. for mut bezpath in bezpaths { @@ -1572,10 +1648,11 @@ async fn offset_path( bezpath_out.apply_affine(transform.inverse()); // One closed subpath, open path. - result.append_bezpath(bezpath_out); + result.append_bezpath(&mut result_paths, &bezpath_out); } *content.element_mut() = result; + content.set_attribute(ATTR_PATHS, result_paths); content }) } @@ -1662,8 +1739,9 @@ fn solidify_stroke_list(content: List) -> List { .first_index_of(Cover::Stroke) .zip(appearance.first_index_of(Cover::Fill)) .is_some_and(|(stroke_index, fill_index)| stroke_index < fill_index); - let bezpaths = vector.stroke_bezpath_iter(); - let mut solidified_stroke = Vector::default(); + let paths = attributes.get::>(ATTR_PATHS).cloned().unwrap_or_default(); + let bezpaths = vector.stroke_bezpath_iter(&paths).collect::>(); + let (mut solidified_stroke, mut solidified_stroke_paths) = (Vector::default(), List::new()); // Taking the existing stroke data and passing it to kurbo::stroke to generate new fill paths. let join = match stroke.join { @@ -1704,7 +1782,7 @@ fn solidify_stroke_list(content: List) -> List { solidified.apply_affine(Affine::new(stroke.transform.inverse().to_cols_array())); } - solidified_stroke.append_bezpath(solidified); + solidified_stroke.append_bezpath(&mut solidified_stroke_paths, &solidified); } // If the original vector has a fill, preserve it as a separate item with the stroke coverages dropped @@ -1723,6 +1801,7 @@ fn solidify_stroke_list(content: List) -> List { let stroke_paint = appearance.first_index_of(Cover::Stroke).and_then(|index| appearance.paint_at(index).cloned()).unwrap_or_default(); stroke_attributes.insert(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), stroke_paint)); } + stroke_attributes.insert(ATTR_PATHS, solidified_stroke_paths); let stroke_row = Item::from_parts(solidified_stroke, stroke_attributes); @@ -1745,7 +1824,8 @@ async fn solidify_stroke(_: impl Ctx, #[implement #[node_macro::node(category("Vector: Modifier"), icon("NodeSeparateSubpaths"), path(core_types::vector))] async fn separate_subpaths(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> List { V::expand_vector_items(content, |content| { - let bezpaths = content.element().stroke_bezpath_iter().collect::>(); + let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::>(); // Pass the original element through unchanged when it has no subpaths, so its attributes // (such as the layer transform) survive downstream rather than being dropped along with the empty list. @@ -1758,10 +1838,11 @@ async fn separate_subpaths(_: impl Ctx, #[impl bezpaths .into_iter() .map(|bezpath| { - let mut vector = Vector::default(); - vector.append_bezpath(bezpath); + let (vector, paths) = Vector::from_bezpath(&bezpath); - Item::from_parts(vector, attributes.clone()) + let mut attributes = attributes.clone(); + attributes.insert(ATTR_PATHS, paths); + Item::from_parts(vector, attributes) }) .collect() }) @@ -1778,7 +1859,8 @@ async fn path_is_closed( index: Item, ) -> Item { let index = usize::try_from(index.into_element()).unwrap_or(usize::MAX); - let closed = content.element().build_stroke_path_iter().map(|(_, closed)| closed).nth(index).unwrap_or(false); + let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); + let closed = content.element().stroke_manipulator_groups(paths).map(|(_, closed)| closed).nth(index).unwrap_or(false); Item::new_from_element(closed) } @@ -1791,11 +1873,16 @@ async fn map_points( ) -> Item { let mut content = content; - for vector in V::vector_elements_mut(&mut content) { - for (index, (_, position)) in vector.point_domain.positions_mut().enumerate() { - let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(*position); + // Handles keep their own positions, so the mapping walks anchors alone, indexed in anchor order + for (vector, paths) in V::vector_elements_mut(&mut content) { + for (index, pool_index) in vector.anchor_indices(&paths).into_iter().enumerate() { + let Some(position) = vector.position(pool_index) else { continue }; + let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(position); - *position = mapped.eval(owned_ctx.into_context()).await.into_element(); + let mapped_position = mapped.eval(owned_ctx.into_context()).await.into_element(); + if let Some(slot) = vector.0.element_mut(pool_index) { + *slot = mapped_position; + } } } @@ -1808,15 +1895,14 @@ pub async fn combine_paths(_: impl Ctx, content: List) -> Item let graphic_list = content.clone(); let flattened = content.into_flattened_list::(); - // Create a `List` with one empty `Vector` element, then get a mutable reference to it which we append flattened subpaths to - let mut output_list = List::new_from_element(Vector::default()); let mut primary_source = None; - - let output = output_list.element_mut(0).unwrap(); + let mut output = Vector::default(); + let mut output_paths = List::new(); // Concatenate every vector element's subpaths into the single output compound path for index in 0..flattened.len() { let Some(element) = flattened.element(index) else { continue }; + let element_paths = paths_from_list_row_attributes(&flattened, index).cloned().unwrap_or_default(); let layer_path: List = flattened.attribute_cloned_or_default::(ATTR_EDITOR_LAYER_PATH, index).0; let node_id = layer_path.iter_element_values().next_back().map(|node_id| node_id.0).unwrap_or_default(); @@ -1825,30 +1911,28 @@ pub async fn combine_paths(_: impl Ctx, content: List) -> Item let collision_hash_seed = hasher.finish(); let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index); - output.concat(element, source_transform, collision_hash_seed); + output.concat(&mut output_paths, element, &element_paths, source_transform, collision_hash_seed); primary_source = Some((index, source_transform)); } + let mut attributes = ItemAttributeValues::new(); if let Some((primary, source_transform)) = primary_source { let source_attributes = flattened.clone_item_attributes(primary); - let mut attributes = ItemAttributeValues::new(); attributes.insert_cloned_from(&source_attributes, ATTR_APPEARANCE); // Adopt the last input item's layer (if any) so the editor can also bucket clicks under a contributing child layer attributes.insert_cloned_from(&source_attributes, ATTR_EDITOR_LAYER_PATH); bake_paint_transforms(&mut attributes, source_transform); - - let output = std::mem::take(output_list.element_mut(0).unwrap()); - output_list = List::new_from_item(Item::from_parts(output, attributes)); } + attributes.insert(ATTR_PATHS, output_paths); // Preserve a reference to the original upstream `List` so the renderer can recurse into it // when collecting metadata, exposing the original child layers' click targets to editor tools. // This is the same mechanism Boolean Operation uses to keep its inputs editable after the merge. - output_list.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, graphic_list); + attributes.insert(ATTR_EDITOR_MERGED_LAYERS, graphic_list); - output_list.into_iter().next().unwrap_or_default() + Item::from_parts(output, attributes) } /// Convert vector geometry into a polyline composed of evenly spaced points. @@ -1885,9 +1969,10 @@ async fn sample_polyline( } }; - let mut result = Vector::default(); + let (mut result, mut result_paths) = (Vector::default(), List::new()); - for local_bezpath in content.element().stroke_bezpath_iter() { + let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + for local_bezpath in content.element().stroke_bezpath_iter(&content_paths).collect::>() { // Apply the transform to compute sample locations in world space (for correct distance-based spacing) let mut world_bezpath = local_bezpath.clone(); let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); @@ -1922,10 +2007,11 @@ async fn sample_polyline( if was_closed { sample_bezpath.close_path(); } - result.append_bezpath(sample_bezpath); + result.append_bezpath(&mut result_paths, &sample_bezpath); } *content.element_mut() = result; + content.set_attribute(ATTR_PATHS, result_paths); content }) } @@ -1956,18 +2042,20 @@ async fn simplify( let transform = Affine::new(transform_attribute.to_cols_array()); let inverse_transform = transform.inverse(); - let mut result = Vector::default(); + let (mut result, mut result_paths) = (Vector::default(), List::new()); - for mut bezpath in item.element().stroke_bezpath_iter() { + let item_paths = paths_from_item_attributes(&item).cloned().unwrap_or_default(); + for mut bezpath in item.element().stroke_bezpath_iter(&item_paths).collect::>() { bezpath.apply_affine(transform); let mut simplified = simplify_bezpath(bezpath, tolerance, &options); simplified.apply_affine(inverse_transform); - result.append_bezpath(simplified); + result.append_bezpath(&mut result_paths, &simplified); } *item.element_mut() = result; + item.set_attribute(ATTR_PATHS, result_paths); item }) } @@ -2051,9 +2139,10 @@ async fn decimate( let transform = Affine::new(transform_attribute.to_cols_array()); let inverse_transform = transform.inverse(); - let mut result = Vector::default(); + let (mut result, mut result_paths) = (Vector::default(), List::new()); - for mut bezpath in content.element().stroke_bezpath_iter() { + let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + for mut bezpath in content.element().stroke_bezpath_iter(&content_paths).collect::>() { bezpath.apply_affine(transform); let is_closed = matches!(bezpath.elements().last(), Some(PathEl::ClosePath)); @@ -2089,10 +2178,11 @@ async fn decimate( } new_bezpath.apply_affine(inverse_transform); - result.append_bezpath(new_bezpath); + result.append_bezpath(&mut result_paths, &new_bezpath); } *content.element_mut() = result; + content.set_attribute(ATTR_PATHS, result_paths); content }) } @@ -2120,7 +2210,8 @@ async fn cut_path( let euclidean = !parameterized_distance; - let bezpaths = content.element().stroke_bezpath_iter().collect::>(); + let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::>(); let bezpath_count = bezpaths.len() as f64; let t_value = progression.clamp(0., bezpath_count); @@ -2128,22 +2219,23 @@ async fn cut_path( let index = if t_value >= bezpath_count { (bezpath_count - 1.) as usize } else { t_value as usize }; if let Some(bezpath) = bezpaths.get(index).cloned() { - let mut result_vector = Vector::default(); + let (mut result_vector, mut result_paths) = (Vector::default(), List::new()); for (_, bezpath) in bezpaths.iter().enumerate().filter(|&(i, _)| i != index) { - result_vector.append_bezpath(bezpath.clone()); + result_vector.append_bezpath(&mut result_paths, bezpath); } let t = if t_value == bezpath_count { 1. } else { t_value.fract() }; let t = if euclidean { TValue::Euclidean(t) } else { TValue::Parametric(t) }; if let Some((first, second)) = split_bezpath(&bezpath, t) { - result_vector.append_bezpath(first); - result_vector.append_bezpath(second); + result_vector.append_bezpath(&mut result_paths, &first); + result_vector.append_bezpath(&mut result_paths, &second); } else { - result_vector.append_bezpath(bezpath); + result_vector.append_bezpath(&mut result_paths, &bezpath); } *content.element_mut() = result_vector; + content.set_attribute(ATTR_PATHS, result_paths); } content @@ -2156,55 +2248,63 @@ async fn cut_segments(_: impl Ctx, #[implementati V::map_vector_items(content, |content| { let mut content = content; // Iterate through every segment and make a copy of each of its endpoints, then reassign each segment's endpoints to its own unique point copy - let vector = content.element_mut(); + edit_item_geometry(&mut content, |vector, paths| { + let mut working = WorkingVector::flatten(vector, paths); - let points_count = vector.point_domain.ids().len(); - let segments_count = vector.segment_domain.ids().len(); + let points_count = working.point_ids.len(); + let segments_count = working.segment_ids.len(); - let mut point_usages = vec![0_usize; points_count]; + let mut point_usages = vec![0_usize; points_count]; - // Count how many times each point is used as an endpoint of the segments - let start_points = vector.segment_domain.start_point().to_vec(); - let end_points = vector.segment_domain.end_point().to_vec(); - for (&start, &end) in start_points.iter().zip(end_points.iter()) { - point_usages[start] += 1; - point_usages[end] += 1; - } - - let mut new_points = PointDomain::new(); - let mut offset_sum: usize = 0; - let mut points_with_new_offsets = Vec::with_capacity(points_count); - - // Build a new point domain with the original points, but with duplications based on their extra usages by the segments - for (index, (point_id, point)) in vector.point_domain.iter().enumerate() { - // Ensure at least one usage to preserve free-floating points not connected to any segments - let usage_count = point_usages[index].max(1); - - new_points.push_unchecked(point_id, point); - - for i in 1..usage_count { - new_points.push_unchecked(point_id.generate_from_hash(i as u64), point); + // Count how many times each point is used as an endpoint of the segments + let start_points = working.segment_start.clone(); + let end_points = working.segment_end.clone(); + for (&start, &end) in start_points.iter().zip(end_points.iter()) { + point_usages[start] += 1; + point_usages[end] += 1; } - points_with_new_offsets.push(offset_sum); - offset_sum += usage_count; - } + let mut new_point_ids = Vec::new(); + let mut new_point_positions = Vec::new(); + let mut offset_sum: usize = 0; + let mut points_with_new_offsets = Vec::with_capacity(points_count); - // Reconcile the segment domain with the new points - vector.point_domain = new_points; - for original_segment_index in 0..segments_count { - let original_point_start_index = start_points[original_segment_index]; - let original_point_end_index = end_points[original_segment_index]; + // Build the new anchor list with the original points, but with duplications based on their extra usages by the segments + for (index, (&point_id, &point)) in working.point_ids.iter().zip(&working.point_positions).enumerate() { + // Ensure at least one usage to preserve free-floating points not connected to any segments + let usage_count = point_usages[index].max(1); - point_usages[original_point_start_index] -= 1; - point_usages[original_point_end_index] -= 1; + new_point_ids.push(point_id); + new_point_positions.push(point); - let start_usage = points_with_new_offsets[original_point_start_index] + point_usages[original_point_start_index]; - let end_usage = points_with_new_offsets[original_point_end_index] + point_usages[original_point_end_index]; + for i in 1..usage_count { + new_point_ids.push(point_id.generate_from_hash(i as u64)); + new_point_positions.push(point); + } - vector.segment_domain.set_start_point(original_segment_index, start_usage); - vector.segment_domain.set_end_point(original_segment_index, end_usage); - } + points_with_new_offsets.push(offset_sum); + offset_sum += usage_count; + } + + // Reconcile the segments with the new points + working.point_ids = new_point_ids; + working.point_positions = new_point_positions; + for original_segment_index in 0..segments_count { + let original_point_start_index = start_points[original_segment_index]; + let original_point_end_index = end_points[original_segment_index]; + + point_usages[original_point_start_index] -= 1; + point_usages[original_point_end_index] -= 1; + + let start_usage = points_with_new_offsets[original_point_start_index] + point_usages[original_point_start_index]; + let end_usage = points_with_new_offsets[original_point_end_index] + point_usages[original_point_end_index]; + + working.segment_start[original_segment_index] = start_usage; + working.segment_end[original_segment_index] = end_usage; + } + + working.reweave(vector, paths); + }); content }) @@ -2241,8 +2341,9 @@ async fn evaluate_path( let (progression, reverse, parameterized_distance) = (progression.into_element(), reverse.into_element(), parameterized_distance.into_element()); let euclidean = !parameterized_distance; + let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); - let mut bezpaths: Vec<_> = content.element().stroke_bezpath_iter().map(|bezpath| (bezpath, transform)).collect(); + let mut bezpaths: Vec<_> = content.element().stroke_bezpath_iter(paths).map(|bezpath| (bezpath, transform)).collect(); let bezpath_count = bezpaths.len() as f64; let progression = progression.clamp(0., bezpath_count); let progression = if reverse { bezpath_count - progression } else { progression }; @@ -2299,11 +2400,12 @@ async fn scatter_points( let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64); - let mut result = Vector::default(); + let mut result = WorkingVector::default(); + let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); let path_with_bounding_boxes: Vec<_> = content .element() - .stroke_bezpath_iter() + .stroke_bezpath_iter(&content_paths) .map(|mut bezpath| { // TODO: apply transform to points instead of modifying the paths bezpath.close_path(); @@ -2318,11 +2420,11 @@ async fn scatter_points( } for point in bezpath_algorithms::poisson_disk_points(i, &path_with_bounding_boxes, separation, || rng.random::()) { - result.point_domain.push(PointId::generate(), point); + push_working_point(&mut result, PointId::generate(), point); } } - *content.element_mut() = result; + edit_item_geometry(&mut content, |vector, paths| result.reweave(vector, paths)); content }) } @@ -2332,39 +2434,60 @@ async fn spline(_: impl Ctx, #[implementations(Gr V::map_vector_items(content, |content| { let mut content = content; // Exit early if there are no points to generate splines from. - if content.element().point_domain.positions().is_empty() { + if content.element().point_count() == 0 { return content; } - let mut segment_domain = SegmentDomain::default(); - let mut next_id = SegmentId::ZERO; - for (manipulator_groups, closed) in content.element().stroke_manipulator_groups() { - let positions = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::>(); - let closed = closed && positions.len() > 2; + edit_item_geometry(&mut content, |vector, paths| { + let manipulator_runs = vector.stroke_manipulator_groups(paths).collect::>(); - // Compute control point handles for Bezier spline. - let first_handles = if closed { - solve_spline_first_handle_closed(&positions) - } else { - solve_spline_first_handle_open(&positions) + let flattened = WorkingVector::flatten(vector, paths); + let mut working = WorkingVector { + point_ids: flattened.point_ids, + point_positions: flattened.point_positions, + ..Default::default() }; - // Create segments with computed Bezier handles and add them to the output vector element's segment domain. - for i in 0..(positions.len() - if closed { 0 } else { 1 }) { - let next_index = (i + 1) % positions.len(); + let mut next_id = SegmentId::ZERO; + let mut smooth_anchors = Vec::new(); + for (manipulator_groups, closed) in manipulator_runs { + let positions = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::>(); + let closed = closed && positions.len() > 2; - let start_index = content.element().point_domain.resolve_id(manipulator_groups[i].id).unwrap(); - let end_index = content.element().point_domain.resolve_id(manipulator_groups[next_index].id).unwrap(); + // The spline runs smoothly through every anchor with a segment on each side + let interior = if closed { + &manipulator_groups[..] + } else { + manipulator_groups.get(1..positions.len().saturating_sub(1)).unwrap_or_default() + }; + smooth_anchors.extend(interior.iter().map(|manipulators| manipulators.id)); - let handle_start = first_handles[i]; - let handle_end = positions[next_index] * 2. - first_handles[next_index]; - let handles = BezierHandles::Cubic { handle_start, handle_end }; + // Compute control point handles for Bezier spline. + let first_handles = if closed { + solve_spline_first_handle_closed(&positions) + } else { + solve_spline_first_handle_open(&positions) + }; - segment_domain.push(next_id.next_id(), start_index, end_index, handles); + // Create segments with computed Bezier handles and add them to the output vector element's segments. + for i in 0..(positions.len() - if closed { 0 } else { 1 }) { + let next_index = (i + 1) % positions.len(); + + let start_index = working.resolve_id(manipulator_groups[i].id).unwrap(); + let end_index = working.resolve_id(manipulator_groups[next_index].id).unwrap(); + + let handle_start = first_handles[i]; + let handle_end = positions[next_index] * 2. - first_handles[next_index]; + let handles = BezierHandles::Cubic { handle_start, handle_end }; + + push_working_segment(&mut working, next_id.next_id(), start_index, end_index, handles); + } } - } - content.element_mut().segment_domain = segment_domain; + working.reweave(vector, paths); + vector.set_smooth_points(paths, smooth_anchors, true); + }); + content }) } @@ -2390,26 +2513,26 @@ fn inverse_linear_or_repair(linear: DMat2) -> DMat2 { repaired.inverse() } -/// Applies per-point displacement deltas to the point and handle positions of a vector element. -fn apply_point_deltas(element: &mut Vector, deltas: &[DVec2], transform: DAffine2) { - let mut already_applied = vec![false; element.point_domain.positions().len()]; +/// Applies per-anchor displacement deltas to the anchor and handle positions of a vector element. +fn apply_point_deltas(vector: &mut Vector, paths: &mut List, deltas: &[DVec2], transform: DAffine2) { + let mut working = WorkingVector::flatten(vector, paths); + let mut already_applied = vec![false; working.point_positions.len()]; - for (handles, start, end) in element.segment_domain.handles_and_points_mut() { - let start_delta = deltas[*start]; - let end_delta = deltas[*end]; + for index in 0..working.segment_ids.len() { + let (start, end) = (working.segment_start[index], working.segment_end[index]); + let start_delta = deltas[start]; + let end_delta = deltas[end]; - if !already_applied[*start] { - let start_position = element.point_domain.positions()[*start]; - element.point_domain.set_position(*start, start_position + start_delta); - already_applied[*start] = true; + if !already_applied[start] { + working.point_positions[start] += start_delta; + already_applied[start] = true; } - if !already_applied[*end] { - let end_position = element.point_domain.positions()[*end]; - element.point_domain.set_position(*end, end_position + end_delta); - already_applied[*end] = true; + if !already_applied[end] { + working.point_positions[end] += end_delta; + already_applied[end] = true; } - match handles { + match &mut working.segment_handles[index] { BezierHandles::Cubic { handle_start, handle_end } => { *handle_start += start_delta; *handle_end += end_delta; @@ -2420,6 +2543,8 @@ fn apply_point_deltas(element: &mut Vector, deltas: &[DVec2], transform: DAffine BezierHandles::Linear => {} } } + + working.reweave(vector, paths); } /// Perturbs the positions of anchor points in vector geometry by random amounts and directions. @@ -2448,30 +2573,26 @@ async fn jitter_points( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2); - let deltas: Vec<_> = (0..content.element().point_domain.positions().len()) - .map(|point_index| { - let normal = if along_normals { - content - .element() - .segment_domain - .point_tangent(point_index, content.element().point_domain.positions()) - .map(|t| -t.perp()) - } else { - None - }; - - let offset = if let Some(normal) = normal { - normal * (rng.random::() * 2. - 1.) - } else { - DVec2::from_angle(rng.random::() * TAU) * rng.random::() - }; - - inverse_linear * offset * max_distance - }) - .collect(); - let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); - apply_point_deltas(content.element_mut(), &deltas, transform); + edit_item_geometry(&mut content, |vector, paths| { + let deltas: Vec<_> = vector + .anchor_indices(paths) + .into_iter() + .map(|point_index| { + let normal = if along_normals { vector.point_tangent(paths, point_index).map(|t| -t.perp()) } else { None }; + + let offset = if let Some(normal) = normal { + normal * (rng.random::() * 2. - 1.) + } else { + DVec2::from_angle(rng.random::() * TAU) * rng.random::() + }; + + inverse_linear * offset * max_distance + }) + .collect(); + + apply_point_deltas(vector, paths, &deltas, transform); + }); content }) @@ -2496,23 +2617,22 @@ async fn offset_points( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2); - let deltas: Vec<_> = (0..content.element().point_domain.positions().len()) - .map(|point_index| { - let Some(normal) = content - .element() - .segment_domain - .point_tangent(point_index, content.element().point_domain.positions()) - .map(|t| -t.perp()) - else { - return DVec2::ZERO; - }; - - inverse_linear * normal * distance - }) - .collect(); - let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); - apply_point_deltas(content.element_mut(), &deltas, transform); + edit_item_geometry(&mut content, |vector, paths| { + let deltas: Vec<_> = vector + .anchor_indices(paths) + .into_iter() + .map(|point_index| { + let Some(normal) = vector.point_tangent(paths, point_index).map(|t| -t.perp()) else { + return DVec2::ZERO; + }; + + inverse_linear * normal * distance + }) + .collect(); + + apply_point_deltas(vector, paths, &deltas, transform); + }); content }) @@ -2602,28 +2722,26 @@ async fn morph( } } - /// Pushes a subpath (list of manipulators) directly into a Vector's point and segment domains, + /// Pushes a subpath (list of manipulators) directly into the working form's points and segments, /// bypassing the BezPath intermediate representation used by `append_bezpath`. - fn push_manipulators_to_vector(vector: &mut Vector, manips: &[ManipulatorGroup], closed: bool, point_id: &mut PointId, segment_id: &mut SegmentId) { + fn push_manipulators_to_vector(working: &mut WorkingVector, manips: &[ManipulatorGroup], closed: bool, point_id: &mut PointId, segment_id: &mut SegmentId) { let Some(first) = manips.first() else { return }; - let first_point_index = vector.point_domain.ids().len(); - vector.point_domain.push_unchecked(point_id.next_id(), first.anchor); + let first_point_index = push_working_point(working, point_id.next_id(), first.anchor); let mut prev_point_index = first_point_index; for manip_window in manips.windows(2) { - let point_index = vector.point_domain.ids().len(); - vector.point_domain.push_unchecked(point_id.next_id(), manip_window[1].anchor); + let point_index = push_working_point(working, point_id.next_id(), manip_window[1].anchor); let handles = handles_from_manips(manip_window[0].out_handle, manip_window[1].in_handle); - vector.segment_domain.push_unchecked(segment_id.next_id(), prev_point_index, point_index, handles); + push_working_segment(working, segment_id.next_id(), prev_point_index, point_index, handles); prev_point_index = point_index; } if closed && manips.len() > 1 { let handles = handles_from_manips(manips.last().unwrap().out_handle, manips[0].in_handle); - vector.segment_domain.push_unchecked(segment_id.next_id(), prev_point_index, first_point_index, handles); + push_working_segment(working, segment_id.next_id(), prev_point_index, first_point_index, handles); } } @@ -2797,9 +2915,10 @@ async fn morph( let control_bezpaths: Vec = { // User-provided path: collect all subpaths with the path's transform applied let path_transform: DAffine2 = path.attribute_cloned_or_default(ATTR_TRANSFORM); + let control_paths = paths_from_item_attributes(&path).unwrap_or_else(|| no_paths()); let paths: Vec = path .element() - .stroke_bezpath_iter() + .stroke_bezpath_iter(control_paths) .map(|mut bezpath| { bezpath.apply_affine(Affine::new(path_transform.to_cols_array())); bezpath @@ -3018,7 +3137,7 @@ async fn morph( return Item::from_parts(endpoint_element.clone(), attributes); } - let mut vector = Vector::default(); + let mut working = WorkingVector::default(); let appearance = { let source = content.attribute::(ATTR_APPEARANCE, source_index); @@ -3028,15 +3147,17 @@ async fn morph( // Work directly with manipulator groups, bypassing the BezPath intermediate representation. // This avoids the full Vector → BezPath → interpolate → BezPath → Vector roundtrip each frame. - let mut source_subpaths: Vec<_> = source_element.stroke_manipulator_groups().collect(); - let mut target_subpaths: Vec<_> = target_element.stroke_manipulator_groups().collect(); + let source_paths = paths_from_list_row_attributes(&content, source_index).unwrap_or_else(|| no_paths()); + let target_paths = paths_from_list_row_attributes(&content, target_index).unwrap_or_else(|| no_paths()); + let mut source_subpaths: Vec<_> = source_element.stroke_manipulator_groups(source_paths).collect(); + let mut target_subpaths: Vec<_> = target_element.stroke_manipulator_groups(target_paths).collect(); // Interpolate geometry in local space (no transform baked in); the lerped transform handles positioning let matched_count = source_subpaths.len().min(target_subpaths.len()); let extra_source = source_subpaths.split_off(matched_count); let extra_target = target_subpaths.split_off(matched_count); - // Pre-allocate domain storage based on total manipulator counts across all subpaths + // Pre-allocate the working form based on total manipulator counts across all subpaths let mut total_points = 0; let mut total_segments = 0; for ((source_manips, source_closed), (target_manips, _)) in source_subpaths.iter().zip(target_subpaths.iter()) { @@ -3051,8 +3172,12 @@ async fn morph( total_points += manips.len(); total_segments += if *closed { manips.len() } else { manips.len().saturating_sub(1) }; } - vector.point_domain.reserve(total_points); - vector.segment_domain.reserve(total_segments); + working.point_ids.reserve(total_points); + working.point_positions.reserve(total_points); + working.segment_ids.reserve(total_segments); + working.segment_start.reserve(total_segments); + working.segment_end.reserve(total_segments); + working.segment_handles.reserve(total_segments); let mut point_id = PointId::ZERO; let mut segment_id = SegmentId::ZERO; @@ -3132,7 +3257,7 @@ async fn morph( } } - push_manipulators_to_vector(&mut vector, &interpolated, source_closed, &mut point_id, &mut segment_id); + push_manipulators_to_vector(&mut working, &interpolated, source_closed, &mut point_id, &mut segment_id); } // Deal with unmatched extra source subpaths by collapsing them toward their end point @@ -3145,7 +3270,7 @@ async fn morph( manip.out_handle = manip.out_handle.map(|h| h.lerp(end, time)); } - push_manipulators_to_vector(&mut vector, &manips, closed, &mut point_id, &mut segment_id); + push_manipulators_to_vector(&mut working, &manips, closed, &mut point_id, &mut segment_id); } // Deal with unmatched extra target subpaths by expanding them from their start point @@ -3158,13 +3283,18 @@ async fn morph( manip.out_handle = manip.out_handle.map(|h| start.lerp(h, time)); } - push_manipulators_to_vector(&mut vector, &manips, closed, &mut point_id, &mut segment_id); + push_manipulators_to_vector(&mut working, &manips, closed, &mut point_id, &mut segment_id); } // The result is a synthesis of source and target, so adopt whichever endpoint the result is closer to as // the click-target identity (so the editor can route clicks back to one of the contributing layers) let primary_index = if time < 0.5 { source_index } else { target_index }; + + let (mut vector, mut paths) = (Vector::default(), List::new()); + working.reweave(&mut vector, &mut paths); + let mut item = Item::new_from_element(vector); + item.set_attribute(ATTR_PATHS, paths); item.set_attribute(ATTR_TRANSFORM, lerped_transform); // Propagate each blending/layer column only when the input carries it, so attribute presence stays determined by the graph rather than by runtime values @@ -3192,7 +3322,7 @@ async fn morph( item } -fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Vector { +fn bevel_algorithm(vector: &mut Vector, paths: &mut List, transform: DAffine2, distance: f64) { // Splits a bézier curve based on a distance measurement fn split_distance(bezier: PathSeg, distance: f64, length: f64) -> PathSeg { let parametric = eval_pathseg_euclidean(bezier, (distance / length).clamp(0., 1.), DEFAULT_ACCURACY); @@ -3200,10 +3330,10 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve } /// Produces a list that corresponds with the point ID. The value is how many segments are connected. - fn segments_connected_count(vector: &Vector) -> Vec { + fn segments_connected_count(working: &WorkingVector) -> Vec { // Count the number of segments connecting to each point. - let mut segments_connected_count = vec![0; vector.point_domain.ids().len()]; - for &point_index in vector.segment_domain.start_point().iter().chain(vector.segment_domain.end_point()) { + let mut segments_connected_count = vec![0; working.point_ids.len()]; + for &point_index in working.segment_start.iter().chain(&working.segment_end) { segments_connected_count[point_index] += 1; } @@ -3217,18 +3347,17 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve } /// Updates the index so that it points at a point with the position. If nobody else will look at the index, the original point is updated. Otherwise a new point is created. - fn create_or_modify_point(point_domain: &mut PointDomain, segments_connected_count: &mut [usize], pos: DVec2, index: &mut usize, next_id: &mut PointId, new_segments: &mut Vec<[usize; 2]>) { + fn create_or_modify_point(working: &mut WorkingVector, segments_connected_count: &mut [usize], pos: DVec2, index: &mut usize, next_id: &mut PointId, new_segments: &mut Vec<[usize; 2]>) { segments_connected_count[*index] -= 1; if segments_connected_count[*index] == 0 { // If nobody else is going to look at this point, we're alright to modify it - point_domain.set_position(*index, pos); + working.point_positions[*index] = pos; } else { - let new_index = point_domain.ids().len(); let original_index = *index; // Create a new point (since someone will wish to look at the point in the original position in future) + let new_index = push_working_point(working, next_id.next_id(), pos); *index = new_index; - point_domain.push(next_id.next_id(), pos); // Add a new segment to be created later new_segments.push([new_index, original_index]); @@ -3310,14 +3439,14 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve split_distance } - fn sort_segments(segment_domain: &SegmentDomain) -> Vec { - let start_points = segment_domain.start_point(); - let end_points = segment_domain.end_point(); + fn sort_segments(working: &WorkingVector) -> Vec { + let start_points = &working.segment_start; + let end_points = &working.segment_end; let mut sorted_segments = vec![0]; - let segment_domain_length = segment_domain.ids().len(); + let segment_count = working.segment_ids.len(); - for _ in 0..segment_domain_length { + for _ in 0..segment_count { match sorted_segments.last() { Some(&last) => { if let Some(index) = start_points.iter().position(|&p| p == end_points[last]) { @@ -3331,8 +3460,8 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve } } - if segment_domain_length != sorted_segments.len() { - for i in 0..segment_domain_length { + if segment_count != sorted_segments.len() { + for i in 0..segment_count { if !sorted_segments.contains(&i) { sorted_segments.push(i); } @@ -3342,34 +3471,35 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve sorted_segments } - fn update_existing_segments(vector: &mut Vector, transform: DAffine2, distance: f64, segments_connected: &mut [usize]) -> Vec<[usize; 2]> { - let mut next_id = vector.point_domain.next_id(); + fn update_existing_segments(working: &mut WorkingVector, transform: DAffine2, distance: f64, segments_connected: &mut [usize]) -> Vec<[usize; 2]> { + let mut next_id = next_working_point_id(working); let mut new_segments = Vec::new(); - let sorted_segments = sort_segments(&vector.segment_domain); - let segment_domain = &mut vector.segment_domain; - let segment_domain_length = segment_domain.ids().len(); + let sorted_segments = sort_segments(working); + let segment_count = working.segment_ids.len(); let mut first_original_length = 0.; let mut first_length = 0.; let mut prev_original_length = 0.; let mut prev_length = 0.; - for i in 0..segment_domain_length { - let (index, next_index) = if i == segment_domain_length - 1 { (i, 0) } else { (i, i + 1) }; - let pair_handles_and_points = segment_domain.pair_handles_and_points_mut_by_index(sorted_segments[index], sorted_segments[next_index]); - let (handles, start_point, end_point, next_handles, next_start_point, next_end_point) = pair_handles_and_points; + for i in 0..segment_count { + let (index, next_index) = if i == segment_count - 1 { (i, 0) } else { (i, i + 1) }; + let (segment, next_segment) = (sorted_segments[index], sorted_segments[next_index]); - let start = vector.point_domain.positions()[*start_point]; - let end = vector.point_domain.positions()[*end_point]; + let (start_point, mut end_point) = (working.segment_start[segment], working.segment_end[segment]); + let (mut next_start_point, next_end_point) = (working.segment_start[next_segment], working.segment_end[next_segment]); - let mut bezier = handles_to_segment(start, *handles, end); + let start = working.point_positions[start_point]; + let end = working.point_positions[end_point]; + + let mut bezier = handles_to_segment(start, working.segment_handles[segment], end); bezier = Affine::new(transform.to_cols_array()) * bezier; - let next_start = vector.point_domain.positions()[*next_start_point]; - let next_end = vector.point_domain.positions()[*next_end_point]; + let next_start = working.point_positions[next_start_point]; + let next_end = working.point_positions[next_end_point]; - let mut next_bezier = handles_to_segment(next_start, *next_handles, next_end); + let mut next_bezier = handles_to_segment(next_start, working.segment_handles[next_segment], next_end); next_bezier = Affine::new(transform.to_cols_array()) * next_bezier; let calculated_split_distance = calculate_distance_to_split(bezier, next_bezier, distance); @@ -3395,7 +3525,7 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve (prev_original_length, prev_length) }; - let (next_original_length, mut next_length) = if index == segment_domain_length - 1 && next_index == 0 { + let (next_original_length, mut next_length) = if index == segment_count - 1 && next_index == 0 { (first_original_length, first_length) } else { (next_bezier.perimeter(DEFAULT_ACCURACY), next_bezier.perimeter(DEFAULT_ACCURACY)) @@ -3403,7 +3533,7 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve // Only split if the length is big enough to make it worthwhile let valid_length = length > 1e-10; - if segments_connected[*end_point] > 0 && valid_length { + if segments_connected[end_point] > 0 && valid_length { // Apply the bevel to the end let distance = calculated_split_distance.min(original_length.min(next_original_length) / 2.); bezier = split_distance(bezier.reverse(), distance, length).reverse(); @@ -3414,15 +3544,16 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve // Update the end position let pos = inverse_transform.transform_point2(point_to_dvec2(bezier.end())); - create_or_modify_point(&mut vector.point_domain, segments_connected, pos, end_point, &mut next_id, &mut new_segments); + create_or_modify_point(working, segments_connected, pos, &mut end_point, &mut next_id, &mut new_segments); + working.segment_end[segment] = end_point; } // Update the handles - *handles = segment_to_handles(&bezier).apply_transformation(|p| inverse_transform.transform_point2(p)); + working.segment_handles[segment] = segment_to_handles(&bezier).apply_transformation(|p| inverse_transform.transform_point2(p)); // Only split if the length is big enough to make it worthwhile let valid_length = next_length > 1e-10; - if segments_connected[*next_start_point] > 0 && valid_length { + if segments_connected[next_start_point] > 0 && valid_length { // Apply the bevel to the start let distance = calculated_split_distance.min(next_original_length.min(original_length) / 2.); next_bezier = split_distance(next_bezier, distance, next_length); @@ -3431,10 +3562,11 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve // Update the start position let pos = inverse_transform.transform_point2(point_to_dvec2(next_bezier.start())); - create_or_modify_point(&mut vector.point_domain, segments_connected, pos, next_start_point, &mut next_id, &mut new_segments); + create_or_modify_point(working, segments_connected, pos, &mut next_start_point, &mut next_id, &mut new_segments); + working.segment_start[next_segment] = next_start_point; // Update the handles - *next_handles = segment_to_handles(&next_bezier).apply_transformation(|p| inverse_transform.transform_point2(p)); + working.segment_handles[next_segment] = segment_to_handles(&next_bezier).apply_transformation(|p| inverse_transform.transform_point2(p)); } prev_original_length = next_original_length; @@ -3444,22 +3576,27 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve new_segments } - fn insert_new_segments(vector: &mut Vector, new_segments: &[[usize; 2]]) { - let mut next_id = vector.segment_domain.next_id(); + fn insert_new_segments(working: &mut WorkingVector, new_segments: &[[usize; 2]]) { + let mut next_id = next_working_segment_id(working); for &[start, end] in new_segments { let handles = BezierHandles::Linear; - vector.segment_domain.push(next_id.next_id(), start, end, handles); + push_working_segment(working, next_id.next_id(), start, end, handles); } } - if distance > 1. && vector.segment_domain.ids().len() > 1 { - let mut segments_connected = segments_connected_count(&vector); - let new_segments = update_existing_segments(&mut vector, transform, distance, &mut segments_connected); - insert_new_segments(&mut vector, &new_segments); + if distance <= 1. { + return; } - vector + let mut working = WorkingVector::flatten(vector, paths); + if working.segment_ids.len() > 1 { + let mut segments_connected = segments_connected_count(&working); + let new_segments = update_existing_segments(&mut working, transform, distance, &mut segments_connected); + insert_new_segments(&mut working, &new_segments); + + working.reweave(vector, paths); + } } #[node_macro::node(category("Vector: Modifier"), icon("NodeBevel"), path(core_types::vector))] @@ -3472,19 +3609,20 @@ fn bevel( distance: Item, ) -> Item { V::map_vector_items(source, |source| { + let mut source = source; let distance = *distance.element(); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); - let (element, attributes) = source.into_parts(); + edit_item_geometry(&mut source, |vector, paths| bevel_algorithm(vector, paths, transform, distance)); - Item::from_parts(bevel_algorithm(element, transform, distance), attributes) + source }) } #[node_macro::node(category("Vector: Modifier"), icon("NodeClosePath"), path(core_types::vector))] fn close_path(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item) -> Item { V::map_vector_items(source, |mut item| { - item.element_mut().close_subpaths(); + edit_item_geometry(&mut item, |vector, paths| vector.close_subpaths(paths)); item }) } @@ -3492,8 +3630,9 @@ fn close_path(_: impl Ctx, #[implemen #[node_macro::node(category("Vector: Measure"), icon("NodePointInside"), path(core_types::vector))] fn point_inside(_: impl Ctx, source: Item, point: Item) -> Item { let point = point.into_element(); + let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths()); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); - let inside = source.element().check_point_inside_shape(transform, point); + let inside = source.element().check_point_inside_shape(paths, transform, point); Item::new_from_element(inside) } @@ -3507,7 +3646,8 @@ async fn list_length(_: impl Ctx, content: ListDyn) -> Item { #[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector))] async fn count_points(_: impl Ctx, content: Item) -> Item { - let count = content.element().point_domain.positions().len() as f64; + let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); + let count = content.element().anchor_indices(paths).len() as f64; Item::new_from_element(count) } @@ -3523,7 +3663,8 @@ async fn index_points( index: Item, ) -> Item { let index = index.into_element(); - let positions = content.element().point_domain.positions(); + let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); + let positions = content.element().anchor_positions(paths); let Some(last_index) = positions.len().checked_sub(1) else { return Item::new_from_element(DVec2::ZERO); @@ -3541,10 +3682,11 @@ async fn index_points( #[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector))] async fn path_length(_: impl Ctx, source: Item) -> Item { + let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths()); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); let length = source .element() - .stroke_bezpath_iter() + .stroke_bezpath_iter(paths) .map(|mut bezpath| { bezpath.apply_affine(Affine::new(transform.to_cols_array())); bezpath.perimeter(DEFAULT_ACCURACY) @@ -3561,7 +3703,8 @@ async fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node(); + let paths = paths_from_item_attributes(&vector).unwrap_or_else(|| no_paths()); + let area = vector.element().stroke_bezpath_iter(paths).map(|subpath| subpath.area() * area_scale).sum::(); Item::new_from_element(area) } @@ -3573,18 +3716,19 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node< let vector = content.eval(new_ctx).await; let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM); - let position = element_centroid(vector.element(), transform, centroid_type); + let paths = paths_from_item_attributes(&vector).unwrap_or_else(|| no_paths()); + let position = element_centroid(vector.element(), paths, transform, centroid_type); Item::new_from_element(position) } -/// The area- or length-weighted centroid of one vector element's subpaths, averaging raw point positions when the weights all vanish. -fn element_centroid(element: &Vector, transform: DAffine2, centroid_type: CentroidType) -> DVec2 { +/// The area- or length-weighted centroid of one vector element's subpaths, averaging anchor positions when the weights all vanish. +fn element_centroid(element: &Vector, paths: &List, transform: DAffine2, centroid_type: CentroidType) -> DVec2 { // All subpath centroid positions added together as if they were vectors from the origin, weighted by area or length let mut centroid = DVec2::ZERO; let mut sum = 0.; - for bezpath in element.stroke_bezpath_iter() { + for bezpath in element.stroke_bezpath_iter(paths) { let partial = match centroid_type { CentroidType::Area => bezpath_area_centroid_and_area(&bezpath, Some(1e-3), Some(1e-3)).filter(|(_, area)| *area > 0.), CentroidType::Length => bezpath_length_centroid_and_length(&bezpath, None, true), @@ -3600,7 +3744,7 @@ fn element_centroid(element: &Vector, transform: DAffine2, centroid_type: Centro } // Without a summed denominator, return the average of all positions instead - let positions = element.point_domain.positions(); + let positions = element.anchor_positions(paths); if positions.is_empty() { return DVec2::ZERO; } @@ -3630,7 +3774,7 @@ mod test { } fn vector_node_from_bezpath(bezpath: BezPath) -> List { - List::new_from_element(Vector::from_bezpath(bezpath)) + List::new_from_item(Vector::item_from_bezpath(&bezpath)) } /// Stands in for the embedding adapter a compiled graph inserts ahead of a `List` connector. @@ -3639,19 +3783,27 @@ mod test { } fn vector_item_from_bezpath(bezpath: BezPath) -> Item { - Item::new_from_element(Vector::from_bezpath(bezpath)) + Vector::item_from_bezpath(&bezpath) } fn create_vector_item(bezpath: BezPath, transform: DAffine2) -> Item { - let mut row = Vector::default(); - row.append_bezpath(bezpath); - Item::new_from_element(row).with_attribute(ATTR_TRANSFORM, transform) + Vector::item_from_bezpath(&bezpath).with_attribute(ATTR_TRANSFORM, transform) } fn item(value: T) -> Item { Item::new_from_element(value) } + /// The paths riding an item, standing in for the empty weave when the item carries none. + fn item_paths(item: &Item) -> &List { + paths_from_item_attributes(item).unwrap_or_else(|| no_paths()) + } + + /// The paths riding one list row, standing in for the empty weave when the row carries none. + fn row_paths(list: &List, index: usize) -> &List { + paths_from_list_row_attributes(list, index).unwrap_or_else(|| no_paths()) + } + fn vector_item_from_points(points: &[DVec2]) -> Item { super::points_to_vector((), points.iter().map(|&position| Item::new_from_element(position)).collect()) } @@ -3661,8 +3813,9 @@ mod test { #[test] fn points_to_vector_keeps_positions_in_order_and_unconnected() { let result = vector_item_from_points(&SQUARE_WITH_CENTER); - assert_eq!(result.element().point_domain.positions(), SQUARE_WITH_CENTER); - assert!(result.element().segment_domain.ids().is_empty()); + let paths = paths_from_item_attributes(&result).cloned().unwrap_or_default(); + assert_eq!(result.element().anchor_positions(&paths), SQUARE_WITH_CENTER); + assert_eq!(result.element().segment_iter(&paths).count(), 0); } #[tokio::test] @@ -3671,10 +3824,11 @@ mod test { // contour returns to approximately, not exactly, its start; that near-coincident point must close, not duplicate). let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; let offset = super::offset_path((), delaunay, item(0.5), item(StrokeJoin::Miter), item(4.)).await; + let paths = item_paths(&offset); let result = offset.element(); let mut subpaths = 0; - for (group, closed) in result.stroke_manipulator_groups() { + for (group, closed) in result.stroke_manipulator_groups(paths) { subpaths += 1; assert!(closed, "offset of a closed triangle should stay closed"); let first = group.first().unwrap().anchor; @@ -3687,12 +3841,13 @@ mod test { #[tokio::test] async fn delaunay_disconnected_cells_make_one_subpath_per_triangle() { let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; + let paths = item_paths(&result); let vector = result.element(); // The square plus its center tessellates into four triangles, each its own closed subpath. - assert_eq!(vector.stroke_manipulator_groups().filter(|(_, closed)| *closed).count(), 4); - assert_eq!(vector.segment_domain.ids().len(), 4 * 3); - assert_eq!(vector.point_domain.ids().len(), 4 * 3); - assert!(!vector.use_face_fill()); + assert_eq!(vector.stroke_manipulator_groups(paths).filter(|(_, closed)| *closed).count(), 4); + assert_eq!(vector.segment_ids(paths).len(), 4 * 3); + assert_eq!(vector.anchor_indices(paths).len(), 4 * 3); + assert!(!vector.use_face_fill(paths)); } #[tokio::test] @@ -3700,9 +3855,9 @@ mod test { fn signed_area(anchors: &[DVec2]) -> f64 { (0..anchors.len()).map(|i| anchors[i].perp_dot(anchors[(i + 1) % anchors.len()])).sum::() / 2. } - fn subpath_winding_signs(vector: &Vector) -> Vec { + fn subpath_winding_signs(vector: &Vector, paths: &List) -> Vec { vector - .stroke_manipulator_groups() + .stroke_manipulator_groups(paths) .map(|(group, _)| signed_area(&group.iter().map(|g| g.anchor).collect::>()).signum()) .collect() } @@ -3710,18 +3865,18 @@ mod test { // The Rectangle and Ellipse generators define the framework's fill winding convention, built from these // shape constructors (`rectangle_bezpath` / `ellipse_bezpath`), so their winding is the source of truth. use vector_types::vector::algorithms::shapes::{ellipse_bezpath, rectangle_bezpath}; - let rectangle = Vector::from_bezpath(rectangle_bezpath(DVec2::new(-50., -50.), DVec2::new(50., 50.))); - let ellipse = Vector::from_bezpath(ellipse_bezpath(DVec2::new(-50., -25.), DVec2::new(50., 25.))); - let expected = subpath_winding_signs(&rectangle)[0]; - assert_eq!(subpath_winding_signs(&ellipse)[0], expected, "Rectangle and Ellipse should agree on winding"); + let (rectangle, rectangle_paths) = Vector::from_bezpath(&rectangle_bezpath(DVec2::new(-50., -50.), DVec2::new(50., 50.))); + let (ellipse, ellipse_paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::new(-50., -25.), DVec2::new(50., 25.))); + let expected = subpath_winding_signs(&rectangle, &rectangle_paths)[0]; + assert_eq!(subpath_winding_signs(&ellipse, &ellipse_paths)[0], expected, "Rectangle and Ellipse should agree on winding"); // Delaunay and Voronoi must emit subpaths that wind the same way as those generators. let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; let voronoi = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; - for sign in subpath_winding_signs(delaunay.element()) { + for sign in subpath_winding_signs(delaunay.element(), item_paths(&delaunay)) { assert_eq!(sign, expected, "Delaunay subpath winding should match the Rectangle/Ellipse generators"); } - for sign in subpath_winding_signs(voronoi.element()) { + for sign in subpath_winding_signs(voronoi.element(), item_paths(&voronoi)) { assert_eq!(sign, expected, "Voronoi subpath winding should match the Rectangle/Ellipse generators"); } } @@ -3729,25 +3884,27 @@ mod test { #[tokio::test] async fn delaunay_shared_mesh_welds_points_and_shares_edges() { let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await; + let paths = item_paths(&result); let vector = result.element(); // The connected mesh reuses the five input points and shares edges, so it fills face by face. - assert!(vector.use_face_fill()); - assert_eq!(vector.point_domain.ids().len(), 5); + assert!(vector.use_face_fill(paths)); + assert_eq!(vector.anchor_indices(paths).len(), 5); // Four hull edges plus four spokes to the center, each emitted once. - assert_eq!(vector.segment_domain.ids().len(), 8); + assert_eq!(vector.segment_ids(paths).len(), 8); } #[tokio::test] async fn voronoi_disconnected_cells_make_a_subpath_per_cell() { let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; + let paths = item_paths(&result); let vector = result.element(); - let cells = vector.stroke_manipulator_groups().filter(|(_, closed)| *closed).count(); + let cells = vector.stroke_manipulator_groups(paths).filter(|(_, closed)| *closed).count(); assert!(cells > 0, "expected at least one Voronoi cell"); // Every cell is a closed subpath, so segments and points come in matched per-cell loops. - assert_eq!(vector.segment_domain.ids().len(), vector.point_domain.ids().len()); + assert_eq!(vector.segment_ids(paths).len(), vector.anchor_indices(paths).len()); // Clipping to the convex hull keeps all cell vertices within the input bounds. - for &position in vector.point_domain.positions() { + for position in vector.anchor_positions(paths) { assert!(position.x >= -1e-6 && position.x <= 10. + 1e-6); assert!(position.y >= -1e-6 && position.y <= 10. + 1e-6); } @@ -3756,9 +3913,10 @@ mod test { #[tokio::test] async fn voronoi_shared_mesh_uses_face_fill() { let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await; + let paths = item_paths(&result); let vector = result.element(); - assert!(vector.use_face_fill()); - assert!(!vector.segment_domain.ids().is_empty()); + assert!(vector.use_face_fill(paths)); + assert!(!vector.segment_ids(paths).is_empty()); } #[tokio::test] @@ -3766,9 +3924,10 @@ mod test { // Two points cannot form a diagram, so the element passes through unchanged. let points = [DVec2::new(0., 0.), DVec2::new(1., 1.)]; let result = super::voronoi_cells((), vector_item_from_points(&points), item(false)).await; + let paths = item_paths(&result); let vector = result.element(); - assert_eq!(vector.point_domain.ids().len(), 2); - assert_eq!(vector.segment_domain.ids().len(), 0); + assert_eq!(vector.anchor_indices(paths).len(), 2); + assert_eq!(vector.segment_ids(paths).len(), 0); } #[tokio::test] @@ -3783,18 +3942,18 @@ mod test { DVec2::new(7., 5.), ]; let result = super::relax_points((), vector_item_from_points(&points), item(2.)).await; - let vector = result.element(); + let positions = result.element().anchor_positions(item_paths(&result)); // Relaxation preserves the point count but repositions the interior anchors within the hull. - assert_eq!(vector.point_domain.ids().len(), points.len()); - assert_ne!(vector.point_domain.positions(), &points[..]); + assert_eq!(positions.len(), points.len()); + assert_ne!(positions, points); // The convex-hull corners are pinned. Asserted on the count first, since zipping a short result // would skip the checks rather than fail them. - assert!(vector.point_domain.positions().len() >= 4, "the relaxed hull should still have its four corners"); - for (corner, (&position, &point)) in vector.point_domain.positions().iter().zip(&points).take(4).enumerate() { + assert!(positions.len() >= 4, "the relaxed hull should still have its four corners"); + for (corner, (&position, &point)) in positions.iter().zip(&points).take(4).enumerate() { assert_eq!(position, point, "hull corner {corner} should be pinned"); } - for &point in vector.point_domain.positions() { + for point in positions { assert!(point.x >= -1e-6 && point.x <= 10. + 1e-6); assert!(point.y >= -1e-6 && point.y <= 10. + 1e-6); } @@ -3802,11 +3961,12 @@ mod test { #[tokio::test] async fn bounding_box() { - let bounding_box = super::bounding_box((), Item::new_from_element(Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)))).await; + let bounding_box = super::bounding_box((), Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))).await; + let paths = item_paths(&bounding_box); let bounding_box = bounding_box.element(); - assert_eq!(bounding_box.stroke_manipulator_groups().count(), 1); + assert_eq!(bounding_box.stroke_manipulator_groups(paths).count(), 1); let manipulator_groups_anchors = bounding_box - .stroke_manipulator_groups() + .stroke_manipulator_groups(paths) .next() .unwrap() .0 @@ -3817,14 +3977,15 @@ mod test { assert_eq!(&manipulator_groups_anchors[..4], &[DVec2::NEG_ONE, DVec2::new(1., -1.), DVec2::ONE, DVec2::new(-1., 1.),]); // Test a rectangular path with nonzero rotation - let square = Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)); - let mut square = List::new_from_element(square); + let square = Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)); + let mut square = List::new_from_item(square); square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4)); let bounding_box = BoundingBoxNodeMapped { content: FutureWrapperNode(square) }.eval(Footprint::default()).await; + let paths = row_paths(&bounding_box, 0); let bounding_box = bounding_box.element(0).unwrap(); - assert_eq!(bounding_box.stroke_manipulator_groups().count(), 1); + assert_eq!(bounding_box.stroke_manipulator_groups(paths).count(), 1); let manipulator_groups_anchors = bounding_box - .stroke_manipulator_groups() + .stroke_manipulator_groups(paths) .next() .unwrap() .0 @@ -3842,7 +4003,10 @@ mod test { let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY); let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY); - let expected_points = Vector::from_bezpath(points.clone()).point_domain.positions().to_vec(); + let expected_points = { + let (vector, paths) = Vector::from_bezpath(&points); + vector.anchor_positions(&paths) + }; let copy_to_points = super::copy_to_points( Footprint::default(), @@ -3857,11 +4021,12 @@ mod test { ) .await; let combined = List::new_from_item(super::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(copy_to_points))).await); + let combined_paths = row_paths(&combined, 0); let combined_copy_to_points = combined.element(0).unwrap(); - assert_eq!(combined_copy_to_points.stroke_manipulator_groups().count(), expected_points.len()); + assert_eq!(combined_copy_to_points.stroke_manipulator_groups(combined_paths).count(), expected_points.len()); - for (index, (manipulator_groups, _)) in combined_copy_to_points.stroke_manipulator_groups().enumerate() { + for (index, (manipulator_groups, _)) in combined_copy_to_points.stroke_manipulator_groups(combined_paths).enumerate() { let offset = expected_points[index]; let manipulator_groups_anchors = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::>(); assert_eq!( @@ -3885,9 +4050,9 @@ mod test { Item::new_from_element(false), ) .await; - let sample_polyline = sample_polyline.element(); - assert_eq!(sample_polyline.point_domain.positions().len(), 4); - for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) { + let positions = sample_polyline.element().anchor_positions(item_paths(&sample_polyline)); + assert_eq!(positions.len(), 4); + for (pos, expected) in positions.iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) { assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}"); } } @@ -3905,9 +4070,9 @@ mod test { Item::new_from_element(true), ) .await; - let sample_polyline = sample_polyline.element(); - assert_eq!(sample_polyline.point_domain.positions().len(), 4); - for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) { + let positions = sample_polyline.element().anchor_positions(item_paths(&sample_polyline)); + assert_eq!(positions.len(), 4); + for (pos, expected) in positions.iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) { assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}"); } } @@ -3920,13 +4085,9 @@ mod test { Item::new_from_element(0), ) .await; - let poisson_points = poisson_points.element(); - assert!( - (20..=40).contains(&poisson_points.point_domain.positions().len()), - "actual len {}", - poisson_points.point_domain.positions().len() - ); - for point in poisson_points.point_domain.positions() { + let positions = poisson_points.element().anchor_positions(item_paths(&poisson_points)); + assert!((20..=40).contains(&positions.len()), "actual len {}", positions.len()); + for point in positions { assert!(point.length() < 50. + 1., "Expected point in circle {point}") } } @@ -3944,9 +4105,79 @@ mod test { #[tokio::test] async fn spline() { let spline = super::spline(Footprint::default(), vector_item_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))).await; + let paths = item_paths(&spline); let spline = spline.element(); - assert_eq!(spline.stroke_bezpath_iter().count(), 1); - assert_eq!(spline.point_domain.positions(), &[DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]); + assert_eq!(spline.stroke_bezpath_iter(paths).count(), 1); + assert_eq!(spline.anchor_positions(paths), [DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]); + assert_eq!(spline.colinear_pairs(paths).len(), 4, "every anchor of the closed spline should be smooth"); + + // An open spline is smooth only between its ends + let mut open = BezPath::new(); + open.move_to((0., 0.)); + open.line_to((10., 10.)); + open.line_to((20., 0.)); + open.line_to((30., 10.)); + let spline = super::spline(Footprint::default(), vector_item_from_bezpath(open)).await; + assert_eq!(smooth_anchors_by_contour(&spline), [[false, true, true, false]]); + } + + /// Whether each anchor keeps a smooth tangent pair, contour by contour. + fn smooth_anchors_by_contour(item: &Item) -> Vec> { + use vector_types::vector::misc::ManipulatorPointId; + + let (vector, paths) = (item.element(), item_paths(item)); + vector + .stroke_manipulator_groups(paths) + .map(|(group, _)| group.iter().map(|manipulators| vector.colinear(paths, ManipulatorPointId::Anchor(manipulators.id))).collect()) + .collect() + } + + // Existing handles are kept, so only the anchors without them are tangented and smooth + #[tokio::test] + async fn auto_tangents_marks_the_tangented_anchors_smooth() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 10.)); + bezpath.line_to((20., 0.)); + bezpath.line_to((30., 10.)); + bezpath.move_to((100., 0.)); + bezpath.line_to((150., 0.)); + bezpath.line_to((125., 40.)); + bezpath.close_path(); + bezpath.move_to((200., 0.)); + bezpath.curve_to((210., -20.), (240., 30.), (250., 0.)); + bezpath.line_to((250., 50.)); + bezpath.line_to((200., 50.)); + bezpath.close_path(); + + let output = super::auto_tangents((), vector_item_from_bezpath(bezpath), item(0.5), item(true)).await; + + assert_eq!( + smooth_anchors_by_contour(&output), + [vec![false, true, true, false], vec![true, true, true], vec![false, false, true, true]] + ); + } + + // A loop of one segment has no neighbor to share a tangent with, so it passes through unchanged + #[tokio::test] + async fn auto_tangents_keeps_a_single_segment_loop() { + let teardrop = CubicBez::new((0., 0.), (50., -50.), (100., 50.), (0., 0.)); + let mut bezpath = BezPath::new(); + bezpath.move_to(teardrop.p0); + bezpath.curve_to(teardrop.p1, teardrop.p2, teardrop.p3); + bezpath.close_path(); + bezpath.move_to((200., 0.)); + bezpath.line_to((250., 0.)); + bezpath.line_to((225., 40.)); + bezpath.close_path(); + + let output = super::auto_tangents((), vector_item_from_bezpath(bezpath), item(0.5), item(true)).await; + let paths = item_paths(&output); + + let segments: Vec = output.element().segment_iter(paths).map(|(_, segment, ..)| segment).collect(); + assert_eq!(segments.len(), 4); + assert!(segments.contains(&PathSeg::Cubic(teardrop)), "the loop should keep its curve, not among {segments:?}"); + assert_eq!(smooth_anchors_by_contour(&output), [vec![false], vec![true, true, true]]); } #[tokio::test] async fn morph() { @@ -3965,29 +4196,20 @@ mod test { ) .await; let morphed = List::new_from_item(morphed); - let morphed_element = morphed.element(0).unwrap(); + let morphed_positions = morphed.element(0).unwrap().anchor_positions(row_paths(&morphed, 0)); // Geometry stays in local space (original rectangle coordinates) - assert_eq!( - &morphed_element.point_domain.positions()[..4], - vec![DVec2::new(0., 0.), DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)] - ); + assert_eq!(&morphed_positions[..4], vec![DVec2::new(0., 0.), DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]); // The interpolated transform carries the midpoint translation (approximate due to arc-length parameterization) assert!((morphed.attribute_cloned_or_default::(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3); } #[tokio::test] async fn morph_interpolates_fill() { - let rect = || { - let mut v = Vector::default(); - v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); - v - }; + let rect = || Vector::item_from_bezpath(&Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); let solid_fill = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::from(List::new_from_element(color))); - let item_a = Item::new_from_element(rect()) - .with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY) - .with_attribute(ATTR_APPEARANCE, solid_fill(Color::RED)); - let item_b = Item::new_from_element(rect()) + let item_a = rect().with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY).with_attribute(ATTR_APPEARANCE, solid_fill(Color::RED)); + let item_b = rect() .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into())) .with_attribute(ATTR_APPEARANCE, solid_fill(Color::BLUE)); @@ -4018,11 +4240,7 @@ mod test { #[tokio::test] async fn morph_pairs_appearance_coverages_by_cover() { - let rect = || { - let mut v = Vector::default(); - v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); - v - }; + let rect = || Vector::item_from_bezpath(&Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); let paint_color = |appearance: &Appearance, cover| { let paint = appearance.first_paint_of(cover).expect("Morph should keep both paints at the midpoint"); @@ -4040,10 +4258,10 @@ mod test { appearance }; - let item_a = Item::new_from_element(rect()) + let item_a = rect() .with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY) .with_attribute(ATTR_APPEARANCE, appearance(Color::RED, Color::BLACK, CoverPlacement::Above)); - let item_b = Item::new_from_element(rect()) + let item_b = rect() .with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into())) .with_attribute(ATTR_APPEARANCE, appearance(Color::BLUE, Color::WHITE, CoverPlacement::Below)); @@ -4075,8 +4293,8 @@ mod test { } #[track_caller] - fn contains_segment(vector: Vector, target: PathSeg) { - let segments = vector.segment_iter().map(|x| x.1); + fn contains_segment(vector: &Vector, paths: &List, target: PathSeg) { + let segments = vector.segment_iter(paths).map(|x| x.1); let count = segments .filter(|segment| pathseg_abs_diff_eq(*segment, target, 0.01) || pathseg_abs_diff_eq(segment.reverse(), target, 0.01)) .count(); @@ -4085,7 +4303,7 @@ mod test { count, 1, "Expected exactly one matching segment for {target:?}, but found {count}. The given segments are: {:#?}", - vector.segment_iter().collect::>() + vector.segment_iter(paths).collect::>() ); } @@ -4093,22 +4311,23 @@ mod test { async fn bevel_rect() { let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY); let beveled = super::bevel(Footprint::default(), vector_item_from_bezpath(source), Item::new_from_element(2_f64.sqrt() * 10.)); + let paths = item_paths(&beveled); let beveled = beveled.element(); - assert_eq!(beveled.point_domain.positions().len(), 8); - assert_eq!(beveled.segment_domain.ids().len(), 8); + assert_eq!(beveled.anchor_positions(paths).len(), 8); + assert_eq!(beveled.segment_ids(paths).len(), 8); // Segments - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 0.), Point::new(90., 0.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(90., 100.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(0., 10.), Point::new(0., 90.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 10.), Point::new(100., 90.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 0.), Point::new(90., 0.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(90., 100.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(0., 10.), Point::new(0., 90.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 10.), Point::new(100., 90.)))); // Joins - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 0.), Point::new(0., 10.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(90., 0.), Point::new(100., 10.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 90.), Point::new(90., 100.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 0.), Point::new(0., 10.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(90., 0.), Point::new(100., 10.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 90.), Point::new(90., 100.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.)))); } #[tokio::test] @@ -4121,18 +4340,19 @@ mod test { source.push(curve.as_path_el()); let beveled = super::bevel((), vector_item_from_bezpath(source), Item::new_from_element(2_f64.sqrt() * 10.)); + let paths = item_paths(&beveled); let beveled = beveled.element(); - assert_eq!(beveled.point_domain.positions().len(), 4); - assert_eq!(beveled.segment_domain.ids().len(), 3); + assert_eq!(beveled.anchor_positions(paths).len(), 4); + assert_eq!(beveled.segment_ids(paths).len(), 3); // Segments - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), Point::new(-100., 0.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), Point::new(-100., 0.)))); let trimmed = trim_pathseg(curve, TValue::Euclidean(8.2 / curve.perimeter(DEFAULT_ACCURACY)), TValue::Parametric(1.)).unwrap(); - contains_segment(beveled.clone(), trimmed); + contains_segment(beveled, paths, trimmed); // Join - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start()))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start()))); } #[tokio::test] @@ -4145,21 +4365,22 @@ mod test { source.push(curve.as_path_el()); let transform = DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.)); - let vector_item = Item::new_from_element(Vector::from_bezpath(source)).with_attribute(ATTR_TRANSFORM, transform); + let vector_item = Vector::item_from_bezpath(&source).with_attribute(ATTR_TRANSFORM, transform); let beveled = super::bevel((), vector_item, Item::new_from_element(2_f64.sqrt() * 100.)); + let paths = item_paths(&beveled); let beveled = beveled.element(); - assert_eq!(beveled.point_domain.positions().len(), 4); - assert_eq!(beveled.segment_domain.ids().len(), 3); + assert_eq!(beveled.anchor_positions(paths).len(), 4); + assert_eq!(beveled.segment_ids(paths).len(), 3); // Segments - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), Point::new(-100., 0.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), Point::new(-100., 0.)))); let trimmed = trim_pathseg(curve, TValue::Euclidean(8.2 / curve.perimeter(DEFAULT_ACCURACY)), TValue::Parametric(1.)).unwrap(); - contains_segment(beveled.clone(), trimmed); + contains_segment(beveled, paths, trimmed); // Join - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start()))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start()))); } #[tokio::test] @@ -4171,19 +4392,20 @@ mod test { source.line_to(Point::new(0., 100.)); let beveled = super::bevel(Footprint::default(), vector_item_from_bezpath(source), Item::new_from_element(999.)); + let paths = item_paths(&beveled); let beveled = beveled.element(); - assert_eq!(beveled.point_domain.positions().len(), 6); - assert_eq!(beveled.segment_domain.ids().len(), 5); + assert_eq!(beveled.anchor_positions(paths).len(), 6); + assert_eq!(beveled.segment_ids(paths).len(), 5); // Segments - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(0., 0.), Point::new(50., 0.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(100., 50.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(0., 0.), Point::new(50., 0.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(100., 50.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.)))); // Joins - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(50., 0.), Point::new(100., 50.)))); - contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(50., 0.), Point::new(100., 50.)))); + contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.)))); } #[tokio::test] @@ -4195,10 +4417,11 @@ mod test { let subpath = BezPath::from_path_segments([line, point, curve].into_iter()); let beveled_item = super::bevel(Footprint::default(), vector_item_from_bezpath(subpath), Item::new_from_element(5.)); + let paths = item_paths(&beveled_item); let beveled = beveled_item.element(); - assert_eq!(beveled.point_domain.positions().len(), 6); - assert_eq!(beveled.segment_domain.ids().len(), 5); + assert_eq!(beveled.anchor_positions(paths).len(), 6); + assert_eq!(beveled.segment_ids(paths).len(), 5); } // A rank-0 vector reaches the same per-list styling path as a vector list, rather than being skipped @@ -4235,7 +4458,7 @@ mod test { let mut content = Item::new_from_element(Graphic::Vector(Box::new(item))); let mut visited = Vec::new(); - content.for_each_vector_mut(|vector, vector_transform| visited.push((vector.bounding_box(), vector_transform))); + content.for_each_vector_mut(|vector, vector_paths, vector_transform| visited.push((vector.bounding_box(vector_paths), vector_transform))); assert_eq!(visited.len(), 1, "the lone vector should be visited exactly once"); assert_eq!(visited[0].1, transform, "its own transform attribute should come along for placement"); @@ -4244,7 +4467,7 @@ mod test { async fn round_corners_of(bezpath: BezPath, transform: DAffine2) -> Vec { let rounded = super::round_corners((), create_vector_item(bezpath, transform), item(10.), item(0.5), item(100.), item(5.)).await; - rounded.element().stroke_bezpath_iter().collect() + rounded.element().stroke_bezpath_iter(item_paths(&rounded)).collect() } fn distance_to_path(point: DVec2, bezpath: &BezPath) -> f64 { From 514b894be36fe89c49105e129f054e89dc3093ec Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 16 Oct 2026 16:01:42 -0700 Subject: [PATCH 29/47] Finish porting the point nodes to vector pool storage and apply Path node edits in linear time (#4735) * Port the point nodes off the working form to weave the pool directly * Move quadratic handles and free points correctly under a point delta * Name a handle by its HandleId in the modification verbs * Apply a modification in linear passes over the working form --- .../tool/common_functionality/shape_editor.rs | 53 ++-- .../messages/tool/tool_messages/path_tool.rs | 32 +++ .../messages/tool/tool_messages/pen_tool.rs | 10 +- .../vector-types/src/vector/flatten.rs | 4 - .../src/vector/vector_modification.rs | 254 ++++++++++++----- .../vector-types/src/vector/vector_types.rs | 10 + node-graph/nodes/vector/src/vector_nodes.rs | 257 +++++++++++++----- 7 files changed, 439 insertions(+), 181 deletions(-) diff --git a/editor/src/messages/tool/common_functionality/shape_editor.rs b/editor/src/messages/tool/common_functionality/shape_editor.rs index f2ab877275..be21f9e96b 100644 --- a/editor/src/messages/tool/common_functionality/shape_editor.rs +++ b/editor/src/messages/tool/common_functionality/shape_editor.rs @@ -863,20 +863,6 @@ impl ShapeState { self.selected_shape_state.get(&layer).map(|state| &state.selected_segments) } - pub fn move_primary(&self, segment: SegmentId, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque) { - responses.add(GraphOperationMessage::Vector { - layer, - modification_type: VectorModificationType::ApplyPrimaryDelta { segment, delta }, - }); - } - - pub fn move_end(&self, segment: SegmentId, delta: DVec2, layer: LayerNodeIdentifier, responses: &mut VecDeque) { - responses.add(GraphOperationMessage::Vector { - layer, - modification_type: VectorModificationType::ApplyEndDelta { segment, delta }, - }); - } - pub fn move_anchor(&self, point: PointId, vector: &VectorGeometry, delta: DVec2, layer: LayerNodeIdentifier, selected: Option<&SelectedLayerState>, responses: &mut VecDeque) { // Move anchor responses.add(GraphOperationMessage::Vector { @@ -894,7 +880,10 @@ impl ShapeState { } let relative_position = handle - point_to_dvec2(path_segment.start()) + delta; - let modification_type = VectorModificationType::SetPrimaryHandle { segment, relative_position }; + let modification_type = VectorModificationType::SetHandlePosition { + handle: HandleId::primary(segment), + relative_position, + }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -919,24 +908,20 @@ impl ShapeState { let transform = network_interface.document_metadata().transform_to_document_if_feeds(layer, network_interface).inverse(); let position = transform.transform_point2(new_position); let current_position = vector.position_of(*point)?; - let delta = position - current_position; match *point { - ManipulatorPointId::Anchor(point) => self.move_anchor(point, &vector, delta, layer, None, responses), - ManipulatorPointId::PrimaryHandle(segment) => { - self.move_primary(segment, delta, layer, responses); - if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_pair_containing(handle) - { - let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; - responses.add(GraphOperationMessage::Vector { layer, modification_type }); - } - } - ManipulatorPointId::EndHandle(segment) => { - self.move_end(segment, delta, layer, responses); - if let Some(handle) = point.as_handle() - && let Some(handles) = vector.colinear_pair_containing(handle) - { + ManipulatorPointId::Anchor(anchor) => self.move_anchor(anchor, &vector, position - current_position, layer, None, responses), + ManipulatorPointId::PrimaryHandle(_) | ManipulatorPointId::EndHandle(_) => { + let handle = point.as_handle()?; + + // Set by its offset from the anchor, since a delta has no stored offset to add onto until the Path node edits this handle + let relative_position = position - vector.anchor_position_of(*point)?; + responses.add(GraphOperationMessage::Vector { + layer, + modification_type: handle.set_relative_position(relative_position), + }); + + if let Some(handles) = vector.colinear_pair_containing(handle) { let modification_type = VectorModificationType::SetG1Continuous { handles, enabled: false }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } @@ -1587,11 +1572,7 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); // Update segment - let HandleId { ty, segment } = handle; - let modification_type = match ty { - graphene_std::vector::misc::HandleType::Primary => VectorModificationType::SetStartPoint { segment, id }, - graphene_std::vector::misc::HandleType::End => VectorModificationType::SetEndPoint { segment, id }, - }; + let modification_type = VectorModificationType::SetEndpoint { handle, id }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index 493f5c61b0..7378fe3aae 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -4113,4 +4113,36 @@ mod test_path_tool { assert_eq!(pasted.colinear_pairs().len(), 2, "the pasted copy of the smooth anchor should be smooth too"); } + + // The ellipse's handles come from its generator, so the first typed position is the Path node's first edit to the handle + #[tokio::test] + async fn a_typed_handle_position_moves_the_handle_there() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_ellipse(100., 100., 300., 200.).await; + let layer = editor.get_selected_layer().await.expect("the drawn ellipse should be selected"); + + let handle_in_document = |editor: &EditorTestUtils, handle: ManipulatorPointId| { + let document = editor.active_document(); + let vector = document.network_interface.compute_modified_vector(layer).expect("the ellipse should have a vector"); + let to_document = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface); + to_document.transform_point2(vector.position_of(handle).expect("the handle should exist")) + }; + + let segment = { + let document = editor.active_document(); + let vector = document.network_interface.compute_modified_vector(layer).expect("the ellipse should have a vector"); + vector.segment_ids()[0] + }; + let handle = ManipulatorPointId::PrimaryHandle(segment); + let before = handle_in_document(&editor, handle); + + editor.select_tool(ToolType::Path).await; + editor.editor.dispatcher.message_handlers.tool_message_handler.shape_editor.select_point_by_layer_and_id(handle, layer); + editor.handle_message(PathToolMessage::SelectedPointUpdated).await; + editor.handle_message(PathToolMessage::SelectedPointXChanged { new_x: before.x + 5. }).await; + + let after = handle_in_document(&editor, handle); + assert!(after.distance(before + DVec2::new(5., 0.)) < 1e-6, "the handle moved from {before} to {after}"); + } } diff --git a/editor/src/messages/tool/tool_messages/pen_tool.rs b/editor/src/messages/tool/tool_messages/pen_tool.rs index 9c7d3facc8..2aadd7e852 100644 --- a/editor/src/messages/tool/tool_messages/pen_tool.rs +++ b/editor/src/messages/tool/tool_messages/pen_tool.rs @@ -596,12 +596,18 @@ impl PenToolData { } TargetHandle::PriorInHandle(segment) => { let relative_position = delta - anchor_pos; - let modification_type = VectorModificationType::SetEndHandle { segment, relative_position }; + let modification_type = VectorModificationType::SetHandlePosition { + handle: HandleId::end(segment), + relative_position, + }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } TargetHandle::PriorOutHandle(segment) => { let relative_position = delta - anchor_pos; - let modification_type = VectorModificationType::SetPrimaryHandle { segment, relative_position }; + let modification_type = VectorModificationType::SetHandlePosition { + handle: HandleId::primary(segment), + relative_position, + }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); } TargetHandle::None => {} diff --git a/node-graph/libraries/vector-types/src/vector/flatten.rs b/node-graph/libraries/vector-types/src/vector/flatten.rs index be20579b22..75cb09556b 100644 --- a/node-graph/libraries/vector-types/src/vector/flatten.rs +++ b/node-graph/libraries/vector-types/src/vector/flatten.rs @@ -124,10 +124,6 @@ impl WorkingVector { vector.set_smooth_at_indices(paths, smooth_anchors, true); } - - pub fn resolve_id(&self, id: PointId) -> Option { - self.point_ids.iter().position(|&check_id| check_id == id) - } } // TODO: Eventually remove this document upgrade code diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index b90388f901..743831087f 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -52,6 +52,8 @@ impl PointModification { working.point_positions.retain(|_| keep.next().unwrap_or_default()); working.point_ids.retain(|id| !self.remove.contains(id)); + // Gathering the moves first keeps the segment pass below off the common path where nothing moves + let mut moved: HashMap = HashMap::new(); for (index, id) in working.point_ids.iter().enumerate() { let Some(&delta) = self.delta.get(id) else { continue }; if !delta.is_finite() { @@ -60,17 +62,22 @@ impl PointModification { } working.point_positions[index] += delta; + moved.insert(index, delta); + } - for segment_index in 0..working.segment_ids.len() { - if working.segment_start[segment_index] == index { - working.segment_handles[segment_index].move_start(delta); + // Handles travel with their anchor, carried in one pass over the segment ends + if !moved.is_empty() { + for index in 0..working.segment_ids.len() { + if let Some(&delta) = moved.get(&working.segment_start[index]) { + working.segment_handles[index].move_start(delta); } - if working.segment_end[segment_index] == index { - working.segment_handles[segment_index].move_end(delta); + if let Some(&delta) = moved.get(&working.segment_end[index]) { + working.segment_handles[index].move_end(delta); } } } + let mut named: HashSet = if self.add.is_empty() { HashSet::new() } else { working.point_ids.iter().copied().collect() }; for &add_id in &self.add { let Some(&position) = self.delta.get(&add_id) else { continue }; if !position.is_finite() { @@ -78,8 +85,7 @@ impl PointModification { continue; } - #[cfg(debug_assertions)] - if working.point_ids.contains(&add_id) { + if !named.insert(add_id) { warn!("Tried to push a duplicate point to the working form"); continue; } @@ -144,16 +150,26 @@ impl SegmentModification { let mut keep_iter = keep.iter(); working.segment_ids.retain(|_| *keep_iter.next().unwrap_or(&false)); + // The points no longer change here, so one index serves every endpoint lookup below. + // Nothing looks an endpoint up in the common pure-handle case, so it skips the build. + let mut point_index: HashMap = HashMap::new(); + if !self.start_point.is_empty() || !self.end_point.is_empty() || !self.add.is_empty() { + point_index.reserve(working.point_ids.len()); + for (index, &id) in working.point_ids.iter().enumerate() { + point_index.entry(id).or_insert(index); + } + } + for (index, id) in working.segment_ids.iter().enumerate() { - if let Some(&new) = self.start_point.get(id) { - match working.resolve_id(new) { - Some(point) => working.segment_start[index] = point, + if let Some(new) = self.start_point.get(id) { + match point_index.get(new) { + Some(&point) => working.segment_start[index] = point, None => warn!("Invalid start ID when applying a segment modification"), } } - if let Some(&new) = self.end_point.get(id) { - match working.resolve_id(new) { - Some(point) => working.segment_end[index] = point, + if let Some(new) = self.end_point.get(id) { + match point_index.get(new) { + Some(&point) => working.segment_end[index] = point, None => warn!("Invalid end ID when applying a segment modification"), } } @@ -203,18 +219,24 @@ impl SegmentModification { }; } + let mut named: HashSet = if self.add.is_empty() { HashSet::new() } else { working.segment_ids.iter().copied().collect() }; for &add_id in &self.add { let Some(&start) = self.start_point.get(&add_id) else { continue }; let Some(&end) = self.end_point.get(&add_id) else { continue }; let Some(&handle_start) = self.handle_primary.get(&add_id) else { continue }; let Some(&handle_end) = self.handle_end.get(&add_id) else { continue }; - let Some(start_index) = working.resolve_id(start) else { - warn!("invalid start id: {start:#?}"); + if !named.insert(add_id) { + warn!("Tried to push a duplicate segment to the working form"); + continue; + } + + let Some(&start_index) = point_index.get(&start) else { + warn!("Invalid start ID: {start:#?}"); continue; }; - let Some(end_index) = working.resolve_id(end) else { - warn!("invalid end id: {end:#?}"); + let Some(&end_index) = point_index.get(&end) else { + warn!("Invalid end ID: {end:#?}"); continue; }; @@ -230,7 +252,7 @@ impl SegmentModification { }; if !handles.is_finite() { - warn!("invalid handles"); + warn!("Invalid handles"); continue; } @@ -267,6 +289,22 @@ impl SegmentModification { } } + /// The handle map for the side of its segment that the given handle sits on. + fn handle_side_of(&mut self, handle: HandleId) -> &mut HashMap> { + match handle.ty { + HandleType::Primary => &mut self.handle_primary, + HandleType::End => &mut self.handle_end, + } + } + + /// The endpoint map for the side of its segment that the given handle sits on. + fn endpoint_side_of(&mut self, handle: HandleId) -> &mut HashMap { + match handle.ty { + HandleType::Primary => &mut self.start_point, + HandleType::End => &mut self.end_point, + } + } + fn push(&mut self, id: SegmentId, points: [PointId; 2], handles: [Option; 2]) { self.remove.remove(&id); self.add.push(id); @@ -302,22 +340,45 @@ pub struct VectorModification { #[derive(PartialEq, Clone, Debug)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum VectorModificationType { - InsertSegment { id: SegmentId, points: [PointId; 2], handles: [Option; 2] }, - InsertPoint { id: PointId, position: DVec2 }, + InsertSegment { + id: SegmentId, + points: [PointId; 2], + handles: [Option; 2], + }, + InsertPoint { + id: PointId, + position: DVec2, + }, - RemoveSegment { id: SegmentId }, - RemovePoint { id: PointId }, + RemoveSegment { + id: SegmentId, + }, + RemovePoint { + id: PointId, + }, - SetG1Continuous { handles: [HandleId; 2], enabled: bool }, - SetHandles { segment: SegmentId, handles: [Option; 2] }, - SetPrimaryHandle { segment: SegmentId, relative_position: DVec2 }, - SetEndHandle { segment: SegmentId, relative_position: DVec2 }, - SetStartPoint { segment: SegmentId, id: PointId }, - SetEndPoint { segment: SegmentId, id: PointId }, + SetG1Continuous { + handles: [HandleId; 2], + enabled: bool, + }, + SetHandles { + segment: SegmentId, + handles: [Option; 2], + }, + SetHandlePosition { + handle: HandleId, + relative_position: DVec2, + }, + /// Reconnects one end of the handle's segment to another point: the start for a primary handle, the end for an end handle. + SetEndpoint { + handle: HandleId, + id: PointId, + }, - ApplyPointDelta { point: PointId, delta: DVec2 }, - ApplyPrimaryDelta { segment: SegmentId, delta: DVec2 }, - ApplyEndDelta { segment: SegmentId, delta: DVec2 }, + ApplyPointDelta { + point: PointId, + delta: DVec2, + }, } impl VectorModificationType { @@ -325,13 +386,8 @@ impl VectorModificationType { fn is_finite(&self) -> bool { match self { Self::InsertSegment { handles, .. } | Self::SetHandles { handles, .. } => handles.iter().flatten().all(|handle| handle.is_finite()), - Self::InsertPoint { position: value, .. } - | Self::SetPrimaryHandle { relative_position: value, .. } - | Self::SetEndHandle { relative_position: value, .. } - | Self::ApplyPointDelta { delta: value, .. } - | Self::ApplyPrimaryDelta { delta: value, .. } - | Self::ApplyEndDelta { delta: value, .. } => value.is_finite(), - Self::RemoveSegment { .. } | Self::RemovePoint { .. } | Self::SetG1Continuous { .. } | Self::SetStartPoint { .. } | Self::SetEndPoint { .. } => true, + Self::InsertPoint { position: value, .. } | Self::SetHandlePosition { relative_position: value, .. } | Self::ApplyPointDelta { delta: value, .. } => value.is_finite(), + Self::RemoveSegment { .. } | Self::RemovePoint { .. } | Self::SetG1Continuous { .. } | Self::SetEndpoint { .. } => true, } } } @@ -444,14 +500,18 @@ impl VectorModification { self.points.apply(&mut working); self.segments.apply(&mut working); - let valid = |val: &[HandleId; 2]| working.segment_ids.contains(&val[0].segment) && working.segment_ids.contains(&val[1].segment); + let surviving_segments: HashSet = working.segment_ids.iter().copied().collect(); + let valid = |val: &[HandleId; 2]| surviving_segments.contains(&val[0].segment) && surviving_segments.contains(&val[1].segment); working .colinear .retain(|val| !self.remove_g1_continuous.contains(val) && !self.remove_g1_continuous.contains(&[val[1], val[0]]) && valid(val)); + // Both orientations go in, since a pair and its reverse name the same tangent + let mut present: HashSet<[HandleId; 2]> = working.colinear.iter().flat_map(|&[first, second]| [[first, second], [second, first]]).collect(); for handles in &self.add_g1_continuous { - if !working.colinear.iter().any(|test| test == handles || test == &[handles[1], handles[0]]) && valid(handles) { + if !present.contains(handles) && valid(handles) { working.colinear.push(*handles); + present.extend([*handles, [handles[1], handles[0]]]); } } @@ -492,30 +552,16 @@ impl VectorModification { self.segments.handle_primary.insert(*segment, handles[0]); self.segments.handle_end.insert(*segment, handles[1]); } - VectorModificationType::SetPrimaryHandle { segment, relative_position } => { - self.segments.handle_primary.insert(*segment, Some(*relative_position)); + VectorModificationType::SetHandlePosition { handle, relative_position } => { + self.segments.handle_side_of(*handle).insert(handle.segment, Some(*relative_position)); } - VectorModificationType::SetEndHandle { segment, relative_position } => { - self.segments.handle_end.insert(*segment, Some(*relative_position)); - } - VectorModificationType::SetStartPoint { segment, id } => { - self.segments.start_point.insert(*segment, *id); - } - VectorModificationType::SetEndPoint { segment, id } => { - self.segments.end_point.insert(*segment, *id); + VectorModificationType::SetEndpoint { handle, id } => { + self.segments.endpoint_side_of(*handle).insert(handle.segment, *id); } VectorModificationType::ApplyPointDelta { point, delta } => { *self.points.delta.entry(*point).or_default() += *delta; } - VectorModificationType::ApplyPrimaryDelta { segment, delta } => { - let position = self.segments.handle_primary.entry(*segment).or_default(); - *position = Some(position.unwrap_or_default() + *delta); - } - VectorModificationType::ApplyEndDelta { segment, delta } => { - let position = self.segments.handle_end.entry(*segment).or_default(); - *position = Some(position.unwrap_or_default() + *delta); - } } } @@ -648,11 +694,7 @@ pub trait HandleExt { impl HandleExt for HandleId { fn set_relative_position(self, relative_position: DVec2) -> VectorModificationType { - let Self { ty, segment } = self; - match ty { - HandleType::Primary => VectorModificationType::SetPrimaryHandle { segment, relative_position }, - HandleType::End => VectorModificationType::SetEndHandle { segment, relative_position }, - } + VectorModificationType::SetHandlePosition { handle: self, relative_position } } } @@ -672,6 +714,88 @@ mod tests { vector.position(vector.index_of_point_id(id).unwrap() as usize).unwrap() } + // Re-adding a segment or point under an ID the geometry already holds adds no second copy under that ID + #[test] + fn duplicate_adds_are_skipped() { + use kurbo::{Rect, Shape}; + + let (mut vector, mut paths) = Vector::from_bezpath(&Rect::new(0., 0., 10., 10.).to_path(0.)); + let segment = vector.segment_iter(&paths).next().map(|(id, ..)| id).unwrap(); + let [start, end] = [anchor_id(&vector, &paths, 0), anchor_id(&vector, &paths, 2)]; + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::InsertSegment { + id: segment, + points: [start, end], + handles: [None, None], + }); + modification.modify(&VectorModificationType::InsertPoint { + id: start, + position: DVec2::new(99., 99.), + }); + modification.apply(&mut vector, &mut paths); + + assert_eq!(vector.segment_iter(&paths).count(), 4); + assert_eq!(vector.anchor_points(&paths).count(), 4); + let ids: HashSet<_> = vector.segment_iter(&paths).map(|(id, ..)| id).collect(); + assert_eq!(ids.len(), 4); + } + + // An end handle addresses the end of its segment, both where its handle sits and which point that end connects to + #[test] + fn end_handles_address_the_end_of_their_segment() { + let mut open = BezPath::new(); + open.move_to(Point::new(0., 0.)); + open.curve_to(Point::new(1., 1.), Point::new(2., 1.), Point::new(3., 0.)); + + let (vector, paths) = Vector::from_bezpath(&open); + let segment = vector.segment_iter(&paths).next().map(|(id, ..)| id).unwrap(); + let new_end = PointId::generate(); + + let mut modification = VectorModification::create_from_vector(&vector, &paths); + modification.modify(&VectorModificationType::InsertPoint { + id: new_end, + position: DVec2::new(10., 5.), + }); + modification.modify(&VectorModificationType::SetEndpoint { + handle: HandleId::end(segment), + id: new_end, + }); + modification.modify(&HandleId::end(segment).set_relative_position(DVec2::new(1., 2.))); + + let (mut applied, mut applied_paths) = (Vector::default(), List::new()); + modification.apply(&mut applied, &mut applied_paths); + + let (_, curve, start, end) = applied.segment_iter(&applied_paths).find(|&(id, ..)| id == segment).unwrap(); + assert_eq!(curve, PathSeg::Cubic(kurbo::CubicBez::new((0., 0.), (1., 1.), (11., 7.), (10., 5.)))); + assert_eq!(start, anchor_id(&vector, &paths, 0)); + assert_eq!(end, new_end); + } + + // A pair and its reverse name the same tangent, so removing either order clears a pair the incoming geometry holds + #[test] + fn g1_pair_removal_ignores_the_order_of_its_handles() { + let mut open = BezPath::new(); + open.move_to(Point::new(0., 0.)); + open.curve_to(Point::new(1., 1.), Point::new(2., 1.), Point::new(3., 0.)); + open.curve_to(Point::new(4., -1.), Point::new(5., -1.), Point::new(6., 0.)); + + let (mut smooth, mut smooth_paths) = Vector::from_bezpath(&open); + let middle = anchor_id(&smooth, &smooth_paths, 1); + smooth.set_smooth(&mut smooth_paths, middle, true); + let pairs = smooth.colinear_pairs(&smooth_paths); + let [pair] = pairs[..] else { panic!("the middle anchor should be smooth, not {pairs:?}") }; + + for removed in [pair, [pair[1], pair[0]]] { + let (mut vector, mut paths) = (smooth.clone(), smooth_paths.clone()); + let mut modification = VectorModification::default(); + modification.remove_g1_continuous.insert(removed); + modification.apply(&mut vector, &mut paths); + + assert!(vector.colinear_pairs(&paths).is_empty(), "removing {removed:?} should clear the tangent"); + } + } + #[test] fn modify_new() { let (mut vector, mut paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::ZERO, DVec2::ONE)); @@ -732,8 +856,8 @@ mod tests { #[test] fn non_finite_modifications_are_ignored() { let mut modification = VectorModification::default(); - modification.modify(&VectorModificationType::SetPrimaryHandle { - segment: SegmentId::generate(), + modification.modify(&VectorModificationType::SetHandlePosition { + handle: HandleId::primary(SegmentId::generate()), relative_position: DVec2::NAN, }); modification.modify(&VectorModificationType::ApplyPointDelta { diff --git a/node-graph/libraries/vector-types/src/vector/vector_types.rs b/node-graph/libraries/vector-types/src/vector/vector_types.rs index 86f51aa7b9..4b10f76291 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_types.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_types.rs @@ -384,6 +384,16 @@ impl Vector { .collect() } + /// Drops the paths and every point used only as a handle, leaving the anchors and free points as a bare cloud. + /// A point serving as an anchor in any path is kept even where another path uses it as a handle. + pub fn keep_only_anchors(&mut self, paths: &mut List) { + let anchors = self.anchor_indices(paths); + let pool = anchors.into_iter().filter_map(|index| self.0.clone_item(index)).collect(); + + self.0 = pool; + *paths = List::new(); + } + /// The positions of all anchor points and free points in pool order, skipping handles. pub fn anchor_positions(&self, paths: &List) -> Vec { self.anchor_indices(paths).into_iter().filter_map(|index| self.position(index)).collect() diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index a7bc75d1f7..6a26f286ed 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -33,7 +33,10 @@ use vector_types::vector::misc::{ bezpath_from_manipulator_groups, dvec2_to_point, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles, }; use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin}; -use vector_types::vector::{Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, no_paths, paths_from_item_attributes, paths_from_list_row_attributes}; +use vector_types::vector::{ + CurveType, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, handle_point, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path, + span_endpoints, spans, +}; /// Appends one point to the working form, returning the index that names it. pub(crate) fn push_working_point(working: &mut WorkingVector, id: PointId, position: DVec2) -> usize { @@ -1415,27 +1418,23 @@ async fn points_to_polyline(_: impl Ctx, #[implem let mut points = points; edit_item_geometry(&mut points, |vector, paths| { - let flattened = WorkingVector::flatten(vector, paths); - let mut working = WorkingVector { - point_ids: flattened.point_ids, - point_positions: flattened.point_positions, - ..Default::default() - }; - let mut next_id = SegmentId::ZERO; + vector.keep_only_anchors(paths); - let points_count = working.point_ids.len(); - - if points_count >= 2 { - (0..points_count - 1).for_each(|i| { - push_working_segment(&mut working, next_id.next_id(), i, i + 1, BezierHandles::Linear); - }); - - if closed && points_count != 2 { - push_working_segment(&mut working, next_id.next_id(), points_count - 1, 0, BezierHandles::Linear); - } + let points_count = vector.point_count(); + if points_count < 2 { + return; } - working.reweave(vector, paths); + // A pair has nowhere to close back to, so its two anchors draw one segment either way + let closing = closed && points_count != 2; + let mut next_id = SegmentId::ZERO; + + push_path( + paths, + CurveType::Linear, + (0..points_count as u32).chain(closing.then_some(0)), + std::iter::repeat_with(|| next_id.next_id()), + ); }); points @@ -2400,7 +2399,7 @@ async fn scatter_points( let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64); - let mut result = WorkingVector::default(); + let mut cloud = List::new(); let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); let path_with_bounding_boxes: Vec<_> = content @@ -2420,11 +2419,16 @@ async fn scatter_points( } for point in bezpath_algorithms::poisson_disk_points(i, &path_with_bounding_boxes, separation, || rng.random::()) { - push_working_point(&mut result, PointId::generate(), point); + cloud.push(Item::new_from_element(point).with_attribute(ATTR_ID, PointId::generate())); } } - edit_item_geometry(&mut content, |vector, paths| result.reweave(vector, paths)); + // The scattered points replace the source shape entirely, leaving no paths + edit_item_geometry(&mut content, |vector, paths| { + *vector = Vector(cloud); + *paths = List::new(); + }); + content }) } @@ -2440,20 +2444,30 @@ async fn spline(_: impl Ctx, #[implementations(Gr edit_item_geometry(&mut content, |vector, paths| { let manipulator_runs = vector.stroke_manipulator_groups(paths).collect::>(); + vector.keep_only_anchors(paths); - let flattened = WorkingVector::flatten(vector, paths); - let mut working = WorkingVector { - point_ids: flattened.point_ids, - point_positions: flattened.point_positions, - ..Default::default() - }; + // An ID shared by several points resolves to the first of them + let mut anchor_index: HashMap = HashMap::new(); + for index in 0..vector.point_count() as u32 { + if let Some(id) = vector.point_id_at(index) { + anchor_index.entry(id).or_insert(index); + } + } let mut next_id = SegmentId::ZERO; let mut smooth_anchors = Vec::new(); for (manipulator_groups, closed) in manipulator_runs { let positions = manipulator_groups.iter().map(|manipulators| manipulators.anchor).collect::>(); + if positions.len() < 2 { + continue; + } let closed = closed && positions.len() > 2; + let Some(anchors) = manipulator_groups.iter().map(|group| anchor_index.get(&group.id).copied()).collect::>>() else { + log::error!("Spline skipped a run with anchor IDs that name no point"); + continue; + }; + // The spline runs smoothly through every anchor with a segment on each side let interior = if closed { &manipulator_groups[..] @@ -2469,22 +2483,27 @@ async fn spline(_: impl Ctx, #[implementations(Gr solve_spline_first_handle_open(&positions) }; - // Create segments with computed Bezier handles and add them to the output vector element's segments. - for i in 0..(positions.len() - if closed { 0 } else { 1 }) { + // Weave the run as one cubic path, each span's two handles appended to the pool and referenced between its anchors + let span_count = positions.len() - if closed { 0 } else { 1 }; + let (mut references, mut ids) = (Vec::with_capacity(span_count * 3 + 1), Vec::with_capacity(span_count)); + + for i in 0..span_count { let next_index = (i + 1) % positions.len(); - - let start_index = working.resolve_id(manipulator_groups[i].id).unwrap(); - let end_index = working.resolve_id(manipulator_groups[next_index].id).unwrap(); - let handle_start = first_handles[i]; let handle_end = positions[next_index] * 2. - first_handles[next_index]; - let handles = BezierHandles::Cubic { handle_start, handle_end }; - push_working_segment(&mut working, next_id.next_id(), start_index, end_index, handles); + references.push(anchors[i]); + for handle in [handle_start, handle_end] { + references.push(vector.point_count() as u32); + vector.0.push(Item::new_from_element(handle).with_attribute(ATTR_ID, PointId::UNNAMED)); + } + ids.push(next_id.next_id()); } + references.push(anchors[span_count % positions.len()]); + + push_path(paths, CurveType::Cubic, references, ids); } - working.reweave(vector, paths); vector.set_smooth_points(paths, smooth_anchors, true); }); @@ -2513,38 +2532,40 @@ fn inverse_linear_or_repair(linear: DMat2) -> DMat2 { repaired.inverse() } -/// Applies per-anchor displacement deltas to the anchor and handle positions of a vector element. -fn apply_point_deltas(vector: &mut Vector, paths: &mut List, deltas: &[DVec2], transform: DAffine2) { - let mut working = WorkingVector::flatten(vector, paths); - let mut already_applied = vec![false; working.point_positions.len()]; +/// Applies displacement deltas to the anchors at the given pool indices, moving the handles of their segments along with them. +fn apply_point_deltas(vector: &mut Vector, paths: &List, anchors: &[usize], deltas: &[DVec2]) { + let mut anchor_delta = vec![None; vector.point_count()]; + for (&anchor, &delta) in anchors.iter().zip(deltas) { + anchor_delta[anchor] = Some(delta); + } + let mut delta_at: Vec = anchor_delta.iter().map(|delta| delta.unwrap_or_default()).collect(); + let delta_of = |anchor: u32| anchor_delta.get(anchor as usize).copied().flatten().unwrap_or_default(); - for index in 0..working.segment_ids.len() { - let (start, end) = (working.segment_start[index], working.segment_end[index]); - let start_delta = deltas[start]; - let end_delta = deltas[end]; + // A handle travels with the anchor on its own side of the segment, unless it is also an anchor with a delta of its own + for span in spans(paths) { + let Some((start, end)) = span_endpoints(paths, span) else { continue }; + let (start_delta, end_delta) = (delta_of(start), delta_of(end)); - if !already_applied[start] { - working.point_positions[start] += start_delta; - already_applied[start] = true; - } - if !already_applied[end] { - working.point_positions[end] += end_delta; - already_applied[end] = true; - } + let carried = match curve_type_at(paths, span.path as usize) { + CurveType::Linear => [(None, DVec2::ZERO); 2], + // A quadratic's lone handle answers to both anchors, so it splits the difference between them + CurveType::Quadratic => [(handle_point(paths, span, true), (start_delta + end_delta) / 2.), (None, DVec2::ZERO)], + CurveType::Cubic => [(handle_point(paths, span, true), start_delta), (handle_point(paths, span, false), end_delta)], + }; - match &mut working.segment_handles[index] { - BezierHandles::Cubic { handle_start, handle_end } => { - *handle_start += start_delta; - *handle_end += end_delta; + for (handle, delta) in carried { + if let Some(handle) = handle + && anchor_delta.get(handle as usize).is_some_and(Option::is_none) + && let Some(slot) = delta_at.get_mut(handle as usize) + { + *slot = delta; } - BezierHandles::Quadratic { handle } => { - *handle = transform.transform_point2(*handle) + (start_delta + end_delta) / 2.; - } - BezierHandles::Linear => {} } } - working.reweave(vector, paths); + for (position, delta) in vector.0.iter_element_values_mut().zip(delta_at) { + *position += delta; + } } /// Perturbs the positions of anchor points in vector geometry by random amounts and directions. @@ -2573,12 +2594,11 @@ async fn jitter_points( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2); - let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); edit_item_geometry(&mut content, |vector, paths| { - let deltas: Vec<_> = vector - .anchor_indices(paths) - .into_iter() - .map(|point_index| { + let anchors = vector.anchor_indices(paths); + let deltas: Vec<_> = anchors + .iter() + .map(|&point_index| { let normal = if along_normals { vector.point_tangent(paths, point_index).map(|t| -t.perp()) } else { None }; let offset = if let Some(normal) = normal { @@ -2591,7 +2611,7 @@ async fn jitter_points( }) .collect(); - apply_point_deltas(vector, paths, &deltas, transform); + apply_point_deltas(vector, paths, &anchors, &deltas); }); content @@ -2617,12 +2637,11 @@ async fn offset_points( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2); - let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); edit_item_geometry(&mut content, |vector, paths| { - let deltas: Vec<_> = vector - .anchor_indices(paths) - .into_iter() - .map(|point_index| { + let anchors = vector.anchor_indices(paths); + let deltas: Vec<_> = anchors + .iter() + .map(|&point_index| { let Some(normal) = vector.point_tangent(paths, point_index).map(|t| -t.perp()) else { return DVec2::ZERO; }; @@ -2631,7 +2650,7 @@ async fn offset_points( }) .collect(); - apply_point_deltas(vector, paths, &deltas, transform); + apply_point_deltas(vector, paths, &anchors, &deltas); }); content @@ -3818,6 +3837,57 @@ mod test { assert_eq!(result.element().segment_iter(&paths).count(), 0); } + // The lone handle of a quadratic answers to both anchors, so it moves by the average of their deltas + #[test] + fn point_deltas_carry_a_quadratic_handle_with_both_anchors() { + let mut quadratic = BezPath::new(); + quadratic.move_to((0., 0.)); + quadratic.quad_to((5., 10.), (10., 0.)); + + let (mut vector, paths) = Vector::from_bezpath(&quadratic); + let anchors = vector.anchor_indices(&paths); + super::apply_point_deltas(&mut vector, &paths, &anchors, &[DVec2::X, DVec2::X * 3.]); + + assert_eq!(vector.position(0), Some(DVec2::new(1., 0.))); + assert_eq!(vector.position(1), Some(DVec2::new(7., 10.))); + assert_eq!(vector.position(2), Some(DVec2::new(13., 0.))); + } + + // A point no segment touches still takes its delta, so jitter can shift a bare point cloud + #[test] + fn point_deltas_move_free_floating_points() { + let cloud = vector_item_from_points(&[DVec2::ZERO, DVec2::new(10., 0.)]); + let paths = item_paths(&cloud).clone(); + let mut vector = cloud.element().clone(); + + let anchors = vector.anchor_indices(&paths); + super::apply_point_deltas(&mut vector, &paths, &anchors, &[DVec2::Y, DVec2::Y * 2.]); + + assert_eq!(vector.position(0), Some(DVec2::new(0., 1.))); + assert_eq!(vector.position(1), Some(DVec2::new(10., 2.))); + } + + // Point 1 is a handle of the first path and an anchor of the second, so it keeps its own delta rather than its neighbor's + #[test] + fn point_deltas_keep_an_anchor_that_is_also_a_handle_on_its_own_delta() { + let mut vector = Vector::default(); + for x in 0..7 { + vector.0.push(Item::new_from_element(DVec2::new(x as f64 * 10., 0.))); + } + let mut paths = List::new(); + vector_types::vector::push_path(&mut paths, CurveType::Cubic, [0, 1, 2, 3], []); + vector_types::vector::push_path(&mut paths, CurveType::Cubic, [1, 4, 5, 6], []); + + let anchors = vector.anchor_indices(&paths); + assert_eq!(anchors, [0, 1, 3, 6]); + super::apply_point_deltas(&mut vector, &paths, &anchors, &[DVec2::X, DVec2::Y, DVec2::X * 2., DVec2::X * 3.]); + + assert_eq!(vector.position(1), Some(DVec2::new(10., 1.))); + assert_eq!(vector.position(2), Some(DVec2::new(22., 0.))); + assert_eq!(vector.position(4), Some(DVec2::new(40., 1.))); + assert_eq!(vector.position(5), Some(DVec2::new(53., 0.))); + } + #[tokio::test] async fn offset_path_does_not_duplicate_closing_anchors() { // Offsetting closed triangles must not leave each subpath with a redundant start/end anchor (a Kurbo offset @@ -4121,6 +4191,45 @@ mod test { assert_eq!(smooth_anchors_by_contour(&spline), [[false, true, true, false]]); } + // A curved source's handles are replaced by the spline's own rather than kept alongside them + #[tokio::test] + async fn spline_replaces_the_handles_of_a_curved_source() { + let ellipse = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))); + let anchors = ellipse.element().anchor_positions(item_paths(&ellipse)); + assert_eq!(anchors.len(), 4); + + let spline = super::spline(Footprint::default(), ellipse).await; + let paths = item_paths(&spline); + let spline = spline.element(); + + assert_eq!(spline.anchor_positions(paths), anchors); + assert_eq!(spline.segment_iter(paths).count(), 4); + assert_eq!(spline.point_count(), 4 + 4 * 2, "each of the four spans should hold two new handles and no old ones"); + } + + // Only the source's anchors become corners, joined by lines in their stored order + #[tokio::test] + async fn points_to_polyline_joins_the_anchors_with_lines() { + let ellipse = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))); + let anchors = ellipse.element().anchor_positions(item_paths(&ellipse)); + + let closed = super::points_to_polyline(Footprint::default(), ellipse.clone(), item(true)).await; + let paths = item_paths(&closed); + let segments: Vec = closed.element().segment_iter(paths).map(|(_, segment, ..)| segment).collect(); + assert_eq!(closed.element().point_count(), anchors.len(), "the source's handles should be dropped"); + assert_eq!(closed.element().anchor_positions(paths), anchors); + assert_eq!(segments.len(), 4); + assert!(segments.iter().all(|segment| matches!(segment, PathSeg::Line(_)))); + assert!(closed.element().stroke_bezpath_iter(paths).all(|bezpath| bezpath.elements().last() == Some(&PathEl::ClosePath))); + + let open = super::points_to_polyline(Footprint::default(), ellipse, item(false)).await; + assert_eq!(open.element().segment_iter(item_paths(&open)).count(), 3); + + // Two points have nowhere to close back to, so they draw one segment either way + let pair = super::points_to_polyline(Footprint::default(), vector_item_from_points(&[DVec2::ZERO, DVec2::X]), item(true)).await; + assert_eq!(pair.element().segment_iter(item_paths(&pair)).count(), 1); + } + /// Whether each anchor keeps a smooth tangent pair, contour by contour. fn smooth_anchors_by_contour(item: &Item) -> Vec> { use vector_types::vector::misc::ManipulatorPointId; From 9e19a46ba645b7217a26be6a029ebed4971c35ab Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 16 Oct 2026 17:26:11 -0700 Subject: [PATCH 30/47] Build vector pool storage in bulk and apply move-only Path node edits in place (#4736) * Build a list from its elements and write an attribute for every item at once * Index connectivity roles once and build pools, paths, and IDs in bulk * Apply point and handle moves in place without reweaving the paths * Walk contours with curve types read once and tally junction spokes in a single pass --- node-graph/libraries/core-types/src/list.rs | 63 +++ .../vector-types/src/vector/addressing.rs | 8 +- .../vector-types/src/vector/connectivity.rs | 82 +-- .../vector-types/src/vector/contour.rs | 35 +- .../vector-types/src/vector/flatten.rs | 74 +-- .../libraries/vector-types/src/vector/path.rs | 62 ++- .../src/vector/vector_attributes.rs | 39 +- .../src/vector/vector_modification.rs | 493 +++++++++++++++++- .../vector-types/src/vector/vector_types.rs | 125 +++-- 9 files changed, 791 insertions(+), 190 deletions(-) diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index 128f1ff515..399f573bdc 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -909,6 +909,23 @@ impl Attributes { attribute.0[index] = value; } + /// Replaces the attribute for the given key with one value per item, keeping its place unless its type changes. + fn set_attribute_values(&mut self, key: String, values: Vec) { + // An attribute changing type moves to the end, as it does when set one value at a time + let existing = self.attributes.iter().position(|(k, _)| k == &key); + let same_type = existing.is_some_and(|position| (*self.attributes[position].1).as_any().downcast_ref::>().is_some()); + + let attribute: Box = Box::new(Attribute(values)); + match existing { + Some(position) if same_type => self.attributes[position].1 = attribute, + Some(position) => { + self.attributes.remove(position); + self.attributes.push((key, attribute)); + } + None => self.attributes.push((key, attribute)), + } + } + /// Returns a debug-formatted string for the value at the given index in the attribute for the given key. fn display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option) -> Option { self.attributes.iter().find_map(|(k, attribute)| { @@ -1029,6 +1046,15 @@ impl List { } } + /// Creates a list holding the given elements in order, with no attributes. + pub fn new_from_elements(elements: Vec) -> Self { + let len = elements.len(); + Self { + element: elements, + attributes: Attributes::with_len(len), + } + } + /// Creates a list containing a single item from the given [`Item`], preserving its attributes. pub fn new_from_item(item: Item) -> Self { let mut attributes = Attributes::new(); @@ -1140,6 +1166,18 @@ impl List { self.attributes.set_value(key, index, value); } + /// Sets the attribute's value for every item at once from one value per item, replacing any values the key held (an empty list still gains the key). + /// Logs an error and leaves the list unchanged if the number of values differs from the number of items. + pub fn set_attribute_values(&mut self, key: impl Into, values: Vec) { + let key = key.into(); + if values.len() != self.element.len() { + log::error!("Attribute '{key}' was given {} values for a list of {} items", values.len(), self.element.len()); + return; + } + + self.attributes.set_attribute_values(key, values); + } + /// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length). /// Falls back to default if the value's type doesn't match an existing attribute. pub fn set_attribute_value_dyn(&mut self, key: impl Into, index: usize, value: AttributeValueDyn) { @@ -1577,4 +1615,29 @@ mod tests { other.push(Item::new_from_element(()).with_attribute(ATTR_START, 5_u64)); assert_eq!(other.attribute_cloned_or_default::(ATTR_START, 0), 0); } + + // Whole-attribute writes replace an existing attribute in place and refuse a value count that doesn't match + #[test] + fn set_attribute_values_writes_every_item_at_once() { + let mut list = List::new_from_elements(vec![10_u32, 20, 30]); + list.set_attribute(ATTR_START, 0, 7_u64); + list.set_attribute_values(ATTR_END, vec![1_u64, 2, 3]); + list.set_attribute_values(ATTR_START, vec![4_u64, 5, 6]); + + assert_eq!(list.len(), 3); + assert_eq!(list.attribute_keys().collect::>(), [ATTR_START, ATTR_END]); + assert_eq!(list.iter_attribute_values::(ATTR_START).unwrap().copied().collect::>(), [4, 5, 6]); + + list.set_attribute_values(ATTR_END, vec![9_u64]); + assert_eq!(list.iter_attribute_values::(ATTR_END).unwrap().copied().collect::>(), [1, 2, 3]); + + // Changing an attribute's type moves it last, whichever way it is written + let mut one_at_a_time = list.clone(); + for index in 0..3 { + one_at_a_time.set_attribute(ATTR_START, index, index as f64); + } + list.set_attribute_values(ATTR_START, vec![0., 1., 2.]); + assert_eq!(list.attribute_keys().collect::>(), [ATTR_END, ATTR_START]); + assert_eq!(list, one_at_a_time); + } } diff --git a/node-graph/libraries/vector-types/src/vector/addressing.rs b/node-graph/libraries/vector-types/src/vector/addressing.rs index 7481e3d4c6..4f25b09f78 100644 --- a/node-graph/libraries/vector-types/src/vector/addressing.rs +++ b/node-graph/libraries/vector-types/src/vector/addressing.rs @@ -86,13 +86,11 @@ pub fn spans_at(pool_index: u32, paths: &List, connectivity: &Connectivity let mut found = Vec::new(); for reference in connectivity.references(pool_index) { - let path_index = reference.path as usize; - let Some(path) = paths.element(path_index) else { continue }; - - let curve_type = curve_type_at(paths, path_index); - if !path.is_anchor_reference(reference.index as usize, curve_type) { + let Some(path) = paths.element(reference.path as usize) else { continue }; + if !reference.is_anchor() { continue; } + let curve_type = reference.curve_type; // An anchor arrives on the span before it and departs the one starting at it let anchor = reference.index as usize / curve_type.stride(); diff --git a/node-graph/libraries/vector-types/src/vector/connectivity.rs b/node-graph/libraries/vector-types/src/vector/connectivity.rs index 1848b70deb..9938aa9f76 100644 --- a/node-graph/libraries/vector-types/src/vector/connectivity.rs +++ b/node-graph/libraries/vector-types/src/vector/connectivity.rs @@ -1,4 +1,4 @@ -use super::path::{Path, curve_type_at}; +use super::path::{CurveType, Path, curve_type_at}; use core_types::list::List; /// One path's reference to a pool point, naming where in the weave that point is used. @@ -6,6 +6,17 @@ use core_types::list::List; pub struct Reference { pub path: u32, pub index: u32, + /// The curve type of the path holding this reference. Its stride decides whether the reference names an anchor. + pub curve_type: CurveType, + /// The segment ends radiating from this reference: none for a handle or a path's only reference, one at a path end, two along a path. + pub spokes: u8, +} + +impl Reference { + /// Whether this reference sits at an anchor slot of its path rather than a handle slot. + pub fn is_anchor(&self) -> bool { + (self.index as usize).is_multiple_of(self.curve_type.stride()) + } } /// Reverse index from each pool point to the references naming it. @@ -39,11 +50,21 @@ impl Connectivity { let mut cursors = starts[..point_count].to_vec(); let mut references = vec![Reference::default(); starts[point_count] as usize]; for (path_index, path) in paths.iter_element_values().enumerate() { + // Each path's curve type is read once here, so queries never look it up again + let curve_type = curve_type_at(paths, path_index); + let last = path.0.len().saturating_sub(1); + for (reference_index, point) in path.references().enumerate() { let Some(cursor) = cursors.get_mut(point as usize) else { continue }; + + let anchor = reference_index.is_multiple_of(curve_type.stride()); + let spokes = if anchor { u8::from(reference_index > 0) + u8::from(reference_index < last) } else { 0 }; + references[*cursor as usize] = Reference { path: path_index as u32, index: reference_index as u32, + curve_type, + spokes, }; *cursor += 1; } @@ -66,27 +87,21 @@ impl Connectivity { !self.references(point).is_empty() } + /// Whether this point is a handle, named by paths only at handle slots. + pub fn is_handle(&self, point: u32) -> bool { + let references = self.references(point); + !references.is_empty() && !references.iter().any(Reference::is_anchor) + } + /// The segment ends meeting at this point: 1 at a free end, 2 along a chain, 3 or more at a junction. /// Handle references contribute none, since only anchors have segments radiating from them. - pub fn spokes(&self, point: u32, paths: &List) -> usize { - self.references(point) - .iter() - .filter_map(|reference| { - let path = paths.element(reference.path as usize)?; - if !path.is_anchor_reference(reference.index as usize, curve_type_at(paths, reference.path as usize)) { - return None; - } - - let last = path.0.len().saturating_sub(1) as u32; - Some(usize::from(reference.index > 0) + usize::from(reference.index < last)) - }) - .sum() + pub fn spokes(&self, point: u32) -> usize { + self.references(point).iter().map(|reference| usize::from(reference.spokes)).sum() } } #[cfg(test)] mod tests { - use super::super::path::CurveType; use super::*; use core_types::list::{ATTR_CURVE_TYPE, Item}; @@ -101,6 +116,10 @@ mod tests { paths } + fn places(connectivity: &Connectivity, point: u32) -> Vec<(u32, u32)> { + connectivity.references(point).iter().map(|reference| (reference.path, reference.index)).collect() + } + // A closed circle crossed by a chord welded at two of its anchors, plus two points no path names #[test] fn spokes_at_welds_and_free_points() { @@ -108,14 +127,17 @@ mod tests { let connectivity = Connectivity::build(15, &paths); // The seam contributes two spokes and the chord a third - assert_eq!(connectivity.spokes(0, &paths), 3); - assert_eq!(connectivity.spokes(6, &paths), 3); + assert_eq!(connectivity.spokes(0), 3); + assert_eq!(connectivity.spokes(6), 3); - assert_eq!(connectivity.spokes(3, &paths), 2); - assert_eq!(connectivity.spokes(12, &paths), 2); + assert_eq!(connectivity.spokes(3), 2); + assert_eq!(connectivity.spokes(12), 2); // Handles carry no segments, and unreferenced points are free - assert_eq!(connectivity.spokes(1, &paths), 0); + assert_eq!(connectivity.spokes(1), 0); + assert!(connectivity.is_handle(1)); + assert!(!connectivity.is_handle(0)); + assert!(!connectivity.is_handle(13)); assert!(!connectivity.is_referenced(13)); assert!(connectivity.is_referenced(12)); } @@ -125,9 +147,9 @@ mod tests { let paths = paths(&[(CurveType::Linear, &[0, 1, 2]), (CurveType::Linear, &[2, 3])]); let connectivity = Connectivity::build(4, &paths); - assert_eq!(connectivity.references(0), [Reference { path: 0, index: 0 }]); - assert_eq!(connectivity.references(2), [Reference { path: 0, index: 2 }, Reference { path: 1, index: 0 }]); - assert_eq!(connectivity.spokes(2, &paths), 2); + assert_eq!(places(&connectivity, 0), [(0, 0)]); + assert_eq!(places(&connectivity, 2), [(0, 2), (1, 0)]); + assert_eq!(connectivity.spokes(2), 2); } // References falling anywhere outside the pool are ignored, including one exactly at its end @@ -136,10 +158,10 @@ mod tests { let paths = paths(&[(CurveType::Linear, &[0, 3, 1, 4])]); let connectivity = Connectivity::build(3, &paths); - assert_eq!(connectivity.references(0), [Reference { path: 0, index: 0 }]); - assert_eq!(connectivity.references(1), [Reference { path: 0, index: 2 }]); - assert_eq!(connectivity.references(3), []); - assert_eq!(connectivity.references(4), []); + assert_eq!(places(&connectivity, 0), [(0, 0)]); + assert_eq!(places(&connectivity, 1), [(0, 2)]); + assert!(places(&connectivity, 3).is_empty()); + assert!(places(&connectivity, 4).is_empty()); } // An open end has one spoke, which is what makes it a cap site @@ -148,8 +170,8 @@ mod tests { let paths = paths(&[(CurveType::Linear, &[0, 1, 2])]); let connectivity = Connectivity::build(3, &paths); - assert_eq!(connectivity.spokes(0, &paths), 1); - assert_eq!(connectivity.spokes(2, &paths), 1); - assert_eq!(connectivity.spokes(1, &paths), 2); + assert_eq!(connectivity.spokes(0), 1); + assert_eq!(connectivity.spokes(2), 1); + assert_eq!(connectivity.spokes(1), 2); } } diff --git a/node-graph/libraries/vector-types/src/vector/contour.rs b/node-graph/libraries/vector-types/src/vector/contour.rs index c3be65e84b..10c7230100 100644 --- a/node-graph/libraries/vector-types/src/vector/contour.rs +++ b/node-graph/libraries/vector-types/src/vector/contour.rs @@ -1,5 +1,5 @@ use super::misc::dvec2_to_point; -use super::path::{Path, append_segment, curve_type_at}; +use super::path::{CurveType, Path, append_segment, curve_type_at}; use core_types::list::List; use glam::DVec2; use kurbo::BezPath; @@ -100,17 +100,26 @@ impl SpanEnds { /// then the rest from the lowest point with spans left. A walk follows the earliest woven span waiting at each /// point, backwards when that span ends there, and closes on arriving back where it began. pub fn subpaths(point_count: usize, paths: &List) -> Vec { + subpaths_with(point_count, paths, &curve_types(paths)) +} + +/// The curve type of every path, read once so the walkers below never look one up per span. +fn curve_types(paths: &List) -> Vec { + (0..paths.len()).map(|index| curve_type_at(paths, index)).collect() +} + +fn subpaths_with(point_count: usize, paths: &List, curve_types: &[CurveType]) -> Vec { let mut edges = Vec::new(); for (path_index, path) in paths.iter_element_values().enumerate() { - let curve_type = curve_type_at(paths, path_index); + let curve_type = curve_types.get(path_index).copied().unwrap_or_default(); let stride = curve_type.stride(); + let references = path.0.iter_element_values().as_slice(); for span in 0..path.segment_count(curve_type) { - let references = (span * stride..=(span + 1) * stride).map(|index| path.reference(index)); - let Some(references) = references.collect::>>() else { continue }; + let Some(references) = references.get(span * stride..=(span + 1) * stride) else { continue }; // A span naming a point outside the pool cannot be drawn, so it takes no part in the walk - if references.iter().any(|&reference| reference as usize >= point_count) { + if references.iter().any(|&reference| !(0..point_count as i64).contains(&reference)) { continue; } let (Some(&start), Some(&end)) = (references.first(), references.last()) else { continue }; @@ -118,8 +127,8 @@ pub fn subpaths(point_count: usize, paths: &List) -> Vec { edges.push(Edge { path: path_index as u32, span: span as u32, - start, - end, + start: start as u32, + end: end as u32, }); } } @@ -174,12 +183,16 @@ pub fn subpaths(point_count: usize, paths: &List) -> Vec { /// Emits one subpath as a bezpath, or `None` when it has no drawable geometry. pub fn subpath_to_bezpath(pool: &List, paths: &List, subpath: &Subpath) -> Option { + subpath_to_bezpath_with(pool, paths, &curve_types(paths), subpath) +} + +fn subpath_to_bezpath_with(pool: &List, paths: &List, curve_types: &[CurveType], subpath: &Subpath) -> Option { let mut bezpath = BezPath::new(); bezpath.move_to(dvec2_to_point(*pool.element(subpath.entry as usize)?)); for step in &subpath.steps { let path = paths.element(step.path as usize)?; - let segment = path.segment(pool, curve_type_at(paths, step.path as usize), step.span as usize)?; + let segment = path.segment(pool, *curve_types.get(step.path as usize)?, step.span as usize)?; append_segment(&mut bezpath, if step.reversed { segment.reverse() } else { segment }); } @@ -193,7 +206,11 @@ pub fn subpath_to_bezpath(pool: &List, paths: &List, subpath: &Subp /// Assembles the paths into contours for rendering, one bezpath per subpath in the order they are walked. pub fn contours(pool: &List, paths: &List) -> Vec { - subpaths(pool.len(), paths).iter().filter_map(|subpath| subpath_to_bezpath(pool, paths, subpath)).collect() + let curve_types = curve_types(paths); + subpaths_with(pool.len(), paths, &curve_types) + .iter() + .filter_map(|subpath| subpath_to_bezpath_with(pool, paths, &curve_types, subpath)) + .collect() } #[cfg(test)] diff --git a/node-graph/libraries/vector-types/src/vector/flatten.rs b/node-graph/libraries/vector-types/src/vector/flatten.rs index 75cb09556b..f8734ffda2 100644 --- a/node-graph/libraries/vector-types/src/vector/flatten.rs +++ b/node-graph/libraries/vector-types/src/vector/flatten.rs @@ -1,11 +1,10 @@ -use super::addressing; use super::misc::{BezierHandles, HandleId, HandleType, segment_to_handles}; use super::path::{CurveType, Path, curve_type_at, push_path}; use super::vector_attributes::{PointId, SegmentId}; use super::vector_types::Vector; -use core_types::list::{ATTR_ID, Item, List}; +use core_types::list::{ATTR_ID, List}; use glam::DVec2; -use std::collections::HashMap; +use rustc_hash::{FxHashMap, FxHashSet}; /// One path under construction: its curve type, the pool references it weaves, and the IDs of the spans between them. type Run = (CurveType, Vec, Vec); @@ -29,50 +28,59 @@ impl WorkingVector { pub fn flatten(vector: &Vector, paths: &List) -> Self { let mut working = Self::default(); let connectivity = vector.connectivity(paths); + let pool_ids = vector.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); let mut pool_to_working = vec![None; vector.point_count()]; for (index, slot) in pool_to_working.iter_mut().enumerate() { - if !vector.is_handle_point(paths, &connectivity, index as u32) { + if !connectivity.is_handle(index as u32) { *slot = Some(working.point_ids.len()); - working.point_ids.push(vector.point_id_at(index as u32).unwrap_or_default()); + working.point_ids.push(pool_ids.get(index).copied().unwrap_or_default()); working.point_positions.push(vector.position(index).unwrap_or_default()); } } + let working_point = |pool_index: u32| pool_to_working.get(pool_index as usize).copied().flatten(); // One pass so a span that fails to resolve leaves every array at the same length - for span in addressing::spans(paths) { - let Some(path) = paths.element(span.path as usize) else { continue }; - let Some(segment) = path.segment(&vector.0, curve_type_at(paths, span.path as usize), span.index as usize) else { - continue; - }; - let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; - let working_point = |pool_index: u32| pool_to_working.get(pool_index as usize).copied().flatten(); - let (Some(start), Some(end)) = (working_point(start), working_point(end)) else { continue }; + for (path_index, path) in paths.iter_element_values().enumerate() { + let curve_type = curve_type_at(paths, path_index); + let stride = curve_type.stride(); + let span_ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); - working.segment_ids.push(addressing::segment_id_of(paths, span).unwrap_or_default()); - working.segment_handles.push(segment_to_handles(&segment)); - working.segment_start.push(start); - working.segment_end.push(end); + for span in 0..path.segment_count(curve_type) { + let Some(segment) = path.segment(&vector.0, curve_type, span) else { continue }; + let (Some(start), Some(end)) = (path.reference(span * stride), path.reference(span * stride + stride)) else { + continue; + }; + let (Some(start), Some(end)) = (working_point(start), working_point(end)) else { continue }; + + working.segment_ids.push(span_ids.get(span * stride).copied().unwrap_or_default()); + working.segment_handles.push(segment_to_handles(&segment)); + working.segment_start.push(start); + working.segment_end.push(end); + } } - working.colinear = vector.colinear_pairs(paths); + working.colinear = vector.colinear_pairs_with(paths, &connectivity); working } /// Weaves the working form back into a pool and paths, gathering consecutive segments that meet head to tail into one path. pub fn reweave(self, vector: &mut Vector, paths: &mut List) { - *vector = Vector::default(); *paths = List::new(); - for (index, (&id, &position)) in self.point_ids.iter().zip(&self.point_positions).enumerate() { - vector.0.push(Item::new_from_element(position)); - vector.0.set_attribute(ATTR_ID, index, id); - } - let anchor_count = vector.0.len(); + // The pool is built as plain arrays and handed to the list whole, anchors first and each segment's handles after + let anchor_count = self.point_ids.len().min(self.point_positions.len()); + let mut positions = self.point_positions; + positions.truncate(anchor_count); + let mut point_ids = self.point_ids; + point_ids.truncate(anchor_count); let mut runs: Vec = Vec::new(); - let mut segment_anchors = HashMap::new(); + + // Only segments a G1 pair names need their anchors recorded, to narrow the pairs to smooth flags below + let paired: FxHashSet = self.colinear.iter().flat_map(|pair| pair.map(|handle| handle.segment)).collect(); + let mut segment_anchors = FxHashMap::default(); let ends = self.segment_start.iter().zip(&self.segment_end); for ((&id, (&start, &end)), handles) in self.segment_ids.iter().zip(ends).zip(&self.segment_handles) { @@ -97,13 +105,21 @@ impl WorkingVector { let Some((_, references, ids)) = runs.last_mut() else { continue }; for position in handle_positions { - references.push(vector.0.len() as u32); - vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, PointId::UNNAMED)); + references.push(positions.len() as u32); + positions.push(position); + point_ids.push(PointId::UNNAMED); } references.push(end as u32); ids.push(id); - segment_anchors.insert(id, (start as u32, end as u32)); + if paired.contains(&id) { + segment_anchors.insert(id, (start as u32, end as u32)); + } + } + + vector.0 = List::new_from_elements(positions); + if !point_ids.is_empty() { + vector.0.set_attribute_values(ATTR_ID, point_ids); } for (curve_type, references, ids) in runs { @@ -157,7 +173,7 @@ pub fn vector_from_legacy_parts( #[cfg(test)] mod tests { use super::*; - use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID}; + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, Item}; fn working(points: usize, segments: &[(usize, usize, BezierHandles)]) -> WorkingVector { WorkingVector { diff --git a/node-graph/libraries/vector-types/src/vector/path.rs b/node-graph/libraries/vector-types/src/vector/path.rs index 00c546fa97..3e55529aec 100644 --- a/node-graph/libraries/vector-types/src/vector/path.rs +++ b/node-graph/libraries/vector-types/src/vector/path.rs @@ -50,7 +50,7 @@ pub struct Path(pub List); impl Path { /// Builds a path from pool indices, with no per-reference attributes. pub fn from_references(references: impl IntoIterator) -> Self { - Self(references.into_iter().map(|reference| Item::new_from_element(i64::from(reference))).collect()) + Self(List::new_from_elements(references.into_iter().map(i64::from).collect())) } /// The pool index named by the reference at `index`, or `None` if out of bounds. @@ -69,11 +69,6 @@ impl Path { len > 1 && self.0.element(0) == self.0.element(len - 1) } - /// Whether the reference at the given index is an anchor (rather than a handle) under the given curve type. - pub fn is_anchor_reference(&self, index: usize, curve_type: CurveType) -> bool { - index.is_multiple_of(curve_type.stride()) - } - /// The number of segments this path draws, one fewer than its anchor count when open and equal to it when closed. pub fn segment_count(&self, curve_type: CurveType) -> usize { self.0.len().saturating_sub(1) / curve_type.stride() @@ -138,9 +133,14 @@ impl Path { pub fn push_path(paths: &mut List, curve_type: CurveType, references: impl IntoIterator, ids: impl IntoIterator) { let mut path = Path::from_references(references); - let span_count = path.segment_count(curve_type); - for (span, id) in ids.into_iter().enumerate().take(span_count) { - path.0.set_attribute(ATTR_ID, span * curve_type.stride(), id); + let stride = curve_type.stride(); + let mut ids = ids.into_iter().take(path.segment_count(curve_type)).peekable(); + if ids.peek().is_some() { + let mut span_ids = vec![SegmentId::default(); path.0.len()]; + for (span, id) in ids.enumerate() { + span_ids[span * stride] = id; + } + path.0.set_attribute_values(ATTR_ID, span_ids); } paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); @@ -180,6 +180,7 @@ pub fn curve_type_at(paths: &List, index: usize) -> CurveType { /// path keeps one stride. The runs of a split subpath share the anchor they meet at, welding them. struct PathWeaver { positions: Vec, + anchors: Vec, offset: u32, woven: Vec<(CurveType, Vec)>, references: Vec, @@ -191,6 +192,7 @@ impl PathWeaver { fn new(offset: u32) -> Self { Self { positions: Vec::new(), + anchors: Vec::new(), offset, woven: Vec::new(), references: Vec::new(), @@ -199,9 +201,10 @@ impl PathWeaver { } } - /// Adds a point to the pool being built and returns the reference naming it. - fn push_point(&mut self, point: Point) -> u32 { + /// Adds an anchor or handle point to the pool being built and returns the reference naming it. + fn push_point(&mut self, point: Point, anchor: bool) -> u32 { self.positions.push(point_to_dvec2(point)); + self.anchors.push(anchor); self.offset + self.positions.len() as u32 - 1 } @@ -248,7 +251,7 @@ impl PathWeaver { match element { PathEl::MoveTo(point) => { self.flush(); - let reference = self.push_point(point); + let reference = self.push_point(point, true); self.subpath_start = Some(reference); self.references.push(reference); } @@ -264,8 +267,9 @@ impl PathWeaver { return; } - for &point in points { - let reference = self.push_point(point); + // Every point but the last is a handle leading to the anchor that ends the segment + for (index, &point) in points.iter().enumerate() { + let reference = self.push_point(point, index + 1 == points.len()); self.references.push(reference); } } @@ -286,6 +290,7 @@ impl PathWeaver { self.references.push(start); if last as usize + 1 == self.offset as usize + self.positions.len() { self.positions.pop(); + self.anchors.pop(); } } else if self.begin_segment(CurveType::Linear) { self.references.push(start); @@ -294,29 +299,35 @@ impl PathWeaver { self.flush(); } - fn finish(mut self, pool: &mut List, paths: &mut List) { + /// Appends the woven points and paths, returning whether each appended point is an anchor rather than a handle. + fn finish(mut self, pool: &mut List, paths: &mut List) -> Vec { self.flush(); - for position in self.positions { - pool.push(Item::new_from_element(position)); - } + pool.extend(List::new_from_elements(self.positions)); for (curve_type, references) in self.woven { let path = Path::from_references(references); paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); } + + self.anchors } } /// Appends a bezpath's contours to a point pool and its paths. pub fn append_bezpath(pool: &mut List, paths: &mut List, bezpath: &BezPath) { + weave_bezpath(pool, paths, bezpath); +} + +/// Appends a bezpath's contours to a point pool and its paths, returning whether each appended point is an anchor. +pub(crate) fn weave_bezpath(pool: &mut List, paths: &mut List, bezpath: &BezPath) -> Vec { let mut weaver = PathWeaver::new(pool.len() as u32); for &element in bezpath.elements() { weaver.push_element(element); } - weaver.finish(pool, paths); + weaver.finish(pool, paths) } /// Builds a fresh point pool and its paths from a bezpath. @@ -365,19 +376,6 @@ mod tests { ); } - // Anchor occurrences fall on stride multiples, and the references between them are handles - #[test] - fn anchor_references_by_stride() { - let path = path(&[0, 1, 2, 3]); - - assert!(path.is_anchor_reference(0, CurveType::Cubic)); - assert!(!path.is_anchor_reference(1, CurveType::Cubic)); - assert!(!path.is_anchor_reference(2, CurveType::Cubic)); - assert!(path.is_anchor_reference(3, CurveType::Cubic)); - assert!(path.is_anchor_reference(2, CurveType::Quadratic)); - assert!(path.is_anchor_reference(2, CurveType::Linear)); - } - // A reference naming a point the pool does not have drops its segment instead of panicking #[test] fn dangling_reference_skips_its_segment() { diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index 7a799d0e7b..1450a6ece5 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -1,9 +1,9 @@ use crate::vector::addressing::{self, Span}; use crate::vector::contour::subpaths; use crate::vector::misc::{ManipulatorGroup, Tangent, point_to_dvec2, segment_to_handles}; -use crate::vector::path::{Path, append_segment, curve_type_at}; +use crate::vector::path::{CurveType, Path, append_segment, curve_type_at}; use crate::vector::vector_types::Vector; -use core_types::list::{Item, List}; +use core_types::list::{ATTR_ID, Item, List}; use dyn_any::DynAny; use fixedbitset::FixedBitSet; use glam::DVec2; @@ -589,8 +589,23 @@ impl SegmentGraph { impl Vector { /// Whether any point has more than two segment ends meeting at it, making the vector a mesh. pub fn is_branching(&self, paths: &List) -> bool { - let connectivity = self.connectivity(paths); - (0..self.point_count() as u32).any(|point| connectivity.spokes(point, paths) > 2) + // Tally the segment ends at each anchor in one pass over the references, stopping at the first junction + let mut spokes = vec![0_u8; self.point_count()]; + for (path_index, path) in paths.iter_element_values().enumerate() { + let stride = curve_type_at(paths, path_index).stride(); + let references = path.0.iter_element_values().as_slice(); + let last = references.len().saturating_sub(1); + + for (index, &point) in references.iter().enumerate().step_by(stride) { + let Some(count) = spokes.get_mut(point as usize) else { continue }; + *count = count.saturating_add(u8::from(index > 0) + u8::from(index < last)); + if *count > 2 { + return true; + } + } + } + + false } /// Determines if face-by-face fill rendering should be used. Branching vectors are meshes, whose @@ -735,17 +750,23 @@ impl Vector { pub fn stroke_manipulator_groups(&self, paths: &List) -> impl Iterator, bool)> { let mut groups = Vec::new(); + let curve_types: Vec = (0..paths.len()).map(|index| curve_type_at(paths, index)).collect(); + let ids = self.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); + let id_at = |point: u32| ids.get(point as usize).copied().unwrap_or_default(); + for subpath in subpaths(self.point_count(), paths) { let mut manipulators_list: Vec = Vec::new(); let mut in_handle: Option = None; for step in &subpath.steps { - let span = Span { path: step.path, index: step.span }; let Some(path) = paths.element(step.path as usize) else { continue }; - let Some(segment) = path.segment(&self.0, curve_type_at(paths, step.path as usize), step.span as usize) else { + let Some(&curve_type) = curve_types.get(step.path as usize) else { continue }; + let Some(segment) = path.segment(&self.0, curve_type, step.span as usize) else { continue }; + + let first = step.span as usize * curve_type.stride(); + let (Some(start), Some(end)) = (path.reference(first), path.reference(first + curve_type.stride())) else { continue; }; - let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; // A quadratic's one handle leaves its anchor whichever way the span is crossed let handles = segment_to_handles(&segment); @@ -756,7 +777,7 @@ impl Vector { anchor: point_to_dvec2(if step.reversed { segment.end() } else { segment.start() }), in_handle, out_handle: handles.start(), - id: self.point_id_at(anchor).unwrap_or_default(), + id: id_at(anchor), }); in_handle = handles.end(); @@ -771,7 +792,7 @@ impl Vector { anchor: position, in_handle, out_handle: None, - id: self.point_id_at(subpath.exit).unwrap_or_default(), + id: id_at(subpath.exit), }); } diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index 743831087f..c9c8dc80cb 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -1,11 +1,12 @@ use super::*; use crate::vector::flatten::WorkingVector; use crate::vector::misc::{BezierHandles, HandleId, HandleType}; -use crate::vector::path::Path; -use core_types::list::List; +use crate::vector::path::{CurveType, Path, curve_type_at}; +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}; use serde::de::{SeqAccess, Visitor}; use serde::ser::SerializeSeq; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -53,31 +54,37 @@ impl PointModification { working.point_ids.retain(|id| !self.remove.contains(id)); // Gathering the moves first keeps the segment pass below off the common path where nothing moves - let mut moved: HashMap = HashMap::new(); - for (index, id) in working.point_ids.iter().enumerate() { - let Some(&delta) = self.delta.get(id) else { continue }; - if !delta.is_finite() { - warn!("Invalid delta when applying a point modification"); - continue; - } + let mut moved = Vec::new(); + let mut any_moved = false; + if !self.delta.is_empty() { + moved.resize(working.point_ids.len(), None); + for (index, id) in working.point_ids.iter().enumerate() { + let Some(&delta) = self.delta.get(id) else { continue }; + if !delta.is_finite() { + warn!("Invalid delta when applying a point modification"); + continue; + } - working.point_positions[index] += delta; - moved.insert(index, delta); + working.point_positions[index] += delta; + moved[index] = Some(delta); + any_moved = true; + } } // Handles travel with their anchor, carried in one pass over the segment ends - if !moved.is_empty() { + if any_moved { + let moved_by = |index: usize| moved.get(index).copied().flatten(); for index in 0..working.segment_ids.len() { - if let Some(&delta) = moved.get(&working.segment_start[index]) { + if let Some(delta) = moved_by(working.segment_start[index]) { working.segment_handles[index].move_start(delta); } - if let Some(&delta) = moved.get(&working.segment_end[index]) { + if let Some(delta) = moved_by(working.segment_end[index]) { working.segment_handles[index].move_end(delta); } } } - let mut named: HashSet = if self.add.is_empty() { HashSet::new() } else { working.point_ids.iter().copied().collect() }; + let mut named: FxHashSet = if self.add.is_empty() { FxHashSet::default() } else { working.point_ids.iter().copied().collect() }; for &add_id in &self.add { let Some(&position) = self.delta.get(&add_id) else { continue }; if !position.is_finite() { @@ -95,6 +102,67 @@ impl PointModification { } } + /// Moves each point named by a delta directly in the pool, carrying the handles that follow it. `handles` marks the pool's handles, + /// none of which may be shared between segments, or a shared one would move once for each. + fn move_in_place(&self, vector: &mut Vector, paths: &List, handles: &[bool]) { + if self.delta.is_empty() { + return; + } + + let ids = vector.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); + + // Deltas move only anchors and free points, as the working form leaves handles out of its points + let mut moved = vec![None; vector.point_count()]; + let mut any_moved = false; + for (index, _) in handles.iter().enumerate().filter(|&(_, &handle)| !handle) { + let Some(&delta) = self.delta.get(&ids.get(index).copied().unwrap_or_default()) else { continue }; + if !delta.is_finite() { + warn!("Invalid delta when applying a point modification"); + continue; + } + + moved[index] = Some(delta); + any_moved = true; + } + + if !any_moved { + return; + } + + for (position, delta) in vector.0.iter_element_values_mut().zip(&moved) { + if let Some(delta) = delta { + *position += *delta; + } + } + + // A segment's first handle follows its start anchor, and a cubic's second handle follows its end anchor + for (path_index, path) in paths.iter_element_values().enumerate() { + let curve_type = curve_type_at(paths, path_index); + if curve_type == CurveType::Linear { + continue; + } + + let stride = curve_type.stride(); + let moved_by = |reference: usize| path.reference(reference).and_then(|point| moved.get(point as usize).copied().flatten()); + + for span in 0..path.segment_count(curve_type) { + let start = span * stride; + let mut carry = |handle_reference: usize, delta: Option| { + if let (Some(delta), Some(handle)) = (delta, path.reference(handle_reference)) + && let Some(position) = vector.0.element_mut(handle as usize) + { + *position += delta; + } + }; + + carry(start + 1, moved_by(start)); + if curve_type == CurveType::Cubic { + carry(start + 2, moved_by(start + stride)); + } + } + } + } + /// Create a new modification that will convert an empty [`Vector`] into the target working form. fn create_from_working(working: &WorkingVector) -> Self { Self { @@ -152,7 +220,7 @@ impl SegmentModification { // The points no longer change here, so one index serves every endpoint lookup below. // Nothing looks an endpoint up in the common pure-handle case, so it skips the build. - let mut point_index: HashMap = HashMap::new(); + let mut point_index: FxHashMap = FxHashMap::default(); if !self.start_point.is_empty() || !self.end_point.is_empty() || !self.add.is_empty() { point_index.reserve(working.point_ids.len()); for (index, &id) in working.point_ids.iter().enumerate() { @@ -219,7 +287,11 @@ impl SegmentModification { }; } - let mut named: HashSet = if self.add.is_empty() { HashSet::new() } else { working.segment_ids.iter().copied().collect() }; + let mut named: FxHashSet = if self.add.is_empty() { + FxHashSet::default() + } else { + working.segment_ids.iter().copied().collect() + }; for &add_id in &self.add { let Some(&start) = self.start_point.get(&add_id) else { continue }; let Some(&end) = self.end_point.get(&add_id) else { continue }; @@ -266,6 +338,98 @@ impl SegmentModification { assert!(working.segment_end.iter().all(|&index| index < working.point_ids.len()), "index should be in range"); } + /// The curve type a segment ends up with once its handle edits apply, following the same rules as [`Self::apply`]. + fn edited_curve_type(current: CurveType, primary: Option>, end: Option>) -> CurveType { + match (primary.map(|handle| handle.is_some()), end.map(|handle| handle.is_some())) { + (Some(true), Some(true)) => CurveType::Cubic, + (Some(true), Some(false)) | (Some(false), Some(true)) => CurveType::Quadratic, + (Some(false), Some(false)) | (Some(false), None) => CurveType::Linear, + (None, Some(false)) if current == CurveType::Cubic => CurveType::Quadratic, + (None, Some(true)) if current == CurveType::Linear => CurveType::Quadratic, + (None, Some(true)) => CurveType::Cubic, + (Some(true), None) if current == CurveType::Linear => CurveType::Quadratic, + _ => current, + } + } + + /// Calls the visitor with each span a handle edit names, along with its curve type, references, starting reference, and edits. + fn for_each_edited_span(&self, paths: &List, mut visit: impl FnMut(CurveType, &Path, usize, Option>, Option>)) { + for (path_index, path) in paths.iter_element_values().enumerate() { + let curve_type = curve_type_at(paths, path_index); + let stride = curve_type.stride(); + let ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); + + for span in 0..path.segment_count(curve_type) { + let id = ids.get(span * stride).copied().unwrap_or_default(); + let (primary, end) = (self.handle_primary.get(&id).copied(), self.handle_end.get(&id).copied()); + if primary.is_some() || end.is_some() { + visit(curve_type, path, span * stride, primary, end); + } + } + } + } + + /// Whether every handle edit leaves its segment's curve type as it is, so the edits can land in the pool without reweaving. + fn handle_edits_keep_curve_types(&self, paths: &List) -> bool { + if self.handle_primary.is_empty() && self.handle_end.is_empty() { + return true; + } + + let mut keeps = true; + self.for_each_edited_span(paths, |curve_type, _, _, primary, end| { + keeps &= Self::edited_curve_type(curve_type, primary, end) == curve_type; + }); + keeps + } + + /// Sets each edited handle directly in the pool, relative to its anchor's current position. Only valid once + /// [`Self::handle_edits_keep_curve_types`] has confirmed no curve type changes and [`Vector::point_roles`] that no handle is shared. + fn set_handles_in_place(&self, vector: &mut Vector, paths: &List) { + if self.handle_primary.is_empty() && self.handle_end.is_empty() { + return; + } + + let mut writes = Vec::new(); + self.for_each_edited_span(paths, |curve_type, path, start, primary, end| { + let position_at = |reference: usize| path.reference(reference).and_then(|point| vector.position(point as usize)); + let (Some(start_position), Some(end_position)) = (position_at(start), position_at(start + curve_type.stride())) else { + return; + }; + + let new_start = primary.map(|handle| handle.map(|handle| handle + start_position)); + let new_end = end.map(|handle| handle.map(|handle| handle + end_position)); + if !new_start.unwrap_or_default().is_none_or(|start| start.is_finite()) || !new_end.unwrap_or_default().is_none_or(|end| end.is_finite()) { + warn!("Invalid handles when applying a segment modification"); + return; + } + + let mut write = |reference: usize, position: DVec2| { + if let Some(point) = path.reference(reference) { + writes.push((point, position)); + } + }; + match (curve_type, new_start.flatten(), new_end.flatten()) { + // A quadratic's lone handle takes whichever side's position the edit sets + (CurveType::Quadratic, Some(handle), _) | (CurveType::Quadratic, None, Some(handle)) => write(start + 1, handle), + (CurveType::Cubic, handle_start, handle_end) => { + if let Some(handle_start) = handle_start { + write(start + 1, handle_start); + } + if let Some(handle_end) = handle_end { + write(start + 2, handle_end); + } + } + _ => {} + } + }); + + for (point, position) in writes { + if let Some(slot) = vector.0.element_mut(point as usize) { + *slot = position; + } + } + } + /// Create a new modification that will convert an empty [`Vector`] into the target working form. fn create_from_working(working: &WorkingVector) -> Self { let point_id = |(&segment, &index): (&SegmentId, &usize)| (segment, working.point_ids[index]); @@ -489,6 +653,38 @@ impl VectorModification { self.points == PointModification::default() && self.segments == SegmentModification::default() && self.add_g1_continuous.is_empty() && self.remove_g1_continuous.is_empty() } + /// Whether this modification only moves existing points and handles, adding, removing, and reconnecting nothing. + fn only_moves_points(&self) -> bool { + // Every field is named so that adding one forces a decision here + let Self { + points: PointModification { + add: added_points, + remove: removed_points, + delta: _, + }, + segments, + add_g1_continuous, + remove_g1_continuous, + } = self; + let SegmentModification { + add: added_segments, + remove: removed_segments, + start_point, + end_point, + handle_primary: _, + handle_end: _, + } = segments; + + added_points.is_empty() + && removed_points.is_empty() + && added_segments.is_empty() + && removed_segments.is_empty() + && start_point.is_empty() + && end_point.is_empty() + && add_g1_continuous.is_empty() + && remove_g1_continuous.is_empty() + } + /// Apply this modification to the specified [`Vector`] and its paths. pub fn apply(&self, vector: &mut Vector, paths: &mut List) { // An untouched vector keeps its incoming path structure instead of being flattened and rewoven @@ -496,18 +692,34 @@ impl VectorModification { return; } + // Moving points and handles leaves the weave intact, so the pool is edited where it lies in O(points + references), keeping + // upstream storage as it is. A handle shared between segments would move once for each there, so that weave is rewoven instead. + if self.only_moves_points() && self.segments.handle_edits_keep_curve_types(paths) { + let (handles, handles_unshared) = vector.point_roles(paths); + if handles_unshared { + self.points.move_in_place(vector, paths, &handles); + self.segments.set_handles_in_place(vector, paths); + return; + } + } + + self.apply_through_working_form(vector, paths); + } + + /// Applies this modification by flattening to the legacy working form, editing that, and weaving the result back. + fn apply_through_working_form(&self, vector: &mut Vector, paths: &mut List) { let mut working = WorkingVector::flatten(vector, paths); self.points.apply(&mut working); self.segments.apply(&mut working); - let surviving_segments: HashSet = working.segment_ids.iter().copied().collect(); + let surviving_segments: FxHashSet = working.segment_ids.iter().copied().collect(); let valid = |val: &[HandleId; 2]| surviving_segments.contains(&val[0].segment) && surviving_segments.contains(&val[1].segment); working .colinear .retain(|val| !self.remove_g1_continuous.contains(val) && !self.remove_g1_continuous.contains(&[val[1], val[0]]) && valid(val)); // Both orientations go in, since a pair and its reverse name the same tangent - let mut present: HashSet<[HandleId; 2]> = working.colinear.iter().flat_map(|&[first, second]| [[first, second], [second, first]]).collect(); + let mut present: FxHashSet<[HandleId; 2]> = working.colinear.iter().flat_map(|&[first, second]| [[first, second], [second, first]]).collect(); for handles in &self.add_g1_continuous { if !present.contains(handles) && valid(handles) { working.colinear.push(*handles); @@ -714,6 +926,249 @@ mod tests { vector.position(vector.index_of_point_id(id).unwrap() as usize).unwrap() } + /// What the tests compare of a modification's result: anchors by ID, segments by ID, the stroke walk, and G1 pairs. + fn describe(vector: &Vector, paths: &List) -> String { + let mut anchors: Vec = vector + .anchor_points(paths) + .map(|id| format!("{id:?}@{:?}", vector.index_of_point_id(id).and_then(|index| vector.position(index as usize)))) + .collect(); + anchors.sort(); + + let mut segments: Vec = vector.segment_iter(paths).map(|(id, segment, start, end)| format!("{id:?}:{start:?}>{end:?}:{segment:?}")).collect(); + segments.sort(); + + let strokes: Vec = vector.stroke_bezpath_iter(paths).map(|bezpath| bezpath.to_svg()).collect(); + + let mut pairs: Vec = vector + .colinear_pairs(paths) + .into_iter() + .map(|pair| { + let mut handles = pair.map(|handle| format!("{handle:?}")); + handles.sort(); + handles.join("~") + }) + .collect(); + pairs.sort(); + + format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}") + } + + /// Every curve type, a weld where they change, a smooth anchor, and a second subpath. + fn mixed_geometry() -> (Vector, List) { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.curve_to((10., -10.), (20., -10.), (30., 0.)); + bezpath.line_to((30., 30.)); + bezpath.quad_to((15., 45.), (0., 30.)); + bezpath.close_path(); + bezpath.move_to((100., 100.)); + bezpath.curve_to((110., 90.), (120., 90.), (130., 100.)); + + let (mut vector, mut paths) = Vector::from_bezpath(&bezpath); + let smooth_anchor = anchor_id(&vector, &paths, 1); + vector.set_smooth(&mut paths, smooth_anchor, true); + + (vector, paths) + } + + // Moving points and handles where they lie gives the same result as flattening and reweaving + #[test] + fn moving_in_place_matches_the_working_form() { + let (vector, paths) = mixed_geometry(); + let anchors: Vec = vector.anchor_points(&paths).collect(); + let segments: Vec = vector.segment_iter(&paths).map(|(id, ..)| id).collect(); + + let mut modification = VectorModification::default(); + for (index, &anchor) in anchors.iter().enumerate() { + let delta = DVec2::new(index as f64, -(index as f64) * 2.); + modification.modify(&VectorModificationType::ApplyPointDelta { point: anchor, delta }); + } + let handle_edits = [ + (HandleId::primary(segments[0]), DVec2::new(3., 4.)), + (HandleId::primary(segments[2]), DVec2::new(-5., 6.)), + (HandleId::end(segments[4]), DVec2::new(7., -8.)), + ]; + for (handle, relative_position) in handle_edits { + modification.modify(&VectorModificationType::SetHandlePosition { handle, relative_position }); + } + + let (mut in_place, mut in_place_paths) = (vector.clone(), paths.clone()); + modification.apply(&mut in_place, &mut in_place_paths); + let (mut rewoven, mut rewoven_paths) = (vector.clone(), paths.clone()); + modification.apply_through_working_form(&mut rewoven, &mut rewoven_paths); + + assert_eq!(describe(&in_place, &in_place_paths), describe(&rewoven, &rewoven_paths)); + assert_ne!(describe(&in_place, &in_place_paths), describe(&vector, &paths)); + assert_eq!(in_place_paths, paths, "moving points leaves the weave untouched"); + } + + // An edit that turns a line into a curve changes the weave, so it still goes through the working form + #[test] + fn curve_type_changes_still_apply() { + let (mut vector, mut paths) = mixed_geometry(); + let line = vector.segment_iter(&paths).nth(1).map(|(id, ..)| id).unwrap(); + + let mut modification = VectorModification::default(); + let handles = [Some(DVec2::new(1., 1.)), Some(DVec2::new(-1., -1.))]; + modification.modify(&VectorModificationType::SetHandles { segment: line, handles }); + modification.apply(&mut vector, &mut paths); + + let curved = vector.segment_iter(&paths).find(|&(id, ..)| id == line).map(|(_, segment, ..)| segment); + assert!(matches!(curved, Some(PathSeg::Cubic(_)))); + } + + // Every way of editing a segment's two handles gives the same result in place as through the working form + #[test] + fn every_handle_edit_matches_the_working_form() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.move_to((0., 20.)); + bezpath.quad_to((5., 30.), (10., 20.)); + bezpath.move_to((0., 40.)); + bezpath.curve_to((3., 50.), (7., 50.), (10., 40.)); + let (vector, paths) = Vector::from_bezpath(&bezpath); + + let edits = [None, Some(None), Some(Some(DVec2::new(2., 3.)))]; + for (segment, ..) in vector.segment_iter(&paths) { + for (primary, end) in edits.into_iter().flat_map(|primary| edits.map(|end| (primary, end))) { + let mut modification = VectorModification::default(); + if let Some(primary) = primary { + modification.segments.handle_primary.insert(segment, primary); + } + if let Some(end) = end { + modification.segments.handle_end.insert(segment, end); + } + + let (mut in_place, mut in_place_paths) = (vector.clone(), paths.clone()); + modification.apply(&mut in_place, &mut in_place_paths); + let (mut rewoven, mut rewoven_paths) = (vector.clone(), paths.clone()); + modification.apply_through_working_form(&mut rewoven, &mut rewoven_paths); + + assert_eq!( + describe(&in_place, &in_place_paths), + describe(&rewoven, &rewoven_paths), + "{segment:?} edited by {primary:?} and {end:?}" + ); + } + } + } + + // A handle shared by two segments is unwelded by a move, as the working form does, instead of moving for both + #[test] + fn a_shared_handle_is_rewoven_instead_of_moved_twice() { + use crate::vector::path::push_path; + use core_types::list::Item; + + let ids = [PointId::generate(), PointId::generate(), PointId::generate(), PointId::generate()]; + let anchors = [DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(0., 10.), DVec2::new(10., 10.)]; + let mut vector = Vector::default(); + for (&position, id) in anchors.iter().zip(ids) { + vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, id)); + } + for position in [DVec2::new(5., 5.), DVec2::new(8., -2.), DVec2::new(8., 12.)] { + vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, PointId::UNNAMED)); + } + let mut paths = List::new(); + push_path(&mut paths, CurveType::Cubic, [0, 4, 5, 1], [SegmentId::generate()]); + push_path(&mut paths, CurveType::Cubic, [2, 4, 6, 3], [SegmentId::generate()]); + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::ApplyPointDelta { point: ids[0], delta: DVec2::X }); + modification.modify(&VectorModificationType::ApplyPointDelta { point: ids[2], delta: DVec2::Y }); + + let (mut applied, mut applied_paths) = (vector.clone(), paths.clone()); + modification.apply(&mut applied, &mut applied_paths); + let (mut rewoven, mut rewoven_paths) = (vector.clone(), paths.clone()); + modification.apply_through_working_form(&mut rewoven, &mut rewoven_paths); + + assert_eq!(describe(&applied, &applied_paths), describe(&rewoven, &rewoven_paths)); + } + + // A delta that isn't finite moves nothing, and neither do the handles beside it, while a finite one beside it still applies + #[test] + fn non_finite_deltas_are_ignored_in_place() { + let (vector, paths) = mixed_geometry(); + let [skipped, moved] = [anchor_id(&vector, &paths, 0), anchor_id(&vector, &paths, 1)]; + + // Stored directly, since recording an edit already discards a non-finite value + let mut modification = VectorModification::default(); + modification.points.delta.insert(skipped, DVec2::new(f64::NAN, 0.)); + modification.points.delta.insert(moved, DVec2::new(3., 4.)); + + let (mut in_place, mut in_place_paths) = (vector.clone(), paths.clone()); + modification.apply(&mut in_place, &mut in_place_paths); + let (mut rewoven, mut rewoven_paths) = (vector.clone(), paths.clone()); + modification.apply_through_working_form(&mut rewoven, &mut rewoven_paths); + + assert_eq!(describe(&in_place, &in_place_paths), describe(&rewoven, &rewoven_paths)); + assert_eq!(anchor_position(&in_place, &in_place_paths, 0), anchor_position(&vector, &paths, 0)); + assert_eq!(anchor_position(&in_place, &in_place_paths, 1), anchor_position(&vector, &paths, 1) + DVec2::new(3., 4.)); + } + + // A point that is a handle in one path and an anchor in another has two ways to move, so it goes through the working form + #[test] + fn a_point_both_handle_and_anchor_is_rewoven_instead_of_moved_in_place() { + use crate::vector::path::push_path; + use core_types::list::Item; + + let ids: [PointId; 4] = std::array::from_fn(|_| PointId::generate()); + let anchors = [DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(5., 5.), DVec2::new(5., 20.)]; + let mut vector = Vector::default(); + for (position, id) in anchors.into_iter().zip(ids) { + vector.0.push(Item::new_from_element(position).with_attribute(ATTR_ID, id)); + } + vector.0.push(Item::new_from_element(DVec2::new(8., -2.)).with_attribute(ATTR_ID, PointId::UNNAMED)); + + // Point 2 is the cubic's first handle and the line's start + let mut paths = List::new(); + push_path(&mut paths, CurveType::Cubic, [0, 2, 4, 1], [SegmentId::generate()]); + push_path(&mut paths, CurveType::Linear, [2, 3], [SegmentId::generate()]); + assert!(!vector.point_roles(&paths).1, "a point with both roles should rule out moving in place"); + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::ApplyPointDelta { point: ids[0], delta: DVec2::X }); + modification.modify(&VectorModificationType::ApplyPointDelta { point: ids[2], delta: DVec2::Y }); + + let (mut applied, mut applied_paths) = (vector.clone(), paths.clone()); + modification.apply(&mut applied, &mut applied_paths); + let (mut rewoven, mut rewoven_paths) = (vector.clone(), paths.clone()); + modification.apply_through_working_form(&mut rewoven, &mut rewoven_paths); + + assert_eq!(describe(&applied, &applied_paths), describe(&rewoven, &rewoven_paths)); + } + + // A free point and an anchor where three segments meet move in place just as the working form moves them + #[test] + fn free_points_and_junctions_move_in_place_like_the_working_form() { + use crate::vector::path::push_path; + + let (mut vector, mut paths) = mixed_geometry(); + for position in [(200., 200.), (-20., -20.)] { + let mut lone_point = BezPath::new(); + lone_point.move_to(position); + vector.append_bezpath(&mut paths, &lone_point); + } + + // The closed loop starts at pool point 0, so a line from there to the second lone point makes it a junction + let spur_end = vector.point_count() as u32 - 1; + push_path(&mut paths, CurveType::Linear, [0, spur_end], [SegmentId::generate()]); + + let mut modification = VectorModification::default(); + for (index, anchor) in vector.anchor_points(&paths).enumerate() { + let delta = DVec2::new(index as f64 + 1., 2.); + modification.modify(&VectorModificationType::ApplyPointDelta { point: anchor, delta }); + } + + let (mut in_place, mut in_place_paths) = (vector.clone(), paths.clone()); + modification.apply(&mut in_place, &mut in_place_paths); + let (mut rewoven, mut rewoven_paths) = (vector.clone(), paths.clone()); + modification.apply_through_working_form(&mut rewoven, &mut rewoven_paths); + + assert_eq!(describe(&in_place, &in_place_paths), describe(&rewoven, &rewoven_paths)); + assert_eq!(in_place_paths, paths, "moving points leaves the weave untouched"); + } + // Re-adding a segment or point under an ID the geometry already holds adds no second copy under that ID #[test] fn duplicate_adds_are_skipped() { diff --git a/node-graph/libraries/vector-types/src/vector/vector_types.rs b/node-graph/libraries/vector-types/src/vector/vector_types.rs index 4b10f76291..05508d8056 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_types.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_types.rs @@ -2,7 +2,7 @@ use super::addressing; use super::connectivity::Connectivity; use super::contour::{contours, subpaths}; use super::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; -use super::path::{CurveType, Path, append_bezpath, curve_type_at, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path}; +use super::path::{CurveType, Path, curve_type_at, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path, weave_bezpath}; use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use super::vector_attributes::{PointId, SegmentId}; use core_types::bounds::{BoundingBox, RenderBoundingBox}; @@ -105,38 +105,37 @@ fn next_segment_id(paths: &List) -> SegmentId { } impl Vector { - /// Names the anchors and spans appended since the given watermarks, continuing the ID sequences. - /// Handles take `PointId::UNNAMED`. - fn stamp_appended_ids(&mut self, paths: &mut List, first_new_point: usize, first_new_path: usize) { - let mut point_id = next_point_id(&self.0); - let mut segment_id = next_segment_id(paths); + /// Weaves a bezpath's contours onto this pool and the given paths, naming the new anchors and spans + /// by continuing the ID sequences. Handles take `PointId::UNNAMED`. + pub fn append_bezpath(&mut self, paths: &mut List, bezpath: &BezPath) { + let (first_new_point, first_new_path) = (self.0.len(), paths.len()); + let anchors = weave_bezpath(&mut self.0, paths, bezpath); // Pool order is traversal order, so anchors and free points take IDs in the order they were drawn - let connectivity = Connectivity::build(self.0.len(), paths); - for index in first_new_point..self.0.len() { - let id = if self.is_handle_point(paths, &connectivity, index as u32) { - PointId::UNNAMED - } else { - point_id.next_id() - }; - self.0.set_attribute(ATTR_ID, index, id); + if !anchors.is_empty() { + let mut point_id = next_point_id(&self.0); + let ids = self.0.iter_attribute_values_mut_or_default::(ATTR_ID).skip(first_new_point); + for (id, anchor) in ids.zip(anchors) { + *id = if anchor { point_id.next_id() } else { PointId::UNNAMED }; + } } + let mut segment_id = next_segment_id(paths); for path_index in first_new_path..paths.len() { let curve_type = curve_type_at(paths, path_index); let Some(path) = paths.element_mut(path_index) else { continue }; - for span in 0..path.segment_count(curve_type) { - path.0.set_attribute(ATTR_ID, span * curve_type.stride(), segment_id.next_id()); + let span_count = path.segment_count(curve_type); + if span_count == 0 { + continue; } - } - } - /// Weaves a bezpath's contours onto this pool and the given paths, naming the new anchors and spans. - pub fn append_bezpath(&mut self, paths: &mut List, bezpath: &BezPath) { - let (first_new_point, first_new_path) = (self.0.len(), paths.len()); - append_bezpath(&mut self.0, paths, bezpath); - self.stamp_appended_ids(paths, first_new_point, first_new_path); + let mut span_ids = vec![SegmentId::default(); path.0.len()]; + for span in 0..span_count { + span_ids[span * curve_type.stride()] = segment_id.next_id(); + } + path.0.set_attribute_values(ATTR_ID, span_ids); + } } /// Builds a fresh pool and paths from a single bezpath. @@ -365,23 +364,41 @@ impl Vector { } impl Vector { - /// Whether the pool point at the given index is a handle, referenced only between anchors. - pub(crate) fn is_handle_point(&self, paths: &List, connectivity: &Connectivity, index: u32) -> bool { - let references = connectivity.references(index); + /// Marks each pool point that paths name only at handle slots, in O(points + references). + pub(crate) fn handle_mask(&self, paths: &List) -> Vec { + self.point_roles(paths).0 + } - !references.is_empty() - && references - .iter() - .all(|reference| !matches!(paths.element(reference.path as usize), Some(path) if path.is_anchor_reference(reference.index as usize, curve_type_at(paths, reference.path as usize)))) + /// The handle mask, along with whether every handle is one segment's alone: no point fills two handle slots, and none + /// is an anchor in one place and a handle in another. + pub(crate) fn point_roles(&self, paths: &List) -> (Vec, bool) { + // Each point is referenced by no path, only at a handle slot, or at an anchor slot somewhere + const UNREFERENCED: u8 = 0; + const HANDLE: u8 = 1; + const ANCHOR: u8 = 2; + + let mut roles = vec![UNREFERENCED; self.0.len()]; + let mut handles_unshared = true; + for (path_index, path) in paths.iter_element_values().enumerate() { + let stride = curve_type_at(paths, path_index).stride(); + for (reference_index, point) in path.references().enumerate() { + let Some(role) = roles.get_mut(point as usize) else { continue }; + if reference_index.is_multiple_of(stride) { + handles_unshared &= *role != HANDLE; + *role = ANCHOR; + } else { + handles_unshared &= *role == UNREFERENCED; + *role = (*role).max(HANDLE); + } + } + } + + (roles.into_iter().map(|role| role == HANDLE).collect(), handles_unshared) } /// The pool indices of all anchor points and free points in pool order, skipping handles. pub fn anchor_indices(&self, paths: &List) -> Vec { - let connectivity = self.connectivity(paths); - (0..self.0.len() as u32) - .filter(|&index| !self.is_handle_point(paths, &connectivity, index)) - .map(|index| index as usize) - .collect() + self.handle_mask(paths).into_iter().enumerate().filter(|&(_, handle)| !handle).map(|(index, _)| index).collect() } /// Drops the paths and every point used only as a handle, leaving the anchors and free points as a bare cloud. @@ -401,11 +418,8 @@ impl Vector { /// Iterator over the IDs of all anchor points and free points, skipping handles. pub fn anchor_points(&self, paths: &List) -> impl Iterator { - let connectivity = self.connectivity(paths); - let anchors: Vec<_> = (0..self.0.len() as u32) - .filter(|&index| !self.is_handle_point(paths, &connectivity, index)) - .filter_map(|index| self.point_id_at(index)) - .collect(); + let ids = self.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); + let anchors: Vec<_> = self.handle_mask(paths).into_iter().zip(ids).filter(|&(handle, _)| !handle).map(|(_, &id)| id).collect(); anchors.into_iter() } @@ -414,14 +428,14 @@ impl Vector { pub fn anchor_endpoints(&self, paths: &List) -> impl Iterator { let connectivity = self.connectivity(paths); let endpoints: Vec<_> = (0..self.0.len() as u32) - .filter(|&index| connectivity.spokes(index, paths) == 1) + .filter(|&index| connectivity.spokes(index) == 1) .filter_map(|index| self.point_id_at(index)) .collect(); endpoints.into_iter() } - // Each per-point query below builds its own connectivity index, O(points + references) with two allocations. + // Each per-point query below builds its own connectivity index, O(points + references) with three allocations. // Callers looping over many points should hoist `connectivity()` and use `addressing` directly. /// Enumerate all segments that start at the point. @@ -458,7 +472,7 @@ impl Vector { pub fn connected_count(&self, paths: &List, point: PointId) -> usize { let Some(index) = self.index_of_point_id(point) else { return 0 }; - self.connectivity(paths).spokes(index, paths) + self.connectivity(paths).spokes(index) } /// Whether any segment starts or ends at the point. @@ -497,12 +511,8 @@ impl Vector { impl Vector { /// Whether the junction at the given anchor keeps its tangent pair smooth, read from any of its occurrences. fn smooth_at_anchor_index(&self, paths: &List, connectivity: &Connectivity, index: u32) -> bool { - connectivity.references(index).iter().any(|reference| { + connectivity.references(index).iter().filter(|reference| reference.is_anchor()).any(|reference| { let Some(path) = paths.element(reference.path as usize) else { return false }; - if !path.is_anchor_reference(reference.index as usize, curve_type_at(paths, reference.path as usize)) { - return false; - } - path.0.attribute::(ATTR_SMOOTH, reference.index as usize).copied().unwrap_or_default() }) } @@ -510,7 +520,7 @@ impl Vector { /// Whether the anchor at the given pool index forms a smooth tangent pair, which needs exactly two /// segment ends meeting there. A junction has no unambiguous pair to keep smooth. fn pairs_smoothly(&self, paths: &List, connectivity: &Connectivity, index: u32) -> bool { - self.smooth_at_anchor_index(paths, connectivity, index) && connectivity.spokes(index, paths) == 2 + self.smooth_at_anchor_index(paths, connectivity, index) && connectivity.spokes(index) == 2 } /// Whether the anchor (or the handle's anchor) keeps a smooth tangent pair, which needs exactly two segment ends meeting there. @@ -535,15 +545,19 @@ impl Vector { /// Every G1 pair: the two facing handles at each smooth anchor where exactly two segment ends meet. pub fn colinear_pairs(&self, paths: &List) -> Vec<[HandleId; 2]> { - let connectivity = self.connectivity(paths); + self.colinear_pairs_with(paths, &self.connectivity(paths)) + } + + /// The G1 pairs, read through a connectivity the caller already built. + pub(crate) fn colinear_pairs_with(&self, paths: &List, connectivity: &Connectivity) -> Vec<[HandleId; 2]> { let mut pairs = Vec::new(); for index in 0..self.point_count() as u32 { - if connectivity.spokes(index, paths) != 2 || !self.smooth_at_anchor_index(paths, &connectivity, index) { + if connectivity.spokes(index) != 2 || !self.smooth_at_anchor_index(paths, connectivity, index) { continue; } - let handles: Vec = addressing::spans_at(index, paths, &connectivity) + let handles: Vec = addressing::spans_at(index, paths, connectivity) .into_iter() .filter_map(|(span, arriving)| { let segment = addressing::segment_id_of(paths, span)?; @@ -607,12 +621,9 @@ impl Vector { let connectivity = self.connectivity(paths); for index in indices { - for reference in connectivity.references(index) { - let curve_type = curve_type_at(paths, reference.path as usize); + for reference in connectivity.references(index).iter().filter(|reference| reference.is_anchor()) { let Some(path) = paths.element_mut(reference.path as usize) else { continue }; - if path.is_anchor_reference(reference.index as usize, curve_type) { - path.0.set_attribute(ATTR_SMOOTH, reference.index as usize, smooth); - } + path.0.set_attribute(ATTR_SMOOTH, reference.index as usize, smooth); } } } From e1bc46a6bbeea2d33b13ed914f3d50b2a881f086 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 16 Oct 2026 19:17:39 -0700 Subject: [PATCH 31/47] Draw vector pool paths in their stored order and direction instead of re-walking segments (#4737) * Stitch contours from stored path order and direction in place of the walker * Keep each path's boundary through the working form * Bake the straightest route through junctions into legacy segment soups * Keep Extrude's split pieces in their segment's place and order shared Close Path placements --- .../vector/algorithms/merge_by_distance.rs | 25 +- .../vector-types/src/vector/contour.rs | 411 ++++++++++-------- .../vector-types/src/vector/flatten.rs | 317 +++++++++++++- .../libraries/vector-types/src/vector/path.rs | 61 ++- .../src/vector/vector_attributes.rs | 204 ++++++--- .../src/vector/vector_modification.rs | 27 +- .../vector-types/src/vector/vector_types.rs | 128 +++++- .../vector/src/vector_modification_nodes.rs | 30 +- node-graph/nodes/vector/src/vector_nodes.rs | 42 +- 9 files changed, 953 insertions(+), 292 deletions(-) diff --git a/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs b/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs index 3bed3916cf..03e0c9d000 100644 --- a/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs +++ b/node-graph/libraries/vector-types/src/vector/algorithms/merge_by_distance.rs @@ -103,10 +103,12 @@ impl MergeByDistanceExt for Vector { // Drop the collapsed segments, then the merged-away points, remapping segment endpoints let keep_segment: Vec = working.segment_ids.iter().map(|id| !segments_to_delete.contains(id)).collect(); + working.carry_path_beginnings(&keep_segment); retain_by(&mut working.segment_ids, &keep_segment); retain_by(&mut working.segment_start, &keep_segment); retain_by(&mut working.segment_end, &keep_segment); retain_by(&mut working.segment_handles, &keep_segment); + retain_by(&mut working.segment_begins_path, &keep_segment); let mut point_map = Vec::with_capacity(working.point_ids.len()); let mut new_index = 0; @@ -130,7 +132,7 @@ impl MergeByDistanceExt for Vector { } fn merge_by_distance_spatial(&mut self, paths: &mut List, transform: DAffine2, distance: f64) { - let working = WorkingVector::flatten(self, paths); + let mut working = WorkingVector::flatten(self, paths); let point_count = working.point_positions.len(); // Find min x and y for grid cell normalization @@ -212,7 +214,13 @@ impl MergeByDistanceExt for Vector { } } - // Build the merged working form, skipping segments with endpoints that collapsed together + // Segments with endpoints that collapsed together drop out, handing on any path they began + let keep_segment: Vec = (0..working.segment_ids.len()) + .map(|segment_index| point_index_map[working.segment_start[segment_index]] != point_index_map[working.segment_end[segment_index]]) + .collect(); + working.carry_path_beginnings(&keep_segment); + + // Build the merged working form from the kept segments let mut merged = WorkingVector { point_ids: merged_indices, point_positions: merged_positions, @@ -220,16 +228,15 @@ impl MergeByDistanceExt for Vector { ..Default::default() }; - for segment_index in 0..working.segment_ids.len() { + for segment_index in (0..working.segment_ids.len()).filter(|&segment_index| keep_segment[segment_index]) { let new_start = point_index_map[working.segment_start[segment_index]].unwrap(); let new_end = point_index_map[working.segment_end[segment_index]].unwrap(); - if new_start != new_end { - merged.segment_ids.push(working.segment_ids[segment_index]); - merged.segment_start.push(new_start); - merged.segment_end.push(new_end); - merged.segment_handles.push(working.segment_handles[segment_index]); - } + merged.segment_ids.push(working.segment_ids[segment_index]); + merged.segment_start.push(new_start); + merged.segment_end.push(new_end); + merged.segment_handles.push(working.segment_handles[segment_index]); + merged.segment_begins_path.push(working.segment_begins_path.get(segment_index).copied().unwrap_or(false)); } merged.reweave(self, paths); diff --git a/node-graph/libraries/vector-types/src/vector/contour.rs b/node-graph/libraries/vector-types/src/vector/contour.rs index 10c7230100..b0cf78faf5 100644 --- a/node-graph/libraries/vector-types/src/vector/contour.rs +++ b/node-graph/libraries/vector-types/src/vector/contour.rs @@ -4,212 +4,228 @@ use core_types::list::List; use glam::DVec2; use kurbo::BezPath; -/// One span of a path as a subpath walks it, running against its stored direction when reversed. +/// One path's part in a contour, crossed against its stored direction when reversed. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Step { +pub struct ContourPart { pub path: u32, - pub span: u32, pub reversed: bool, } -/// Spans walked end to end across the anchors they share, from one pool point to another. -/// A closed subpath arrives back at the point it left from. +/// Paths stitched end to end into one outline, as [`contours`] describes. +/// A closed contour arrives back at the point it left from. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Subpath { - pub steps: Vec, +pub struct Contour { + pub parts: Vec, pub closed: bool, pub entry: u32, pub exit: u32, } -/// A span flattened out of its path, naming the anchors at its two ends. -struct Edge { - path: u32, - span: u32, - start: u32, - end: u32, +/// The path ends meeting at each pool point, kept up to the two a weld can stitch, beside every spoke there. +struct Welds { + ends: Vec<[(u32, bool); 2]>, + end_count: Vec, + spokes: Vec, + /// Which paths can be drawn whole: at least one segment, no partial one, and every reference inside the pool. + drawable: Vec, } -/// Each anchor's span ends in the order the spans were woven, consumed as the walk uses them up. -/// An end is named by twice its edge's index, plus one for the end the span arrives at. -struct SpanEnds { - offsets: Vec, - ends: Vec, - cursors: Vec, - used: Vec, - remaining: Vec, -} +impl Welds { + fn new(point_count: usize, paths: &List, curve_types: &[CurveType]) -> Self { + let mut welds = Self { + ends: vec![[(0, false); 2]; point_count], + end_count: vec![0; point_count], + spokes: vec![0; point_count], + drawable: vec![false; paths.len()], + }; -impl SpanEnds { - fn new(point_count: usize, edges: &[Edge]) -> Self { - let mut offsets = vec![0; point_count + 1]; - for edge in edges { - offsets[edge.start as usize + 1] += 1; - offsets[edge.end as usize + 1] += 1; - } - for point in 0..point_count { - offsets[point + 1] += offsets[point]; - } + for (path_index, path) in paths.iter_element_values().enumerate() { + let references = path.0.iter_element_values().as_slice(); + let stride = curve_types.get(path_index).copied().unwrap_or_default().stride(); + let last = references.len().saturating_sub(1); + if last == 0 || !last.is_multiple_of(stride) || references.iter().any(|&point| point as usize >= point_count) { + continue; + } + welds.drawable[path_index] = true; - let mut ends = vec![0; edges.len() * 2]; - let mut fill = offsets.clone(); - for (index, edge) in edges.iter().enumerate() { - for (point, end) in [(edge.start as usize, index * 2), (edge.end as usize, index * 2 + 1)] { - ends[fill[point]] = end; - fill[point] += 1; + for (index, &point) in references.iter().enumerate().step_by(stride) { + let Some(spokes) = welds.spokes.get_mut(point as usize) else { continue }; + *spokes = spokes.saturating_add(u8::from(index > 0) + u8::from(index < last)); + } + + // A closed path's two ends are one anchor, which welds with nothing + let (start, end) = (references[0], references[last]); + if start != end { + welds.add_end(start as u32, path_index as u32, false); + welds.add_end(end as u32, path_index as u32, true); } } - let remaining = (0..point_count).map(|point| offsets[point + 1] - offsets[point]).collect(); - - Self { - cursors: offsets[..point_count].to_vec(), - offsets, - ends, - used: vec![false; edges.len() * 2], - remaining, - } + welds } - /// Uses up the earliest woven span end still waiting at the point. - fn take_earliest(&mut self, point: usize) -> Option { - while self.cursors[point] < self.offsets[point + 1] { - let end = self.ends[self.cursors[point]]; - self.cursors[point] += 1; - - if !self.used[end] { - self.used[end] = true; - self.remaining[point] -= 1; - return Some(end); - } + fn add_end(&mut self, point: u32, path: u32, arriving: bool) { + let Some(count) = self.end_count.get_mut(point as usize) else { return }; + if let Some(slot) = self.ends[point as usize].get_mut(*count as usize) { + *slot = (path, arriving); } - - None + *count = count.saturating_add(1); } - /// Uses up one particular span end, which is the far side of a span the walk just crossed. - fn take(&mut self, point: usize, end: usize) { - if !self.used[end] { - self.used[end] = true; - self.remaining[point] -= 1; + /// The one other path end at the point, when exactly two path ends meet there and nothing passes through. + fn other_end(&self, point: u32, this: (u32, bool)) -> Option<(u32, bool)> { + let point = point as usize; + if *self.end_count.get(point)? != 2 || *self.spokes.get(point)? != 2 { + return None; } + + self.ends[point].iter().copied().find(|&end| end != this) } } -/// Walks every span into subpaths in O(points + spans): open ones first, each from a point one span end meets, -/// then the rest from the lowest point with spans left. A walk follows the earliest woven span waiting at each -/// point, backwards when that span ends there, and closes on arriving back where it began. -pub fn subpaths(point_count: usize, paths: &List) -> Vec { - subpaths_with(point_count, paths, &curve_types(paths)) +/// Stitches the paths into contours in O(points + references), each seeded by the earliest stored path not yet taken +/// and running in that path's direction until it arrives back where it set out. A path runs on into the next stored +/// path when that one sets out from where it ends, and otherwise into the one path welded to its end where exactly two +/// path ends meet and nothing passes through. Every other meeting is a junction, where paths end. A closed path is +/// always a contour of its own, and a path that cannot be drawn whole takes no part. +pub fn contours(point_count: usize, paths: &List) -> Vec { + contours_with(point_count, paths, &curve_types(paths)) } -/// The curve type of every path, read once so the walkers below never look one up per span. +/// The curve type of every path, read once so the stitching below never looks one up per path. fn curve_types(paths: &List) -> Vec { (0..paths.len()).map(|index| curve_type_at(paths, index)).collect() } -fn subpaths_with(point_count: usize, paths: &List, curve_types: &[CurveType]) -> Vec { - let mut edges = Vec::new(); - for (path_index, path) in paths.iter_element_values().enumerate() { - let curve_type = curve_types.get(path_index).copied().unwrap_or_default(); - let stride = curve_type.stride(); - let references = path.0.iter_element_values().as_slice(); +fn contours_with(point_count: usize, paths: &List, curve_types: &[CurveType]) -> Vec { + let welds = Welds::new(point_count, paths, curve_types); + let ends_of = |path: u32| match paths.element(path as usize)?.0.iter_element_values().as_slice() { + [start, .., end] if welds.drawable[path as usize] => Some((*start as u32, *end as u32)), + _ => None, + }; - for span in 0..path.segment_count(curve_type) { - let Some(references) = references.get(span * stride..=(span + 1) * stride) else { continue }; + // The points a part is crossed from and to, in the direction the contour runs along it + let crossing_ends = |part: ContourPart| ends_of(part.path).map(|(start, end)| if part.reversed { (end, start) } else { (start, end) }); - // A span naming a point outside the pool cannot be drawn, so it takes no part in the walk - if references.iter().any(|&reference| !(0..point_count as i64).contains(&reference)) { - continue; - } - let (Some(&start), Some(&end)) = (references.first(), references.last()) else { continue }; + // The stored neighbor that carries on from this part at the point: onward, the one setting out from it, and backward, the one arriving at it + let consecutive = |part: ContourPart, point: u32, onward: bool| { + let step = if onward != part.reversed { 1 } else { -1 }; + let candidate = ContourPart { + path: u32::try_from(part.path as i64 + step).ok()?, + reversed: part.reversed, + }; + let (from, to) = crossing_ends(candidate)?; - edges.push(Edge { - path: path_index as u32, - span: span as u32, - start: start as u32, - end: end as u32, - }); - } - } + (from != to && if onward { from } else { to } == point).then_some(candidate) + }; - let mut span_ends = SpanEnds::new(point_count, &edges); + // The one path welded to this part's end at the point, crossed away from it + let welded = |part: ContourPart, point: u32, onward: bool| { + let (path, arriving) = welds.other_end(point, (part.path, onward != part.reversed))?; + + Some(ContourPart { path, reversed: arriving == onward }) + }; + + let mut consumed = vec![false; paths.len()]; let mut found = Vec::new(); - let (mut skip, mut open_ends_done) = (0, false); - loop { - let mut entry = None; - if !open_ends_done { - entry = (skip..point_count).find(|&point| span_ends.remaining[point] == 1); - open_ends_done = entry.is_none(); - skip = entry.map_or(0, |point| point + 1); + for seed in 0..paths.len() as u32 { + if consumed[seed as usize] { + continue; } - if entry.is_none() { - entry = (skip..point_count).find(|&point| span_ends.remaining[point] > 0); - skip = entry.unwrap_or(point_count); - } - let Some(entry) = entry else { break }; + let Some((start, end)) = ends_of(seed) else { continue }; + consumed[seed as usize] = true; - let (mut point, mut steps, mut closed) = (entry, Vec::new(), false); - while let Some(end) = span_ends.take_earliest(point) { - let edge = &edges[end / 2]; - let reversed = end % 2 == 1; - let next = if reversed { edge.start } else { edge.end } as usize; - - steps.push(Step { - path: edge.path, - span: edge.span, - reversed, + let mut parts = vec![ContourPart { path: seed, reversed: false }]; + if start == end { + found.push(Contour { + parts, + closed: true, + entry: start, + exit: start, }); - span_ends.take(next, end ^ 1); - point = next; + continue; + } - if next == entry { + // Onward from the seed's end until the contour arrives back where it set out or nothing carries on + let (mut exit, mut last) = (end, parts[0]); + let mut closed = false; + loop { + if exit == start { closed = true; break; } + let unconsumed = |part: &ContourPart| !consumed[part.path as usize]; + let Some(next) = consecutive(last, exit, true).filter(unconsumed).or_else(|| welded(last, exit, true).filter(unconsumed)) else { + break; + }; + let Some((_, to)) = crossing_ends(next) else { break }; + + consumed[next.path as usize] = true; + parts.push(next); + (exit, last) = (to, next); } - found.push(Subpath { - steps, + // Backward from the seed's start, so the contour begins where the stitched paths run out or meet its end + let (mut entry, mut first) = (start, parts[0]); + let mut before = Vec::new(); + while !closed { + let unconsumed = |part: &ContourPart| !consumed[part.path as usize]; + let Some(previous) = consecutive(first, entry, false).filter(unconsumed).or_else(|| welded(first, entry, false).filter(unconsumed)) else { + break; + }; + let Some((from, _)) = crossing_ends(previous) else { break }; + + consumed[previous.path as usize] = true; + before.push(previous); + (entry, first) = (from, previous); + closed = entry == exit; + } + before.reverse(); + before.append(&mut parts); + + found.push(Contour { + parts: before, closed, - entry: entry as u32, - exit: point as u32, + entry, + exit: if closed { entry } else { exit }, }); } found } -/// Emits one subpath as a bezpath, or `None` when it has no drawable geometry. -pub fn subpath_to_bezpath(pool: &List, paths: &List, subpath: &Subpath) -> Option { - subpath_to_bezpath_with(pool, paths, &curve_types(paths), subpath) -} - -fn subpath_to_bezpath_with(pool: &List, paths: &List, curve_types: &[CurveType], subpath: &Subpath) -> Option { +/// Emits one contour as a bezpath, or `None` when its entry point is not in the pool. +fn contour_to_bezpath(pool: &List, paths: &List, curve_types: &[CurveType], contour: &Contour) -> Option { let mut bezpath = BezPath::new(); - bezpath.move_to(dvec2_to_point(*pool.element(subpath.entry as usize)?)); + bezpath.move_to(dvec2_to_point(*pool.element(contour.entry as usize)?)); - for step in &subpath.steps { - let path = paths.element(step.path as usize)?; - let segment = path.segment(pool, *curve_types.get(step.path as usize)?, step.span as usize)?; + for part in &contour.parts { + let path = paths.element(part.path as usize)?; + let curve_type = *curve_types.get(part.path as usize)?; + let count = path.segment_count(curve_type); - append_segment(&mut bezpath, if step.reversed { segment.reverse() } else { segment }); + for step in 0..count { + let span = if part.reversed { count - 1 - step } else { step }; + let Some(segment) = path.segment(pool, curve_type, span) else { continue }; + + append_segment(&mut bezpath, if part.reversed { segment.reverse() } else { segment }); + } } - if subpath.closed { + if contour.closed { bezpath.close_path(); } Some(bezpath) } -/// Assembles the paths into contours for rendering, one bezpath per subpath in the order they are walked. -pub fn contours(pool: &List, paths: &List) -> Vec { +/// Every contour as a bezpath, in the order the paths are stored. +pub fn contour_bezpaths(pool: &List, paths: &List) -> Vec { let curve_types = curve_types(paths); - subpaths_with(pool.len(), paths, &curve_types) + contours_with(pool.len(), paths, &curve_types) .iter() - .filter_map(|subpath| subpath_to_bezpath_with(pool, paths, &curve_types, subpath)) + .filter_map(|contour| contour_to_bezpath(pool, paths, &curve_types, contour)) .collect() } @@ -235,22 +251,25 @@ mod tests { (pool, paths) } - /// The anchors each subpath visits, with whether it closed. - fn walked(point_count: usize, paths: &List) -> Vec<(Vec, bool)> { - subpaths(point_count, paths) + /// The anchors each contour visits in order, with whether it closed. + fn stitched(point_count: usize, paths: &List) -> Vec<(Vec, bool)> { + contours(point_count, paths) .into_iter() - .map(|subpath| { - let mut anchors = vec![subpath.entry]; - for step in &subpath.steps { - let path = paths.element(step.path as usize).expect("the step names a path"); - let (start, end) = (path.reference(step.span as usize), path.reference(step.span as usize + 1)); - anchors.push(if step.reversed { start } else { end }.expect("the span has both ends")); + .map(|contour| { + let mut anchors = vec![contour.entry]; + for part in &contour.parts { + let path = paths.element(part.path as usize).expect("the part names a path"); + let mut references: Vec = path.references().collect(); + if part.reversed { + references.reverse(); + } + anchors.extend(references.into_iter().skip(1)); } - if subpath.closed { + if contour.closed { anchors.pop(); } - (anchors, subpath.closed) + (anchors, contour.closed) }) .collect() } @@ -267,7 +286,7 @@ mod tests { let (pool, paths) = pool_and_paths_from_bezpath(&source); assert_eq!(paths.len(), 3); - let assembled = contours(&pool, &paths); + let assembled = contour_bezpaths(&pool, &paths); assert_eq!(assembled.len(), 1); assert!(matches!( assembled[0].elements(), @@ -289,7 +308,7 @@ mod tests { }); let (pool, paths) = pool_and_paths_from_bezpath(&source); - assert_eq!(contours(&pool, &paths).len(), 2); + assert_eq!(contour_bezpaths(&pool, &paths).len(), 2); } // An open subpath emits one contour that stays open @@ -303,64 +322,106 @@ mod tests { let (pool, paths) = pool_and_paths_from_bezpath(&source); assert_eq!(paths.len(), 2); - let assembled = contours(&pool, &paths); + let assembled = contour_bezpaths(&pool, &paths); assert_eq!(assembled.len(), 1); assert!(matches!(assembled[0].elements(), [PathEl::MoveTo(_), PathEl::LineTo(_), PathEl::CurveTo(..)])); } - // A loop leaves from its lowest point along the earliest span there, which it crosses backwards when that span ends at the point + // A loop is read from the anchor it is stored from, in the direction it is stored in #[test] - fn loop_walks_backwards_when_its_earliest_span_arrives() { + fn a_loop_keeps_its_stored_start_and_direction() { let (_, paths) = linear(4, &[&[1, 2, 3, 0, 1]]); - assert_eq!(walked(4, &paths), [(vec![0, 3, 2, 1], true)]); + assert_eq!(stitched(4, &paths), [(vec![1, 2, 3, 0], true)]); } - // An open subpath leaves from its lower end even when that is where it was woven to + // A path welded ahead of the first one is stitched on in front, running its own stored direction #[test] - fn open_subpath_leaves_from_its_lower_end() { + fn a_welded_path_is_stitched_on_in_front() { let (_, paths) = linear(4, &[&[0, 1, 2], &[3, 0]]); - assert_eq!(walked(4, &paths), [(vec![2, 1, 0, 3], false)]); + assert_eq!(stitched(4, &paths), [(vec![3, 0, 1, 2], false)]); } - // Open subpaths lead, however high their points, and loops follow in the order of their lowest points + // Contours come out in the order their paths are stored, open or closed #[test] - fn open_subpaths_lead_the_loops() { + fn contours_follow_path_order() { let (_, paths) = linear(8, &[&[5, 6, 7, 5], &[0, 1, 2, 0], &[3, 4]]); - assert_eq!(walked(8, &paths), [(vec![3, 4], false), (vec![0, 1, 2], true), (vec![5, 6, 7], true)]); + assert_eq!(stitched(8, &paths), [(vec![5, 6, 7], true), (vec![0, 1, 2], true), (vec![3, 4], false)]); } - // Loops that touch an outline are walked apart from it, since the outline's own spans were woven first + // Loops that touch an outline are each their own contour, since a closed path welds with nothing #[test] - fn touching_loops_walk_apart_from_the_outline() { + fn touching_loops_stay_apart_from_the_outline() { let (_, paths) = linear(6, &[&[0, 1, 2, 3, 0], &[1, 4, 1], &[3, 5, 3]]); - assert_eq!(walked(6, &paths), [(vec![0, 1, 2, 3], true), (vec![1, 4], true), (vec![3, 5], true)]); + assert_eq!(stitched(6, &paths), [(vec![0, 1, 2, 3], true), (vec![1, 4], true), (vec![3, 5], true)]); } - // A walk carries on through a junction along its earliest span and ends where none are left + // Three paths meeting at one anchor make a junction, where every one of them ends #[test] - fn junction_is_walked_through_along_its_earliest_span() { + fn every_path_ends_at_a_junction() { let (_, paths) = linear(4, &[&[0, 3], &[1, 3], &[2, 3]]); - assert_eq!(walked(4, &paths), [(vec![0, 3, 1], false), (vec![2, 3], false)]); + assert_eq!(stitched(4, &paths), [(vec![0, 3], false), (vec![1, 3], false), (vec![2, 3], false)]); } - // A walk that arrives back at a point other than the one it left from stays open + // A path passing through a junction stays whole, and a path ending there is not stitched onto it #[test] - fn loop_on_a_tail_stays_open() { - let (_, paths) = linear(4, &[&[0, 1, 2, 3, 1]]); + fn a_path_through_a_junction_stays_whole() { + let (_, paths) = linear(5, &[&[0, 1, 2, 3, 1], &[4, 1]]); - assert_eq!(walked(4, &paths), [(vec![0, 1, 2, 3, 1], false)]); + assert_eq!(stitched(5, &paths), [(vec![0, 1, 2, 3, 1], false), (vec![4, 1], false)]); } - // A span naming a point outside the pool is left out of the walk + // Consecutive paths meeting head to tail are one stroke even through a junction, while the path passing through it stays whole #[test] - fn dangling_span_is_left_out() { - let (_, paths) = linear(3, &[&[0, 1, 9], &[1, 2]]); + fn consecutive_paths_carry_on_through_a_junction() { + let (_, paths) = linear(5, &[&[0, 1], &[1, 2, 0], &[3, 1, 4]]); - assert_eq!(walked(3, &paths), [(vec![0, 1, 2], false)]); + assert_eq!(stitched(5, &paths), [(vec![0, 1, 2], true), (vec![3, 1, 4], false)]); + } + + // Crossing a stored path backward carries on backward into the path stored before it, here through the junction at point 1 + #[test] + fn a_backward_crossing_carries_on_into_the_path_before() { + let (_, paths) = linear(8, &[&[5, 2], &[0, 1], &[1, 2], &[7, 1]]); + + assert_eq!(stitched(8, &paths), [(vec![5, 2, 1, 0], false), (vec![7, 1], false)]); + } + + // Two halves both running top to bottom, welded at both ends, render as one outline with the second half crossed backwards + #[test] + fn heart_halves_stitch_into_one_outline() { + let (_, paths) = linear(4, &[&[0, 1, 2], &[0, 3, 2]]); + + assert_eq!(stitched(4, &paths), [(vec![0, 1, 2, 3], true)]); + assert!(contours(4, &paths)[0].parts[1].reversed); + } + + // A walk that stops at a junction still closes when stitching backward from its start arrives at that junction + #[test] + fn a_contour_closes_when_the_walk_back_meets_its_end() { + let (_, paths) = linear(5, &[&[0, 1], &[2, 0], &[1, 2], &[3, 2, 4]]); + + assert_eq!(stitched(5, &paths), [(vec![2, 0, 1], true), (vec![3, 2, 4], false)]); + } + + // A closed path is never stitched onto the path stored before it, even when it sets out from that path's end + #[test] + fn a_closed_path_is_never_stitched_on() { + let (_, paths) = linear(4, &[&[3, 0], &[0, 1, 2, 0]]); + + assert_eq!(stitched(4, &paths), [(vec![3, 0], false), (vec![0, 1, 2], true)]); + } + + // A path naming a point outside the pool, or ending partway through a segment, is left out whole + #[test] + fn a_path_that_cannot_be_drawn_whole_is_left_out() { + let (pool, paths) = linear(3, &[&[0, 1, 9], &[1, 2]]); + + assert_eq!(stitched(3, &paths), [(vec![1, 2], false)]); + assert_eq!(contour_bezpaths(&pool, &paths).len(), 1); } } diff --git a/node-graph/libraries/vector-types/src/vector/flatten.rs b/node-graph/libraries/vector-types/src/vector/flatten.rs index f8734ffda2..3296a5807f 100644 --- a/node-graph/libraries/vector-types/src/vector/flatten.rs +++ b/node-graph/libraries/vector-types/src/vector/flatten.rs @@ -20,6 +20,8 @@ pub struct WorkingVector { pub segment_start: Vec, pub segment_end: Vec, pub segment_handles: Vec, + /// Which segments open a path of their own, kept as path boundaries when rewoven. Missing entries count as false. + pub segment_begins_path: Vec, pub colinear: Vec<[HandleId; 2]>, } @@ -46,6 +48,7 @@ impl WorkingVector { let stride = curve_type.stride(); let span_ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); + let mut begins_path = true; for span in 0..path.segment_count(curve_type) { let Some(segment) = path.segment(&vector.0, curve_type, span) else { continue }; let (Some(start), Some(end)) = (path.reference(span * stride), path.reference(span * stride + stride)) else { @@ -57,6 +60,8 @@ impl WorkingVector { working.segment_handles.push(segment_to_handles(&segment)); working.segment_start.push(start); working.segment_end.push(end); + working.segment_begins_path.push(begins_path); + begins_path = false; } } @@ -65,7 +70,21 @@ impl WorkingVector { working } - /// Weaves the working form back into a pool and paths, gathering consecutive segments that meet head to tail into one path. + /// Hands each removed segment's mark as the beginning of a path to the next kept segment, which begins what is left of that path. + pub(crate) fn carry_path_beginnings(&mut self, keep: &[bool]) { + let mut carried = false; + for (begins, &kept) in self.segment_begins_path.iter_mut().zip(keep) { + if !kept { + carried |= *begins; + } else if carried { + *begins = true; + carried = false; + } + } + } + + /// Weaves the working form back into a pool and paths, gathering consecutive segments that meet head to tail into one path + /// until it closes or a segment begins a path of its own. pub fn reweave(self, vector: &mut Vector, paths: &mut List) { *paths = List::new(); @@ -83,7 +102,7 @@ impl WorkingVector { let mut segment_anchors = FxHashMap::default(); let ends = self.segment_start.iter().zip(&self.segment_end); - for ((&id, (&start, &end)), handles) in self.segment_ids.iter().zip(ends).zip(&self.segment_handles) { + for (index, ((&id, (&start, &end)), handles)) in self.segment_ids.iter().zip(ends).zip(&self.segment_handles).enumerate() { if start >= anchor_count || end >= anchor_count { continue; } @@ -94,11 +113,13 @@ impl WorkingVector { BezierHandles::Cubic { handle_start, handle_end } => (CurveType::Cubic, vec![handle_start, handle_end]), }; - // Runs stay in segment order, since the order spans are woven in decides how subpaths are walked. - // A run carries on through a junction and gives way only once it has closed. - let continues_run = runs - .last() - .is_some_and(|(run_curve_type, references, _)| *run_curve_type == curve_type && references.last() == Some(&(start as u32)) && references.first() != references.last()); + // Runs stay in segment order, which is the order the paths come out in. A run carries on through a + // junction and gives way once it has closed, or when the next segment opens a path of its own. + let begins_path = self.segment_begins_path.get(index).copied().unwrap_or(false); + let continues_run = !begins_path + && runs + .last() + .is_some_and(|(run_curve_type, references, _)| *run_curve_type == curve_type && references.last() == Some(&(start as u32)) && references.first() != references.last()); if !continues_run { runs.push((curve_type, vec![start as u32], Vec::new())); } @@ -140,11 +161,163 @@ impl WorkingVector { vector.set_smooth_at_indices(paths, smooth_anchors, true); } + + /// Reorders and reorients the segments so each continues the one it meets head to tail, taking the straightest + /// route through every junction, and marks where each chain begins. This bakes path structure into a segment soup once. + pub fn chain_by_straightest_route(&mut self) { + let segment_count = [self.segment_ids.len(), self.segment_start.len(), self.segment_end.len(), self.segment_handles.len()] + .into_iter() + .min() + .unwrap_or(0); + let point_count = self.point_positions.len(); + + // Every segment end at each point, named by twice the segment's index plus one for its arriving end + let mut ends_at: Vec> = vec![Vec::new(); point_count]; + for index in 0..segment_count { + let (start, end) = (self.segment_start[index], self.segment_end[index]); + if start < point_count && end < point_count { + ends_at[start].push(index * 2); + ends_at[end].push(index * 2 + 1); + } + } + + // The direction a segment leaves its anchor in from the given end, toward the nearest control point not sitting on the anchor + let direction = |end: usize| { + let (index, arriving) = (end / 2, end % 2 == 1); + let (start, finish) = (self.point_positions[self.segment_start[index]], self.point_positions[self.segment_end[index]]); + let handles = self.segment_handles[index]; + let (anchor, toward) = if arriving { + (finish, [handles.end(), handles.start(), Some(start)]) + } else { + (start, [handles.start(), handles.end(), Some(finish)]) + }; + + let along = toward.into_iter().flatten().map(|point| point - anchor).find(|along| along.length_squared() > 1e-12); + along.unwrap_or_default().normalize_or_zero() + }; + + // Pair off the ends meeting at each point, the straightest pair through a junction first, in O(k² log k) for k ends there + let mut partner = vec![usize::MAX; segment_count * 2]; + for ends in ends_at.iter().filter(|ends| ends.len() >= 2) { + let directions: Vec = ends.iter().map(|&end| direction(end)).collect(); + + // Straightness is rounded so pairs differing only by float error are equally straight, leaving the earlier stored ends first + let mut pairs: Vec<(i64, usize, usize)> = (0..ends.len()) + .flat_map(|i| (i + 1..ends.len()).map(move |j| (i, j))) + .map(|(i, j)| ((-directions[i].dot(directions[j]) * 1e9).round() as i64, i, j)) + .collect(); + pairs.sort_by(|a, b| b.0.cmp(&a.0).then((a.1, a.2).cmp(&(b.1, b.2)))); + + let mut paired = vec![false; ends.len()]; + for (_, i, j) in pairs { + if paired[i] || paired[j] { + continue; + } + paired[i] = true; + paired[j] = true; + partner[ends[i]] = ends[j]; + partner[ends[j]] = ends[i]; + } + } + + // Follow the pairings into chains, each seeded by the earliest unvisited segment and keeping its direction + let mut visited = vec![false; segment_count]; + let mut order: Vec<(usize, bool)> = Vec::with_capacity(segment_count); + let mut begins_path = Vec::with_capacity(segment_count); + for seed in 0..segment_count { + if std::mem::replace(&mut visited[seed], true) { + continue; + } + + let mut chain = vec![(seed, false)]; + let mut closed = false; + let mut end = seed * 2 + 1; + loop { + let next = partner[end]; + if next == usize::MAX { + break; + } + let segment = next / 2; + if segment == seed { + closed = true; + break; + } + if std::mem::replace(&mut visited[segment], true) { + break; + } + + // Entering at the segment's arriving end crosses it backwards + let reversed = next % 2 == 1; + chain.push((segment, reversed)); + end = if reversed { segment * 2 } else { segment * 2 + 1 }; + } + + // An open chain also grows backwards from the seed's start, which is then where it begins + let mut before = Vec::new(); + let mut end = seed * 2; + if !closed { + loop { + let next = partner[end]; + if next == usize::MAX { + break; + } + let segment = next / 2; + if std::mem::replace(&mut visited[segment], true) { + break; + } + + // Joining at the segment's arriving end means it runs forward into the chain + let reversed = next % 2 == 0; + before.push((segment, reversed)); + end = if reversed { segment * 2 + 1 } else { segment * 2 }; + } + } + before.reverse(); + + begins_path.extend((0..before.len() + chain.len()).map(|position| position == 0)); + order.append(&mut before); + order.append(&mut chain); + } + + // Rebuild the segment arrays in chain order, turning around the segments that run against their chain + let mut reversed_ids = FxHashSet::default(); + let (mut ids, mut starts, mut ends, mut handles) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for &(segment, reversed) in &order { + ids.push(self.segment_ids[segment]); + let (start, end) = (self.segment_start[segment], self.segment_end[segment]); + if reversed { + reversed_ids.insert(self.segment_ids[segment]); + starts.push(end); + ends.push(start); + handles.push(self.segment_handles[segment].reversed()); + } else { + starts.push(start); + ends.push(end); + handles.push(self.segment_handles[segment]); + } + } + self.segment_ids = ids; + self.segment_start = starts; + self.segment_end = ends; + self.segment_handles = handles; + self.segment_begins_path = begins_path; + + // A turned segment's handles swap sides, so the G1 pairs naming them follow + for handle in self.colinear.iter_mut().flatten() { + if reversed_ids.contains(&handle.segment) { + handle.ty = match handle.ty { + HandleType::Primary => HandleType::End, + HandleType::End => HandleType::Primary, + }; + } + } + } } // TODO: Eventually remove this document upgrade code -/// Builds storage from the legacy flat arrays: anchors with IDs and positions, segments with IDs, -/// endpoint indices, and absolute handles, plus G1 pairs. Used by document migration. +/// Builds storage from the legacy flat arrays: anchors with IDs and positions, segments with IDs, endpoint indices, +/// and absolute handles, plus G1 pairs. Legacy segments carry no path structure, so they are chained by the straightest +/// route through each junction before weaving. Used by document migration. pub fn vector_from_legacy_parts( point_ids: Vec, point_positions: Vec, @@ -154,15 +327,17 @@ pub fn vector_from_legacy_parts( segment_handles: Vec, colinear: Vec<[HandleId; 2]>, ) -> (Vector, List) { - let working = WorkingVector { + let mut working = WorkingVector { point_ids, point_positions, segment_ids, segment_start, segment_end, segment_handles, + segment_begins_path: Vec::new(), colinear, }; + working.chain_by_straightest_route(); let (mut vector, mut paths) = (Vector::default(), List::new()); working.reweave(&mut vector, &mut paths); @@ -173,7 +348,7 @@ pub fn vector_from_legacy_parts( #[cfg(test)] mod tests { use super::*; - use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, Item}; + use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_SMOOTH, Item}; fn working(points: usize, segments: &[(usize, usize, BezierHandles)]) -> WorkingVector { WorkingVector { @@ -183,10 +358,18 @@ mod tests { segment_start: segments.iter().map(|&(start, ..)| start).collect(), segment_end: segments.iter().map(|&(_, end, _)| end).collect(), segment_handles: segments.iter().map(|(.., handles)| *handles).collect(), + segment_begins_path: Vec::new(), colinear: Vec::new(), } } + fn working_at(positions: &[DVec2], segments: &[(usize, usize, BezierHandles)]) -> WorkingVector { + let mut working = working(positions.len(), segments); + working.point_positions = positions.to_vec(); + + working + } + fn woven(working: WorkingVector) -> (Vector, List) { let (mut vector, mut paths) = (Vector::default(), List::new()); working.reweave(&mut vector, &mut paths); @@ -341,6 +524,118 @@ mod tests { assert_eq!(references(&paths, 0), [0, 1, 2]); } + // Flattened paths welded head to tail stay apart when rewoven, since a path boundary is data of its own + #[test] + fn reweave_keeps_flattened_paths_apart() { + let mut vector = Vector::default(); + for index in 0..4 { + vector.0.push(Item::new_from_element(DVec2::new(index as f64, 0.)).with_attribute(ATTR_ID, PointId::generate())); + } + let mut paths = List::new(); + push_path(&mut paths, CurveType::Linear, [0, 1, 2], [SegmentId::generate(), SegmentId::generate()]); + push_path(&mut paths, CurveType::Linear, [2, 3], [SegmentId::generate()]); + + let working = WorkingVector::flatten(&vector, &paths); + assert_eq!(working.segment_begins_path, vec![true, false, true]); + + let (mut rewoven, mut rewoven_paths) = (Vector::default(), List::new()); + working.reweave(&mut rewoven, &mut rewoven_paths); + assert_eq!(rewoven_paths.len(), 2); + assert_eq!(references(&rewoven_paths, 0), [0, 1, 2]); + assert_eq!(references(&rewoven_paths, 1), [2, 3]); + } + + // The bar of a T keeps going through the junction, being the straightest route, and the stem starts its own path + #[test] + fn straightest_route_continues_through_a_junction() { + let positions = [DVec2::new(0., 0.), DVec2::new(1., 0.), DVec2::new(2., 0.), DVec2::new(1., 1.)]; + let soup = [(1, 3, BezierHandles::Linear), (0, 1, BezierHandles::Linear), (1, 2, BezierHandles::Linear)]; + let mut working = working_at(&positions, &soup); + + working.chain_by_straightest_route(); + assert_eq!(working.segment_begins_path, vec![true, true, false]); + + let (_, paths) = woven(working); + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), [1, 3]); + assert_eq!(references(&paths, 1), [0, 1, 2]); + } + + // A curve whose end handle is retracted onto the junction arrives along its other handle, so it carries on downward rather than along its chord + #[test] + fn straightest_route_reads_a_retracted_handle_from_the_other_one() { + let positions = [DVec2::new(-10., 0.), DVec2::ZERO, DVec2::new(0., -10.), DVec2::new(10., 0.)]; + let curve = BezierHandles::Cubic { + handle_start: DVec2::new(0., 10.), + handle_end: DVec2::ZERO, + }; + let soup = [(0, 1, curve), (1, 3, BezierHandles::Linear), (1, 2, BezierHandles::Linear)]; + let mut working = working_at(&positions, &soup); + let ids = working.segment_ids.clone(); + + working.chain_by_straightest_route(); + assert_eq!(working.segment_ids, vec![ids[0], ids[2], ids[1]]); + assert_eq!(working.segment_begins_path, vec![true, false, true]); + } + + // Four segments all drawn into one crossing pair off into two straight lines, turning around the ones drawn the other way + #[test] + fn crossing_lines_each_stay_whole() { + let positions = [DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., -1.), DVec2::new(0., 1.), DVec2::ZERO]; + let soup = [ + (0, 4, BezierHandles::Linear), + (2, 4, BezierHandles::Linear), + (1, 4, BezierHandles::Linear), + (3, 4, BezierHandles::Linear), + ]; + let mut working = working_at(&positions, &soup); + let ids = working.segment_ids.clone(); + + working.chain_by_straightest_route(); + assert_eq!(working.segment_ids, vec![ids[0], ids[2], ids[1], ids[3]]); + assert_eq!(working.segment_start, vec![0, 4, 2, 4]); + assert_eq!(working.segment_end, vec![4, 1, 4, 3]); + + let (_, paths) = woven(working); + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), [0, 4, 1]); + assert_eq!(references(&paths, 1), [2, 4, 3]); + } + + // A G1 pair follows its segment when that segment is turned around, so the shared anchor still comes out smooth + #[test] + fn a_turned_segment_keeps_its_smooth_pair() { + let cubic = |from: DVec2, to: DVec2| BezierHandles::Cubic { + handle_start: from + DVec2::new(1., 0.), + handle_end: to - DVec2::new(1., 0.), + }; + let positions = [DVec2::new(0., 0.), DVec2::new(3., 0.), DVec2::new(6., 0.)]; + let ids = [SegmentId::generate(), SegmentId::generate()]; + + // The second segment runs back toward the shared anchor, so both handles facing it, one on each side, are stored as end handles + let (_, paths) = vector_from_legacy_parts( + (0..3).map(|_| PointId::generate()).collect(), + positions.to_vec(), + ids.to_vec(), + vec![0, 2], + vec![1, 1], + vec![ + cubic(positions[0], positions[1]), + BezierHandles::Cubic { + handle_start: positions[2] - DVec2::X, + handle_end: positions[1] + DVec2::X, + }, + ], + vec![[HandleId::end(ids[0]), HandleId::end(ids[1])]], + ); + + assert_eq!(paths.len(), 1); + assert_eq!(curve_type_at(&paths, 0), CurveType::Cubic); + assert_eq!(references(&paths, 0), [0, 3, 4, 1, 5, 6, 2]); + let path = paths.element(0).expect("the chain became one path"); + assert_eq!(path.0.attribute::(ATTR_SMOOTH, 3), Some(&true)); + } + // Gathering runs stays invisible to the bridge: the same segments come back in the same order #[test] fn reweave_round_trips_through_flatten() { diff --git a/node-graph/libraries/vector-types/src/vector/path.rs b/node-graph/libraries/vector-types/src/vector/path.rs index 3e55529aec..328d3c950a 100644 --- a/node-graph/libraries/vector-types/src/vector/path.rs +++ b/node-graph/libraries/vector-types/src/vector/path.rs @@ -108,23 +108,29 @@ impl Path { piece } - /// Reverses the path in place, so the weave walks its references in the opposite direction. + /// Reverses the given spans where they sit, so contours cross them in the opposite direction. /// Per-reference attributes travel with their references, and each span's ID moves to the anchor it now departs from. - pub fn reverse(&mut self, curve_type: CurveType) { + pub fn reverse_spans(&mut self, curve_type: CurveType, spans: std::ops::Range) { let stride = curve_type.stride(); - let count = self.segment_count(curve_type); - let ids: Vec> = (0..count).map(|span| self.0.attribute::(ATTR_ID, span * stride).copied()).collect(); - - self.0 = (0..self.0.len()).rev().filter_map(|index| self.0.clone_item(index)).collect(); - - // Span k of the reversed path walks old span (count - 1 - k) backwards, so it takes over that span's ID - for span in 0..count { - if let Some(id) = ids[count - 1 - span] { - self.0.set_attribute(ATTR_ID, span * stride, id); - } + let spans = spans.start..spans.end.min(self.segment_count(curve_type)); + if spans.is_empty() { + return; } - if count > 0 && self.0.attribute::(ATTR_ID, count * stride).is_some() { - self.0.set_attribute(ATTR_ID, count * stride, SegmentId::default()); + let (first, last) = (spans.start * stride, spans.end * stride); + + // The cell on the last anchor belongs to whichever span follows these, so it stays where it is + let id_at = |path: &Self, index: usize| path.0.attribute::(ATTR_ID, index).copied(); + let ids: Vec> = spans.clone().map(|span| id_at(self, span * stride)).collect(); + let following_id = id_at(self, last); + + let mirrored = |index: usize| if (first..=last).contains(&index) { first + last - index } else { index }; + self.0 = (0..self.0.len()).filter_map(|index| self.0.clone_item(mirrored(index))).collect(); + + // Each reversed span walks the old span mirrored across the range backwards, so it takes over that span's ID + for (place, id) in ids.into_iter().rev().chain([following_id]).enumerate() { + if let Some(id) = id { + self.0.set_attribute(ATTR_ID, first + place * stride, id); + } } } } @@ -376,6 +382,33 @@ mod tests { ); } + // Turning around the middle of a path keeps every span's ID on the anchor it sets out from + #[test] + fn reversing_spans_where_they_sit() { + let mut lasso = path(&[0, 1, 2, 3, 4, 1, 5]); + let mut segment_id = SegmentId::ZERO; + let ids: Vec = (0..6).map(|_| segment_id.next_id()).collect(); + for (span, &id) in ids.iter().enumerate() { + lasso.0.set_attribute(ATTR_ID, span, id); + } + + lasso.reverse_spans(CurveType::Linear, 1..5); + + assert_eq!(lasso.0.iter_element_values().copied().collect::>(), vec![0, 1, 4, 3, 2, 1, 5]); + let span_ids: Vec = (0..6).map(|span| lasso.0.attribute_cloned_or_default(ATTR_ID, span)).collect(); + assert_eq!(span_ids, [ids[0], ids[4], ids[3], ids[2], ids[1], ids[5]]); + } + + // A partial segment trailing a path is left where it is, so anchors and handles keep their roles + #[test] + fn reversing_leaves_a_partial_tail_in_place() { + let mut ragged = path(&[4, 10, 11, 0, 12, 13, 2, 14]); + + ragged.reverse_spans(CurveType::Cubic, 0..2); + + assert_eq!(ragged.0.iter_element_values().copied().collect::>(), vec![2, 13, 12, 0, 11, 10, 4, 14]); + } + // A reference naming a point the pool does not have drops its segment instead of panicking #[test] fn dangling_reference_skips_its_segment() { diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index 1450a6ece5..b4b8adf545 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -1,5 +1,5 @@ use crate::vector::addressing::{self, Span}; -use crate::vector::contour::subpaths; +use crate::vector::contour::contours; use crate::vector::misc::{ManipulatorGroup, Tangent, point_to_dvec2, segment_to_handles}; use crate::vector::path::{CurveType, Path, append_segment, curve_type_at}; use crate::vector::vector_types::Vector; @@ -746,7 +746,7 @@ impl Vector { /// Construct and return an iterator of `(Vec, bool)` for each stroke. /// The boolean in the tuple indicates if the path is closed. - /// The groups pair index-for-index with the contours emission, both walking the same subpaths. + /// The groups pair index-for-index with the contours emission, both stitching the same contours. pub fn stroke_manipulator_groups(&self, paths: &List) -> impl Iterator, bool)> { let mut groups = Vec::new(); @@ -754,50 +754,53 @@ impl Vector { let ids = self.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); let id_at = |point: u32| ids.get(point as usize).copied().unwrap_or_default(); - for subpath in subpaths(self.point_count(), paths) { + for contour in contours(self.point_count(), paths) { let mut manipulators_list: Vec = Vec::new(); let mut in_handle: Option = None; - for step in &subpath.steps { - let Some(path) = paths.element(step.path as usize) else { continue }; - let Some(&curve_type) = curve_types.get(step.path as usize) else { continue }; - let Some(segment) = path.segment(&self.0, curve_type, step.span as usize) else { continue }; + for part in &contour.parts { + let Some(path) = paths.element(part.path as usize) else { continue }; + let Some(&curve_type) = curve_types.get(part.path as usize) else { continue }; + let (stride, count) = (curve_type.stride(), path.segment_count(curve_type)); - let first = step.span as usize * curve_type.stride(); - let (Some(start), Some(end)) = (path.reference(first), path.reference(first + curve_type.stride())) else { - continue; - }; + for step in 0..count { + let span = if part.reversed { count - 1 - step } else { step }; + let Some(segment) = path.segment(&self.0, curve_type, span) else { continue }; + let (Some(start), Some(end)) = (path.reference(span * stride), path.reference(span * stride + stride)) else { + continue; + }; - // A quadratic's one handle leaves its anchor whichever way the span is crossed - let handles = segment_to_handles(&segment); - let handles = if step.reversed { handles.reversed() } else { handles }; - let anchor = if step.reversed { end } else { start }; + // A quadratic's one handle leaves its anchor whichever way the span is crossed + let handles = segment_to_handles(&segment); + let handles = if part.reversed { handles.reversed() } else { handles }; + let anchor = if part.reversed { end } else { start }; - manipulators_list.push(ManipulatorGroup { - anchor: point_to_dvec2(if step.reversed { segment.end() } else { segment.start() }), - in_handle, - out_handle: handles.start(), - id: id_at(anchor), - }); + manipulators_list.push(ManipulatorGroup { + anchor: point_to_dvec2(if part.reversed { segment.end() } else { segment.start() }), + in_handle, + out_handle: handles.start(), + id: id_at(anchor), + }); - in_handle = handles.end(); + in_handle = handles.end(); + } } - if subpath.closed { + if contour.closed { if let Some(first) = manipulators_list.first_mut() { first.in_handle = in_handle; } - } else if let Some(position) = self.position(subpath.exit as usize) { + } else if let Some(position) = self.position(contour.exit as usize) { manipulators_list.push(ManipulatorGroup { anchor: position, in_handle, out_handle: None, - id: id_at(subpath.exit), + id: id_at(contour.exit), }); } if !manipulators_list.is_empty() { - groups.push((manipulators_list, subpath.closed)); + groups.push((manipulators_list, contour.closed)); } } @@ -916,41 +919,69 @@ impl Vector { } } -/// Reweaves the paths with the given `(path, span)` pairs reversed. Each reversed span keeps its place in span -/// order, which decides how subpaths are walked, so it becomes a path of its own among the pieces left around it. +/// Reweaves the paths with the given `(path, span)` pairs reversed. Reversed spans that run on from one into the next, within +/// a path or across consecutive paths, reverse together as one stretch, so a flipped loop with its pieces stored together is +/// still read from the same anchor. fn reverse_spans_in_place(paths: &List, reversed: &HashSet<(u32, u32)>) -> List { let mut rewoven = List::new(); - for path_index in 0..paths.len() { - let Some(template) = paths.clone_item(path_index) else { continue }; - let curve_type = curve_type_at(paths, path_index); - let span_count = template.element().segment_count(curve_type); - let is_reversed = |span: usize| reversed.contains(&(path_index as u32, span as u32)); + // Reversed pieces of the stretch being gathered, output in the opposite order once it ends + let mut stretch: Vec> = Vec::new(); + let mut stretch_end = None; - if !(0..span_count).any(is_reversed) { + for path_index in 0..paths.len() { + let Some(mut template) = paths.clone_item(path_index) else { continue }; + let curve_type = curve_type_at(paths, path_index); + let stride = curve_type.stride(); + let span_count = template.element().segment_count(curve_type); + let mut flips: Vec = (0..span_count).map(|span| reversed.contains(&(path_index as u32, span as u32))).collect(); + let run_end = |flips: &[bool], start: usize| (start + 1..span_count).find(|&span| flips[span] != flips[start]).unwrap_or(span_count); + + // A reversed run arriving back at the anchor it leaves from turns around where it sits, which keeps the path whole + let mut start = 0; + while start < span_count { + let end = run_end(&flips, start); + let references = &template.element().0; + if flips[start] && references.element(start * stride) == references.element(end * stride) { + template.element_mut().reverse_spans(curve_type, start..end); + flips[start..end].fill(false); + } + start = end; + } + + if !flips.contains(&true) { + rewoven.extend(stretch.drain(..).rev().collect()); rewoven.push(template); continue; } + // Cut the path into pieces wherever it changes between kept and reversed spans let path = template.element(); - let mut push_piece = |piece: Path| rewoven.push(Item::from_parts(piece, template.attributes().clone())); + let mut start = 0; + while start < span_count { + let end = run_end(&flips, start); - let mut kept_from = 0; - for span in (0..span_count).filter(|&span| is_reversed(span)) { - if kept_from < span { - push_piece(path.clone_span_range(curve_type, kept_from, span)); + let mut piece = Item::from_parts(path.clone_span_range(curve_type, start, end), template.attributes().clone()); + let references = &piece.element().0; + let (first, last) = (references.element(0).copied(), references.element(references.len().saturating_sub(1)).copied()); + + // A reversed piece joins the stretch only by setting out from where the stretch has reached + if !flips[start] || stretch_end != first { + rewoven.extend(stretch.drain(..).rev().collect()); } - let mut flipped = path.clone_span_range(curve_type, span, span + 1); - flipped.reverse(curve_type); - push_piece(flipped); + if flips[start] { + piece.element_mut().reverse_spans(curve_type, 0..end - start); + stretch.push(piece); + stretch_end = last; + } else { + rewoven.push(piece); + } - kept_from = span + 1; - } - if kept_from < span_count { - push_piece(path.clone_span_range(curve_type, kept_from, span_count)); + start = end; } } + rewoven.extend(stretch.drain(..).rev().collect()); rewoven } @@ -959,7 +990,7 @@ fn reverse_spans_in_place(paths: &List, reversed: &HashSet<(u32, u32)>) -> mod tests { use super::*; use crate::vector::path::CurveType; - use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, Item}; + use core_types::list::ATTR_CURVE_TYPE; use kurbo::Shape; fn build_vector(points: &[DVec2], segments: &[(usize, usize)]) -> (Vector, List) { @@ -981,12 +1012,11 @@ mod tests { (vector, paths) } - // A morph pairs manipulators by position, so a loop's walk is fixed: from its lowest anchor, along the earliest span there + // A morph pairs manipulators by position, so a loop is read from the anchor it is stored from, in its stored direction #[test] - fn a_closed_loop_walks_from_its_lowest_anchor_along_its_earliest_span() { + fn a_closed_loop_keeps_its_stored_start_and_direction() { let (vector, mut paths) = build_vector(&[DVec2::new(0., 10.), DVec2::new(0., 0.), DVec2::new(10., 0.)], &[]); - // The loop weaves 1 to 2 to 0 and back, so the earliest span at anchor 0 arrives there and is crossed backwards let mut path = Path::from_references([1, 2, 0, 1]); let mut segment_id = SegmentId::ZERO; for span in 0..3 { @@ -994,20 +1024,20 @@ mod tests { } paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); - let (manipulators, closed) = vector.stroke_manipulator_groups(&paths).next().expect("the loop is one subpath"); + let (manipulators, closed) = vector.stroke_manipulator_groups(&paths).next().expect("the loop is one contour"); assert!(closed); let anchors: Vec = manipulators.iter().map(|manipulator| manipulator.anchor).collect(); - assert_eq!(anchors, vec![DVec2::new(0., 10.), DVec2::new(10., 0.), DVec2::new(0., 0.)]); + assert_eq!(anchors, vec![DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(0., 10.)]); } - /// Manipulator groups and contours are two views of the same walk, so they must agree on order and + /// Manipulator groups and contours are two views of the same stitching, so they must agree on order and /// geometry. Click targets, the snapper's point recovery, and outline stitching all rely on it. #[test] fn manipulator_groups_and_contours_agree() { use crate::vector::misc::bezpath_from_manipulator_groups; use crate::vector::path::pool_and_paths_from_bezpath; - // A closed contour woven before an open one, so path order alone would emit them the other way around + // A closed contour woven before an open one, which is the order both views keep let mut source = kurbo::BezPath::new(); source.move_to((0., 0.)); source.line_to((10., 0.)); @@ -1025,19 +1055,19 @@ mod tests { assert_eq!(groups.len(), 2); assert_eq!(contours.len(), 2); - // Open runs lead, and each group re-emits its own contour - assert!(!groups[0].1, "the open run should be emitted first"); - assert!(groups[1].1, "the closed loop should follow"); + // Each group re-emits its own contour, in stored order + assert!(groups[0].1, "the closed loop should be emitted first"); + assert!(!groups[1].1, "the open run should follow"); for (index, (manipulators, closed)) in groups.iter().enumerate() { let rebuilt = bezpath_from_manipulator_groups(manipulators, *closed); assert_eq!(rebuilt.elements(), contours[index].elements(), "group {index} should describe contour {index}"); } } - /// Two paths welded head to head, so the subpath must walk the second one backward and still + /// Two paths welded head to head, so the contour must cross the second one backward and still /// emit anchors and geometry in travel order. #[test] - fn subpath_walks_a_welded_path_backward() { + fn contour_crosses_a_welded_path_backward() { use crate::vector::misc::bezpath_from_manipulator_groups; let points = [DVec2::new(0., 0.), DVec2::new(10., 0.), DVec2::new(20., 0.)]; @@ -1275,8 +1305,7 @@ mod tests { assert!(faces.is_empty(), "a reverse-wound loop with an interior spur should produce no filled faces"); } - /// Shoelace sum over the drawn direction of a range of line segments, so tests can read the - /// stored winding directly rather than through a path walker that may pick its own direction. + /// Shoelace sum over the stored direction of a range of line segments, so tests read each segment's winding as stored. fn drawn_signed_area(vector: &Vector, paths: &List, segment_range: std::ops::Range) -> f64 { let graph = SegmentGraph::new(vector, paths); segment_range @@ -1299,6 +1328,54 @@ mod tests { assert!(drawn_signed_area(&vector, &paths, 0..4) > 0., "a lone loop should wind positively after normalization"); } + fn references(paths: &List) -> Vec> { + paths.iter_element_values().map(|path| path.references().collect()).collect() + } + + fn span_ids(paths: &List, path_index: usize, span_count: usize) -> Vec { + let path = paths.element(path_index).unwrap(); + (0..span_count).map(|span| path.0.attribute_cloned_or_default(ATTR_ID, span)).collect() + } + + // A morph or a dash pattern reads a loop from where it is stored, so flipping it must not move that anchor + #[test] + fn normalization_flips_a_closed_path_from_the_same_start() { + let points = [DVec2::new(0., 0.), DVec2::new(0., 10.), DVec2::new(10., 10.), DVec2::new(10., 0.)]; + let (mut vector, mut paths) = build_vector(&points, &[]); + + let mut path = Path::from_references([0, 1, 2, 3, 0]); + let mut segment_id = SegmentId::ZERO; + let ids: Vec = (0..4).map(|_| segment_id.next_id()).collect(); + for (span, &id) in ids.iter().enumerate() { + path.0.set_attribute(ATTR_ID, span, id); + } + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + + vector.normalize_winding_directions(&mut paths); + + assert_eq!(references(&paths), vec![vec![0, 3, 2, 1, 0]]); + assert_eq!(span_ids(&paths, 0, 4), ids.iter().rev().copied().collect::>(), "each span keeps its ID"); + } + + #[test] + fn normalization_flips_a_loop_of_several_paths_from_the_same_start() { + let points = [DVec2::new(0., 0.), DVec2::new(0., 10.), DVec2::new(10., 10.), DVec2::new(10., 0.)]; + let (mut vector, mut paths) = build_vector(&points, &[]); + + for references in [[0, 1, 2], [2, 3, 0]] { + let path = Path::from_references(references); + paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + } + + vector.normalize_winding_directions(&mut paths); + + assert_eq!(references(&paths), vec![vec![0, 3, 2], vec![2, 1, 0]]); + let contours = contours(vector.0.len(), &paths); + assert_eq!(contours.len(), 1); + assert!(contours[0].closed); + assert_eq!(contours[0].entry, 0); + } + #[test] fn normalization_gives_nested_loops_alternating_winding() { let points = [ @@ -1351,9 +1428,9 @@ mod tests { assert_eq!((graph.start_point[spur], graph.end_point[spur]), (0, 4), "the spur should keep its drawn direction"); } - /// A loop covering only the middle spans of one longer path splits that path so just the loop reverses. + /// A loop covering only the middle spans of one longer path reverses where it sits, leaving the path whole. #[test] - fn normalization_splits_a_path_to_flip_its_inner_loop() { + fn normalization_flips_a_loop_inside_a_longer_path() { let points = [ DVec2::new(-5., 0.), DVec2::new(0., 0.), @@ -1391,5 +1468,6 @@ mod tests { .sum::() / 2.; assert!(loop_area > 0., "the inner loop should wind positively after normalization"); + assert_eq!(references(&paths), vec![vec![0, 1, 4, 3, 2, 1, 5]], "the path stays whole around its flipped loop"); } } diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index c9c8dc80cb..fe8ce4f27e 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -209,6 +209,7 @@ impl SegmentModification { let keep: Vec = (0..working.segment_ids.len()) .map(|index| !self.remove.contains(&working.segment_ids[index]) && working.segment_start[index] < point_count && working.segment_end[index] < point_count) .collect(); + working.carry_path_beginnings(&keep); let mut keep_iter = keep.iter(); working.segment_start.retain(|_| *keep_iter.next().unwrap_or(&false)); let mut keep_iter = keep.iter(); @@ -217,6 +218,8 @@ impl SegmentModification { working.segment_handles.retain(|_| *keep_iter.next().unwrap_or(&false)); let mut keep_iter = keep.iter(); working.segment_ids.retain(|_| *keep_iter.next().unwrap_or(&false)); + let mut keep_iter = keep.iter(); + working.segment_begins_path.retain(|_| *keep_iter.next().unwrap_or(&false)); // The points no longer change here, so one index serves every endpoint lookup below. // Nothing looks an endpoint up in the common pure-handle case, so it skips the build. @@ -926,7 +929,7 @@ mod tests { vector.position(vector.index_of_point_id(id).unwrap() as usize).unwrap() } - /// What the tests compare of a modification's result: anchors by ID, segments by ID, the stroke walk, and G1 pairs. + /// What the tests compare of a modification's result: anchors by ID, segments by ID, the stroke contours, and G1 pairs. fn describe(vector: &Vector, paths: &List) -> String { let mut anchors: Vec = vector .anchor_points(paths) @@ -1169,6 +1172,28 @@ mod tests { assert_eq!(in_place_paths, paths, "moving points leaves the weave untouched"); } + // Removing the segment a path begins with leaves the rest of that path beginning one of its own, rather than joining the path it touches + #[test] + fn a_path_keeps_its_start_when_its_first_segment_is_removed() { + use crate::vector::path::push_path; + use core_types::list::Item; + + let mut vector = Vector::default(); + for position in [(0., 0.), (10., 0.), (20., 0.), (20., 10.), (30., 0.)] { + vector.0.push(Item::new_from_element(DVec2::from(position)).with_attribute(ATTR_ID, PointId::generate())); + } + let mut paths = List::new(); + let removed = SegmentId::generate(); + push_path(&mut paths, CurveType::Linear, [0, 1, 2], [SegmentId::generate(), SegmentId::generate()]); + push_path(&mut paths, CurveType::Linear, [3, 2, 4], [removed, SegmentId::generate()]); + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::RemoveSegment { id: removed }); + modification.apply(&mut vector, &mut paths); + + assert_eq!(paths.len(), 2, "the remainder of the second path stays a path of its own"); + } + // Re-adding a segment or point under an ID the geometry already holds adds no second copy under that ID #[test] fn duplicate_adds_are_skipped() { diff --git a/node-graph/libraries/vector-types/src/vector/vector_types.rs b/node-graph/libraries/vector-types/src/vector/vector_types.rs index 05508d8056..64dacb7f5b 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_types.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_types.rs @@ -1,6 +1,6 @@ use super::addressing; use super::connectivity::Connectivity; -use super::contour::{contours, subpaths}; +use super::contour::{contour_bezpaths, contours}; use super::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; use super::path::{CurveType, Path, curve_type_at, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path, weave_bezpath}; use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin}; @@ -225,9 +225,9 @@ impl Vector { } } - /// Emits the assembled contours, one bezpath per subpath walked. + /// Emits the stitched contours, one bezpath each, in the order the paths are stored. pub fn stroke_bezpath_iter(&self, paths: &List) -> impl Iterator { - contours(&self.0, paths).into_iter() + contour_bezpaths(&self.0, paths).into_iter() } } @@ -677,20 +677,55 @@ impl Vector { push_path(paths, curve_type, references, [id]); } - /// Welds every open subpath shut with a linear segment from its first point to its last. + /// Welds every open contour shut with a linear segment from its last point back to its first, stored where the contour runs on into it. pub fn close_subpaths(&mut self, paths: &mut List) { - let closures: Vec<_> = subpaths(self.point_count(), paths) + // A closing segment sits after the contour's last stored path, or before it when the contour crosses that path + // backward, since that is the neighbor the contour reads on into. Either way it is read from the contour's exit. + let closings: Vec<(usize, bool, [u32; 2])> = contours(self.point_count(), paths) .into_iter() - .filter(|subpath| !subpath.closed) - .map(|subpath| (subpath.entry, subpath.exit)) + .filter(|contour| !contour.closed) + .filter_map(|contour| { + let last = contour.parts.last()?; + Some(if last.reversed { + (last.path as usize, true, [contour.entry, contour.exit]) + } else { + (last.path as usize + 1, false, [contour.exit, contour.entry]) + }) + }) .collect(); - - for (entry, exit) in closures { - let mut base = next_segment_id(paths); - let id = base.next_id(); - - push_path(paths, CurveType::Linear, [entry, exit], [id]); + if closings.is_empty() { + return; } + + // Each closing segment's ID skips one after the previous, as the IDs of a newly appended bezpath do + let mut base = next_segment_id(paths); + let mut closing_paths = Vec::with_capacity(closings.len()); + for (before, backward, references) in closings { + let id = base.next_id(); + base.next_id(); + + let mut single = List::new(); + push_path(&mut single, CurveType::Linear, references, [id]); + closing_paths.extend(single.into_iter().map(|path| (before, backward, path))); + } + + // Two closing segments can share a place between two stored paths, where the one read on from the path before goes first + closing_paths.sort_by_key(|&(before, backward, _)| (before, backward)); + + // Rebuild the paths with each closing segment in its place, keeping every other path in its stored order + let mut closing_paths = closing_paths.into_iter().peekable(); + let mut rebuilt = List::new(); + for (index, path) in std::mem::take(paths).into_iter().enumerate() { + while let Some((_, _, closing)) = closing_paths.next_if(|&(before, ..)| before == index) { + rebuilt.push(closing); + } + rebuilt.push(path); + } + for (_, _, closing) in closing_paths { + rebuilt.push(closing); + } + + *paths = rebuilt; } /// Appends another vector's points and paths, remapping IDs that collide with this vector's. @@ -986,4 +1021,71 @@ mod tests { vector.close_subpaths(&mut paths); assert_eq!(paths.len(), 2); } + + // A crossbar between two junctions closes in one pass like the uprights it joins, and closing again adds nothing + #[test] + fn close_subpaths_closes_a_path_between_two_junctions() { + let mut vector = Vector::default(); + for position in [(0., 0.), (0., 5.), (0., 10.), (10., 0.), (10., 5.), (10., 10.)] { + vector.0.push(Item::new_from_element(DVec2::from(position))); + } + + // Two uprights joined by a crossbar at their midpoints, like an H + let mut paths = List::new(); + for references in [vec![0, 1, 2], vec![3, 4, 5], vec![1, 4]] { + push_path(&mut paths, CurveType::Linear, references, []); + } + + vector.close_subpaths(&mut paths); + let contours: Vec<_> = vector.stroke_bezpath_iter(&paths).collect(); + assert_eq!(contours.len(), 3); + assert!(contours.iter().all(|contour| matches!(contour.elements().last(), Some(PathEl::ClosePath)))); + + vector.close_subpaths(&mut paths); + assert_eq!(paths.len(), 6); + } + + // Two contours whose closing segments belong in the same place between two stored paths both close in one pass + #[test] + fn close_subpaths_closes_contours_meeting_between_the_same_paths() { + let mut vector = Vector::default(); + for position in [(0., 0.), (10., 0.), (10., 10.), (20., 0.), (30., 0.), (30., 10.)] { + vector.0.push(Item::new_from_element(DVec2::from(position))); + } + + // The first contour runs along path 0, then backward along path 3, so its closing segment goes before path 3. + // The second runs along paths 1 and 2, so its closing segment goes after path 2, the same place. + let mut paths = List::new(); + for references in [vec![0, 1], vec![3, 4], vec![4, 5], vec![2, 1]] { + push_path(&mut paths, CurveType::Linear, references, []); + } + + vector.close_subpaths(&mut paths); + let contours: Vec<_> = vector.stroke_bezpath_iter(&paths).collect(); + assert_eq!(contours.len(), 2); + assert!(contours.iter().all(|contour| matches!(contour.elements().last(), Some(PathEl::ClosePath)))); + + vector.close_subpaths(&mut paths); + assert_eq!(paths.len(), 6); + } + + // Paths ending at a junction close too, and closing them again adds nothing + #[test] + fn close_subpaths_closes_paths_ending_at_a_junction() { + let mut vector = Vector::default(); + for index in 0..5 { + vector.0.push(Item::new_from_element(DVec2::new(index as f64, (index * index) as f64))); + } + let mut paths = List::new(); + for references in [vec![0, 1, 2], vec![3, 2], vec![4, 2]] { + push_path(&mut paths, CurveType::Linear, references, []); + } + + vector.close_subpaths(&mut paths); + assert_eq!(paths.len(), 6); + assert!(vector.stroke_bezpath_iter(&paths).all(|contour| matches!(contour.elements().last(), Some(PathEl::ClosePath)))); + + vector.close_subpaths(&mut paths); + assert_eq!(paths.len(), 6); + } } diff --git a/node-graph/nodes/vector/src/vector_modification_nodes.rs b/node-graph/nodes/vector/src/vector_modification_nodes.rs index 8c201ca64c..f902f9fec8 100644 --- a/node-graph/nodes/vector/src/vector_modification_nodes.rs +++ b/node-graph/nodes/vector/src/vector_modification_nodes.rs @@ -15,9 +15,11 @@ async fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item(_ctx: impl Ctx, content } + +#[cfg(test)] +mod tests { + use super::*; + use vector_types::vector::paths_from_item_attributes; + + // A lone loop fills by its contour alone, so it keeps the direction it was drawn in even when that winds backwards + #[tokio::test] + async fn a_drawn_loop_keeps_its_direction() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((0., 10.)); + bezpath.line_to((10., 10.)); + bezpath.line_to((10., 0.)); + bezpath.close_path(); + let drawn = Vector::item_from_bezpath(&bezpath); + + let modified = path_modify((), drawn.clone(), Item::default(), Item::default()).await; + + assert_eq!(paths_from_item_attributes(&modified), paths_from_item_attributes(&drawn)); + } +} diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index 6a26f286ed..033a63a51d 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -829,6 +829,8 @@ pub mod extrude_algorithms { let mut next_point = next_working_point_id(working); let mut next_segment = next_working_segment_id(working); + // Each segment's pieces take its place in order, so the path it belongs to stays whole and still begins where it did + let mut pieces = WorkingVector::default(); for segment_index in 0..segment_count { let start = working.point_positions[working.segment_start[segment_index]]; let end = working.point_positions[working.segment_end[segment_index]]; @@ -836,6 +838,8 @@ pub mod extrude_algorithms { let mut start_index = working.segment_start[segment_index]; let pathseg = segment.to_cubic(); let mut start_t = 0.; + let mut remaining_handles = working.segment_handles[segment_index]; + let mut begins_path = working.segment_begins_path.get(segment_index).copied().unwrap_or(false); for split_t in find_splits(pathseg, direction) { let [first, second] = [pathseg.subsegment(start_t..split_t), pathseg.subsegment(split_t..1.)]; @@ -844,14 +848,24 @@ pub mod extrude_algorithms { let start_segment = next_segment.next_id(); let middle_point_index = push_working_point(working, middle_point, DVec2::new(first.end().x, first.end().y)); - push_working_segment(working, start_segment, start_index, middle_point_index, first_handles); - working.segment_start[segment_index] = middle_point_index; - working.segment_handles[segment_index] = second_handles; + push_working_segment(&mut pieces, start_segment, start_index, middle_point_index, first_handles); + pieces.segment_begins_path.push(std::mem::take(&mut begins_path)); start_t = split_t; start_index = middle_point_index; + remaining_handles = second_handles; } + + // The last piece keeps the segment's own ID + push_working_segment(&mut pieces, working.segment_ids[segment_index], start_index, working.segment_end[segment_index], remaining_handles); + pieces.segment_begins_path.push(begins_path); } + + working.segment_ids = pieces.segment_ids; + working.segment_start = pieces.segment_start; + working.segment_end = pieces.segment_end; + working.segment_handles = pieces.segment_handles; + working.segment_begins_path = pieces.segment_begins_path; } /// Copy all segments with the offset of `direction`. @@ -871,6 +885,10 @@ pub mod extrude_algorithms { push_working_segment(working, next_segment.next_id(), start, end, handles); } + + // The copies begin paths where the originals do + working.segment_begins_path.resize(segment_count, false); + working.segment_begins_path.extend_from_within(..segment_count); } /// Join points from the original to the copied that are on opposite sides of the direction. @@ -979,6 +997,24 @@ pub mod extrude_algorithms { assert_eq!(working.segment_ids.len(), 3); assert_eq!(working.point_ids.len(), 4); } + + // A split curve's pieces stay in its place, so the path holding it stays one path + #[test] + fn split_keeps_the_path_whole() { + let mut bezpath = kurbo::BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.curve_to((100., -10.), (100., 110.), (0., 100.)); + bezpath.curve_to((0., 130.), (0., 170.), (0., 200.)); + let (mut vector, mut paths) = graphic_types::Vector::from_bezpath(&bezpath); + assert_eq!(paths.len(), 1); + + let mut working = super::WorkingVector::flatten(&vector, &paths); + super::split(&mut working, DVec2::X); + assert_eq!(working.segment_ids.len(), 4); + + working.reweave(&mut vector, &mut paths); + assert_eq!(paths.len(), 1); + } } } From ab99e0e5132d6124fd7850c0ed8f2d756e14c7e6 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 16 Oct 2026 21:18:02 -0700 Subject: [PATCH 32/47] Record vector pool path structure in Path node edits and chain older edits into paths on load (#4738) * Chain segments by their connections when weaving the working form * Chain legacy segment soups into paths in the order they used to be drawn * Record where a Path node's paths begin and chain older stored edits into paths on load * Resolve turned segments through network ports and mark path starts after removals by what arrives --- .../clipboard/clipboard_message_handler.rs | 10 + .../messages/portfolio/document_migration.rs | 244 ++++++- .../graph_modification_utils.rs | 22 +- .../tool/common_functionality/shape_editor.rs | 32 +- .../common_functionality/utility_functions.rs | 4 +- .../messages/tool/tool_messages/path_tool.rs | 19 + node-graph/graph-craft/src/document/value.rs | 4 +- node-graph/libraries/graphic-types/src/lib.rs | 15 +- .../vector-types/src/vector/flatten.rs | 614 +++++++++++++----- .../vector-types/src/vector/geometry.rs | 4 + .../libraries/vector-types/src/vector/path.rs | 12 + .../src/vector/vector_attributes.rs | 11 +- .../src/vector/vector_modification.rs | 562 +++++++++++++++- .../nodes/vector/src/generator_nodes.rs | 17 + 14 files changed, 1380 insertions(+), 190 deletions(-) diff --git a/editor/src/messages/clipboard/clipboard_message_handler.rs b/editor/src/messages/clipboard/clipboard_message_handler.rs index 77d0da3c56..fd977c2f49 100644 --- a/editor/src/messages/clipboard/clipboard_message_handler.rs +++ b/editor/src/messages/clipboard/clipboard_message_handler.rs @@ -454,6 +454,7 @@ impl MessageHandler> for Clipboard // Create new segment IDs and add the segments into the existing Vector path let mut segments_map = HashMap::new(); + let path_beginnings = pasted_vector.path_beginnings(&pasted_paths); for (segment_id, segment, start, end) in pasted_vector.segment_iter(&pasted_paths) { let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else { warn!("Skipping pasted vector segment with an unknown endpoint"); @@ -474,6 +475,15 @@ impl MessageHandler> for Clipboard let points = [start_point, end_point]; let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + + // Every pasted path stays a path of its own, even where it sets out from the end of another + if path_beginnings.contains(&segment_id) { + let modification_type = VectorModificationType::SetPathBreak { + segment: new_segment_id, + breaks: true, + }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } } // Set G1 continuity diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 6511f4d7d4..668dc412e7 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -21,7 +21,7 @@ use graphene_std::transform::ScaleType; use graphene_std::uuid::NodeId; use graphene_std::vector::graphic_types; use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign}; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::f64::consts::PI; use std::ops::Range; @@ -1634,6 +1634,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open); } create_layer_stacks(document); + follow_segments_turned_on_load(document); // The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> converter pair, which reuses the same proto // identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current 12-input @@ -3347,6 +3348,136 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], Some(()) } +// TODO: Eventually remove this document upgrade code +/// Older stored edits are turned around where they chain into paths on load. Edits naming those segments by side (a handle, +/// an endpoint, or a G1 pair) in the Path nodes downstream of the one that turned them are turned with them, so each stays on +/// the side it was made on. Segment IDs are only unique within one shape, so nodes not downstream are left alone. +fn follow_segments_turned_on_load(document: &mut DocumentMessageHandler) { + for (network_path, node_id, index, input) in modifications_following_turned_segments(document.network_interface.document_network()) { + document.network_interface.set_input(&InputConnector::node_at_index(node_id, index), input, &network_path); + } +} + +// TODO: Eventually remove this document upgrade code +/// The stored edits to rewrite after loading, each with its network path, node, and input index: those that turned segments, +/// with their record taken, and those downstream of them, turned to follow. Costs O(nodes + wires) per node that turned any. +fn modifications_following_turned_segments(network: &graph_craft::document::NodeNetwork) -> Vec<(Vec, NodeId, usize, NodeInput)> { + type Location = (Vec, NodeId); + + // The nodes reading each node's data, wired straight to the node producing it through nested networks' imports and exports + let mut readers: HashMap> = HashMap::new(); + let mut turned_by: Vec<(Location, HashSet)> = Vec::new(); + for (node_id, node, network_path) in network.recursive_nodes() { + let here = (network_path.clone(), *node_id); + + for input in &node.inputs { + if let NodeInput::Value { tagged_value, .. } = input + && let TaggedValue::VectorModification(modification) = &**tagged_value + && !modification.segments_turned_on_load().is_empty() + { + turned_by.push((here.clone(), modification.segments_turned_on_load().clone())); + } + } + + // A network node's inputs only pass through to the nodes inside it, which are wired as readers themselves + if matches!(node.implementation, DocumentNodeImplementation::Network(_)) { + continue; + } + for input in &node.inputs { + if let Some(producer) = producing_node(network, &network_path, input, 0) { + readers.entry(producer).or_default().push(here.clone()); + } + } + } + if turned_by.is_empty() { + return Vec::new(); + } + + // Each node's turned segments reach the nodes reading its output, then their readers, and so on + let mut following: HashMap> = HashMap::new(); + for (origin, turned) in &turned_by { + let (origin_path, origin_id) = origin; + let Some(origin_node) = network.nested_network(origin_path).and_then(|nested| nested.nodes.get(origin_id)) else { + continue; + }; + + // Where the output comes from: the node itself, or the nodes a network node exports + let sources: Vec = match &origin_node.implementation { + DocumentNodeImplementation::Network(nested) => (0..nested.exports.len()) + .filter_map(|output| producing_node(network, origin_path, &NodeInput::node(*origin_id, output), 0)) + .collect(), + _ => vec![origin.clone()], + }; + + let mut reached = HashSet::new(); + let mut pending: Vec = sources.iter().flat_map(|source| readers.get(source).into_iter().flatten().cloned()).collect(); + while let Some(location) = pending.pop() { + if reached.insert(location.clone()) { + pending.extend(readers.get(&location).into_iter().flatten().cloned()); + } + } + + // An edit follows when the node holding it, or a node inside it, reads the turned data + for (path, node_id) in reached { + let enclosing = (0..path.len()).map(|depth| (path[..depth].to_vec(), path[depth])); + for holder in enclosing.chain([(path.clone(), node_id)]).filter(|holder| holder != origin) { + following.entry(holder).or_default().extend(turned.iter().copied()); + } + } + } + + let mut rewritten = Vec::new(); + for (node_id, node, network_path) in network.recursive_nodes() { + let location = (network_path.clone(), *node_id); + let follows = following.get(&location); + + for (index, input) in node.inputs.iter().enumerate() { + let NodeInput::Value { tagged_value, exposed } = input else { continue }; + let TaggedValue::VectorModification(modification) = &**tagged_value else { continue }; + let had_record = !modification.segments_turned_on_load().is_empty(); + if !had_record && follows.is_none() { + continue; + } + + let mut modification = modification.clone(); + modification.take_segments_turned_on_load(); + let changed = follows.is_some_and(|turned| modification.follow_segments_turned_elsewhere(turned)); + + if had_record || changed { + let input = NodeInput::value(TaggedValue::VectorModification(modification), *exposed); + rewritten.push((network_path.clone(), *node_id, index, input)); + } + } + } + + rewritten +} + +// TODO: Eventually remove this document upgrade code +/// The node, not itself a network, producing the data an input reads, looking through the imports and exports of nested networks. +fn producing_node(network: &graph_craft::document::NodeNetwork, network_path: &[NodeId], input: &NodeInput, depth: usize) -> Option<(Vec, NodeId)> { + // Nesting is shallow in practice, so this only guards against a malformed document wiring a network back into itself + if depth > 64 { + return None; + } + + match input { + NodeInput::Node { node_id, output_index } => { + let node = network.nested_network(network_path)?.nodes.get(node_id)?; + match &node.implementation { + DocumentNodeImplementation::Network(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1), + _ => Some((network_path.to_vec(), *node_id)), + } + } + NodeInput::Import { import_index, .. } => { + let (parent, parent_path) = network_path.split_last()?; + let parent_node = network.nested_network(parent_path)?.nodes.get(parent)?; + producing_node(network, parent_path, parent_node.inputs.get(*import_index)?, depth + 1) + } + _ => None, + } +} + /// Ensure layers are positioned as stacks if they are upstream siblings of another layer fn create_layer_stacks(document: &mut DocumentMessageHandler) { document.network_interface.load_structure(); @@ -4081,4 +4212,115 @@ mod tests { panic!("Duplicate entries in `NODE_REPLACEMENTS`: {duplicates:?}"); } } + + // Segment IDs repeat across shapes, so a segment turned on load is followed only by the stored edits downstream of the node that turned it + #[test] + fn turned_segments_are_followed_only_downstream() { + use graph_craft::document::NodeNetwork; + use graphene_std::vector::misc::HandleId; + use graphene_std::vector::{SegmentId, VectorModification, VectorModificationType}; + + let segment = SegmentId::generate(); + let turned = VectorModification::default().with_segments_turned_on_load(HashSet::from([segment])); + let edited_on = |handle: HandleId| { + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::SetHandlePosition { handle, relative_position: DVec2::X }); + modification + }; + let value = |modification: VectorModification| NodeInput::value(TaggedValue::VectorModification(Box::new(modification)), false); + let node = |inputs: Vec| DocumentNode { inputs, ..Default::default() }; + + // One turned Path node feeds another directly, and a second sits inside a nested network whose export feeds a third + let [turning, following, unrelated, group, following_group] = [1, 2, 3, 4, 5].map(NodeId); + let nested = NodeNetwork { + exports: vec![NodeInput::node(turning, 0)], + nodes: [(turning, node(vec![value(turned.clone())]))].into_iter().collect(), + ..Default::default() + }; + let network = NodeNetwork { + nodes: [ + (turning, node(vec![value(turned)])), + (following, node(vec![NodeInput::node(turning, 0), value(edited_on(HandleId::primary(segment)))])), + (unrelated, node(vec![value(edited_on(HandleId::primary(segment)))])), + ( + group, + DocumentNode { + implementation: DocumentNodeImplementation::Network(nested), + ..Default::default() + }, + ), + (following_group, node(vec![NodeInput::node(group, 0), value(edited_on(HandleId::primary(segment)))])), + ] + .into_iter() + .collect(), + ..Default::default() + }; + + let rewritten = modifications_following_turned_segments(&network); + let rewritten_at = |location: (&[NodeId], NodeId)| rewritten.iter().find(|(path, node_id, ..)| (path.as_slice(), *node_id) == location); + + assert!(rewritten_at((&[], turning)).is_some(), "the record of what turned is taken"); + assert!(rewritten_at((&[group], turning)).is_some(), "the nested record of what turned is taken"); + assert!(rewritten_at((&[], unrelated)).is_none(), "an edit not downstream stays as it was"); + + let expected = value(edited_on(HandleId::end(segment))); + for downstream in [following, following_group] { + let (.., index, input) = rewritten_at((&[], downstream)).expect("an edit downstream follows the turn"); + assert_eq!(*index, 1); + assert_eq!(*input, expected); + } + } + + // Inside a network fed by a turned node on one input and something else on another, only the edit reading the turned input follows + #[test] + fn turned_segments_follow_only_the_network_input_they_enter() { + use graph_craft::document::NodeNetwork; + use graphene_std::vector::misc::HandleId; + use graphene_std::vector::{SegmentId, VectorModification, VectorModificationType}; + + let segment = SegmentId::generate(); + let turned = VectorModification::default().with_segments_turned_on_load(HashSet::from([segment])); + let mut edited = VectorModification::default(); + edited.modify(&VectorModificationType::SetHandlePosition { + handle: HandleId::primary(segment), + relative_position: DVec2::X, + }); + let value = |modification: VectorModification| NodeInput::value(TaggedValue::VectorModification(Box::new(modification)), false); + let import = |import_index: usize| NodeInput::Import { + import_type: concrete!(()), + import_index, + }; + let node = |inputs: Vec| DocumentNode { inputs, ..Default::default() }; + + let [turning, other, group, reads_turned, reads_other] = [1, 2, 3, 4, 5].map(NodeId); + let nested = NodeNetwork { + exports: vec![NodeInput::node(reads_turned, 0)], + nodes: [(reads_turned, node(vec![import(0), value(edited.clone())])), (reads_other, node(vec![import(1), value(edited)]))] + .into_iter() + .collect(), + ..Default::default() + }; + let network = NodeNetwork { + nodes: [ + (turning, node(vec![value(turned)])), + (other, node(Vec::new())), + ( + group, + DocumentNode { + inputs: vec![NodeInput::node(turning, 0), NodeInput::node(other, 0)], + implementation: DocumentNodeImplementation::Network(nested), + ..Default::default() + }, + ), + ] + .into_iter() + .collect(), + ..Default::default() + }; + + let rewritten = modifications_following_turned_segments(&network); + let rewritten_at = |node_id: NodeId| rewritten.iter().any(|(path, rewritten_id, ..)| path.as_slice() == [group] && *rewritten_id == node_id); + assert!(rewritten_at(reads_turned)); + assert!(!rewritten_at(reads_other)); + } } diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index d3b73dd857..4f790f9727 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -164,11 +164,11 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde } /// Merge the `first_endpoint` with `second_endpoint`. -pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, first_endpoint: PointId, second_endpont: PointId, responses: &mut VecDeque) { +pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifier, first_endpoint: PointId, second_endpoint: PointId, responses: &mut VecDeque) { let transform = document.metadata().transform_to_document(layer); let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return }; - let segment = vector.segment_iter().find(|(_, _, start, end)| *end == second_endpont || *start == second_endpont); + let segment = vector.segment_iter().find(|(_, _, start, end)| *end == second_endpoint || *start == second_endpoint); let Some((segment, _, mut segment_start_point, mut segment_end_point)) = segment else { log::error!("Could not get the segment for second_endpoint."); return; @@ -190,20 +190,28 @@ pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifie handles[1] = Some(anchor_to_handle); } - if segment_start_point == second_endpont { - core::mem::swap(&mut segment_start_point, &mut segment_end_point); - handles.reverse(); + // The segment keeps its direction, with whichever end sat on the merged-away point moving to the point it merges into + if segment_start_point == second_endpoint { + segment_start_point = first_endpoint; + } else { + segment_end_point = first_endpoint; } - let modification_type = VectorModificationType::RemovePoint { id: second_endpont }; + let modification_type = VectorModificationType::RemovePoint { id: second_endpoint }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); let modification_type = VectorModificationType::RemoveSegment { id: segment }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); - let points = [segment_start_point, first_endpoint]; + let points = [segment_start_point, segment_end_point]; let id = SegmentId::generate(); let modification_type = VectorModificationType::InsertSegment { id, points, handles }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + + // The replacement takes over as the beginning of the path that the removed segment began + if vector.path_beginnings().contains(&segment) { + let modification_type = VectorModificationType::SetPathBreak { segment: id, breaks: true }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } } /// Create a new bitmap layer. diff --git a/editor/src/messages/tool/common_functionality/shape_editor.rs b/editor/src/messages/tool/common_functionality/shape_editor.rs index be21f9e96b..99d09532f8 100644 --- a/editor/src/messages/tool/common_functionality/shape_editor.rs +++ b/editor/src/messages/tool/common_functionality/shape_editor.rs @@ -11,7 +11,9 @@ use crate::messages::tool::tool_messages::path_tool::{PathOverlayMode, PointSele use glam::{DAffine2, DVec2}; use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table; use graphene_std::vector::algorithms::shapes::polyline_bezpath; -use graphene_std::vector::misc::{BezierHandles, HandleId, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles}; +use graphene_std::vector::misc::{ + BezierHandles, HandleId, HandleType, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles, +}; use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{Affine, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveNearest, PathSeg, Rect, Shape}; use std::f64::consts::TAU; @@ -187,6 +189,7 @@ pub struct ClosestSegment { bezier: PathSeg, points: [PointId; 2], colinear: [Option; 2], + begins_path: bool, t: f64, bezier_point_to_viewport: DVec2, } @@ -277,6 +280,15 @@ impl ClosestSegment { }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + // The first half takes over as the beginning of the path that the split segment began + if self.begins_path { + let modification_type = VectorModificationType::SetPathBreak { + segment: segment_ids[0], + breaks: true, + }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } + // Last segment let modification_type = VectorModificationType::InsertSegment { id: segment_ids[1], @@ -1360,9 +1372,11 @@ impl ShapeState { } } - // Add in new segment if possible + // Add in new segment if possible, running on from the segment that arrives at the anchor into the one that leaves it let mut handles = vector.handle_pair_of(ManipulatorPointId::Anchor(anchor))?; - handles.reverse(); + if handles[0].ty != HandleType::End || handles[1].ty != HandleType::Primary { + handles.reverse(); + } let opposites = handles.map(|handle| handle.opposite()); let [Some(start), Some(end)] = opposites.map(|opposite| vector.anchor_of(opposite.to_manipulator_point())) else { @@ -1380,6 +1394,7 @@ impl ShapeState { let mut deleted_anchors = HashSet::new(); let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue }; let colinear_pairs = vector.colinear_pairs(); + let path_beginnings = vector.path_beginnings(); let selected_segments = &state.selected_segments; @@ -1460,6 +1475,12 @@ impl ShapeState { responses.add(GraphOperationMessage::Vector { layer, modification_type }); + // Removing the segment dropped its mark as the beginning of a path, which the reconnection takes over + if path_beginnings.contains(&segment) { + let modification_type = VectorModificationType::SetPathBreak { segment, breaks: true }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } + for &handles in &colinear_pairs { if !handles.iter().any(|&handle| handle == start.0.opposite() || handle == end.0.opposite()) { continue; @@ -1784,6 +1805,7 @@ impl ShapeState { bezier: segment, points: [start, end], colinear: [primary_handle, end_handle], + begins_path: false, t, bezier_point_to_viewport: screenspace, layer, @@ -1791,6 +1813,10 @@ impl ShapeState { } } + if let Some(closest) = &mut closest { + closest.begins_path = vector.path_beginnings().contains(&closest.segment); + } + closest } diff --git a/editor/src/messages/tool/common_functionality/utility_functions.rs b/editor/src/messages/tool/common_functionality/utility_functions.rs index 8192407ece..754b3defd1 100644 --- a/editor/src/messages/tool/common_functionality/utility_functions.rs +++ b/editor/src/messages/tool/common_functionality/utility_functions.rs @@ -14,7 +14,7 @@ use graph_craft::document::value::TaggedValue; use graphene_std::renderer::Quad; use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table; use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; -use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModification, VectorModificationType}; +use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType}; use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape}; /// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable. @@ -618,7 +618,7 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac // Must not already have an existing Path node, in the right-most part of the layer chain, which has an empty set of modifications // (otherwise users could repeatedly keep running this command and stacking up empty Path nodes) if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1) - && modifications.as_ref() == &VectorModification::default() + && modifications.is_empty() { return None; } diff --git a/editor/src/messages/tool/tool_messages/path_tool.rs b/editor/src/messages/tool/tool_messages/path_tool.rs index 7378fe3aae..ab10565fda 100644 --- a/editor/src/messages/tool/tool_messages/path_tool.rs +++ b/editor/src/messages/tool/tool_messages/path_tool.rs @@ -2799,6 +2799,7 @@ impl Fsm for PathToolFsmState { } let find_index = |new_vector: &WorkingVector, id: PointId| new_vector.point_ids.iter().position(|&point_id| point_id == id); + let path_beginnings = old_vector.path_beginnings(); // Add segments which have selected ends for (segment_id, segment, start, end) in old_vector.segment_iter() { @@ -2815,6 +2816,7 @@ impl Fsm for PathToolFsmState { new_vector.segment_start.push(start_index); new_vector.segment_end.push(end_index); new_vector.segment_handles.push(segment_to_handles(&segment)); + new_vector.segment_begins_path.push(path_beginnings.contains(&segment_id)); } } @@ -2899,6 +2901,7 @@ impl Fsm for PathToolFsmState { // Create new segment IDs and add the segments into the existing vector content let mut segments_map = HashMap::new(); + let path_beginnings = pasted.path_beginnings(); for (segment_id, bezier, start, end) in pasted.segment_iter() { let new_segment_id = SegmentId::generate(); @@ -2911,6 +2914,15 @@ impl Fsm for PathToolFsmState { let modification_type = VectorModificationType::InsertSegment { id: new_segment_id, points, handles }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + + // Every pasted path stays a path of its own, even where it sets out from the end of another + if path_beginnings.contains(&segment_id) { + let modification_type = VectorModificationType::SetPathBreak { + segment: new_segment_id, + breaks: true, + }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } } // Set G1 continuity @@ -2999,6 +3011,7 @@ impl Fsm for PathToolFsmState { } let mut segments_map = HashMap::new(); + let path_beginnings = old_vector.path_beginnings(); for (segment_id, bezier, start, end) in old_vector.segment_iter() { let both_ends_selected = layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(start)) && layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(end)); @@ -3016,6 +3029,12 @@ impl Fsm for PathToolFsmState { let modification_type = VectorModificationType::InsertSegment { id: new_id, points, handles }; responses.add(GraphOperationMessage::Vector { layer, modification_type }); + + // Every duplicated path stays a path of its own, even where it sets out from the end of another + if path_beginnings.contains(&segment_id) { + let modification_type = VectorModificationType::SetPathBreak { segment: new_id, breaks: true }; + responses.add(GraphOperationMessage::Vector { layer, modification_type }); + } } } diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 086d632bd1..729dcebbae 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -779,8 +779,8 @@ pub fn deserialize_tagged_value_with_legacy_migration<'de, D: serde::Deserialize } "Vector" | "VectorData" => { let vector = graphic_types::migrations::migrate_to_optional_vector(content.clone()).map_err(serde::de::Error::custom)?; - if let Some((vector, paths)) = vector { - let modification = Box::new(VectorModification::create_from_vector(&vector, &paths)); + if let Some((vector, paths, turned)) = vector { + let modification = Box::new(VectorModification::create_from_vector(&vector, &paths).with_segments_turned_on_load(turned)); return Ok(MemoHash::new(TaggedValue::VectorModification(modification))); } return Ok(MemoHash::new(TaggedValue::TypeDefault(list!(Vector)))); diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index 1903291f51..82a375bdbd 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -135,7 +135,7 @@ pub mod migrations { } impl LegacyVector { - pub(super) fn into_parts(self) -> (Vector, List) { + pub(super) fn into_parts(self) -> (Vector, List, std::collections::HashSet) { vector_from_legacy_parts( self.point_domain.id, self.point_domain.position, @@ -168,7 +168,10 @@ pub mod migrations { // TODO: Eventually remove this document upgrade code /// Returns the first vector recovered from any of the legacy on-disk shapes (the legacy `VectorData` flat struct, a legacy `Vector` struct, or any of the historical list variants). - pub fn migrate_to_optional_vector<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result)>, D::Error> { + #[allow(clippy::type_complexity)] + pub fn migrate_to_optional_vector<'de, D: serde::Deserializer<'de>>( + deserializer: D, + ) -> Result, std::collections::HashSet)>, D::Error> { use serde::Deserialize; #[derive(serde::Deserialize)] @@ -257,7 +260,7 @@ pub mod migrations { .unwrap() .insert("fill".into(), serde_json::to_value(legacy::LegacyFill::default()).unwrap()); - let (migrated, _paths) = migrate_to_optional_vector(value).unwrap().expect("the legacy shape should parse into a vector"); + let (migrated, _paths, _) = migrate_to_optional_vector(value).unwrap().expect("the legacy shape should parse into a vector"); assert_eq!( migrated.positions().collect::>(), @@ -277,7 +280,7 @@ pub mod migrations { }; let value = serde_json::to_value(&vector).unwrap(); - let (migrated, _paths) = migrate_to_optional_vector(value).unwrap().unwrap(); + let (migrated, _paths, _) = migrate_to_optional_vector(value).unwrap().unwrap(); assert_eq!(migrated.positions().collect::>(), [glam::DVec2::new(3., 4.)]); } @@ -291,7 +294,7 @@ pub mod migrations { "segment_domain": { "ids": [7], "start_point": [0], "end_point": [1], "handles": ["Linear"] }, }); - let (migrated, paths) = migrate_to_optional_vector(value).unwrap().expect("the plural field names should parse"); + let (migrated, paths, _) = migrate_to_optional_vector(value).unwrap().expect("the plural field names should parse"); assert_eq!(migrated.positions().collect::>(), [glam::DVec2::new(3., 4.), glam::DVec2::new(5., 6.)]); assert_eq!(paths.len(), 1); @@ -316,7 +319,7 @@ pub mod migrations { }, }); - let (vector, paths) = migrate_to_optional_vector(value).unwrap().expect("the legacy vector should parse"); + let (vector, paths, _) = migrate_to_optional_vector(value).unwrap().expect("the legacy vector should parse"); // Looked up by ID, since storage order is free to differ from the legacy order let mut anchors: Vec<(u64, DVec2)> = vector diff --git a/node-graph/libraries/vector-types/src/vector/flatten.rs b/node-graph/libraries/vector-types/src/vector/flatten.rs index 3296a5807f..da3cb3a8ff 100644 --- a/node-graph/libraries/vector-types/src/vector/flatten.rs +++ b/node-graph/libraries/vector-types/src/vector/flatten.rs @@ -1,10 +1,11 @@ use super::misc::{BezierHandles, HandleId, HandleType, segment_to_handles}; -use super::path::{CurveType, Path, curve_type_at, push_path}; +use super::path::{CurveType, Path, continues_previous_path, curve_type_at, push_path}; use super::vector_attributes::{PointId, SegmentId}; use super::vector_types::Vector; use core_types::list::{ATTR_ID, List}; use glam::DVec2; use rustc_hash::{FxHashMap, FxHashSet}; +use std::collections::HashSet; /// One path under construction: its curve type, the pool references it weaves, and the IDs of the spans between them. type Run = (CurveType, Vec, Vec); @@ -48,7 +49,8 @@ impl WorkingVector { let stride = curve_type.stride(); let span_ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); - let mut begins_path = true; + // A path that only carries on the one before it in another curve type is no beginning, so the two rejoin if their types ever match + let mut begins_path = !continues_previous_path(paths, path_index); for span in 0..path.segment_count(curve_type) { let Some(segment) = path.segment(&vector.0, curve_type, span) else { continue }; let (Some(start), Some(end)) = (path.reference(span * stride), path.reference(span * stride + stride)) else { @@ -70,6 +72,14 @@ impl WorkingVector { working } + /// The number of segments that every parallel segment array holds. + fn segment_count(&self) -> usize { + [self.segment_ids.len(), self.segment_start.len(), self.segment_end.len(), self.segment_handles.len()] + .into_iter() + .min() + .unwrap_or(0) + } + /// Hands each removed segment's mark as the beginning of a path to the next kept segment, which begins what is left of that path. pub(crate) fn carry_path_beginnings(&mut self, keep: &[bool]) { let mut carried = false; @@ -83,11 +93,14 @@ impl WorkingVector { } } - /// Weaves the working form back into a pool and paths, gathering consecutive segments that meet head to tail into one path - /// until it closes or a segment begins a path of its own. + /// Weaves the working form back into a pool and paths in O(points + segments). Segments chain head to tail into paths: + /// each runs on into the segment stored after it when that one sets out from its end, and segments left unlinked pair + /// up where they are the only two loose ends at an anchor. A segment marked as beginning a path joins nothing before it. pub fn reweave(self, vector: &mut Vector, paths: &mut List) { *paths = List::new(); + let segment_count = self.segment_count(); + // The pool is built as plain arrays and handed to the list whole, anchors first and each segment's handles after let anchor_count = self.point_ids.len().min(self.point_positions.len()); let mut positions = self.point_positions; @@ -95,46 +108,113 @@ impl WorkingVector { let mut point_ids = self.point_ids; point_ids.truncate(anchor_count); - let mut runs: Vec = Vec::new(); + let drawable = |index: usize| self.segment_start[index] < anchor_count && self.segment_end[index] < anchor_count; + let begins_path = |index: usize| self.segment_begins_path.get(index).copied().unwrap_or(false); + + // Each segment's successor and predecessor in its chain, at most one of each. A segment carries on into the one + // stored after it when that one sets out from its end. + const NONE: u32 = u32::MAX; + let (mut successor, mut predecessor) = (vec![NONE; segment_count], vec![NONE; segment_count]); + for index in (1..segment_count).filter(|&index| drawable(index) && drawable(index - 1)) { + if self.segment_start[index] == self.segment_end[index - 1] && !begins_path(index) { + successor[index - 1] = index as u32; + predecessor[index] = (index - 1) as u32; + } + } + + // Segments left unlinked pair up where one arriving and one setting out are the only such two at an anchor, which + // rejoins a path around segments that were replaced and so are stored out of order + let (mut loose_arrivals, mut loose_departures) = (vec![(0_u8, NONE); anchor_count], vec![(0_u8, NONE); anchor_count]); + for index in (0..segment_count).filter(|&index| drawable(index)) { + if successor[index] == NONE { + let (count, arrival) = &mut loose_arrivals[self.segment_end[index]]; + (*count, *arrival) = (count.saturating_add(1), index as u32); + } + if predecessor[index] == NONE && !begins_path(index) { + let (count, departure) = &mut loose_departures[self.segment_start[index]]; + (*count, *departure) = (count.saturating_add(1), index as u32); + } + } + for (&(arrivals, arrival), &(departures, departure)) in loose_arrivals.iter().zip(&loose_departures) { + if arrivals == 1 && departures == 1 && arrival != departure { + successor[arrival as usize] = departure; + predecessor[departure as usize] = arrival; + } + } // Only segments a G1 pair names need their anchors recorded, to narrow the pairs to smooth flags below let paired: FxHashSet = self.colinear.iter().flat_map(|pair| pair.map(|handle| handle.segment)).collect(); let mut segment_anchors = FxHashMap::default(); - let ends = self.segment_start.iter().zip(&self.segment_end); - for (index, ((&id, (&start, &end)), handles)) in self.segment_ids.iter().zip(ends).zip(&self.segment_handles).enumerate() { - if start >= anchor_count || end >= anchor_count { + let curve_type_of = |index: usize| match self.segment_handles[index] { + BezierHandles::Linear => CurveType::Linear, + BezierHandles::Quadratic { .. } => CurveType::Quadratic, + BezierHandles::Cubic { .. } => CurveType::Cubic, + }; + + // Each chain is woven where its earliest stored segment sits, so paths keep their order. A path holds one curve + // type, so a chain changing type starts another path right after, as does one arriving back where it set out. + let mut runs: Vec = Vec::new(); + let mut woven = vec![false; segment_count]; + let mut chain_start = usize::MAX; + for seed in (0..segment_count).filter(|&seed| drawable(seed)) { + if woven[seed] { continue; } - let (curve_type, handle_positions) = match *handles { - BezierHandles::Linear => (CurveType::Linear, Vec::new()), - BezierHandles::Quadratic { handle } => (CurveType::Quadratic, vec![handle]), - BezierHandles::Cubic { handle_start, handle_end } => (CurveType::Cubic, vec![handle_start, handle_end]), - }; - - // Runs stay in segment order, which is the order the paths come out in. A run carries on through a - // junction and gives way once it has closed, or when the next segment opens a path of its own. - let begins_path = self.segment_begins_path.get(index).copied().unwrap_or(false); - let continues_run = !begins_path - && runs - .last() - .is_some_and(|(run_curve_type, references, _)| *run_curve_type == curve_type && references.last() == Some(&(start as u32)) && references.first() != references.last()); - if !continues_run { - runs.push((curve_type, vec![start as u32], Vec::new())); + // Back to where the chain begins, which for a loop is the segment the search set out from + let mut index = seed; + loop { + let previous = predecessor[index] as usize; + if previous >= segment_count || woven[previous] { + break; + } + index = previous; + if index == seed { + break; + } } - let Some((_, references, ids)) = runs.last_mut() else { continue }; - for position in handle_positions { - references.push(positions.len() as u32); - positions.push(position); - point_ids.push(PointId::UNNAMED); + // Setting out in another curve type from where the last path ended reads back as carrying it on, so it is woven that way + let carries_on = runs + .last() + .is_some_and(|(curve_type, references, _)| *curve_type != curve_type_of(index) && references.last() == Some(&(self.segment_start[index] as u32))); + if !carries_on { + chain_start = self.segment_start[index]; } - references.push(end as u32); - ids.push(id); + let mut continues_run = false; + loop { + woven[index] = true; + let (id, start, end) = (self.segment_ids[index], self.segment_start[index], self.segment_end[index]); + let (curve_type, handle_positions) = match self.segment_handles[index] { + BezierHandles::Linear => (CurveType::Linear, [None, None]), + BezierHandles::Quadratic { handle } => (CurveType::Quadratic, [Some(handle), None]), + BezierHandles::Cubic { handle_start, handle_end } => (CurveType::Cubic, [Some(handle_start), Some(handle_end)]), + }; - if paired.contains(&id) { - segment_anchors.insert(id, (start as u32, end as u32)); + if !continues_run || runs.last().is_none_or(|(run_curve_type, ..)| *run_curve_type != curve_type) { + runs.push((curve_type, vec![start as u32], Vec::new())); + } + continues_run = end != chain_start; + + let Some((_, references, ids)) = runs.last_mut() else { break }; + for position in handle_positions.into_iter().flatten() { + references.push(positions.len() as u32); + positions.push(position); + point_ids.push(PointId::UNNAMED); + } + references.push(end as u32); + ids.push(id); + + if paired.contains(&id) { + segment_anchors.insert(id, (start as u32, end as u32)); + } + + let next = successor[index] as usize; + if next >= segment_count || woven[next] { + break; + } + index = next; } } @@ -163,126 +243,32 @@ impl WorkingVector { } /// Reorders and reorients the segments so each continues the one it meets head to tail, taking the straightest - /// route through every junction, and marks where each chain begins. This bakes path structure into a segment soup once. - pub fn chain_by_straightest_route(&mut self) { - let segment_count = [self.segment_ids.len(), self.segment_start.len(), self.segment_end.len(), self.segment_handles.len()] - .into_iter() - .min() - .unwrap_or(0); + /// route through every junction, and marks where each chain begins. This bakes path structure into a segment soup once, + /// returning the IDs of the segments it turns around. + pub fn chain_by_straightest_route(&mut self) -> HashSet { + let segment_count = self.segment_count(); let point_count = self.point_positions.len(); + let endpoints: Vec<(usize, usize)> = (0..segment_count).map(|index| (self.segment_start[index], self.segment_end[index])).collect(); - // Every segment end at each point, named by twice the segment's index plus one for its arriving end - let mut ends_at: Vec> = vec![Vec::new(); point_count]; - for index in 0..segment_count { - let (start, end) = (self.segment_start[index], self.segment_end[index]); - if start < point_count && end < point_count { - ends_at[start].push(index * 2); - ends_at[end].push(index * 2 + 1); - } - } - - // The direction a segment leaves its anchor in from the given end, toward the nearest control point not sitting on the anchor - let direction = |end: usize| { - let (index, arriving) = (end / 2, end % 2 == 1); - let (start, finish) = (self.point_positions[self.segment_start[index]], self.point_positions[self.segment_end[index]]); - let handles = self.segment_handles[index]; + // The direction a segment leaves its anchor in from either end, toward the nearest control point not sitting on the anchor + let direction = |segment: usize, arriving: bool| { + let (start, finish) = (self.point_positions[self.segment_start[segment]], self.point_positions[self.segment_end[segment]]); + let handles = self.segment_handles[segment]; let (anchor, toward) = if arriving { (finish, [handles.end(), handles.start(), Some(start)]) } else { (start, [handles.start(), handles.end(), Some(finish)]) }; - let along = toward.into_iter().flatten().map(|point| point - anchor).find(|along| along.length_squared() > 1e-12); - along.unwrap_or_default().normalize_or_zero() + toward.into_iter().flatten().map(|point| point - anchor).find(|along| along.length_squared() > 1e-12) }; - - // Pair off the ends meeting at each point, the straightest pair through a junction first, in O(k² log k) for k ends there - let mut partner = vec![usize::MAX; segment_count * 2]; - for ends in ends_at.iter().filter(|ends| ends.len() >= 2) { - let directions: Vec = ends.iter().map(|&end| direction(end)).collect(); - - // Straightness is rounded so pairs differing only by float error are equally straight, leaving the earlier stored ends first - let mut pairs: Vec<(i64, usize, usize)> = (0..ends.len()) - .flat_map(|i| (i + 1..ends.len()).map(move |j| (i, j))) - .map(|(i, j)| ((-directions[i].dot(directions[j]) * 1e9).round() as i64, i, j)) - .collect(); - pairs.sort_by(|a, b| b.0.cmp(&a.0).then((a.1, a.2).cmp(&(b.1, b.2)))); - - let mut paired = vec![false; ends.len()]; - for (_, i, j) in pairs { - if paired[i] || paired[j] { - continue; - } - paired[i] = true; - paired[j] = true; - partner[ends[i]] = ends[j]; - partner[ends[j]] = ends[i]; - } - } - - // Follow the pairings into chains, each seeded by the earliest unvisited segment and keeping its direction - let mut visited = vec![false; segment_count]; - let mut order: Vec<(usize, bool)> = Vec::with_capacity(segment_count); - let mut begins_path = Vec::with_capacity(segment_count); - for seed in 0..segment_count { - if std::mem::replace(&mut visited[seed], true) { - continue; - } - - let mut chain = vec![(seed, false)]; - let mut closed = false; - let mut end = seed * 2 + 1; - loop { - let next = partner[end]; - if next == usize::MAX { - break; - } - let segment = next / 2; - if segment == seed { - closed = true; - break; - } - if std::mem::replace(&mut visited[segment], true) { - break; - } - - // Entering at the segment's arriving end crosses it backwards - let reversed = next % 2 == 1; - chain.push((segment, reversed)); - end = if reversed { segment * 2 } else { segment * 2 + 1 }; - } - - // An open chain also grows backwards from the seed's start, which is then where it begins - let mut before = Vec::new(); - let mut end = seed * 2; - if !closed { - loop { - let next = partner[end]; - if next == usize::MAX { - break; - } - let segment = next / 2; - if std::mem::replace(&mut visited[segment], true) { - break; - } - - // Joining at the segment's arriving end means it runs forward into the chain - let reversed = next % 2 == 0; - before.push((segment, reversed)); - end = if reversed { segment * 2 + 1 } else { segment * 2 }; - } - } - before.reverse(); - - begins_path.extend((0..before.len() + chain.len()).map(|position| position == 0)); - order.append(&mut before); - order.append(&mut chain); - } + // A quadratic keeps its direction, since an edit elsewhere to its lone handle could not be re-based onto its other end + let chained = chain_order(point_count, &endpoints, direction, |segment| !matches!(self.segment_handles[segment], BezierHandles::Quadratic { .. })); // Rebuild the segment arrays in chain order, turning around the segments that run against their chain let mut reversed_ids = FxHashSet::default(); let (mut ids, mut starts, mut ends, mut handles) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); - for &(segment, reversed) in &order { + for &(segment, reversed) in &chained.order { ids.push(self.segment_ids[segment]); let (start, end) = (self.segment_start[segment], self.segment_end[segment]); if reversed { @@ -300,24 +286,199 @@ impl WorkingVector { self.segment_start = starts; self.segment_end = ends; self.segment_handles = handles; - self.segment_begins_path = begins_path; + self.segment_begins_path = chained.begins_path; // A turned segment's handles swap sides, so the G1 pairs naming them follow for handle in self.colinear.iter_mut().flatten() { if reversed_ids.contains(&handle.segment) { - handle.ty = match handle.ty { - HandleType::Primary => HandleType::End, - HandleType::End => HandleType::Primary, - }; + *handle = handle.opposite(); } } + + reversed_ids.into_iter().collect() } } +/// A segment soup put in the order and orientation that chains it into paths. +pub(crate) struct ChainOrder { + /// Each segment's index in the order it should be stored, with whether it is turned around. + pub order: Vec<(usize, bool)>, + /// Whether the segment at the same place in `order` begins a chain. + pub begins_path: Vec, +} + +/// Chains a legacy segment soup into paths the way it used to be drawn: each segment continues the one it meets end to end, +/// the straightest pair going through each junction first, and the chains come out open ones first from a free end (the +/// lower one when both are), then loops from their lowest points along their earlier stored segment there. +/// +/// `direction` gives the way a segment leaves the anchor at its start or its end, or `None` when unknown, which pairs last. +/// A chain stays as it was found where turning it around would cross a segment that is not `reversible`. +pub(crate) fn chain_order(point_count: usize, endpoints: &[(usize, usize)], direction: impl Fn(usize, bool) -> Option, reversible: impl Fn(usize) -> bool) -> ChainOrder { + let segment_count = endpoints.len(); + + // Every segment end at each point, named by twice the segment's index plus one for its arriving end + let mut ends_at: Vec> = vec![Vec::new(); point_count]; + for (index, &(start, end)) in endpoints.iter().enumerate() { + if start < point_count && end < point_count { + ends_at[start].push(index * 2); + ends_at[end].push(index * 2 + 1); + } + } + + // Pair off the ends meeting at each point, the straightest pair through a junction first, in O(k² log k) for k ends there. + // Beyond a few dozen ends that grows too costly for any route to stand out, so a crowded point pairs them in stored order. + const MOST_ENDS_PAIRED_BY_STRAIGHTNESS: usize = 64; + let mut partner = vec![usize::MAX; segment_count * 2]; + for ends in ends_at.iter().filter(|ends| ends.len() >= 2) { + if ends.len() > MOST_ENDS_PAIRED_BY_STRAIGHTNESS { + for pair in ends.chunks_exact(2) { + partner[pair[0]] = pair[1]; + partner[pair[1]] = pair[0]; + } + continue; + } + + let directions: Vec> = ends.iter().map(|&end| direction(end / 2, end % 2 == 1).map(DVec2::normalize_or_zero)).collect(); + + // A pair with an unknown direction ranks below every known one. Straightness is rounded so pairs differing only by + // float error are equally straight, leaving the earlier stored ends first. + let straightness = |i: usize, j: usize| directions[i].zip(directions[j]).map_or(-2., |(first, second): (DVec2, DVec2)| -first.dot(second)); + let mut pairs: Vec<(i64, usize, usize)> = (0..ends.len()) + .flat_map(|i| (i + 1..ends.len()).map(move |j| (i, j))) + .map(|(i, j)| ((straightness(i, j) * 1e9).round() as i64, i, j)) + .collect(); + pairs.sort_by(|a, b| b.0.cmp(&a.0).then((a.1, a.2).cmp(&(b.1, b.2)))); + + let mut paired = vec![false; ends.len()]; + for (_, i, j) in pairs { + if paired[i] || paired[j] { + continue; + } + paired[i] = true; + paired[j] = true; + partner[ends[i]] = ends[j]; + partner[ends[j]] = ends[i]; + } + } + + // Follow the pairings into chains, each seeded by the earliest unvisited segment + let mut visited = vec![false; segment_count]; + let mut chains: Vec<(Vec<(usize, bool)>, bool)> = Vec::new(); + for seed in 0..segment_count { + if std::mem::replace(&mut visited[seed], true) { + continue; + } + + let mut chain = vec![(seed, false)]; + let mut closed = false; + let mut end = seed * 2 + 1; + loop { + let next = partner[end]; + if next == usize::MAX { + break; + } + let segment = next / 2; + if segment == seed { + closed = true; + break; + } + + // Entering at the segment's arriving end crosses it against its stored direction + let reversed = next % 2 == 1; + if visited[segment] || (reversed && !reversible(segment)) { + break; + } + visited[segment] = true; + chain.push((segment, reversed)); + end = if reversed { segment * 2 } else { segment * 2 + 1 }; + } + + // An open chain also grows from the seed's start, which is then where it begins + let mut before = Vec::new(); + let mut end = seed * 2; + if !closed { + loop { + let next = partner[end]; + if next == usize::MAX { + break; + } + let segment = next / 2; + + // Joining at the segment's arriving end means it runs with its stored direction into the chain + let reversed = next % 2 == 0; + if visited[segment] || (reversed && !reversible(segment)) { + break; + } + visited[segment] = true; + before.push((segment, reversed)); + end = if reversed { segment * 2 + 1 } else { segment * 2 }; + } + } + before.reverse(); + before.append(&mut chain); + + chains.push((before, closed)); + } + + // The point a chain member is crossed from, and the chain crossed the other way when every member allows it + let from = |&(segment, reversed): &(usize, bool)| if reversed { endpoints[segment].1 } else { endpoints[segment].0 }; + let to = |&(segment, reversed): &(usize, bool)| if reversed { endpoints[segment].0 } else { endpoints[segment].1 }; + let turned = |chain: &[(usize, bool)]| -> Option> { + chain + .iter() + .rev() + .map(|&(segment, reversed)| (reversed || reversible(segment)).then_some((segment, !reversed))) + .collect() + }; + let spokes = |point: usize| ends_at.get(point).map_or(0, Vec::len); + + // Start each chain where it used to be drawn from, and note what it is ordered by + let mut keyed = Vec::with_capacity(chains.len()); + for (mut chain, closed) in chains { + if closed { + // A loop sets out from its lowest point along whichever of its two segments there is stored first + let Some(lowest) = (0..chain.len()).min_by_key(|&place| from(&chain[place])) else { continue }; + chain.rotate_left(lowest); + let (leaving, arriving) = (chain[0].0, chain[chain.len() - 1].0); + if arriving < leaving + && let Some(turned) = turned(&chain) + { + chain = turned; + } + } else { + // An open chain sets out from its free end, or from its lower point when both ends or neither are free + let (Some(first), Some(last)) = (chain.first(), chain.last()) else { continue }; + let (start, end) = (from(first), to(last)); + let from_the_far_end = match (spokes(start) == 1, spokes(end) == 1) { + (true, false) => false, + (false, true) => true, + _ => end < start, + }; + if from_the_far_end && let Some(turned) = turned(&chain) { + chain = turned; + } + } + + let Some(first) = chain.first() else { continue }; + keyed.push(((closed, from(first)), chain)); + } + keyed.sort_by_key(|&(key, _)| key); + + let mut order = Vec::with_capacity(segment_count); + let mut begins_path = Vec::with_capacity(segment_count); + for (_, mut chain) in keyed { + begins_path.extend((0..chain.len()).map(|place| place == 0)); + order.append(&mut chain); + } + + ChainOrder { order, begins_path } +} + // TODO: Eventually remove this document upgrade code /// Builds storage from the legacy flat arrays: anchors with IDs and positions, segments with IDs, endpoint indices, /// and absolute handles, plus G1 pairs. Legacy segments carry no path structure, so they are chained by the straightest -/// route through each junction before weaving. Used by document migration. +/// route through each junction before weaving, and the IDs of any segments turned around come back alongside. +/// Used by document migration. pub fn vector_from_legacy_parts( point_ids: Vec, point_positions: Vec, @@ -326,7 +487,7 @@ pub fn vector_from_legacy_parts( segment_end: Vec, segment_handles: Vec, colinear: Vec<[HandleId; 2]>, -) -> (Vector, List) { +) -> (Vector, List, HashSet) { let mut working = WorkingVector { point_ids, point_positions, @@ -337,12 +498,12 @@ pub fn vector_from_legacy_parts( segment_begins_path: Vec::new(), colinear, }; - working.chain_by_straightest_route(); + let turned = working.chain_by_straightest_route(); let (mut vector, mut paths) = (Vector::default(), List::new()); working.reweave(&mut vector, &mut paths); - (vector, paths) + (vector, paths, turned) } #[cfg(test)] @@ -456,22 +617,130 @@ mod tests { assert_eq!(paths.element(0).expect("the run became a path").segment_count(CurveType::Cubic), 2); } - // Beveling appends its corner segments after the sides, which keep that order and still walk as one closed contour + // Beveling appends its corner segments after the sides, and each still finds the one side setting out from its end #[test] - fn reweave_keeps_segments_appended_out_of_order_in_order() { + fn reweave_chains_segments_stored_out_of_order() { let sides = [(0, 1), (2, 3), (4, 5), (6, 7)]; let corners = [(1, 2), (3, 4), (5, 6), (7, 0)]; let segments: Vec<_> = sides.into_iter().chain(corners).map(|(start, end)| (start, end, BezierHandles::Linear)).collect(); - let (vector, paths) = woven(working(8, &segments)); + let (_, paths) = woven(working(8, &segments)); - assert_eq!(paths.len(), 8); - assert_eq!(references(&paths, 3), vec![6, 7]); - assert_eq!(references(&paths, 4), vec![1, 2]); + assert_eq!(paths.len(), 1); + assert_eq!(references(&paths, 0), vec![0, 1, 2, 3, 4, 5, 6, 7, 0]); + } - let contours: Vec<_> = vector.stroke_bezpath_iter(&paths).collect(); - assert_eq!(contours.len(), 1); - assert_eq!(contours[0].elements().len(), 10); + // A point inserted into a path stores its two halves last, and they still weave back into the one path + #[test] + fn reweave_keeps_a_path_whole_around_a_replaced_segment() { + let soup = [(0, 1), (2, 3), (1, 4), (4, 2)].map(|(start, end)| (start, end, BezierHandles::Linear)); + let (_, paths) = woven(working(5, &soup)); + + assert_eq!(paths.len(), 1); + assert_eq!(references(&paths, 0), vec![0, 1, 4, 2, 3]); + } + + // Where several segments meet, only the one stored next carries a chain on, so a spur ending at a junction stays a spur + #[test] + fn reweave_follows_stored_order_through_a_junction() { + let soup = [(3, 1), (0, 1), (1, 2)].map(|(start, end)| (start, end, BezierHandles::Linear)); + let (_, paths) = woven(working(4, &soup)); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), vec![3, 1]); + assert_eq!(references(&paths, 1), vec![0, 1, 2]); + } + + // A chain that closes partway keeps weaving, so the loops and the tail after them all come out + #[test] + fn reweave_weaves_all_of_a_chain_that_closes_midway() { + let soup = [(2, 0), (0, 3), (0, 1), (1, 0), (0, 2)].map(|(start, end)| (start, end, BezierHandles::Linear)); + let (_, paths) = woven(working(4, &soup)); + + assert_eq!(paths.len(), 3); + assert_eq!(references(&paths, 0), vec![0, 1, 0]); + assert_eq!(references(&paths, 1), vec![0, 2, 0]); + assert_eq!(references(&paths, 2), vec![0, 3]); + } + + // A point inserted next to a junction stores its halves last, and the path still runs through where another path begins + #[test] + fn reweave_rejoins_a_replaced_segment_beside_a_junction() { + let mut soup = working(5, &[(0, 1), (1, 3), (1, 4), (4, 2)].map(|(start, end)| (start, end, BezierHandles::Linear))); + soup.segment_begins_path = vec![true, true, false, false]; + let (_, paths) = woven(soup); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), vec![0, 1, 4, 2]); + assert_eq!(references(&paths, 1), vec![1, 3]); + } + + // No soup loses a segment to the weave, and weaving what was just woven changes nothing + #[test] + fn reweave_keeps_every_segment_of_any_soup() { + let mut state = 0x9E37_79B9_7F4A_7C15_u64; + let mut below = |limit: usize| { + state = state.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + (state >> 33) as usize % limit + }; + + for _ in 0..2000 { + let points = 1 + below(6); + let segments: Vec<_> = (0..below(10)) + .map(|_| { + let handles = match below(3) { + 0 => BezierHandles::Linear, + 1 => BezierHandles::Quadratic { + handle: DVec2::new(below(5) as f64, 1.), + }, + _ => BezierHandles::Cubic { + handle_start: DVec2::new(below(5) as f64, 1.), + handle_end: DVec2::new(below(5) as f64, -1.), + }, + }; + (below(points), below(points), handles) + }) + .collect(); + let mut soup = working(points, &segments); + soup.segment_begins_path = (0..segments.len()).map(|_| below(4) == 0).collect(); + + let (vector, paths) = woven(soup); + let spans: usize = paths.iter_element_values().enumerate().map(|(index, path)| path.segment_count(curve_type_at(&paths, index))).sum(); + assert_eq!(spans, segments.len(), "{segments:?}"); + + let (_, again) = woven(WorkingVector::flatten(&vector, &paths)); + assert_eq!(again, paths, "{segments:?}"); + } + } + + // A path that exists only because the curve type changed rejoins the one before it once their types match + #[test] + fn flatten_lets_a_type_change_rejoin() { + let curve = BezierHandles::Cubic { + handle_start: DVec2::new(1., 1.), + handle_end: DVec2::new(2., 1.), + }; + let (vector, paths) = woven(working(4, &[(0, 1, BezierHandles::Linear), (1, 2, curve), (2, 3, BezierHandles::Linear)])); + assert_eq!(paths.len(), 3); + + let mut flattened = WorkingVector::flatten(&vector, &paths); + assert_eq!(flattened.segment_begins_path, vec![true, false, false]); + + flattened.segment_handles[1] = BezierHandles::Linear; + let (_, straightened) = woven(flattened); + assert_eq!(straightened.len(), 1); + assert_eq!(references(&straightened, 0), vec![0, 1, 2, 3]); + } + + // Segments meeting tail to tail are never turned around to chain them + #[test] + fn reweave_never_reverses_a_segment() { + let soup = [(0, 1), (2, 1)].map(|(start, end)| (start, end, BezierHandles::Linear)); + let (_, paths) = woven(working(3, &soup)); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), vec![0, 1]); + assert_eq!(references(&paths, 1), vec![2, 1]); } // Separate shapes stay where they were, so nothing downstream sees geometry shuffle @@ -553,12 +822,35 @@ mod tests { let mut working = working_at(&positions, &soup); working.chain_by_straightest_route(); - assert_eq!(working.segment_begins_path, vec![true, true, false]); + assert_eq!(working.segment_begins_path, vec![true, false, true]); let (_, paths) = woven(working); assert_eq!(paths.len(), 2); - assert_eq!(references(&paths, 0), [1, 3]); - assert_eq!(references(&paths, 1), [0, 1, 2]); + assert_eq!(references(&paths, 0), [0, 1, 2]); + assert_eq!(references(&paths, 1), [3, 1]); + } + + // An open chain comes out from its lower end and a loop from its lowest point along its earlier stored segment, as both used to be drawn + #[test] + fn chains_come_out_in_the_order_they_used_to_be_drawn() { + let positions = [ + DVec2::new(0., 0.), + DVec2::new(1., 0.), + DVec2::new(2., 0.), + DVec2::new(3., 0.), + DVec2::new(5., 0.), + DVec2::new(6., 0.), + DVec2::new(5., 1.), + ]; + let soup = [(5, 6), (6, 4), (4, 5), (2, 1), (3, 2), (1, 0)].map(|(start, end)| (start, end, BezierHandles::Linear)); + let mut working = working_at(&positions, &soup); + + working.chain_by_straightest_route(); + let (_, paths) = woven(working); + + assert_eq!(paths.len(), 2); + assert_eq!(references(&paths, 0), [0, 1, 2, 3]); + assert_eq!(references(&paths, 1), [4, 6, 5, 4]); } // A curve whose end handle is retracted onto the junction arrives along its other handle, so it carries on downward rather than along its chord @@ -613,7 +905,7 @@ mod tests { let ids = [SegmentId::generate(), SegmentId::generate()]; // The second segment runs back toward the shared anchor, so both handles facing it, one on each side, are stored as end handles - let (_, paths) = vector_from_legacy_parts( + let (_, paths, _) = vector_from_legacy_parts( (0..3).map(|_| PointId::generate()).collect(), positions.to_vec(), ids.to_vec(), diff --git a/node-graph/libraries/vector-types/src/vector/geometry.rs b/node-graph/libraries/vector-types/src/vector/geometry.rs index 7685be903d..9672efee69 100644 --- a/node-graph/libraries/vector-types/src/vector/geometry.rs +++ b/node-graph/libraries/vector-types/src/vector/geometry.rs @@ -93,6 +93,10 @@ impl VectorGeometry { self.vector.segment_ids(&self.paths) } + pub fn path_beginnings(&self) -> rustc_hash::FxHashSet { + self.vector.path_beginnings(&self.paths) + } + pub fn segment_from_id(&self, id: SegmentId) -> Option { self.vector.segment_from_id(&self.paths, id) } diff --git a/node-graph/libraries/vector-types/src/vector/path.rs b/node-graph/libraries/vector-types/src/vector/path.rs index 328d3c950a..22ecd44da3 100644 --- a/node-graph/libraries/vector-types/src/vector/path.rs +++ b/node-graph/libraries/vector-types/src/vector/path.rs @@ -182,6 +182,18 @@ pub fn curve_type_at(paths: &List, index: usize) -> CurveType { paths.attribute_cloned_or_default(ATTR_CURVE_TYPE, index) } +/// Whether the path at `index` only carries on the one stored before it in another curve type, setting out from +/// that path's last anchor. Such a path begins nothing of its own. +pub fn continues_previous_path(paths: &List, index: usize) -> bool { + let Some(previous_index) = index.checked_sub(1) else { return false }; + let (Some(path), Some(previous)) = (paths.element(index), paths.element(previous_index)) else { + return false; + }; + let previous_last = previous.0.len().saturating_sub(1); + + previous_last > 0 && path.0.element(0) == previous.0.element(previous_last) && curve_type_at(paths, index) != curve_type_at(paths, previous_index) +} + /// Weaves bezpath contours into pool points and paths, starting a new path at each verb change so every /// path keeps one stride. The runs of a split subpath share the anchor they meet at, welding them. struct PathWeaver { diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index b4b8adf545..42ecbb7a0d 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -1,13 +1,14 @@ use crate::vector::addressing::{self, Span}; use crate::vector::contour::contours; use crate::vector::misc::{ManipulatorGroup, Tangent, point_to_dvec2, segment_to_handles}; -use crate::vector::path::{CurveType, Path, append_segment, curve_type_at}; +use crate::vector::path::{CurveType, Path, append_segment, continues_previous_path, curve_type_at}; use crate::vector::vector_types::Vector; use core_types::list::{ATTR_ID, Item, List}; use dyn_any::DynAny; use fixedbitset::FixedBitSet; use glam::DVec2; use kurbo::{ParamCurve, PathSeg}; +use rustc_hash::FxHashSet; use std::collections::HashSet; use std::hash::{Hash, Hasher}; @@ -629,6 +630,14 @@ impl Vector { addressing::spans(paths).map(|span| addressing::segment_id_of(paths, span).unwrap_or_default()).collect() } + /// The ID of the first segment of every path that begins one, leaving out the paths that only carry on the one before them in another curve type. + pub fn path_beginnings(&self, paths: &List) -> FxHashSet { + addressing::spans(paths) + .filter(|span| span.index == 0 && !continues_previous_path(paths, span.path as usize)) + .filter_map(|span| addressing::segment_id_of(paths, span)) + .collect() + } + pub fn auto_join_paths(&self, paths: &List) -> Vec { let graph = SegmentGraph::new(self, paths); let segments = (0..graph.len()).map(|index| HalfEdge::new(graph.ids[index], graph.start_point[index], graph.end_point[index], false)); diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index fe8ce4f27e..3a483e9652 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -202,14 +202,43 @@ pub(crate) struct SegmentModification { } impl SegmentModification { - /// Apply this modification to the working form's segments. - fn apply(&self, working: &mut WorkingVector) { + /// The kept segment after removed ones begins a path when it carried on from the last of them or one of them began a path, + /// unless an added segment arrives where it sets out and so carries the path on into it. Runs in O(segments + adds). + fn mark_path_beginnings_after_removals(&self, working: &mut WorkingVector, keep: &[bool]) { + if !keep.contains(&false) { + return; + } + + let arrivals: FxHashSet = self.add.iter().filter_map(|id| self.end_point.get(id).copied()).collect(); + let segment_count = keep.len(); + working.segment_begins_path.resize(segment_count, false); + + let (mut removed_began_path, mut removed_end) = (false, None); + for index in 0..segment_count { + if !keep[index] { + removed_began_path |= std::mem::take(&mut working.segment_begins_path[index]); + removed_end = Some(working.segment_end[index]); + continue; + } + let Some(end) = removed_end.take() else { continue }; + + let start = working.segment_start[index]; + let carried_on = start == end; + let arrived_at = working.point_ids.get(start).is_some_and(|point| arrivals.contains(point)); + if (std::mem::take(&mut removed_began_path) || carried_on) && !arrived_at { + working.segment_begins_path[index] = true; + } + } + } + + /// Apply this modification to the working form's segments, where the added ones named by `path_breaks` each begin a path. + fn apply(&self, working: &mut WorkingVector, path_breaks: &HashSet) { // Remove the deleted segments, plus any segment left referencing a removed point let point_count = working.point_ids.len(); let keep: Vec = (0..working.segment_ids.len()) .map(|index| !self.remove.contains(&working.segment_ids[index]) && working.segment_start[index] < point_count && working.segment_end[index] < point_count) .collect(); - working.carry_path_beginnings(&keep); + self.mark_path_beginnings_after_removals(working, &keep); let mut keep_iter = keep.iter(); working.segment_start.retain(|_| *keep_iter.next().unwrap_or(&false)); let mut keep_iter = keep.iter(); @@ -290,6 +319,8 @@ impl SegmentModification { }; } + working.segment_begins_path.resize(working.segment_ids.len(), false); + let mut named: FxHashSet = if self.add.is_empty() { FxHashSet::default() } else { @@ -335,6 +366,7 @@ impl SegmentModification { working.segment_start.push(start_index); working.segment_end.push(end_index); working.segment_handles.push(handles); + working.segment_begins_path.push(path_breaks.contains(&add_id)); } assert!(working.segment_start.iter().all(|&index| index < working.point_ids.len()), "index should be in range"); @@ -493,7 +525,7 @@ impl SegmentModification { /// Represents a procedural change to the [`Vector`]. #[derive(Clone, Debug, Default, PartialEq, DynAny)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct VectorModification { points: PointModification, segments: SegmentModification, @@ -501,6 +533,47 @@ pub struct VectorModification { add_g1_continuous: HashSet<[HandleId; 2]>, #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_hashset"))] remove_g1_continuous: HashSet<[HandleId; 2]>, + /// The added segments that each begin a path of their own, even where one sets out from the end of another segment. + // TODO: Stop always writing this as a marker when switching to the new document format and Ctrl-C node serialization format + #[cfg_attr(feature = "serde", serde(serialize_with = "serialize_hashset_as_some"))] + path_breaks: HashSet, + /// The added segments turned around when this modification was loaded as a soup, which other modifications naming them by side follow. + // TODO: Eventually remove this document upgrade code + #[cfg_attr(feature = "serde", serde(skip))] + turned_on_load: HashSet, +} + +// TODO: Eventually remove this document upgrade code +#[cfg(feature = "serde")] +impl<'de> serde::Deserialize<'de> for VectorModification { + fn deserialize>(deserializer: D) -> Result { + // Modifications stored before paths recorded where they begin lack `path_breaks` and hold their segments as an unordered soup, which is chained into paths on load + #[derive(serde::Deserialize)] + struct StoredVectorModification { + points: PointModification, + segments: SegmentModification, + add_g1_continuous: HashSet<[HandleId; 2]>, + remove_g1_continuous: HashSet<[HandleId; 2]>, + #[serde(default)] + path_breaks: Option>, + } + + let stored = StoredVectorModification::deserialize(deserializer)?; + let legacy = stored.path_breaks.is_none(); + let mut modification = Self { + points: stored.points, + segments: stored.segments, + add_g1_continuous: stored.add_g1_continuous, + remove_g1_continuous: stored.remove_g1_continuous, + path_breaks: stored.path_breaks.unwrap_or_default(), + turned_on_load: HashSet::new(), + }; + if legacy { + modification.chain_legacy_segments(); + } + + Ok(modification) + } } /// A modification type that can be added to a [`VectorModification`]. @@ -541,6 +614,11 @@ pub enum VectorModificationType { handle: HandleId, id: PointId, }, + /// Marks or unmarks a segment this modification adds as beginning a path of its own. Segments from upstream are unaffected. + SetPathBreak { + segment: SegmentId, + breaks: bool, + }, ApplyPointDelta { point: PointId, @@ -554,7 +632,7 @@ impl VectorModificationType { match self { Self::InsertSegment { handles, .. } | Self::SetHandles { handles, .. } => handles.iter().flatten().all(|handle| handle.is_finite()), Self::InsertPoint { position: value, .. } | Self::SetHandlePosition { relative_position: value, .. } | Self::ApplyPointDelta { delta: value, .. } => value.is_finite(), - Self::RemoveSegment { .. } | Self::RemovePoint { .. } | Self::SetG1Continuous { .. } | Self::SetEndpoint { .. } => true, + Self::RemoveSegment { .. } | Self::RemovePoint { .. } | Self::SetG1Continuous { .. } | Self::SetEndpoint { .. } | Self::SetPathBreak { .. } => true, } } } @@ -668,6 +746,9 @@ impl VectorModification { segments, add_g1_continuous, remove_g1_continuous, + // Path beginnings only concern added segments, and any of those already rules this out + path_breaks: _, + turned_on_load: _, } = self; let SegmentModification { add: added_segments, @@ -713,7 +794,7 @@ impl VectorModification { fn apply_through_working_form(&self, vector: &mut Vector, paths: &mut List) { let mut working = WorkingVector::flatten(vector, paths); self.points.apply(&mut working); - self.segments.apply(&mut working); + self.segments.apply(&mut working, &self.path_breaks); let surviving_segments: FxHashSet = working.segment_ids.iter().copied().collect(); let valid = |val: &[HandleId; 2]| surviving_segments.contains(&val[0].segment) && surviving_segments.contains(&val[1].segment); @@ -745,7 +826,10 @@ impl VectorModification { VectorModificationType::InsertSegment { id, points, handles } => self.segments.push(*id, *points, *handles), VectorModificationType::InsertPoint { id, position } => self.points.push(*id, *position), - VectorModificationType::RemoveSegment { id } => self.segments.remove(*id), + VectorModificationType::RemoveSegment { id } => { + self.segments.remove(*id); + self.path_breaks.remove(id); + } VectorModificationType::RemovePoint { id } => self.points.remove(*id), VectorModificationType::SetG1Continuous { handles, enabled } => { @@ -773,6 +857,14 @@ impl VectorModification { VectorModificationType::SetEndpoint { handle, id } => { self.segments.endpoint_side_of(*handle).insert(handle.segment, *id); } + VectorModificationType::SetPathBreak { segment, breaks } => { + // Only a segment this modification adds can begin a path of its own + if *breaks && self.segments.add.contains(segment) { + self.path_breaks.insert(*segment); + } else { + self.path_breaks.remove(segment); + } + } VectorModificationType::ApplyPointDelta { point, delta } => { *self.points.delta.entry(*point).or_default() += *delta; @@ -783,13 +875,209 @@ impl VectorModification { /// Create a new modification that will convert an empty [`Vector`] into the target [`Vector`]. pub fn create_from_vector(vector: &Vector, paths: &List) -> Self { let working = WorkingVector::flatten(vector, paths); + let begins_path = working.segment_ids.iter().zip(&working.segment_begins_path).filter(|&(_, &begins)| begins).map(|(&id, _)| id); Self { points: PointModification::create_from_working(&working), segments: SegmentModification::create_from_working(&working), add_g1_continuous: working.colinear.iter().copied().collect(), remove_g1_continuous: HashSet::new(), + path_breaks: begins_path.collect(), + turned_on_load: HashSet::new(), } } + + // TODO: Eventually remove this document upgrade code + /// Chains the added segments of a modification stored as an unordered soup into paths: reorders them, turns around + /// the ones running against their chain along with their handles and G1 pairs, and records where each chain begins. + fn chain_legacy_segments(&mut self) { + // Segments missing any of their parts are never applied, so they sit out of the chaining and follow the chained ones + let segments = &self.segments; + let mut seen = FxHashSet::default(); + let (mut complete, mut unchainable) = (Vec::new(), Vec::new()); + for &id in &segments.add { + if !seen.insert(id) { + continue; + } + let parts = ( + segments.start_point.get(&id), + segments.end_point.get(&id), + segments.handle_primary.get(&id), + segments.handle_end.get(&id), + ); + match parts { + (Some(&start), Some(&end), Some(&primary), Some(&end_handle)) => complete.push((id, start, end, primary, end_handle)), + _ => unchainable.push(id), + } + } + + // Points are numbered the way they used to be stored, upstream ones first and then the added ones in the order they + // were added. Only the added ones have positions here. What else meets an upstream point is unknown, so each + // segment end there is numbered apart and pairs with nothing, leaving it to be joined once upstream is known. + let added: FxHashMap = self.points.add.iter().enumerate().filter_map(|(place, id)| Some((*id, (place, *self.points.delta.get(id)?)))).collect(); + let upstream_ends = complete.iter().flat_map(|&(_, start, end, ..)| [start, end]).filter(|point| !added.contains_key(point)).count(); + let mut next_upstream_end = 0; + let mut index_of = |point: PointId| match added.get(&point) { + Some(&(place, _)) => upstream_ends + place, + None => { + next_upstream_end += 1; + next_upstream_end - 1 + } + }; + + let mut positions = vec![None; upstream_ends + self.points.add.len()]; + for &(place, position) in added.values() { + positions[upstream_ends + place] = Some(position); + } + let chainable: Vec<_> = complete + .iter() + .map(|&(id, start, end, primary, end_handle)| (id, index_of(start), index_of(end), primary, end_handle)) + .collect(); + let endpoints: Vec<(usize, usize)> = chainable.iter().map(|&(_, start, end, ..)| (start, end)).collect(); + + // A cubic's handles are stored relative to their own anchors, and a quadratic's one handle relative to its start. A segment + // leaves an anchor toward its nearest control point not sitting on that anchor, as legacy vectors are chained too. + let nonzero = |along: DVec2| (along.length_squared() > 1e-12).then_some(along); + let direction = |segment: usize, arriving: bool| { + let (_, start, end, primary, end_handle) = chainable[segment]; + let (start, end) = (positions[start], positions[end]); + let across = |from: Option, offset: DVec2, to: Option| from.zip(to).map(|(from, to)| from + offset - to); + + // Each handle as an offset from this end's anchor, nearest first, then the other anchor + let toward = match (primary, end_handle) { + (Some(primary), Some(end_handle)) if arriving => [Some(end_handle), across(start, primary, end)], + (Some(primary), Some(end_handle)) => [Some(primary), across(end, end_handle, start)], + (Some(handle), None) | (None, Some(handle)) if arriving => [across(start, handle, end), None], + (Some(handle), None) | (None, Some(handle)) => [Some(handle), None], + (None, None) => [None, None], + }; + let chord = if arriving { across(start, DVec2::ZERO, end) } else { across(end, DVec2::ZERO, start) }; + + toward.into_iter().chain([chord]).flatten().find_map(nonzero) + }; + + // A segment touching an upstream point keeps its direction, since what upstream carries on into it is unknown, and so + // does a quadratic, since another modification's offset for its lone handle could not be re-based onto the other end + let reversible = |segment: usize| { + let (_, start, end, primary, end_handle) = chainable[segment]; + positions[start].is_some() && positions[end].is_some() && primary.is_some() == end_handle.is_some() + }; + let chained = crate::vector::flatten::chain_order(positions.len(), &endpoints, direction, reversible); + + let mut reversed_ids = FxHashSet::default(); + let mut path_breaks = HashSet::new(); + let mut add = Vec::with_capacity(segments.add.len()); + let mut turned = Vec::new(); + for (&(segment, reversed), &begins) in chained.order.iter().zip(&chained.begins_path) { + let (id, start, end, primary, end_handle) = chainable[segment]; + add.push(id); + + // A chain setting out from an upstream point may be carrying on a path that ends there, so only the rest begin paths + let sets_out_from = if reversed { end } else { start }; + if begins && positions[sets_out_from].is_some() { + path_breaks.insert(id); + } + + if reversed { + reversed_ids.insert(id); + turned.push((id, (end_handle, primary))); + } + } + add.extend(unchainable); + + self.segments.add = add; + for (id, (primary, end_handle)) in turned { + let (start, end) = (self.segments.start_point.remove(&id), self.segments.end_point.remove(&id)); + if let (Some(start), Some(end)) = (start, end) { + self.segments.start_point.insert(id, end); + self.segments.end_point.insert(id, start); + } + self.segments.handle_primary.insert(id, primary); + self.segments.handle_end.insert(id, end_handle); + } + self.path_breaks = path_breaks; + + // A turned segment's handles swap sides, so the G1 pairs naming them follow + let follow = |pairs: &mut HashSet<[HandleId; 2]>| { + *pairs = pairs + .drain() + .map(|pair| pair.map(|handle| if reversed_ids.contains(&handle.segment) { handle.opposite() } else { handle })) + .collect(); + }; + follow(&mut self.add_g1_continuous); + follow(&mut self.remove_g1_continuous); + + self.turned_on_load = reversed_ids.into_iter().collect(); + } + + // TODO: Eventually remove this document upgrade code + /// Records the segments a legacy conversion turned around before this modification was captured from its result. + pub fn with_segments_turned_on_load(mut self, turned: HashSet) -> Self { + self.turned_on_load = turned; + self + } + + // TODO: Eventually remove this document upgrade code + /// Takes the record of the segments this modification turned around when it was loaded. + pub fn take_segments_turned_on_load(&mut self) -> HashSet { + std::mem::take(&mut self.turned_on_load) + } + + // TODO: Eventually remove this document upgrade code + /// The segments this modification turned around when it was loaded. + pub fn segments_turned_on_load(&self) -> &HashSet { + &self.turned_on_load + } + + // TODO: Eventually remove this document upgrade code + /// Turns this modification's edits around to match segments another modification turned when it was loaded, so each edit + /// stays on the side of its segment it was made on. Returns whether anything changed. + pub fn follow_segments_turned_elsewhere(&mut self, turned: &HashSet) -> bool { + let own: HashSet = self.segments.add.iter().copied().collect(); + let named_elsewhere = |segment: &SegmentId| turned.contains(segment) && !own.contains(segment); + let mut changed = false; + + // Only the segments this modification names by side can need turning, so this is linear in its own edits + let segments = &self.segments; + let named: HashSet = [&segments.handle_primary, &segments.handle_end] + .into_iter() + .flat_map(|handles| handles.keys()) + .chain([&segments.start_point, &segments.end_point].into_iter().flat_map(|points| points.keys())) + .copied() + .filter(named_elsewhere) + .collect(); + + for segment in named { + let (primary, end_handle) = (self.segments.handle_primary.remove(&segment), self.segments.handle_end.remove(&segment)); + changed |= primary.is_some() || end_handle.is_some(); + if let Some(primary) = primary { + self.segments.handle_end.insert(segment, primary); + } + if let Some(end_handle) = end_handle { + self.segments.handle_primary.insert(segment, end_handle); + } + + let (start, end) = (self.segments.start_point.remove(&segment), self.segments.end_point.remove(&segment)); + changed |= start.is_some() || end.is_some(); + if let Some(start) = start { + self.segments.end_point.insert(segment, start); + } + if let Some(end) = end { + self.segments.start_point.insert(segment, end); + } + } + + for pairs in [&mut self.add_g1_continuous, &mut self.remove_g1_continuous] { + if pairs.iter().flatten().any(|handle| named_elsewhere(&handle.segment)) { + changed = true; + *pairs = pairs + .drain() + .map(|pair| pair.map(|handle| if named_elsewhere(&handle.segment) { handle.opposite() } else { handle })) + .collect(); + } + } + + changed + } } // Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order, @@ -861,6 +1149,19 @@ where seq.end() } +/// Serializes sorted `[value, ...]` as a present optional, matching the field being read back as an `Option` in formats that tag one. +pub(crate) fn serialize_hashset_as_some(set: &HashSet, serializer: S) -> Result +where + T: Serialize + Eq + Hash + Ord, + S: Serializer, + H: BuildHasher, +{ + let mut entries: Vec<_> = set.iter().collect(); + entries.sort(); + + serializer.serialize_some(&entries) +} + pub fn deserialize_hashmap<'de, K, V, D, H>(deserializer: D) -> Result, D::Error> where K: Deserialize<'de> + Eq + Hash, @@ -1347,4 +1648,251 @@ mod tests { assert_eq!(modification, VectorModification::default()); } + + /// A modification placing the points in a row and drawing a straight segment between each pair of them given. + fn drawn(points: &[PointId], segments: &[(SegmentId, usize, usize)]) -> VectorModification { + let mut modification = VectorModification::default(); + for (index, &id) in points.iter().enumerate() { + let position = DVec2::new(index as f64 * 10., 0.); + modification.modify(&VectorModificationType::InsertPoint { id, position }); + } + for &(id, start, end) in segments { + let points = [points[start], points[end]]; + modification.modify(&VectorModificationType::InsertSegment { id, points, handles: [None, None] }); + } + + modification + } + + /// The anchors each path visits once the modification is applied to nothing, as places in the given points. + fn woven_paths(modification: &VectorModification, points: &[PointId]) -> Vec> { + let (mut vector, mut paths) = (Vector::default(), List::new()); + modification.apply(&mut vector, &mut paths); + + let place = |point: u32| vector.point_id_at(point).and_then(|id| points.iter().position(|&candidate| candidate == id)).expect("a known anchor"); + paths.iter_element_values().map(|path| path.references().map(place).collect()).collect() + } + + fn generated(count: usize, generate: fn() -> T) -> Vec { + (0..count).map(|_| generate()).collect() + } + + // A modification stored before paths recorded where they begin is a soup, which loading chains into one path and turns around where needed + #[test] + fn a_stored_soup_is_chained_into_paths_on_load() { + let (points, ids) = (generated(5, PointId::generate), generated(4, SegmentId::generate)); + let soup = drawn(&points, &[(ids[0], 1, 2), (ids[1], 1, 0), (ids[2], 3, 2), (ids[3], 3, 4)]); + assert_eq!(woven_paths(&soup, &points).len(), 4); + + let mut stored = serde_json::to_value(&soup).unwrap(); + stored.as_object_mut().unwrap().remove("path_breaks"); + let loaded: VectorModification = serde_json::from_value(stored).unwrap(); + + assert_eq!(woven_paths(&loaded, &points), [[0, 1, 2, 3, 4]]); + assert_eq!(loaded.path_breaks, HashSet::from([ids[1]])); + } + + // A modification stored with its record of path beginnings loads exactly as it was saved, without being chained again + #[test] + fn the_path_record_survives_a_round_trip() { + let (points, ids) = (generated(3, PointId::generate), generated(2, SegmentId::generate)); + let mut modification = drawn(&points, &[(ids[0], 1, 2), (ids[1], 1, 0)]); + modification.modify(&VectorModificationType::SetPathBreak { segment: ids[1], breaks: true }); + + let stored = serde_json::to_string(&modification).unwrap(); + let loaded: VectorModification = serde_json::from_str(&stored).unwrap(); + + assert_eq!(loaded, modification); + assert_eq!(woven_paths(&loaded, &points), [vec![1, 2], vec![1, 0]]); + } + + // Splitting the first side of an upstream closed path, as the Path tool inserts a point, keeps one closed path beginning where it did + #[test] + fn splitting_an_upstream_path_beginning_keeps_the_path_whole() { + use kurbo::{Rect, Shape}; + + let (mut vector, mut paths) = Vector::from_bezpath(&Rect::new(0., 0., 10., 10.).to_path(0.)); + let (first, _, start, end) = vector.segment_iter(&paths).next().unwrap(); + let middle = PointId::generate(); + let halves = [SegmentId::generate(), SegmentId::generate()]; + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::RemoveSegment { id: first }); + modification.modify(&VectorModificationType::InsertPoint { + id: middle, + position: DVec2::new(5., 0.), + }); + for (id, points) in [(halves[0], [start, middle]), (halves[1], [middle, end])] { + modification.modify(&VectorModificationType::InsertSegment { id, points, handles: [None, None] }); + } + modification.modify(&VectorModificationType::SetPathBreak { segment: halves[0], breaks: true }); + modification.apply(&mut vector, &mut paths); + + assert_eq!(paths.len(), 1); + assert!(paths.element(0).unwrap().is_closed()); + assert_eq!(vector.segment_iter(&paths).count(), 5); + assert_eq!(vector.segment_iter(&paths).next().map(|(id, ..)| id), Some(halves[0])); + } + + // Deleting a segment cuts its path, so what is left past it stays apart from another path ending at the same junction + #[test] + fn deleting_a_segment_beside_a_junction_keeps_the_paths_apart() { + use crate::vector::path::push_path; + use core_types::list::Item; + + let mut vector = Vector::default(); + for index in 0..8 { + vector.0.push(Item::new_from_element(DVec2::new(index as f64, 0.)).with_attribute(ATTR_ID, PointId::generate())); + } + let mut paths = List::new(); + for references in [vec![0, 1, 2, 3], vec![5, 2], vec![6, 2, 7]] { + let ids: Vec = (1..references.len()).map(|_| SegmentId::generate()).collect(); + push_path(&mut paths, CurveType::Linear, references, ids); + } + let removed = vector.segment_iter(&paths).nth(1).map(|(id, ..)| id).unwrap(); + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::RemoveSegment { id: removed }); + modification.apply(&mut vector, &mut paths); + + // Anchors are named by their x positions, which were their original pool indices + let drawn: Vec> = paths + .iter_element_values() + .map(|path| path.references().map(|point| vector.position(point as usize).unwrap().x as i32).collect()) + .collect(); + assert!(drawn.contains(&vec![2, 3]), "{drawn:?}"); + assert!(drawn.contains(&vec![5, 2]), "{drawn:?}"); + } + + // A segment marked as beginning a path stays apart from the one it sets out from the end of + #[test] + fn a_path_break_keeps_a_stroke_apart() { + let (points, ids) = (generated(3, PointId::generate), generated(2, SegmentId::generate)); + let mut modification = drawn(&points, &[(ids[0], 0, 1), (ids[1], 1, 2)]); + assert_eq!(woven_paths(&modification, &points), [[0, 1, 2]]); + + modification.modify(&VectorModificationType::SetPathBreak { segment: ids[1], breaks: true }); + assert_eq!(woven_paths(&modification, &points), [vec![0, 1], vec![1, 2]]); + } + + // A stroke drawn out of an upstream point and one drawn into it are not paired there, and each keeps its direction + #[test] + fn a_stored_soup_pairs_nothing_at_an_upstream_point() { + let (points, ids) = (generated(4, PointId::generate), generated(3, SegmentId::generate)); + let mut soup = drawn(&points[1..], &[]); + for (id, start, end) in [(ids[0], 0, 1), (ids[1], 1, 2), (ids[2], 3, 0)] { + let points = [points[start], points[end]]; + soup.modify(&VectorModificationType::InsertSegment { id, points, handles: [None, None] }); + } + + let mut stored = serde_json::to_value(&soup).unwrap(); + stored.as_object_mut().unwrap().remove("path_breaks"); + let loaded: VectorModification = serde_json::from_value(stored).unwrap(); + + // Paired at the upstream point, the stroke arriving there would have led the one leaving it + assert_eq!(loaded.segments.add, vec![ids[0], ids[1], ids[2]]); + assert_eq!(loaded.segments.start_point[&ids[0]], points[0]); + assert_eq!(loaded.segments.start_point[&ids[2]], points[3]); + assert_eq!(loaded.path_breaks, HashSet::from([ids[2]])); + } + + // Loading turns a stored cubic around along with its handles and G1 pair, and an edit elsewhere naming it by side follows + #[test] + fn a_segment_turned_on_load_keeps_its_handles_and_edits_on_their_anchors() { + let (points, ids) = (generated(3, PointId::generate), generated(2, SegmentId::generate)); + let (toward, away) = (DVec2::new(1., 2.), DVec2::new(3., 4.)); + let mut soup = drawn(&points, &[]); + soup.modify(&VectorModificationType::InsertSegment { + id: ids[0], + points: [points[1], points[0]], + handles: [Some(toward), Some(away)], + }); + soup.modify(&VectorModificationType::InsertSegment { + id: ids[1], + points: [points[1], points[2]], + handles: [None, None], + }); + let pair = [HandleId::primary(ids[0]), HandleId::primary(ids[1])]; + soup.modify(&VectorModificationType::SetG1Continuous { handles: pair, enabled: true }); + + let mut stored = serde_json::to_value(&soup).unwrap(); + stored.as_object_mut().unwrap().remove("path_breaks"); + let mut loaded: VectorModification = serde_json::from_value(stored).unwrap(); + + // The first segment now runs from point 0 into point 1, each handle still on the anchor it was drawn from + assert_eq!(loaded.segments.start_point[&ids[0]], points[0]); + assert_eq!(loaded.segments.handle_primary[&ids[0]], Some(away)); + assert_eq!(loaded.segments.handle_end[&ids[0]], Some(toward)); + assert!(loaded.add_g1_continuous.contains(&[HandleId::end(ids[0]), HandleId::primary(ids[1])])); + + let turned = loaded.take_segments_turned_on_load(); + assert_eq!(turned, HashSet::from([ids[0]])); + + let mut downstream = VectorModification::default(); + downstream.modify(&VectorModificationType::SetHandlePosition { + handle: HandleId::primary(ids[0]), + relative_position: DVec2::X, + }); + assert!(downstream.follow_segments_turned_elsewhere(&turned)); + assert_eq!(downstream.segments.handle_end.get(&ids[0]), Some(&Some(DVec2::X))); + assert!(!downstream.segments.handle_primary.contains_key(&ids[0])); + } + + // Capturing a vector records where its paths begin, so two paths welded head to tail come back as two + #[test] + fn a_captured_vector_keeps_its_paths() { + use crate::vector::path::push_path; + use core_types::list::Item; + + let points = generated(3, PointId::generate); + let mut vector = Vector::default(); + for (index, &id) in points.iter().enumerate() { + vector.0.push(Item::new_from_element(DVec2::new(index as f64 * 10., 0.)).with_attribute(ATTR_ID, id)); + } + let mut paths = List::new(); + push_path(&mut paths, CurveType::Linear, [0, 1], [SegmentId::generate()]); + push_path(&mut paths, CurveType::Linear, [1, 2], [SegmentId::generate()]); + + let captured = VectorModification::create_from_vector(&vector, &paths); + assert_eq!(woven_paths(&captured, &points), [vec![0, 1], vec![1, 2]]); + } + + // Splitting the segment a closed path begins with hands that beginning to its first half, so the path keeps its start + #[test] + fn a_point_inserted_on_a_paths_first_segment_keeps_its_start() { + let (points, ids) = (generated(5, PointId::generate), generated(6, SegmentId::generate)); + let mut modification = drawn(&points[..4], &[(ids[0], 0, 1), (ids[1], 1, 2), (ids[2], 2, 3), (ids[3], 3, 0)]); + modification.modify(&VectorModificationType::SetPathBreak { segment: ids[0], breaks: true }); + + modification.modify(&VectorModificationType::InsertPoint { + id: points[4], + position: DVec2::new(5., 5.), + }); + for (id, points) in [(ids[4], [points[0], points[4]]), (ids[5], [points[4], points[1]])] { + modification.modify(&VectorModificationType::InsertSegment { id, points, handles: [None, None] }); + } + modification.modify(&VectorModificationType::SetPathBreak { segment: ids[4], breaks: true }); + modification.modify(&VectorModificationType::RemoveSegment { id: ids[0] }); + + assert_eq!(woven_paths(&modification, &points), [[0, 4, 1, 2, 3, 0]]); + } + + // Splitting a segment removes it and stores its two halves last, and the path they sit in stays one path from the same start + #[test] + fn a_point_inserted_into_a_path_leaves_it_one_path() { + let (points, ids) = (generated(5, PointId::generate), generated(6, SegmentId::generate)); + let mut modification = drawn(&points[..4], &[(ids[0], 0, 1), (ids[1], 1, 2), (ids[2], 2, 3), (ids[3], 3, 0)]); + assert_eq!(woven_paths(&modification, &points), [[0, 1, 2, 3, 0]]); + + modification.modify(&VectorModificationType::RemoveSegment { id: ids[1] }); + modification.modify(&VectorModificationType::InsertPoint { + id: points[4], + position: DVec2::new(15., 5.), + }); + for (id, points) in [(ids[4], [points[1], points[4]]), (ids[5], [points[4], points[2]])] { + modification.modify(&VectorModificationType::InsertSegment { id, points, handles: [None, None] }); + } + + assert_eq!(woven_paths(&modification, &points), [[0, 1, 4, 2, 3, 0]]); + } } diff --git a/node-graph/nodes/vector/src/generator_nodes.rs b/node-graph/nodes/vector/src/generator_nodes.rs index 48010419c9..e0860b03fa 100644 --- a/node-graph/nodes/vector/src/generator_nodes.rs +++ b/node-graph/nodes/vector/src/generator_nodes.rs @@ -416,6 +416,11 @@ fn grid( } } + // A segment begins a path unless it carries on from the one stored before it, so the weave joins nothing around the grid's junctions + working.segment_begins_path = (0..working.segment_ids.len()) + .map(|index| index == 0 || working.segment_start[index] != working.segment_end[index - 1]) + .collect(); + let (mut vector, mut paths) = (Vector::default(), List::new()); working.reweave(&mut vector, &mut paths); @@ -465,6 +470,18 @@ mod tests { } } + // Only segments stored one after another join into paths, so no outline closes around the cells + #[test] + fn grid_joins_segments_only_where_they_follow_each_other() { + let grid = grid((), (), item(GridType::Rectangular), item(10.), item(3_i64), item(3_i64), item((30., 30.).into()), item(true)); + let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + let vector = grid.element(); + + assert_eq!(vector.segment_ids(&paths).len(), 2 * 3 + 2 * 3); + assert_eq!(paths.len(), 7); + assert!(vector.stroke_manipulator_groups(&paths).all(|(_, closed)| !closed)); + } + #[test] fn grid_disconnected_cells_test() { // A 3x3 rectangular grid has a 2x2 arrangement of cells, each its own closed quad subpath. From 74a361aafcda2a00376294f88d43db088f25f1e4 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 16 Oct 2026 22:51:17 -0700 Subject: [PATCH 33/47] Share list attributes between clones and read vector pool paths without copying them (#4739) * Clear two Clippy lints from the vector pool path structure code * Find anchor tangents in one pass along the contours * Share a list's attributes between its clones until one is written to * Read each path's curve type, references, and IDs once when resolving its spans * Gather attribute values in a buffer on their way to a trait-object hasher * Append woven paths to their list as one piece * Read an item's paths without copying them and leave them shared when only points move * Weave any number of bezpaths in one pass, looking up the IDs to continue from once * Hold a list's lone attribute in place, sparing each path a collection of its own * Look up the paths' curve types once in the loops that walk every path --- node-graph/libraries/core-types/src/list.rs | 1028 ++++++++++++----- .../vector-types/src/vector/addressing.rs | 47 +- .../vector-types/src/vector/connectivity.rs | 7 +- .../vector-types/src/vector/contour.rs | 4 +- .../vector-types/src/vector/flatten.rs | 16 +- .../vector-types/src/vector/geometry.rs | 4 - .../libraries/vector-types/src/vector/path.rs | 210 +++- .../src/vector/vector_attributes.rs | 231 ++-- .../src/vector/vector_modification.rs | 26 +- .../vector-types/src/vector/vector_types.rs | 166 ++- node-graph/nodes/path-bool/src/lib.rs | 5 +- node-graph/nodes/text/src/path_builder.rs | 18 +- .../nodes/vector/src/generator_nodes.rs | 28 +- .../nodes/vector/src/merge_qr_squares.rs | 8 +- .../vector/src/vector_modification_nodes.rs | 101 +- node-graph/nodes/vector/src/vector_nodes.rs | 154 +-- 16 files changed, 1450 insertions(+), 603 deletions(-) diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index 399f573bdc..832d6a58ca 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -6,6 +6,7 @@ use dyn_any::{DynAny, StaticType, StaticTypeSized}; use glam::DAffine2; use graphene_hash::CacheHash; use std::fmt::Debug; +use std::sync::Arc; // ================================================= // Standard attribute keys used across the data flow @@ -199,7 +200,7 @@ fn implicit_default_value(key: &str) -> Option> { } /// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]). -fn pad_with_implicit_default(key: &str, attribute: &mut Box, count: usize) { +fn pad_with_implicit_default(key: &str, attribute: &mut dyn AnyAttribute, count: usize) { match implicit_default_value(key) { Some(default) => attribute.push_repeated(&*default, count), None => { @@ -210,6 +211,60 @@ fn pad_with_implicit_default(key: &str, attribute: &mut Box, c } } +// ============ +// AttributeKey +// ============ + +/// An attribute's name. Short names are stored inline and longer ones shared, so copying an item's or a list's attributes allocates nothing for their names. +#[derive(Clone)] +enum AttributeKey { + Inline { length: u8, bytes: [u8; AttributeKey::INLINE_CAPACITY] }, + Allocated(Arc), +} + +impl AttributeKey { + /// The longest name stored inline, which keeps a key the size of a `String`. + const INLINE_CAPACITY: usize = 22; + + fn new(key: &str) -> Self { + let mut bytes = [0; Self::INLINE_CAPACITY]; + + match bytes.get_mut(..key.len()) { + Some(inline) => { + inline.copy_from_slice(key.as_bytes()); + Self::Inline { length: key.len() as u8, bytes } + } + None => Self::Allocated(key.into()), + } + } + + fn as_bytes(&self) -> &[u8] { + match self { + Self::Inline { length, bytes } => bytes.get(..*length as usize).unwrap_or_default(), + Self::Allocated(key) => key.as_bytes(), + } + } + + fn as_str(&self) -> &str { + match self { + // The inline bytes are a whole `&str` copied in, so they always read back as one + Self::Inline { .. } => std::str::from_utf8(self.as_bytes()).unwrap_or_default(), + Self::Allocated(key) => key, + } + } + + /// Whether this is the attribute named `key`. + fn is(&self, key: &str) -> bool { + self.as_bytes() == key.as_bytes() + } +} + +impl PartialEq for AttributeKey { + fn eq(&self, other: &Self) -> bool { + self.as_bytes() == other.as_bytes() + } +} + // ======================== // TRAIT: AnyAttributeValue // ======================== @@ -220,6 +275,9 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync { /// Clones this value into a new boxed trait object. fn clone_box(&self) -> Box; + /// Clones this value into a new shared trait object. + fn clone_arc(&self) -> Arc; + /// Returns a shared reference to the underlying concrete type for downcasting. fn as_any(&self) -> &dyn std::any::Any; @@ -229,6 +287,9 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync { /// Consumes the box and returns the underlying concrete type for downcasting. fn into_any(self: Box) -> Box; + /// Converts the shared value into one that can be downcast to its concrete type. + fn into_any_arc(self: Arc) -> Arc; + /// Returns a debug-formatted string representation of this value. fn display_string(&self) -> String; @@ -240,7 +301,7 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync { fn eq_dyn(&self, other: &dyn AnyAttributeValue) -> bool; /// Wraps this scalar value into a new attribute, preceded by `preceding_defaults` implicit defaults for `key`. - fn into_attribute(self: Box, key: &str, preceding_defaults: usize) -> Box; + fn into_attribute(self: Arc, key: &str, preceding_defaults: usize) -> Arc; } impl AnyAttributeValue for T { @@ -249,6 +310,11 @@ impl Arc { + Arc::new(self.clone()) + } + /// Returns a shared reference to the underlying concrete type for downcasting. fn as_any(&self) -> &dyn std::any::Any { self @@ -264,6 +330,11 @@ impl) -> Arc { + self + } + /// Returns a debug-formatted string representation of this value. fn display_string(&self) -> String { format!("{:?}", self) @@ -271,7 +342,7 @@ impl, key: &str, preceding_defaults: usize) -> Box { - let mut attribute: Box = Box::new(Attribute::(Vec::with_capacity(preceding_defaults + 1))); + fn into_attribute(self: Arc, key: &str, preceding_defaults: usize) -> Arc { + let mut attribute = Attribute::(Vec::with_capacity(preceding_defaults + 1)); pad_with_implicit_default(key, &mut attribute, preceding_defaults); - attribute.push(self); - attribute + attribute.0.push(Arc::unwrap_or_clone(self)); + + Arc::new(attribute) } } @@ -295,14 +367,23 @@ impl Clone for Box { } } +/// Gives write access to an attribute value, first copying it if clones of its item still share it. +fn unshared_value(value: &mut Arc) -> &mut dyn AnyAttributeValue { + if Arc::get_mut(value).is_none() { + *value = (**value).clone_arc(); + } + + Arc::get_mut(value).expect("A value that was just copied has no other owner") +} + // =================== // TRAIT: AnyAttribute // =================== /// Enables type-erased storage for parallel attribute lists in a [`List`]. pub trait AnyAttribute: std::any::Any + Send + Sync { - /// Clones this attribute into a new boxed trait object. - fn clone_box(&self) -> Box; + /// Clones this attribute into a new shared trait object. + fn clone_arc(&self) -> Arc; /// Returns a shared reference to the underlying concrete type for downcasting. fn as_any(&self) -> &dyn std::any::Any; @@ -310,8 +391,11 @@ pub trait AnyAttribute: std::any::Any + Send + Sync { /// Returns a mutable reference to the underlying concrete type for downcasting. fn as_any_mut(&mut self) -> &mut dyn std::any::Any; + /// Converts the shared attribute into one that can be downcast to its concrete type. + fn into_any_arc(self: Arc) -> Arc; + /// Pushes a scalar attribute value onto the end of this attribute. - fn push(&mut self, value: Box); + fn push(&mut self, value: Arc); /// Pushes a default value onto the end of this attribute. fn push_default(&mut self); @@ -325,7 +409,7 @@ pub trait AnyAttribute: std::any::Any + Send + Sync { fn set_at(&mut self, index: usize, value: Box); /// Creates a new attribute of the same type filled with `count` number of default values. - fn new_with_defaults(&self, count: usize) -> Box; + fn new_with_defaults(&self, count: usize) -> Arc; /// Returns the number of elements in this attribute. fn len(&self) -> usize; @@ -336,7 +420,7 @@ pub trait AnyAttribute: std::any::Any + Send + Sync { } /// Appends all values from another attribute of the same type. - fn extend(&mut self, other: Box); + fn extend(&mut self, other: Arc); /// Returns a shared reference to the value at the requested index. fn get_any(&self, index: usize) -> Option<&dyn std::any::Any>; @@ -344,11 +428,11 @@ pub trait AnyAttribute: std::any::Any + Send + Sync { /// Returns a debug-formatted display string for the value at the requested index. fn display_at(&self, index: usize) -> Option; - /// Clones a single value from this attribute into a boxed scalar attribute value. - fn clone_value(&self, index: usize) -> Option>; + /// Clones a single value from this attribute into a shared scalar attribute value. + fn clone_value(&self, index: usize) -> Option>; - /// Drains all values out of this attribute into a Vec of scalar attribute values. - fn drain(self: Box) -> Vec>; + /// Turns this attribute into a Vec of scalar attribute values, moving them out unless clones of its list still share it. + fn drain(self: Arc) -> Vec>; /// Hashes every value in this attribute into the given hasher (object-safe wrapper around `CacheHash`). fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher); @@ -359,21 +443,69 @@ pub trait AnyAttribute: std::any::Any + Send + Sync { } /// Adapts a `&mut dyn Hasher` so generic `CacheHash::cache_hash` calls (which require `H: Sized + Hasher`) can -/// drive a trait-object hasher. Forwards both `Hasher` methods to the inner `dyn Hasher`. -struct DynHasher<'a>(&'a mut dyn core::hash::Hasher); -impl core::hash::Hasher for DynHasher<'_> { - fn finish(&self) -> u64 { - self.0.finish() +/// drive a trait-object hasher. Writes gather in a buffer that reaches the inner hasher whole, when the next write +/// would not fit and when this is dropped, which spares a virtual call for every value hashed. +struct DynHasher<'a> { + inner: &'a mut dyn core::hash::Hasher, + buffer: [u8; DynHasher::CAPACITY], + used: usize, +} + +impl<'a> DynHasher<'a> { + const CAPACITY: usize = 128; + + fn new(inner: &'a mut dyn core::hash::Hasher) -> Self { + Self { + inner, + buffer: [0; Self::CAPACITY], + used: 0, + } } - fn write(&mut self, bytes: &[u8]) { - self.0.write(bytes) + + fn flush(&mut self) { + if let Some(gathered) = self.buffer.get(..self.used).filter(|gathered| !gathered.is_empty()) { + self.inner.write(gathered); + } + self.used = 0; } } -impl Clone for Box { - fn clone(&self) -> Self { - (**self).clone_box() +impl core::hash::Hasher for DynHasher<'_> { + /// Reads the inner hasher's state without the bytes still buffered, which only reach it once this hasher is dropped. + fn finish(&self) -> u64 { + debug_assert_eq!(self.used, 0, "The buffered bytes reach the inner hasher only once this hasher is dropped"); + self.inner.finish() } + + fn write(&mut self, bytes: &[u8]) { + if bytes.len() > Self::CAPACITY - self.used { + self.flush(); + } + + // Anything too long for the buffer passes straight through, in order since the buffer was just emptied + match self.buffer.get_mut(self.used..self.used + bytes.len()) { + Some(space) => { + space.copy_from_slice(bytes); + self.used += bytes.len(); + } + None => self.inner.write(bytes), + } + } +} + +impl Drop for DynHasher<'_> { + fn drop(&mut self) { + self.flush(); + } +} + +/// Gives write access to an attribute, first copying it if clones of its list still share it. +fn unshared(attribute: &mut Arc) -> &mut dyn AnyAttribute { + if Arc::get_mut(attribute).is_none() { + *attribute = (**attribute).clone_arc(); + } + + Arc::get_mut(attribute).expect("An attribute that was just copied has no other owner") } // ============ @@ -384,9 +516,9 @@ impl Clone for Box { pub struct Attribute(pub Vec); impl AnyAttribute for Attribute { - /// Clones this attribute into a new boxed trait object. - fn clone_box(&self) -> Box { - Box::new(Attribute(self.0.clone())) + /// Clones this attribute into a new shared trait object. + fn clone_arc(&self) -> Arc { + Arc::new(Attribute(self.0.clone())) } /// Returns a shared reference to the underlying concrete type for downcasting. @@ -399,14 +531,16 @@ impl self } + /// Converts the shared attribute into one that can be downcast to its concrete type. + fn into_any_arc(self: Arc) -> Arc { + self + } + /// Pushes an attribute value onto the end of this attribute's list, downcasting it to `T`. /// Falls back to a default value if the type doesn't match, to maintain the attribute-length invariant. - fn push(&mut self, value: Box) { - if let Ok(value) = value.into_any().downcast::() { - self.0.push(*value); - } else { - self.0.push(T::default()); - } + fn push(&mut self, value: Arc) { + let value = value.into_any_arc().downcast::().map(Arc::unwrap_or_clone).unwrap_or_default(); + self.0.push(value); } /// Pushes a default `T` value onto the end of this attribute list. @@ -435,8 +569,8 @@ impl } /// Creates a new attribute filled with `count` default `T` values. - fn new_with_defaults(&self, count: usize) -> Box { - Box::new(Attribute(vec![T::default(); count])) + fn new_with_defaults(&self, count: usize) -> Arc { + Arc::new(Attribute(vec![T::default(); count])) } /// Returns the number of elements in this attribute. @@ -446,12 +580,13 @@ impl /// Appends all values from another attribute, downcasting it to the same `Attribute` type. /// Falls back to padding with defaults if the type doesn't match, to maintain the attribute-length invariant. - fn extend(&mut self, other: Box) { + fn extend(&mut self, other: Arc) { let other_len = other.len(); - if let Ok(other) = (other as Box).downcast::() { - self.0.extend(other.0); - } else { - self.0.extend(std::iter::repeat_with(T::default).take(other_len)); + + match other.into_any_arc().downcast::().map(Arc::try_unwrap) { + Ok(Ok(other)) => self.0.extend(other.0), + Ok(Err(shared)) => self.0.extend_from_slice(&shared.0), + Err(_) => self.0.extend(std::iter::repeat_with(T::default).take(other_len)), } } @@ -465,19 +600,24 @@ impl self.0.get(index).map(|v| format!("{v:?}")) } - /// Clones the value at the given index into a boxed scalar attribute value. - fn clone_value(&self, index: usize) -> Option> { - self.0.get(index).map(|v| Box::new(v.clone()) as Box) + /// Clones the value at the given index into a shared scalar attribute value. + fn clone_value(&self, index: usize) -> Option> { + self.0.get(index).map(|v| Arc::new(v.clone()) as Arc) } - /// Consumes this attribute and returns all values as a Vec of boxed scalar attribute values. - fn drain(self: Box) -> Vec> { - self.0.into_iter().map(|v| Box::new(v) as Box).collect() + /// Returns all values as a Vec of shared scalar attribute values, moved out unless clones of the list still share them. + fn drain(self: Arc) -> Vec> { + let values = match Arc::try_unwrap(self) { + Ok(attribute) => attribute.0, + Err(shared) => shared.0.clone(), + }; + + values.into_iter().map(|v| Arc::new(v) as Arc).collect() } /// Hashes every value in this attribute into the given hasher (object-safe wrapper around `CacheHash`). fn cache_hash_dyn(&self, state: &mut dyn core::hash::Hasher) { - self.0.cache_hash(&mut DynHasher(state)); + self.0.cache_hash(&mut DynHasher::new(state)); } /// Compares this attribute to another for value-by-value equality (object-safe wrapper around `PartialEq`). @@ -535,75 +675,51 @@ unsafe impl StaticType for AttributeValueDyn { /// Type-erased view of a `List` exposing only its attributes and item count, used as a node graph parameter type. /// Lets a node accept any `List` source via the auto-inserted `Convert` without monomorphizing over `U`, /// for cases where the element type is irrelevant (such as nodes that read out a named attribute regardless of the carrier `List`). -#[derive(Default)] +#[derive(Clone, Default)] pub struct ListDyn { - attributes: Vec<(String, Box)>, - len: usize, + attributes: Attributes, } impl ListDyn { /// Number of items in the underlying `List`. pub fn len(&self) -> usize { - self.len + self.attributes.len } /// Whether the underlying `List` has zero items. pub fn is_empty(&self) -> bool { - self.len == 0 + self.attributes.len == 0 } /// Returns a reference to the attribute value at the given key and item index, downcast to `U`, if present and matching. pub fn attribute(&self, key: &str, index: usize) -> Option<&U> { - self.attributes - .iter() - .find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::() } else { None }) + self.attributes.get_value(key, index) } } impl From> for ListDyn { fn from(list: List) -> Self { - Self { - attributes: list.attributes.attributes, - len: list.attributes.len, - } - } -} - -impl Clone for ListDyn { - fn clone(&self) -> Self { - Self { - attributes: self.attributes.iter().map(|(key, attribute)| (key.clone(), attribute.clone_box())).collect(), - len: self.len, - } + Self { attributes: list.attributes } } } impl Debug for ListDyn { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let keys: Vec<&str> = self.attributes.iter().map(|(k, _)| k.as_str()).collect(); - f.debug_struct("ListDyn").field("keys", &keys).field("len", &self.len).finish() + let keys: Vec<&str> = self.attributes.keys().collect(); + f.debug_struct("ListDyn").field("keys", &keys).field("len", &self.attributes.len).finish() } } impl PartialEq for ListDyn { fn eq(&self, other: &Self) -> bool { - self.len == other.len - && self.attributes.len() == other.attributes.len() - && self - .attributes - .iter() - .zip(&other.attributes) - .all(|((key_a, attribute_a), (key_b, attribute_b))| key_a == key_b && attribute_a.eq_dyn(&**attribute_b)) + self.attributes.len == other.attributes.len && self.attributes.equals(&other.attributes) } } impl CacheHash for ListDyn { fn cache_hash(&self, state: &mut H) { - self.len.cache_hash(state); - for (key, attribute) in &self.attributes { - key.cache_hash(state); - attribute.cache_hash_dyn(state); - } + self.attributes.len.cache_hash(state); + self.attributes.cache_hash_entries(state); } } @@ -611,32 +727,59 @@ unsafe impl StaticType for ListDyn { type Static = Self; } +// ====== +// Shared +// ====== + +/// A handle on an attribute value that an item also holds, for reading it without copying it. It is not an +/// attribute value itself, so it cannot be stored back onto an item in place of the value it reads. +pub struct Shared(Arc); + +impl std::ops::Deref for Shared { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl From> for Shared { + fn from(value: Arc) -> Self { + Self(value) + } +} + // =================== // ItemAttributeValues // =================== +/// An item's attribute values with their keys, in insertion order. +type ValueEntries = Vec<(AttributeKey, Arc)>; + /// Scalar attribute storage for a single item. /// /// A small ordered map of type-erased scalar attribute values, keyed by string name. /// Used for individual attribute values in an [`Item`]. /// Linear search preserves insertion order and is likely faster than a HashMap for small attribute counts. +/// Clones share the map and every value in it until one of them is written to. #[derive(Clone, Default)] -pub struct ItemAttributeValues(Vec<(String, Box)>); +pub struct ItemAttributeValues(Option>); impl Debug for ItemAttributeValues { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let keys: Vec<&str> = self.0.iter().map(|(k, _)| k.as_str()).collect(); + let keys: Vec<&str> = self.keys().collect(); f.debug_struct("Attributes").field("keys", &keys).finish() } } impl PartialEq for ItemAttributeValues { fn eq(&self, other: &Self) -> bool { - self.0.len() == other.0.len() - && self - .0 + let (entries, other_entries) = (self.entries(), other.entries()); + + entries.len() == other_entries.len() + && entries .iter() - .zip(&other.0) + .zip(other_entries) .all(|((self_key, self_value), (other_key, other_value))| self_key == other_key && self_value.eq_dyn(other_value.as_ref())) } } @@ -647,86 +790,121 @@ impl ItemAttributeValues { Self::default() } + fn from_entries(entries: ValueEntries) -> Self { + Self((!entries.is_empty()).then(|| Arc::new(entries))) + } + + fn into_entries(self) -> ValueEntries { + self.0.map(Arc::unwrap_or_clone).unwrap_or_default() + } + + fn entries(&self) -> &[(AttributeKey, Arc)] { + self.0.as_deref().map_or(&[], Vec::as_slice) + } + + /// The entries for writing, which copies the map first if clones of the item still share it. + fn entries_mut(&mut self) -> &mut ValueEntries { + Arc::make_mut(self.0.get_or_insert_default()) + } + + fn position(&self, key: &str) -> Option { + self.entries().iter().position(|(existing_key, _)| existing_key.is(key)) + } + /// Inserts an attribute with the given key and value, replacing any existing entry with the same key. - pub fn insert(&mut self, key: impl Into, value: T) { - let key = key.into(); + pub fn insert(&mut self, key: impl AsRef, value: T) { + let key = key.as_ref(); + let value: Arc = Arc::new(value); - for (existing_key, existing_value) in &mut self.0 { - if *existing_key == key { - *existing_value = Box::new(value); - return; - } + let position = self.position(key); + let entries = self.entries_mut(); + match position.and_then(|position| entries.get_mut(position)) { + Some((_, existing_value)) => *existing_value = value, + None => entries.push((AttributeKey::new(key), value)), } - - self.0.push((key, Box::new(value))); } /// Gets a reference to the value of the attribute with the given key, if it exists and can be downcast to the requested type. pub fn get(&self, key: &str) -> Option<&T> { - // Explicit deref `(**value)` reaches `dyn AttributeValue` (which is !Sized and thus dispatches - // through the vtable to the concrete type) rather than resolving to the blanket - // `impl AttributeValue for Box` which would return the wrong TypeId. - self.0 + self.entries() .iter() - .find_map(|(existing_key, value)| if existing_key == key { (**value).as_any().downcast_ref::() } else { None }) + .find_map(|(existing_key, value)| if existing_key.is(key) { (**value).as_any().downcast_ref::() } else { None }) + } + + /// Gets a shared handle to the value of the attribute with the given key, if it exists and can be downcast to the requested type. + pub fn get_shared(&self, key: &str) -> Option> { + let (_, value) = self.entries().iter().find(|(existing_key, _)| existing_key.is(key))?; + + value.clone().into_any_arc().downcast::().ok().map(Shared) } /// Gets a mutable reference to the value of the attribute with the given key, if it exists and can be downcast to the requested type. pub fn get_mut(&mut self, key: &str) -> Option<&mut T> { - self.0 - .iter_mut() - .find_map(|(existing_key, value)| if existing_key == key { (**value).as_any_mut().downcast_mut::() } else { None }) + // Checked before anything is unshared, so a miss leaves the values shared + let position = self.entries().iter().position(|(existing_key, value)| existing_key.is(key) && (**value).as_any().is::())?; + let (_, value) = self.entries_mut().get_mut(position)?; + + unshared_value(value).as_any_mut().downcast_mut::() } /// Gets a mutable reference to the value, inserting a default if it doesn't exist or has the wrong type. pub fn get_or_insert_default_mut(&mut self, key: &str) -> &mut T { - let needs_insert = match self.0.iter().position(|(existing_key, _)| existing_key == key) { - Some(index) => { - if (*self.0[index].1).as_any().downcast_ref::().is_some() { - false - } else { - self.0.remove(index); - true - } - } - None => true, - }; + let position = self.position(key); + let has_type = position.and_then(|position| self.entries().get(position)).is_some_and(|(_, value)| (**value).as_any().is::()); - if needs_insert { - self.0.push((key.to_string(), Box::new(T::default()))); + if !has_type { + let entries = self.entries_mut(); + if let Some(position) = position { + entries.remove(position); + } + entries.push((AttributeKey::new(key), Arc::new(T::default()))); } self.get_mut::(key).expect("Attribute was just ensured to exist with correct type") } /// Removes and returns the value for the given key, if it exists and can be downcast to the requested type. - pub fn remove(&mut self, key: &str) -> Option { - let index = self.0.iter().position(|(existing_key, _)| existing_key == key)?; - let (_, value) = self.0.remove(index); - value.into_any().downcast::().ok().map(|boxed| *boxed) + pub fn remove(&mut self, key: &str) -> Option { + let position = self.position(key)?; + let (_, mut value) = self.entries_mut().remove(position); + if !(*value).as_any().is::() { + return None; + } + + // A value that clones of the item still share is copied, since it can only be moved out of its last owner + if Arc::get_mut(&mut value).is_none() { + value = (*value).clone_arc(); + } + Arc::try_unwrap(value.into_any_arc().downcast::().ok()?).ok() } /// Returns an iterator over the keys of all stored attributes, in insertion order. pub fn keys(&self) -> impl Iterator { - self.0.iter().map(|(key, _)| key.as_str()) + self.entries().iter().map(|(key, _)| key.as_str()) } /// Returns a type-erased reference to the value of the attribute with the given key, if it exists. pub fn get_any(&self, key: &str) -> Option<&dyn std::any::Any> { - self.0.iter().find_map(|(existing_key, value)| if existing_key == key { Some((**value).as_any()) } else { None }) + self.entries() + .iter() + .find_map(|(existing_key, value)| if existing_key.is(key) { Some((**value).as_any()) } else { None }) } /// Returns an iterator over key and type-erased value pairs of all stored attributes, in insertion order. pub fn iter_any(&self) -> impl Iterator { - self.0.iter().map(|(key, value)| (key.as_str(), (**value).as_any())) + self.entries().iter().map(|(key, value)| (key.as_str(), (**value).as_any())) } /// Returns a debug-formatted string representation of the attribute value for the given key, if it exists. /// The `overrides` function can provide custom formatting for specific type. pub fn display_value(&self, key: &str, overrides: fn(&dyn std::any::Any) -> Option) -> Option { - self.0.iter().find_map(|(k, value)| { - if k == key { - if let Some(text) = overrides(value.as_any()) { Some(text) } else { Some(value.display_string()) } + self.entries().iter().find_map(|(k, value)| { + if k.is(key) { + if let Some(text) = overrides((**value).as_any()) { + Some(text) + } else { + Some(value.display_string()) + } } else { None } @@ -735,32 +913,30 @@ impl ItemAttributeValues { /// Moves the attribute at `from_key` to `to_key`. /// Does nothing if `from_key` is absent, overwrites any existing `to_key`. - pub fn rename(&mut self, from_key: &str, to_key: impl Into) { - let Some(pos) = self.0.iter().position(|(k, _)| k == from_key) else { return }; - let (_, value) = self.0.remove(pos); + pub fn rename(&mut self, from_key: &str, to_key: impl AsRef) { + let Some(position) = self.position(from_key) else { return }; + let entries = self.entries_mut(); + let (_, value) = entries.remove(position); - let to_key = to_key.into(); - for (existing_key, existing_value) in &mut self.0 { - if *existing_key == to_key { - *existing_value = value; - return; - } + let to_key = to_key.as_ref(); + match entries.iter_mut().find(|(existing_key, _)| existing_key.is(to_key)) { + Some((_, existing_value)) => *existing_value = value, + None => entries.push((AttributeKey::new(to_key), value)), } - self.0.push((to_key, value)); } /// Clones the attribute with `key` from `source`, replacing any existing attribute with the same key. pub fn insert_cloned_from(&mut self, source: &Self, key: &str) { - let Some((_, value)) = source.0.iter().find(|(existing_key, _)| existing_key == key) else { + let Some((_, value)) = source.entries().iter().find(|(existing_key, _)| existing_key.is(key)) else { return; }; let value = value.clone(); - if let Some((_, existing_value)) = self.0.iter_mut().find(|(existing_key, _)| existing_key == key) { - *existing_value = value; - } else { - self.0.push((key.to_string(), value)); + let entries = self.entries_mut(); + match entries.iter_mut().find(|(existing_key, _)| existing_key.is(key)) { + Some((_, existing_value)) => *existing_value = value, + None => entries.push((AttributeKey::new(key), value)), } } } @@ -769,20 +945,94 @@ impl ItemAttributeValues { // Attributes // ========== +/// One of a list's attributes with its key. +type AttributeEntry = (AttributeKey, Arc); + +/// A list's attributes with their keys, in insertion order. A lone attribute is held inline, so the many small lists +/// carrying just one need no collection of their own. +#[derive(Clone, Default)] +enum AttributeEntries { + #[default] + None, + One(AttributeEntry), + Many(Arc>), +} + +impl AttributeEntries { + fn as_slice(&self) -> &[AttributeEntry] { + match self { + Self::None => &[], + Self::One(entry) => std::slice::from_ref(entry), + Self::Many(entries) => entries, + } + } + + /// The entries for writing in place, which copies the collection first if clones of the list still share it. + fn as_mut_slice(&mut self) -> &mut [AttributeEntry] { + match self { + Self::None => &mut [], + Self::One(entry) => std::slice::from_mut(entry), + Self::Many(entries) => Arc::make_mut(entries).as_mut_slice(), + } + } + + fn is_empty(&self) -> bool { + self.as_slice().is_empty() + } + + fn push(&mut self, entry: AttributeEntry) { + *self = match std::mem::take(self) { + Self::None => Self::One(entry), + Self::One(first) => { + let mut entries = Vec::with_capacity(4); + entries.extend([first, entry]); + Self::Many(Arc::new(entries)) + } + Self::Many(mut entries) => { + Arc::make_mut(&mut entries).push(entry); + Self::Many(entries) + } + }; + } + + /// Takes out the entry at `position`, doing nothing when there is none there. + fn remove(&mut self, position: usize) { + *self = match std::mem::take(self) { + // What is left of one or two entries is nothing or a lone entry again, neither of which needs the collection + Self::Many(entries) if position < entries.len() && entries.len() <= 2 => entries.get(1 - position).cloned().map_or(Self::None, Self::One), + Self::Many(mut entries) if position < entries.len() => { + Arc::make_mut(&mut entries).remove(position); + Self::Many(entries) + } + Self::One(_) if position == 0 => Self::None, + unchanged => unchanged, + }; + } + + fn into_vec(self) -> Vec { + match self { + Self::None => Vec::new(), + Self::One(entry) => vec![entry], + Self::Many(entries) => Arc::unwrap_or_clone(entries), + } + } +} + /// The storage data structure for attributes. /// /// A collection of type-erased parallel attributes, keyed by string name. /// All access goes through [`List`] and [`Item`] since internals are private. +/// Clones share every attribute until one of them is written to. /// Invariant: every attribute in `attributes` has exactly `len` elements. #[derive(Clone, Default)] struct Attributes { - attributes: Vec<(String, Box)>, + attributes: AttributeEntries, len: usize, } impl Debug for Attributes { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let keys: Vec<&str> = self.attributes.iter().map(|(k, _)| k.as_str()).collect(); + let keys: Vec<&str> = self.keys().collect(); f.debug_struct("Attributes").field("keys", &keys).field("len", &self.len).finish() } } @@ -795,141 +1045,195 @@ impl Attributes { /// Creates an empty attribute store with no attributes but a pre-set item count. fn with_len(len: usize) -> Self { - Self { attributes: Vec::new(), len } + Self { + attributes: AttributeEntries::None, + len, + } + } + + fn entries(&self) -> &[AttributeEntry] { + self.attributes.as_slice() + } + + fn position(&self, key: &str) -> Option { + self.entries().iter().position(|(existing_key, _)| existing_key.is(key)) + } + + /// The position of the attribute for the given key, if it exists and holds values of type `T`. + fn typed_position(&self, key: &str) -> Option { + self.entries() + .iter() + .position(|(existing_key, attribute)| existing_key.is(key) && (**attribute).as_any().is::>()) + } + + /// The values of the attribute at `position` for writing, if it holds values of type `T`. + fn values_mut(&mut self, position: usize) -> Option<&mut Vec> { + let (_, attribute) = self.attributes.as_mut_slice().get_mut(position)?; + + unshared(attribute).as_any_mut().downcast_mut::>().map(|attribute| &mut attribute.0) } /// Pushes an item's scalar attributes into this attribute store. /// Existing attributes that the item lacks receive a default value. /// New attribute keys create a new attribute padded with defaults for all prior items. fn push_item(&mut self, item: ItemAttributeValues) { - let mut item_entries = item.0; + let len = self.len; + self.len += 1; + + if self.attributes.is_empty() && item.0.is_none() { + return; + } + + let mut item_entries = item.into_entries(); // Push values into existing attributes, or the implicit default if the item lacks that attribute - for (attribute_key, attribute) in &mut self.attributes { - if let Some(position) = item_entries.iter().position(|(k, _)| k == attribute_key) { - let (_, value) = item_entries.swap_remove(position); - attribute.push(value); - } else { - pad_with_implicit_default(attribute_key, attribute, 1); + for (attribute_key, attribute) in self.attributes.as_mut_slice() { + let attribute = unshared(attribute); + + match item_entries.iter().position(|(key, _)| key == attribute_key) { + Some(position) => attribute.push(item_entries.swap_remove(position).1), + None => pad_with_implicit_default(attribute_key.as_str(), attribute, 1), } } // Create new attributes for any remaining item values, padded with implicit defaults for prior items for (key, value) in item_entries { - self.attributes.push((key.clone(), value.into_attribute(&key, self.len))); + let attribute = value.into_attribute(key.as_str(), len); + self.attributes.push((key, attribute)); } - - self.len += 1; } /// Appends all attribute data from another attribute store into this one. /// Attributes present in only one side are padded with defaults for the other side's items. fn extend(&mut self, other: Attributes) { - let other_len = other.len; - let mut other_entries = other.attributes; + let (len, other_len) = (self.len, other.len); + self.len += other_len; + + // An empty store takes on the other's attributes whole, sharing them + if len == 0 && self.entries().is_empty() { + self.attributes = other.attributes; + return; + } + // Nothing to add or pad, so self's attributes can stay shared + if other.attributes.is_empty() && (other_len == 0 || self.attributes.is_empty()) { + return; + } + + let mut other_entries = other.attributes.into_vec(); // Extend matching attributes, or pad self's attributes with implicit defaults for the other's item count - for (key, self_attribute) in &mut self.attributes { - if let Some(position) = other_entries.iter().position(|(k, _)| k == key) { - let (_, other_attribute) = other_entries.swap_remove(position); - self_attribute.extend(other_attribute); - } else { - pad_with_implicit_default(key, self_attribute, other_len); + for (key, self_attribute) in self.attributes.as_mut_slice() { + let self_attribute = unshared(self_attribute); + + match other_entries.iter().position(|(other_key, _)| other_key == key) { + Some(position) => self_attribute.extend(other_entries.swap_remove(position).1), + None => pad_with_implicit_default(key.as_str(), self_attribute, other_len), } } // Remaining other attributes are new, so we pad with implicit defaults for self's existing items for (key, other_attribute) in other_entries { let mut combined = other_attribute.new_with_defaults(0); - pad_with_implicit_default(&key, &mut combined, self.len); - combined.extend(other_attribute); + let writable = unshared(&mut combined); + pad_with_implicit_default(key.as_str(), writable, len); + writable.extend(other_attribute); + self.attributes.push((key, combined)); } - - self.len += other_len; } /// Gets a reference to the value at the given index from the attribute for the given key. fn get_value(&self, key: &str, index: usize) -> Option<&T> { - self.attributes + self.entries() .iter() - .find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::() } else { None }) + .find_map(|(k, attribute)| if k.is(key) { attribute.get_any(index)?.downcast_ref::() } else { None }) } /// Removes the entire attribute for the given key, if present. fn remove_attribute(&mut self, key: &str) { - if let Some(position) = self.attributes.iter().position(|(k, _)| k == key) { + if let Some(position) = self.position(key) { self.attributes.remove(position); } } /// Creates a new attribute of type `T` filled with `key`'s implicit default for all existing items. - fn new_attribute_padded(&self, key: &str) -> Box { - let mut attribute: Box = Box::new(Attribute::(Vec::with_capacity(self.len))); + fn new_attribute_padded(&self, key: &str) -> Arc { + let mut attribute = Attribute::(Vec::with_capacity(self.len)); pad_with_implicit_default(key, &mut attribute, self.len); - attribute + + Arc::new(attribute) } /// Finds or creates an attribute for the given key and type, returning its position. /// If an attribute with the key exists but has the wrong type, it is removed and replaced with a new attribute of the correct type, padded with implicit defaults. /// A newly created attribute is filled with `key`'s implicit default for all existing items. fn find_or_create_attribute(&mut self, key: &str) -> usize { - match self.attributes.iter().position(|(k, _)| k == key) { - Some(position) => { - if (*self.attributes[position].1).as_any().downcast_ref::>().is_some() { - position - } else { - self.attributes.remove(position); - let attribute = self.new_attribute_padded::(key); - self.attributes.push((key.to_string(), attribute)); - self.attributes.len() - 1 - } - } - None => { - let attribute = self.new_attribute_padded::(key); - self.attributes.push((key.to_string(), attribute)); - self.attributes.len() - 1 - } + if let Some(position) = self.typed_position::(key) { + return position; } + + let mistyped = self.position(key); + let attribute = self.new_attribute_padded::(key); + + if let Some(position) = mistyped { + self.attributes.remove(position); + } + self.attributes.push((AttributeKey::new(key), attribute)); + + self.entries().len() - 1 } /// Gets a mutable reference to the value at the given index, creating the attribute if it doesn't exist or has the wrong type. fn get_or_insert_default_value(&mut self, key: &str, index: usize) -> &mut T { let attribute_position = self.find_or_create_attribute::(key); - let attribute = (*self.attributes[attribute_position].1).as_any_mut().downcast_mut::>().unwrap(); - &mut attribute.0[index] + let values = self.values_mut::(attribute_position).unwrap(); + &mut values[index] } /// Sets the value at the given index in the attribute for the given key. /// Creates the attribute with defaults if it doesn't exist. - fn set_value(&mut self, key: impl Into, index: usize, value: T) { - let key = key.into(); - let attribute_position = self.find_or_create_attribute::(&key); - let attribute = (*self.attributes[attribute_position].1).as_any_mut().downcast_mut::>().unwrap(); - attribute.0[index] = value; + fn set_value(&mut self, key: &str, index: usize, value: T) { + let attribute_position = self.find_or_create_attribute::(key); + let values = self.values_mut::(attribute_position).unwrap(); + values[index] = value; } /// Replaces the attribute for the given key with one value per item, keeping its place unless its type changes. - fn set_attribute_values(&mut self, key: String, values: Vec) { + fn set_attribute_values(&mut self, key: &str, values: Vec) { // An attribute changing type moves to the end, as it does when set one value at a time - let existing = self.attributes.iter().position(|(k, _)| k == &key); - let same_type = existing.is_some_and(|position| (*self.attributes[position].1).as_any().downcast_ref::>().is_some()); + let (existing, same_type) = (self.position(key), self.typed_position::(key).is_some()); - let attribute: Box = Box::new(Attribute(values)); - match existing { - Some(position) if same_type => self.attributes[position].1 = attribute, - Some(position) => { - self.attributes.remove(position); - self.attributes.push((key, attribute)); - } - None => self.attributes.push((key, attribute)), + let attribute: Arc = Arc::new(Attribute(values)); + if same_type && let Some((_, existing_attribute)) = existing.and_then(|position| self.attributes.as_mut_slice().get_mut(position)) { + *existing_attribute = attribute; + return; + } + + if let Some(position) = existing { + self.attributes.remove(position); + } + self.attributes.push((AttributeKey::new(key), attribute)); + } + + /// Sets a single type-erased value at the given index of a list of `item_count` items, creating the attribute from the + /// value's type if the key holds none. + fn set_value_dyn(&mut self, key: &str, index: usize, value: Box, item_count: usize) { + let position = self.position(key); + + if let Some((_, attribute)) = position.and_then(|position| self.attributes.as_mut_slice().get_mut(position)) { + unshared(attribute).set_at(index, value); + } else { + let mut new_attribute = Arc::::from(value).into_attribute(key, index); + let trailing_defaults = item_count.saturating_sub(new_attribute.len()); + pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults); + self.attributes.push((AttributeKey::new(key), new_attribute)); } } /// Returns a debug-formatted string for the value at the given index in the attribute for the given key. fn display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option) -> Option { - self.attributes.iter().find_map(|(k, attribute)| { - if k == key { + self.entries().iter().find_map(|(k, attribute)| { + if k.is(key) { if let Some(value) = attribute.get_any(index) && let Some(text) = overrides(value) { @@ -944,19 +1248,19 @@ impl Attributes { /// Returns a type-erased reference to the value at the given index in the attribute for the given key. fn get_any_value(&self, key: &str, index: usize) -> Option<&dyn std::any::Any> { - self.attributes.iter().find_map(|(k, attribute)| if k == key { attribute.get_any(index) } else { None }) + self.entries().iter().find_map(|(k, attribute)| if k.is(key) { attribute.get_any(index) } else { None }) } /// Returns an iterator over the keys of all stored attributes (in insertion order). fn keys(&self) -> impl Iterator { - self.attributes.iter().map(|(key, _)| key.as_str()) + self.entries().iter().map(|(key, _)| key.as_str()) } /// Returns a typed slice of the attribute for the given key, if it exists and can be downcast to `Attribute`. fn get_attribute_slice(&self, key: &str) -> Option<&[T]> { - self.attributes.iter().find_map(|(k, attribute)| { - if k == key { - attribute.as_any().downcast_ref::>().map(|c| c.0.as_slice()) + self.entries().iter().find_map(|(k, attribute)| { + if k.is(key) { + (**attribute).as_any().downcast_ref::>().map(|c| c.0.as_slice()) } else { None } @@ -965,46 +1269,56 @@ impl Attributes { /// Returns a mutable typed slice of the attribute for the given key, if it exists and can be downcast to `Attribute`. fn get_attribute_slice_mut(&mut self, key: &str) -> Option<&mut [T]> { - self.attributes.iter_mut().find_map(|(k, attribute)| { - if k == key { - attribute.as_any_mut().downcast_mut::>().map(|c| c.0.as_mut_slice()) - } else { - None - } - }) + // Checked before anything is unshared, so a miss leaves the attributes shared + let position = self.typed_position::(key)?; + + self.values_mut::(position).map(Vec::as_mut_slice) } /// Returns a mutable typed slice of the attribute for the given key, creating a new attribute filled with defaults if it doesn't exist. fn get_or_create_attribute_slice_mut(&mut self, key: &str) -> &mut [T] { let position = self.find_or_create_attribute::(key); - let attribute = (*self.attributes[position].1).as_any_mut().downcast_mut::>().unwrap(); - &mut attribute.0 + self.values_mut::(position).unwrap() } /// Clones all attribute values at the given item index into a new scalar Attributes. fn clone_item(&self, index: usize) -> ItemAttributeValues { - let mut attributes = ItemAttributeValues::new(); + let entries = self.entries().iter().filter_map(|(key, attribute)| Some((key.clone(), attribute.clone_value(index)?))); - for (key, attribute) in &self.attributes { - if let Some(value) = attribute.clone_value(index) { - attributes.0.push((key.clone(), value)); - } - } - - attributes + ItemAttributeValues::from_entries(entries.collect()) } /// Drains all attribute data into a Vec of per-item scalar Attributes. fn into_item_vec(self) -> Vec { - let mut items: Vec = (0..self.len).map(|_| ItemAttributeValues::new()).collect(); + let attributes = self.attributes.into_vec(); + let mut items: Vec> = (0..self.len).map(|_| Vec::with_capacity(attributes.len())).collect(); - for (key, attribute) in self.attributes { - for (i, value) in attribute.drain().into_iter().enumerate() { - items[i].0.push((key.clone(), value)); + for (key, attribute) in attributes { + for (item, value) in items.iter_mut().zip(attribute.drain()) { + item.push((key.clone(), value)); } } - items + items.into_iter().map(ItemAttributeValues::from_entries).collect() + } + + /// Whether both stores hold the same attributes in the same order with equal values. + fn equals(&self, other: &Self) -> bool { + let (entries, other_entries) = (self.entries(), other.entries()); + + entries.len() == other_entries.len() + && entries + .iter() + .zip(other_entries) + .all(|((self_key, self_attribute), (other_key, other_attribute))| self_key == other_key && self_attribute.eq_dyn(other_attribute.as_ref())) + } + + /// Hashes every attribute's key and values. + fn cache_hash_entries(&self, state: &mut H) { + for (key, attribute) in self.entries() { + std::hash::Hash::hash(key.as_str(), state); + attribute.cache_hash_dyn(state); + } } } @@ -1111,7 +1425,7 @@ impl List { self.attributes.get_attribute_slice::(key).map(|s| s.iter()) } - /// Returns an iterator over mutable references to the values of a typed attribute attribute, or `None` if the attribute doesn't exist or has the wrong type. + /// Returns an iterator over mutable references to the values of a typed attribute, or `None` if the attribute doesn't exist or has the wrong type. pub fn iter_attribute_values_mut(&mut self, key: &str) -> Option> { self.attributes.get_attribute_slice_mut::(key).map(|s| s.iter_mut()) } @@ -1162,14 +1476,14 @@ impl List { } /// Sets the attribute value at the given item index and key, creating the attribute with defaults if it doesn't exist. - pub fn set_attribute(&mut self, key: impl Into, index: usize, value: U) { - self.attributes.set_value(key, index, value); + pub fn set_attribute(&mut self, key: impl AsRef, index: usize, value: U) { + self.attributes.set_value(key.as_ref(), index, value); } /// Sets the attribute's value for every item at once from one value per item, replacing any values the key held (an empty list still gains the key). /// Logs an error and leaves the list unchanged if the number of values differs from the number of items. - pub fn set_attribute_values(&mut self, key: impl Into, values: Vec) { - let key = key.into(); + pub fn set_attribute_values(&mut self, key: impl AsRef, values: Vec) { + let key = key.as_ref(); if values.len() != self.element.len() { log::error!("Attribute '{key}' was given {} values for a list of {} items", values.len(), self.element.len()); return; @@ -1180,16 +1494,8 @@ impl List { /// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length). /// Falls back to default if the value's type doesn't match an existing attribute. - pub fn set_attribute_value_dyn(&mut self, key: impl Into, index: usize, value: AttributeValueDyn) { - let key = key.into(); - if let Some(position) = self.attributes.attributes.iter().position(|(k, _)| k == &key) { - self.attributes.attributes[position].1.set_at(index, value.0); - } else { - let mut new_attribute = value.0.into_attribute(&key, index); - let trailing_defaults = self.element.len().saturating_sub(new_attribute.len()); - pad_with_implicit_default(&key, &mut new_attribute, trailing_defaults); - self.attributes.attributes.push((key, new_attribute)); - } + pub fn set_attribute_value_dyn(&mut self, key: impl AsRef, index: usize, value: AttributeValueDyn) { + self.attributes.set_value_dyn(key.as_ref(), index, value.0, self.element.len()); } /// Removes the entire attribute for the given key, if present. @@ -1221,9 +1527,7 @@ impl List { /// This enables simultaneous mutable access to elements and a single attribute without borrowing conflicts. pub fn element_and_attribute_slices_mut(&mut self, key: &str) -> (&mut [T], &mut [U]) { let Self { element, attributes } = self; - let attribute_position = attributes.find_or_create_attribute::(key); - let attribute = (*attributes.attributes[attribute_position].1).as_any_mut().downcast_mut::>().unwrap(); - (element.as_mut_slice(), &mut attribute.0) + (element.as_mut_slice(), attributes.get_or_create_attribute_slice_mut::(key)) } // ================== @@ -1320,26 +1624,16 @@ impl CacheHash for List { fn cache_hash(&self, state: &mut H) { self.element.cache_hash(state); - // Hash every attribute attribute (key + values) rather than just the well-known ones, so changes to user-defined keys + // Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys // (e.g., gradient_form, gradient_spread) invalidate downstream graph caches as expected - for (key, attribute) in &self.attributes.attributes { - std::hash::Hash::hash(key.as_str(), state); - attribute.cache_hash_dyn(state); - } + self.attributes.cache_hash_entries(state); } } impl PartialEq for List { fn eq(&self, other: &Self) -> bool { // Attributes participate in equality so the `a == b` ⇒ `hash(a) == hash(b)` contract holds with `cache_hash` - self.element == other.element - && self.attributes.attributes.len() == other.attributes.attributes.len() - && self - .attributes - .attributes - .iter() - .zip(&other.attributes.attributes) - .all(|((self_key, self_attribute), (other_key, other_attribute))| self_key == other_key && self_attribute.eq_dyn(other_attribute.as_ref())) + self.element == other.element && self.attributes.equals(&other.attributes) } } @@ -1415,7 +1709,7 @@ impl CacheHash for Item { self.element.cache_hash(state); // Hash every attribute (key + value) so attribute changes invalidate downstream caches, mirroring `List` - for (key, attribute) in &self.attributes.0 { + for (key, attribute) in self.attributes.entries() { std::hash::Hash::hash(key.as_str(), state); attribute.cache_hash_dyn(state); } @@ -1468,6 +1762,13 @@ impl Item { self.attributes.get(key) } + /// Returns a shared handle to the attribute value for the given key, if it exists and is of the requested type. + /// The handle goes on reading the value without copying it, whatever then happens to the item. Writing or removing + /// the item's value while a handle is held copies the value first, so a handle is best dropped before then. + pub fn attribute_shared(&self, key: &str) -> Option> { + self.attributes.get_shared(key) + } + /// Returns the attribute value for the given key, or the provided default if absent or of a different type. pub fn attribute_or<'a, U: 'static>(&'a self, key: &str, default: &'a U) -> &'a U { self.attribute(key).unwrap_or(default) @@ -1494,18 +1795,18 @@ impl Item { } /// Sets the attribute value for the given key, replacing any existing entry with the same key. - pub fn set_attribute(&mut self, key: impl Into, value: U) { + pub fn set_attribute(&mut self, key: impl AsRef, value: U) { self.attributes.insert(key, value); } /// Sets the attribute value for the given key and returns the item, enabling builder-style chaining. - pub fn with_attribute(mut self, key: impl Into, value: U) -> Self { + pub fn with_attribute(mut self, key: impl AsRef, value: U) -> Self { self.set_attribute(key, value); self } /// Removes and returns the attribute value for the given key, if it exists and is of the requested type. - pub fn remove_attribute(&mut self, key: &str) -> Option { + pub fn remove_attribute(&mut self, key: &str) -> Option { self.attributes.remove(key) } } @@ -1640,4 +1941,183 @@ mod tests { assert_eq!(list.attribute_keys().collect::>(), [ATTR_END, ATTR_START]); assert_eq!(list, one_at_a_time); } + + fn hash_of(value: &T) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + value.cache_hash(&mut hasher); + core::hash::Hasher::finish(&hasher) + } + + // Attribute values are hashed through a buffer, which must not let a change slip by wherever it falls + #[test] + fn attribute_values_all_reach_the_hash() { + let build = |changed: Option| { + let mut list = List::new_from_elements(vec![0_u8; 300]); + let mut values: Vec = (0..300).collect(); + if let Some(index) = changed { + values[index] += 1; + } + list.set_attribute_values(ATTR_START, values); + list.set_attribute_values(ATTR_NAME, vec![String::from("a string long enough to pass straight through the buffer when repeated").repeat(3); 300]); + list + }; + + let hash = hash_of(&build(None)); + assert_eq!(hash, hash_of(&build(None))); + for index in [0, 15, 16, 17, 127, 128, 299] { + assert_ne!(hash, hash_of(&build(Some(index))), "a change at {index} went unnoticed"); + } + } + + /// Keeps every byte it is given, in order, so a buffered stream can be checked against what went into it. + #[derive(Default)] + struct RecordingHasher(Vec); + + impl core::hash::Hasher for RecordingHasher { + fn finish(&self) -> u64 { + 0 + } + + fn write(&mut self, bytes: &[u8]) { + self.0.extend_from_slice(bytes); + } + } + + // Writes of every length pass through the buffer whole and in order, also from a value hashing through a buffer of its own + #[test] + fn buffered_writes_reach_the_inner_hasher_in_order() { + use core::hash::Hasher; + + let lengths = [3, 125, 1, 200, 0, 128, 64, 65, 300, 127, 2]; + let pieces: Vec> = lengths.iter().enumerate().map(|(index, &length)| (0..length).map(|byte| (byte + index * 31) as u8).collect()).collect(); + + let mut recorder = RecordingHasher::default(); + { + let mut outer = DynHasher::new(&mut recorder); + for (index, piece) in pieces.iter().enumerate() { + // Every third piece comes from a nested value, the way a list stored as an attribute value is hashed + if index % 3 == 2 { + DynHasher::new(&mut outer).write(piece); + } else { + outer.write(piece); + } + } + } + + assert_eq!(recorder.0, pieces.concat()); + } + + // A cloned list shares each attribute with its source until one of the two writes to it + #[test] + fn list_clones_share_attributes_until_written() { + let mut original = List::new_from_elements(vec![1_u32, 2, 3]); + original.set_attribute_values(ATTR_START, vec![10_u64, 20, 30]); + original.set_attribute_values(ATTR_END, vec![1_u64, 2, 3]); + let values = |list: &List, key: &str| list.iter_attribute_values::(key).map(|values| values.as_slice().as_ptr()); + + let mut copy = original.clone(); + assert_eq!(values(&original, ATTR_START), values(©, ATTR_START)); + assert_eq!((&original, hash_of(&original)), (©, hash_of(©))); + + copy.set_attribute(ATTR_START, 1, 99_u64); + assert_eq!(original.attribute::(ATTR_START, 1), Some(&20)); + assert_eq!(copy.attribute::(ATTR_START, 1), Some(&99)); + assert_ne!(original, copy); + + // Only the attribute written to stops being shared + assert_ne!(values(&original, ATTR_START), values(©, ATTR_START)); + assert_eq!(values(&original, ATTR_END), values(©, ATTR_END)); + } + + // A list reads the same however many attributes it has held, and a lone attribute is shared with clones like any other + #[test] + fn a_lone_attribute_reads_like_one_among_several() { + let mut lone = List::new_from_elements(vec![1_u32, 2, 3]); + lone.set_attribute_values(ATTR_START, vec![10_u64, 20, 30]); + let values = |list: &List, key: &str| list.iter_attribute_values::(key).map(|values| values.as_slice().as_ptr()); + + let mut copy = lone.clone(); + assert_eq!(values(&lone, ATTR_START), values(©, ATTR_START)); + copy.set_attribute(ATTR_START, 1, 99_u64); + assert_eq!((lone.attribute::(ATTR_START, 1), copy.attribute::(ATTR_START, 1)), (Some(&20), Some(&99))); + assert_ne!(values(&lone, ATTR_START), values(©, ATTR_START)); + + // A clone giving the lone attribute up or another type leaves the source as it was + let mut emptied = lone.clone(); + emptied.remove_attribute(ATTR_START); + assert_eq!(emptied, List::new_from_elements(vec![1_u32, 2, 3])); + let mut retyped = lone.clone(); + retyped.set_attribute_values(ATTR_START, vec![0.5_f64, 1.5, 2.5]); + assert_eq!(retyped.attribute::(ATTR_START, 2), Some(&2.5)); + assert_eq!(lone.attribute::(ATTR_START, 2), Some(&30)); + + // Gaining a second attribute and losing it again leaves a list equal to one that never had it + let mut regrown = lone.clone(); + regrown.set_attribute_values(ATTR_END, vec![1_u64, 2, 3]); + assert_eq!(regrown.attribute_keys().collect::>(), [ATTR_START, ATTR_END]); + assert_eq!(values(&lone, ATTR_START), values(®rown, ATTR_START)); + regrown.remove_attribute(ATTR_END); + assert_eq!((®rown, hash_of(®rown)), (&lone, hash_of(&lone))); + + regrown.remove_attribute(ATTR_START); + assert_eq!(regrown, List::new_from_elements(vec![1_u32, 2, 3])); + assert_eq!(lone.attribute::(ATTR_START, 2), Some(&30)); + } + + // A cloned item shares each attribute value with its source until one of the two writes to it or takes it out + #[test] + fn item_clones_share_values_until_written() { + let original = Item::new_from_element(()).with_attribute(ATTR_NAME, vec![1_u32, 2, 3]).with_attribute(ATTR_OPACITY, 0.5_f64); + let name = |item: &Item<()>| item.attribute::>(ATTR_NAME).map(|name| name.as_ptr()); + + let mut copy = original.clone(); + assert_eq!(name(&original), name(©)); + assert_eq!((&original, hash_of(&original)), (©, hash_of(©))); + + copy.attribute_mut::>(ATTR_NAME).unwrap().push(4); + assert_eq!(original.attribute::>(ATTR_NAME), Some(&vec![1, 2, 3])); + assert_eq!(copy.attribute::>(ATTR_NAME), Some(&vec![1, 2, 3, 4])); + + let mut emptied = original.clone(); + assert_eq!(emptied.remove_attribute::>(ATTR_NAME), Some(vec![1, 2, 3])); + assert_eq!(emptied.attribute::>(ATTR_NAME), None); + assert_eq!(original.attribute::>(ATTR_NAME), Some(&vec![1, 2, 3])); + } + + // Taking a shared list apart into items and building on them leaves the list it was cloned from as it was + #[test] + fn items_from_a_shared_list_leave_its_source_intact() { + let mut original = List::new_from_elements(vec![1_u32, 2]); + original.set_attribute_values(ATTR_START, vec![10_u64, 20]); + let starts = |list: &List| list.iter_attribute_values::(ATTR_START).unwrap().copied().collect::>(); + + let raise = |mut item: Item| { + *item.attribute_mut_or_insert_default::(ATTR_START) += 1; + item + }; + let mut rebuilt: List = original.clone().into_iter().map(raise).collect(); + rebuilt.extend(original.clone()); + rebuilt.push(Item::new_from_element(3)); + + assert_eq!(starts(&original), [10, 20]); + assert_eq!(starts(&rebuilt), [11, 21, 10, 20, 0]); + } + + // Keys are stored inline up to a length limit and shared beyond it, which reads the same either way + #[test] + fn attribute_keys_of_any_length_read_back() { + let long_key = "a_user_defined_attribute_name_longer_than_the_inline_limit"; + let keys = [long_key, ATTR_GRADIENT_HUE_DIRECTION, "", "name with spaces"]; + + let mut list = List::new_from_elements(vec![0_u8]); + for (value, key) in keys.into_iter().enumerate() { + list.set_attribute(key, 0, value as u64); + } + + assert_eq!(list.attribute_keys().collect::>(), keys); + for (value, key) in keys.into_iter().enumerate() { + assert_eq!(list.attribute::(key, 0), Some(&(value as u64))); + } + assert_eq!(list.attribute::("gradient_hue_directio", 0), None); + } } diff --git a/node-graph/libraries/vector-types/src/vector/addressing.rs b/node-graph/libraries/vector-types/src/vector/addressing.rs index 4f25b09f78..e80df3799a 100644 --- a/node-graph/libraries/vector-types/src/vector/addressing.rs +++ b/node-graph/libraries/vector-types/src/vector/addressing.rs @@ -1,6 +1,6 @@ use super::connectivity::Connectivity; use super::misc::HandleId; -use super::path::{CurveType, Path, curve_type_at}; +use super::path::{CurveType, Path, curve_type_at, curve_types_of}; use super::vector_attributes::{PointId, SegmentId}; use core_types::list::{ATTR_ID, List}; use glam::DVec2; @@ -27,9 +27,46 @@ impl Span { /// Every span of every path, in path order. pub fn spans(paths: &List) -> impl Iterator + '_ { - paths.iter_element_values().enumerate().flat_map(|(path_index, path)| { - let curve_type = curve_type_at(paths, path_index); - (0..path.segment_count(curve_type) as u32).map(move |index| Span { path: path_index as u32, index }) + let paths_with_curve_types = paths.iter_element_values().zip(curve_types_of(paths)).enumerate(); + + paths_with_curve_types.flat_map(|(path_index, (path, curve_type))| (0..path.segment_count(curve_type) as u32).map(move |index| Span { path: path_index as u32, index })) +} + +/// A span together with what its path holds for it. +pub(crate) struct ResolvedSpan<'a> { + pub span: Span, + pub path: &'a Path, + pub curve_type: CurveType, + /// The span's stable ID, absent when its path names no spans. + pub id: Option, + /// The pool points the span runs between. + pub endpoints: (u32, u32), +} + +/// Every span of every path in path order, resolved in O(references) by reading each path's curve type, references, and IDs once. +pub(crate) fn resolved_spans(paths: &List) -> impl Iterator> + '_ { + paths.iter_element_values().zip(curve_types_of(paths)).enumerate().flat_map(move |(path_index, (path, curve_type))| { + let stride = curve_type.stride(); + let references = path.0.iter_element_values().as_slice(); + let ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()); + + (0..path.segment_count(curve_type)).filter_map(move |index| { + let reference = index * stride; + let endpoints = (*references.get(reference)? as u32, *references.get(reference + stride)? as u32); + let span = Span { + path: path_index as u32, + index: index as u32, + }; + let id = ids.and_then(|ids| ids.get(reference).copied()); + + Some(ResolvedSpan { + span, + path, + curve_type, + id, + endpoints, + }) + }) }) } @@ -44,7 +81,7 @@ pub fn segment_id_of(paths: &List, span: Span) -> Option { /// The span a segment ID names, found by scanning every span in O(references). pub fn span_of_segment_id(paths: &List, segment: SegmentId) -> Option { - spans(paths).find(|&span| segment_id_of(paths, span) == Some(segment)) + resolved_spans(paths).find(|resolved| resolved.id == Some(segment)).map(|resolved| resolved.span) } /// The pool points a span runs between. diff --git a/node-graph/libraries/vector-types/src/vector/connectivity.rs b/node-graph/libraries/vector-types/src/vector/connectivity.rs index 9938aa9f76..9a27795847 100644 --- a/node-graph/libraries/vector-types/src/vector/connectivity.rs +++ b/node-graph/libraries/vector-types/src/vector/connectivity.rs @@ -1,4 +1,4 @@ -use super::path::{CurveType, Path, curve_type_at}; +use super::path::{CurveType, Path, curve_types_of}; use core_types::list::List; /// One path's reference to a pool point, naming where in the weave that point is used. @@ -49,9 +49,8 @@ impl Connectivity { let mut cursors = starts[..point_count].to_vec(); let mut references = vec![Reference::default(); starts[point_count] as usize]; - for (path_index, path) in paths.iter_element_values().enumerate() { - // Each path's curve type is read once here, so queries never look it up again - let curve_type = curve_type_at(paths, path_index); + // Each path's curve type is read once here, so queries never look it up again + for ((path_index, path), curve_type) in paths.iter_element_values().enumerate().zip(curve_types_of(paths)) { let last = path.0.len().saturating_sub(1); for (reference_index, point) in path.references().enumerate() { diff --git a/node-graph/libraries/vector-types/src/vector/contour.rs b/node-graph/libraries/vector-types/src/vector/contour.rs index b0cf78faf5..5e8355d021 100644 --- a/node-graph/libraries/vector-types/src/vector/contour.rs +++ b/node-graph/libraries/vector-types/src/vector/contour.rs @@ -1,5 +1,5 @@ use super::misc::dvec2_to_point; -use super::path::{CurveType, Path, append_segment, curve_type_at}; +use super::path::{CurveType, Path, append_segment, curve_types_of}; use core_types::list::List; use glam::DVec2; use kurbo::BezPath; @@ -94,7 +94,7 @@ pub fn contours(point_count: usize, paths: &List) -> Vec { /// The curve type of every path, read once so the stitching below never looks one up per path. fn curve_types(paths: &List) -> Vec { - (0..paths.len()).map(|index| curve_type_at(paths, index)).collect() + curve_types_of(paths).collect() } fn contours_with(point_count: usize, paths: &List, curve_types: &[CurveType]) -> Vec { diff --git a/node-graph/libraries/vector-types/src/vector/flatten.rs b/node-graph/libraries/vector-types/src/vector/flatten.rs index da3cb3a8ff..5cce94d222 100644 --- a/node-graph/libraries/vector-types/src/vector/flatten.rs +++ b/node-graph/libraries/vector-types/src/vector/flatten.rs @@ -1,5 +1,5 @@ use super::misc::{BezierHandles, HandleId, HandleType, segment_to_handles}; -use super::path::{CurveType, Path, continues_previous_path, curve_type_at, push_path}; +use super::path::{CurveType, Path, continues_previous_path, curve_types_of, push_paths}; use super::vector_attributes::{PointId, SegmentId}; use super::vector_types::Vector; use core_types::list::{ATTR_ID, List}; @@ -44,8 +44,7 @@ impl WorkingVector { let working_point = |pool_index: u32| pool_to_working.get(pool_index as usize).copied().flatten(); // One pass so a span that fails to resolve leaves every array at the same length - for (path_index, path) in paths.iter_element_values().enumerate() { - let curve_type = curve_type_at(paths, path_index); + for ((path_index, path), curve_type) in paths.iter_element_values().enumerate().zip(curve_types_of(paths)) { let stride = curve_type.stride(); let span_ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); @@ -223,9 +222,7 @@ impl WorkingVector { vector.0.set_attribute_values(ATTR_ID, point_ids); } - for (curve_type, references, ids) in runs { - push_path(paths, curve_type, references, ids); - } + push_paths(paths, runs); // G1 pairs narrow to the smooth flag on the anchor both handles face, and other pairings are dropped let anchor = |handle: HandleId| { @@ -331,9 +328,9 @@ pub(crate) fn chain_order(point_count: usize, endpoints: &[(usize, usize)], dire let mut partner = vec![usize::MAX; segment_count * 2]; for ends in ends_at.iter().filter(|ends| ends.len() >= 2) { if ends.len() > MOST_ENDS_PAIRED_BY_STRAIGHTNESS { - for pair in ends.chunks_exact(2) { - partner[pair[0]] = pair[1]; - partner[pair[1]] = pair[0]; + for &[first, second] in ends.as_chunks::<2>().0 { + partner[first] = second; + partner[second] = first; } continue; } @@ -509,6 +506,7 @@ pub fn vector_from_legacy_parts( #[cfg(test)] mod tests { use super::*; + use crate::vector::path::{curve_type_at, push_path}; use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_SMOOTH, Item}; fn working(points: usize, segments: &[(usize, usize, BezierHandles)]) -> WorkingVector { diff --git a/node-graph/libraries/vector-types/src/vector/geometry.rs b/node-graph/libraries/vector-types/src/vector/geometry.rs index 9672efee69..589d4f9e50 100644 --- a/node-graph/libraries/vector-types/src/vector/geometry.rs +++ b/node-graph/libraries/vector-types/src/vector/geometry.rs @@ -222,10 +222,6 @@ impl VectorGeometry { self.vector.bezpath_from_segments_ignore_discontinuities(segments) } - pub fn point_tangent(&self, point_index: usize) -> Option { - self.vector.point_tangent(&self.paths, point_index) - } - /// The manipulator's position in layer space. See [`ManipulatorPointId::get_position`]. pub fn position_of(&self, point: ManipulatorPointId) -> Option { point.get_position(&self.vector, &self.paths) diff --git a/node-graph/libraries/vector-types/src/vector/path.rs b/node-graph/libraries/vector-types/src/vector/path.rs index 22ecd44da3..10f3827528 100644 --- a/node-graph/libraries/vector-types/src/vector/path.rs +++ b/node-graph/libraries/vector-types/src/vector/path.rs @@ -1,7 +1,7 @@ use super::algorithms::consts::CLOSE_POINT_TOLERANCE; use super::misc::{dvec2_to_point, point_to_dvec2}; -use super::vector_attributes::SegmentId; -use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List}; +use super::vector_attributes::{PointId, SegmentId}; +use core_types::list::{ATTR_CURVE_TYPE, ATTR_ID, ATTR_PATHS, Item, List, Shared}; use glam::DVec2; use graphene_hash::CacheHash; use kurbo::{BezPath, CubicBez, Line, PathEl, PathSeg, Point, QuadBez}; @@ -135,8 +135,8 @@ impl Path { } } -/// Appends one path weaving the given references in the curve type's stride, naming its spans with the given IDs in order. -pub fn push_path(paths: &mut List, curve_type: CurveType, references: impl IntoIterator, ids: impl IntoIterator) { +/// Weaves the given references into a path in the curve type's stride, naming its spans with the given IDs in order. +fn woven_path(curve_type: CurveType, references: impl IntoIterator, ids: impl IntoIterator) -> Path { let mut path = Path::from_references(references); let stride = curve_type.stride(); @@ -149,9 +149,34 @@ pub fn push_path(paths: &mut List, curve_type: CurveType, references: impl path.0.set_attribute_values(ATTR_ID, span_ids); } + path +} + +/// Appends one path weaving the given references in the curve type's stride, naming its spans with the given IDs in order. +pub fn push_path(paths: &mut List, curve_type: CurveType, references: impl IntoIterator, ids: impl IntoIterator) { + let path = woven_path(curve_type, references, ids); paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); } +/// Appends a path for each run of references, as [`push_path`] would one at a time. +pub(crate) fn push_paths(paths: &mut List, runs: impl IntoIterator, Vec)>) { + let woven = runs.into_iter().map(|(curve_type, references, ids)| (curve_type, woven_path(curve_type, references, ids))); + let (curve_types, woven) = woven.unzip(); + + extend_with_paths(paths, curve_types, woven); +} + +/// Appends paths with their curve types as one piece, which spares each path a pass through an item of its own. +fn extend_with_paths(paths: &mut List, curve_types: Vec, woven: Vec) { + if woven.is_empty() { + return; + } + + let mut appended = List::new_from_elements(woven); + appended.set_attribute_values(ATTR_CURVE_TYPE, curve_types); + paths.extend(appended); +} + /// Appends a segment to a bezpath already positioned at that segment's start point. pub fn append_segment(bezpath: &mut BezPath, segment: PathSeg) { match segment { @@ -166,6 +191,14 @@ pub fn paths_from_item_attributes(item: &Item) -> Option<&List> { item.attribute(ATTR_PATHS) } +/// The paths an item carries beside a vector element, held without copying them and empty when it carries none. +/// The handle goes on reading the paths whatever then happens to the item. +pub fn shared_paths_from_item_attributes(item: &Item) -> Shared> { + static EMPTY: std::sync::LazyLock>> = std::sync::LazyLock::new(Default::default); + + item.attribute_shared(ATTR_PATHS).unwrap_or_else(|| EMPTY.clone().into()) +} + /// The paths a list carries at `index` beside a vector element, absent when the pool is a bare point cloud. pub fn paths_from_list_row_attributes(list: &List, index: usize) -> Option<&List> { list.attribute(ATTR_PATHS, index) @@ -182,6 +215,13 @@ pub fn curve_type_at(paths: &List, index: usize) -> CurveType { paths.attribute_cloned_or_default(ATTR_CURVE_TYPE, index) } +/// The curve type every path weaves in, in path order, found with one lookup for all of them. +pub(crate) fn curve_types_of(paths: &List) -> impl ExactSizeIterator + '_ { + let stored = paths.iter_attribute_values::(ATTR_CURVE_TYPE).map(|curve_types| curve_types.as_slice()).unwrap_or_default(); + + (0..paths.len()).map(move |index| stored.get(index).copied().unwrap_or_default()) +} + /// Whether the path at `index` only carries on the one stored before it in another curve type, setting out from /// that path's last anchor. Such a path begins nothing of its own. pub fn continues_previous_path(paths: &List, index: usize) -> bool { @@ -194,28 +234,48 @@ pub fn continues_previous_path(paths: &List, index: usize) -> bool { previous_last > 0 && path.0.element(0) == previous.0.element(previous_last) && curve_type_at(paths, index) != curve_type_at(paths, previous_index) } +/// The IDs a weave gives the anchors and spans it adds, each bezpath's continuing on from the latest taken before it. +#[derive(Default)] +struct WovenNames { + last_point: Option, + last_segment: Option, + /// The ID of every woven point so far, with `PointId::UNNAMED` for a handle. + point_ids: Vec, + /// The ID of every span of every finished path so far, in order. + segment_ids: Vec, + /// How many finished paths have had their spans named. + named_paths: usize, +} + /// Weaves bezpath contours into pool points and paths, starting a new path at each verb change so every /// path keeps one stride. The runs of a split subpath share the anchor they meet at, welding them. struct PathWeaver { positions: Vec, anchors: Vec, offset: u32, - woven: Vec<(CurveType, Vec)>, + /// The references of every woven path end to end, the last of them belonging to the path being woven. references: Vec, + /// Each finished path's curve type and where its references end. + woven: Vec<(CurveType, usize)>, + /// Where the references of the path being woven begin. + path_start: usize, curve_type: Option, subpath_start: Option, + names: Option, } impl PathWeaver { - fn new(offset: u32) -> Self { + fn new(offset: u32, names: Option) -> Self { Self { positions: Vec::new(), anchors: Vec::new(), offset, - woven: Vec::new(), references: Vec::new(), + woven: Vec::new(), + path_start: 0, curve_type: None, subpath_start: None, + names, } } @@ -230,14 +290,20 @@ impl PathWeaver { self.positions.get(reference.checked_sub(self.offset)? as usize).copied() } + /// The latest reference of the path being woven. + fn last_reference(&self) -> Option { + self.references.get(self.path_start..)?.last().copied() + } + /// Banks the references woven so far as a finished path, dropping a lone anchor that drew nothing. fn flush(&mut self) { - if self.references.len() >= 2 { - let curve_type = self.curve_type.unwrap_or_default(); - self.woven.push((curve_type, std::mem::take(&mut self.references))); + if self.references.len() - self.path_start >= 2 { + self.woven.push((self.curve_type.unwrap_or_default(), self.references.len())); + } else { + self.references.truncate(self.path_start); } - self.references.clear(); + self.path_start = self.references.len(); self.curve_type = None; } @@ -245,8 +311,8 @@ impl PathWeaver { /// Returns whether an anchor exists to draw from. fn begin_segment(&mut self, verb: CurveType) -> bool { // After a close the pen rests on the subpath's first point, so a segment drawn with no new MoveTo departs from there - let weld = match self.references.last() { - Some(&weld) => weld, + let weld = match self.last_reference() { + Some(weld) => weld, None => { let Some(start) = self.subpath_start else { return false }; self.references.push(start); @@ -294,7 +360,7 @@ impl PathWeaver { /// Closes the subpath by naming its first point again, drawing a straight line home when the pen sits elsewhere. fn close(&mut self) { - let (Some(start), Some(&last)) = (self.subpath_start, self.references.last()) else { return }; + let (Some(start), Some(last)) = (self.subpath_start, self.last_reference()) else { return }; if last == start { self.flush(); @@ -317,35 +383,123 @@ impl PathWeaver { self.flush(); } - /// Appends the woven points and paths, returning whether each appended point is an anchor rather than a handle. - fn finish(mut self, pool: &mut List, paths: &mut List) -> Vec { + /// Weaves a whole bezpath, which leaves nothing open for the next one to carry on from. + fn push_bezpath(&mut self, bezpath: &BezPath) { + let elements = bezpath.elements(); + let point_count = |element: &PathEl| match element { + PathEl::MoveTo(_) | PathEl::LineTo(_) => 1, + PathEl::QuadTo(..) => 2, + PathEl::CurveTo(..) => 3, + PathEl::ClosePath => 0, + }; + let points: usize = elements.iter().map(point_count).sum(); + + // Every point is referenced once, and closes and verb changes add a few more + self.positions.reserve(points); + self.anchors.reserve(points); + self.references.reserve(points + elements.len()); + + for &element in elements { + self.push_element(element); + } self.flush(); + self.subpath_start = None; - pool.extend(List::new_from_elements(self.positions)); + self.name_latest(); + } - for (curve_type, references) in self.woven { - let path = Path::from_references(references); - paths.push(Item::new_from_element(path).with_attribute(ATTR_CURVE_TYPE, curve_type)); + /// Names the anchors and spans woven since the last naming, when this weave names what it adds. + fn name_latest(&mut self) { + let Some(names) = &mut self.names else { return }; + + // Pool order is traversal order, so anchors and free points take IDs in the order they were drawn + let new_anchors = self.anchors.get(names.point_ids.len()..).unwrap_or_default(); + if !new_anchors.is_empty() { + let mut point_id = names.last_point.map_or(PointId::ZERO, |mut latest| latest.next_id()); + let ids = new_anchors.iter().map(|&anchor| if anchor { point_id.next_id() } else { PointId::UNNAMED }); + names.point_ids.extend(ids); + names.last_point = Some(point_id); } - self.anchors + let new_paths = self.woven.get(names.named_paths..).unwrap_or_default(); + let mut path_start = names.named_paths.checked_sub(1).and_then(|previous| self.woven.get(previous)).map_or(0, |&(_, end)| end); + let mut segment_id = names.last_segment.map_or(SegmentId::ZERO, |mut latest| latest.next_id()); + for &(curve_type, path_end) in new_paths { + let span_count = (path_end - path_start).saturating_sub(1) / curve_type.stride(); + if span_count > 0 { + names.segment_ids.extend((0..span_count).map(|_| segment_id.next_id())); + names.last_segment = Some(segment_id); + } + + path_start = path_end; + } + names.named_paths = self.woven.len(); + } + + /// Appends the woven points and paths. + fn finish(self, pool: &mut List, paths: &mut List) { + let (point_ids, segment_ids) = self.names.map(|names| (names.point_ids, names.segment_ids)).unzip(); + + if !self.positions.is_empty() { + let mut points = List::new_from_elements(self.positions); + if let Some(point_ids) = point_ids { + // An attribute of another type under the key would keep the IDs out, so it makes way for them + if pool.iter_attribute_values::(ATTR_ID).is_none() { + pool.remove_attribute(ATTR_ID); + } + points.set_attribute_values(ATTR_ID, point_ids); + } + pool.extend(points); + } + + let mut segment_ids = segment_ids.unwrap_or_default().into_iter(); + let mut path_start = 0; + let woven = self.woven.into_iter().map(|(curve_type, path_end)| { + let references = self.references.get(path_start..path_end).unwrap_or_default(); + path_start = path_end; + + (curve_type, woven_path(curve_type, references.iter().copied(), segment_ids.by_ref())) + }); + let (curve_types, woven) = woven.unzip(); + extend_with_paths(paths, curve_types, woven); } } /// Appends a bezpath's contours to a point pool and its paths. pub fn append_bezpath(pool: &mut List, paths: &mut List, bezpath: &BezPath) { - weave_bezpath(pool, paths, bezpath); + let mut weaver = PathWeaver::new(pool.len() as u32, None); + weaver.push_bezpath(bezpath); + weaver.finish(pool, paths); } -/// Appends a bezpath's contours to a point pool and its paths, returning whether each appended point is an anchor. -pub(crate) fn weave_bezpath(pool: &mut List, paths: &mut List, bezpath: &BezPath) -> Vec { - let mut weaver = PathWeaver::new(pool.len() as u32); +/// Appends the contours of each bezpath in turn to a point pool and its paths, naming the anchors and spans they add, +/// and returns how many spans each bezpath added. Each bezpath's IDs skip one after the largest taken before it, as +/// they do when bezpaths are appended one at a time. +pub(crate) fn append_named_bezpaths( + pool: &mut List, + paths: &mut List, + bezpaths: impl IntoIterator>, + last_point: Option, + last_segment: Option, +) -> Vec { + let names = WovenNames { + last_point, + last_segment, + ..Default::default() + }; + let mut weaver = PathWeaver::new(pool.len() as u32, Some(names)); - for &element in bezpath.elements() { - weaver.push_element(element); + // Every span woven is named, so the names taken so far count the spans each bezpath adds + let named_spans = |weaver: &PathWeaver| weaver.names.as_ref().map_or(0, |names| names.segment_ids.len()); + let mut span_counts = Vec::new(); + for bezpath in bezpaths { + let spans_before = named_spans(&weaver); + weaver.push_bezpath(bezpath.borrow()); + span_counts.push(named_spans(&weaver) - spans_before); } - weaver.finish(pool, paths) + weaver.finish(pool, paths); + span_counts } /// Builds a fresh point pool and its paths from a bezpath. diff --git a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs index 42ecbb7a0d..2cfca094db 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_attributes.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_attributes.rs @@ -1,7 +1,7 @@ use crate::vector::addressing::{self, Span}; use crate::vector::contour::contours; use crate::vector::misc::{ManipulatorGroup, Tangent, point_to_dvec2, segment_to_handles}; -use crate::vector::path::{CurveType, Path, append_segment, continues_previous_path, curve_type_at}; +use crate::vector::path::{CurveType, Path, append_segment, continues_previous_path, curve_type_at, curve_types_of}; use crate::vector::vector_types::Vector; use core_types::list::{ATTR_ID, Item, List}; use dyn_any::DynAny; @@ -109,17 +109,15 @@ impl SegmentGraph { point_count: vector.point_count(), }; - for span in addressing::spans(paths) { - let Some(path) = paths.element(span.path as usize) else { continue }; - let Some((start, end)) = addressing::span_endpoints(paths, span) else { continue }; - let Some(segment) = path.segment(&vector.0, curve_type_at(paths, span.path as usize), span.index as usize) else { + for resolved in addressing::resolved_spans(paths) { + let Some(segment) = resolved.path.segment(&vector.0, resolved.curve_type, resolved.span.index as usize) else { continue; }; - graph.spans.push(span); - graph.ids.push(addressing::segment_id_of(paths, span).unwrap_or_default()); - graph.start_point.push(start as usize); - graph.end_point.push(end as usize); + graph.spans.push(resolved.span); + graph.ids.push(resolved.id.unwrap_or_default()); + graph.start_point.push(resolved.endpoints.0 as usize); + graph.end_point.push(resolved.endpoints.1 as usize); graph.segments.push(segment); } @@ -300,90 +298,27 @@ impl Faces { } } +/// The direction of travel at one end of a segment, found from the nearest control point that sits apart from that anchor, +/// which looks past zero-length handles to the limit direction. `DVec2::ZERO` if every control point coincides. +fn tangent_at_endpoint(segment: PathSeg, at_start: bool) -> DVec2 { + let (points, count) = match segment { + PathSeg::Line(line) => ([point_to_dvec2(line.p0), point_to_dvec2(line.p1), DVec2::ZERO, DVec2::ZERO], 2), + PathSeg::Quad(quad) => ([point_to_dvec2(quad.p0), point_to_dvec2(quad.p1), point_to_dvec2(quad.p2), DVec2::ZERO], 3), + PathSeg::Cubic(cubic) => ([point_to_dvec2(cubic.p0), point_to_dvec2(cubic.p1), point_to_dvec2(cubic.p2), point_to_dvec2(cubic.p3)], 4), + }; + + let not_near = |a: DVec2, b: DVec2| a.distance_squared(b) > f64::EPSILON * 1e3; + + if at_start { + let anchor = points[0]; + points[1..count].iter().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| point - anchor) + } else { + let anchor = points[count - 1]; + points[..count - 1].iter().rev().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| anchor - point) + } +} + impl SegmentGraph { - /// Computes the direction-of-travel tangent at one endpoint of a segment. - /// Uses the "first distinct control point" pattern: iterates through the Bezier control points - /// from the anchor outward, returning the direction to the first one that differs in position. - /// This handles zero-length handles by finding the tangent direction in the limit. - /// Returns `DVec2::ZERO` if all control points coincide (fully degenerate segment). - fn segment_tangent_at_endpoint(&self, segment_index: usize, at_start: bool) -> DVec2 { - let (points, count) = match self.segments[segment_index] { - PathSeg::Line(line) => ([point_to_dvec2(line.p0), point_to_dvec2(line.p1), DVec2::ZERO, DVec2::ZERO], 2), - PathSeg::Quad(quad) => ([point_to_dvec2(quad.p0), point_to_dvec2(quad.p1), point_to_dvec2(quad.p2), DVec2::ZERO], 3), - PathSeg::Cubic(cubic) => ([point_to_dvec2(cubic.p0), point_to_dvec2(cubic.p1), point_to_dvec2(cubic.p2), point_to_dvec2(cubic.p3)], 4), - }; - - let not_near = |a: DVec2, b: DVec2| a.distance_squared(b) > f64::EPSILON * 1e3; - - if at_start { - let anchor = points[0]; - points[1..count].iter().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| point - anchor) - } else { - let anchor = points[count - 1]; - points[..count - 1].iter().rev().find(|&&p| not_near(p, anchor)).map_or(DVec2::ZERO, |&point| anchor - point) - } - } - - /// Computes the average tangent direction at a point based on its 1 or 2 connected segments. - /// Returns `None` for points with 0 or 3+ connections (ambiguous or undefined tangent), - /// or if the tangent is degenerate (all control points coincide). - pub fn point_tangent(&self, point_index: usize) -> Option { - // Collect connected segments with their relationship to this point (at_start flag) - let mut connections: [(usize, bool); 2] = [(0, false); 2]; - let mut connection_count = 0; - - for (segment_index, (&start, &end)) in self.start_point.iter().zip(&self.end_point).enumerate() { - // Self-loop segments count as two connections (outgoing and incoming) - let is_start = start == point_index; - let is_end = end == point_index; - - if !is_start && !is_end { - continue; - } - - if is_start { - if connection_count >= 2 { - return None; - } - connections[connection_count] = (segment_index, true); - connection_count += 1; - } - if is_end { - if connection_count >= 2 { - return None; - } - connections[connection_count] = (segment_index, false); - connection_count += 1; - } - } - - if connection_count == 0 { - return None; - } - - // Compute the direction-of-travel tangent for the first connection - let (segment_index, at_start) = connections[0]; - let tangent1 = self.segment_tangent_at_endpoint(segment_index, at_start).try_normalize(); - - if connection_count == 1 { - return tangent1; - } - - // Compute the direction-of-travel tangent for the second connection - let (segment_index, at_start) = connections[1]; - let tangent2 = self.segment_tangent_at_endpoint(segment_index, at_start).try_normalize(); - - // Average the two normalized tangents - let average = tangent1? + tangent2?; - - // If the tangents are nearly opposite (straight-through), use t1 directly - if average.length_squared() < (f64::EPSILON * 1e3).powi(2) { - return tangent1; - } - - average.try_normalize() - } - /// Walks every face orbit of the segment graph and traces each one's path and signed area. fn face_orbits(&self) -> FaceOrbits { let mut adjacency: Vec> = vec![Vec::new(); self.point_count]; @@ -592,8 +527,8 @@ impl Vector { pub fn is_branching(&self, paths: &List) -> bool { // Tally the segment ends at each anchor in one pass over the references, stopping at the first junction let mut spokes = vec![0_u8; self.point_count()]; - for (path_index, path) in paths.iter_element_values().enumerate() { - let stride = curve_type_at(paths, path_index).stride(); + for (path, curve_type) in paths.iter_element_values().zip(curve_types_of(paths)) { + let stride = curve_type.stride(); let references = path.0.iter_element_values().as_slice(); let last = references.len().saturating_sub(1); @@ -620,14 +555,59 @@ impl Vector { SegmentGraph::new(self, paths).construct_faces() } - /// Computes the average tangent direction at a point based on its 1 or 2 connected segments. - pub fn point_tangent(&self, paths: &List, point_index: usize) -> Option { - SegmentGraph::new(self, paths).point_tangent(point_index) + /// The direction of travel through every pool point in O(points + references), following the contour that passes + /// it and averaging the segments on either side. A point has none when no contour passes it, when three or more + /// segments meet at it, or when a segment at it is degenerate. + pub fn anchor_tangents(&self, paths: &List) -> Vec> { + let curve_types: Vec = curve_types_of(paths).collect(); + + // What each point gathers: how many segment ends meet it, their tangents summed, the first of them, and whether any was degenerate + let mut gathered = vec![(0_u8, DVec2::ZERO, DVec2::ZERO, false); self.point_count()]; + for contour in contours(self.point_count(), paths) { + for part in &contour.parts { + let Some(path) = paths.element(part.path as usize) else { continue }; + let Some(&curve_type) = curve_types.get(part.path as usize) else { continue }; + let references = path.0.iter_element_values().as_slice(); + let (stride, count) = (curve_type.stride(), path.segment_count(curve_type)); + + for step in 0..count { + let span = if part.reversed { count - 1 - step } else { step }; + let Some(segment) = path.segment(&self.0, curve_type, span) else { continue }; + let (Some(&start), Some(&end)) = (references.get(span * stride), references.get(span * stride + stride)) else { + continue; + }; + + // The segment as the contour crosses it, leaving one anchor and arriving at the other + let (segment, leaving, arriving) = if part.reversed { (segment.reverse(), end, start) } else { (segment, start, end) }; + for (point, at_start) in [(leaving, true), (arriving, false)] { + let Some((ends, sum, first, degenerate)) = gathered.get_mut(point as usize) else { continue }; + + match tangent_at_endpoint(segment, at_start).try_normalize() { + Some(tangent) if *ends == 0 => (*sum, *first) = (tangent, tangent), + Some(tangent) => *sum += tangent, + None => *degenerate = true, + } + *ends = ends.saturating_add(1); + } + } + } + } + + // Tangents that cancel out mark a cusp doubling straight back, which keeps the first of its two directions + let cancels_out = |sum: DVec2| sum.length_squared() < (f64::EPSILON * 1e3).powi(2); + let resolve = |(ends, sum, first, degenerate): (u8, DVec2, DVec2, bool)| match ends { + _ if degenerate => None, + 1 => Some(first), + 2 if cancels_out(sum) => Some(first), + 2 => sum.try_normalize(), + _ => None, + }; + gathered.into_iter().map(resolve).collect() } /// Every segment's stable ID, in span order. pub fn segment_ids(&self, paths: &List) -> Vec { - addressing::spans(paths).map(|span| addressing::segment_id_of(paths, span).unwrap_or_default()).collect() + addressing::resolved_spans(paths).map(|resolved| resolved.id.unwrap_or_default()).collect() } /// The ID of the first segment of every path that begins one, leaving out the paths that only carry on the one before them in another curve type. @@ -759,7 +739,7 @@ impl Vector { pub fn stroke_manipulator_groups(&self, paths: &List) -> impl Iterator, bool)> { let mut groups = Vec::new(); - let curve_types: Vec = (0..paths.len()).map(|index| curve_type_at(paths, index)).collect(); + let curve_types: Vec = curve_types_of(paths).collect(); let ids = self.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); let id_at = |point: u32| ids.get(point as usize).copied().unwrap_or_default(); @@ -1094,6 +1074,59 @@ mod tests { assert_eq!(bezpath_from_manipulator_groups(manipulators, *closed).elements(), contours[0].elements()); } + // Where two paths weld tail to tail, the tangent follows the contour through the weld instead of the two stored directions + #[test] + fn anchor_tangents_follow_the_contour_through_a_weld() { + let points = [DVec2::new(0., 0.), DVec2::new(-10., 10.), DVec2::new(0., 20.), DVec2::new(10., 10.)]; + let (vector, mut paths) = build_vector(&points, &[]); + for references in [[0, 1, 2], [0, 3, 2]] { + paths.push(Item::new_from_element(Path::from_references(references)).with_attribute(ATTR_CURVE_TYPE, CurveType::Linear)); + } + + let tangents = vector.anchor_tangents(&paths); + let near = |tangent: Option, expected: DVec2| tangent.is_some_and(|tangent| tangent.distance(expected) < 1e-9); + + // The contour runs down the left half and back up the right half + assert!(near(tangents[2], DVec2::X), "{:?}", tangents[2]); + assert!(near(tangents[0], DVec2::NEG_X), "{:?}", tangents[0]); + assert!(near(tangents[1], DVec2::Y), "{:?}", tangents[1]); + assert!(near(tangents[3], DVec2::NEG_Y), "{:?}", tangents[3]); + } + + // An open end takes its one segment's direction and a closed loop's seam averages the two meeting there. A cusp keeps + // the direction arriving at it, and a junction of three ends or a collapsed segment gives no tangent. + #[test] + fn anchor_tangents_at_ends_seams_cusps_junctions_and_collapsed_segments() { + let tangents = |points: &[DVec2], curve_type: CurveType, paths: &[&[u32]]| { + let (vector, mut list) = build_vector(points, &[]); + for &references in paths { + list.push(Item::new_from_element(Path::from_references(references.iter().copied())).with_attribute(ATTR_CURVE_TYPE, curve_type)); + } + vector.anchor_tangents(&list) + }; + let near = |tangent: Option, expected: DVec2| tangent.is_some_and(|tangent| tangent.distance(expected.normalize()) < 1e-9); + + let open = tangents(&[DVec2::ZERO, DVec2::new(10., 0.), DVec2::new(10., 10.)], CurveType::Linear, &[&[0, 1, 2]]); + assert_eq!(open[0], Some(DVec2::X)); + assert!(near(open[1], DVec2::ONE), "{:?}", open[1]); + assert_eq!(open[2], Some(DVec2::Y)); + + let square = [DVec2::ZERO, DVec2::new(10., 0.), DVec2::new(10., 10.), DVec2::new(0., 10.)]; + let closed = tangents(&square, CurveType::Linear, &[&[0, 1, 2, 3, 0]]); + assert!(near(closed[0], DVec2::new(1., -1.)), "{:?}", closed[0]); + + let cusp = tangents(&[DVec2::ZERO, DVec2::new(10., 0.), DVec2::ZERO], CurveType::Linear, &[&[0, 1, 2]]); + assert_eq!(cusp[1], Some(DVec2::X)); + + let junction = tangents(&square, CurveType::Linear, &[&[0, 1], &[0, 2], &[0, 3]]); + assert_eq!(junction[0], None); + assert_eq!(junction[1], Some(DVec2::X)); + + let collapsed = tangents(&[DVec2::ONE; 4], CurveType::Cubic, &[&[0, 1, 2, 3]]); + assert_eq!(collapsed[0], None); + assert_eq!(collapsed[3], None); + } + /// Square wound positively with a reverse-wound triangle welded to its corner: /// the triangle's interior face is deliberate negative space, so only the surrounding face is filled. #[test] diff --git a/node-graph/libraries/vector-types/src/vector/vector_modification.rs b/node-graph/libraries/vector-types/src/vector/vector_modification.rs index 3a483e9652..3b37667e40 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_modification.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_modification.rs @@ -1,7 +1,7 @@ use super::*; use crate::vector::flatten::WorkingVector; use crate::vector::misc::{BezierHandles, HandleId, HandleType}; -use crate::vector::path::{CurveType, Path, curve_type_at}; +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; @@ -136,8 +136,7 @@ impl PointModification { } // A segment's first handle follows its start anchor, and a cubic's second handle follows its end anchor - for (path_index, path) in paths.iter_element_values().enumerate() { - let curve_type = curve_type_at(paths, path_index); + for (path, curve_type) in paths.iter_element_values().zip(curve_types_of(paths)) { if curve_type == CurveType::Linear { continue; } @@ -214,8 +213,8 @@ impl SegmentModification { working.segment_begins_path.resize(segment_count, false); let (mut removed_began_path, mut removed_end) = (false, None); - for index in 0..segment_count { - if !keep[index] { + for (index, &kept) in keep.iter().enumerate() { + if !kept { removed_began_path |= std::mem::take(&mut working.segment_begins_path[index]); removed_end = Some(working.segment_end[index]); continue; @@ -389,8 +388,7 @@ impl SegmentModification { /// Calls the visitor with each span a handle edit names, along with its curve type, references, starting reference, and edits. fn for_each_edited_span(&self, paths: &List, mut visit: impl FnMut(CurveType, &Path, usize, Option>, Option>)) { - for (path_index, path) in paths.iter_element_values().enumerate() { - let curve_type = curve_type_at(paths, path_index); + for (path, curve_type) in paths.iter_element_values().zip(curve_types_of(paths)) { let stride = curve_type.stride(); let ids = path.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); @@ -771,9 +769,17 @@ impl VectorModification { /// Apply this modification to the specified [`Vector`] and its paths. pub fn apply(&self, vector: &mut Vector, paths: &mut List) { + if !self.apply_in_place(vector, paths) { + self.apply_through_working_form(vector, paths); + } + } + + /// Applies this modification if it leaves the paths as they are, returning whether it did. Otherwise nothing + /// changes and [`Self::apply`] has to rewrite the paths. + pub fn apply_in_place(&self, vector: &mut Vector, paths: &List) -> bool { // An untouched vector keeps its incoming path structure instead of being flattened and rewoven if self.is_empty() { - return; + return true; } // Moving points and handles leaves the weave intact, so the pool is edited where it lies in O(points + references), keeping @@ -783,11 +789,11 @@ impl VectorModification { if handles_unshared { self.points.move_in_place(vector, paths, &handles); self.segments.set_handles_in_place(vector, paths); - return; + return true; } } - self.apply_through_working_form(vector, paths); + false } /// Applies this modification by flattening to the legacy working form, editing that, and weaving the result back. diff --git a/node-graph/libraries/vector-types/src/vector/vector_types.rs b/node-graph/libraries/vector-types/src/vector/vector_types.rs index 64dacb7f5b..65c509f057 100644 --- a/node-graph/libraries/vector-types/src/vector/vector_types.rs +++ b/node-graph/libraries/vector-types/src/vector/vector_types.rs @@ -2,7 +2,9 @@ use super::addressing; use super::connectivity::Connectivity; use super::contour::{contour_bezpaths, contours}; use super::misc::{HandleId, ManipulatorPointId, dvec2_to_point}; -use super::path::{CurveType, Path, curve_type_at, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path, weave_bezpath}; +use super::path::{ + CurveType, Path, append_named_bezpaths, curve_type_at, curve_types_of, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path, shared_paths_from_item_attributes, +}; use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use super::vector_attributes::{PointId, SegmentId}; use core_types::bounds::{BoundingBox, RenderBoundingBox}; @@ -84,58 +86,38 @@ impl Vector { } } -/// The ID continuing the pool's point ID sequence. -fn next_point_id(pool: &List) -> PointId { - let ids = pool.iter_attribute_values::(ATTR_ID); - ids.and_then(|ids| ids.copied().filter(|id| *id != PointId::UNNAMED).max()) - .map(|mut id| id.next_id()) - .unwrap_or(PointId::ZERO) +/// The largest ID in the pool's point ID sequence, which a pool has once it holds point IDs at all. +fn largest_point_id(pool: &List) -> Option { + let ids = pool.iter_attribute_values::(ATTR_ID)?; + + // An ID attribute that names nothing yet counts as a sequence at zero, which documents saved with edits to such geometry rely on + Some(ids.copied().filter(|id| *id != PointId::UNNAMED).max().unwrap_or_default()) } -/// The ID continuing the paths' segment ID sequence. -fn next_segment_id(paths: &List) -> SegmentId { - let ids = paths - .iter_element_values() - .filter_map(|path| path.0.iter_attribute_values::(ATTR_ID)) - .flatten() - .copied() - .max(); +/// The largest ID in the paths' segment ID sequence. +fn largest_segment_id(paths: &List) -> Option { + let ids = paths.iter_element_values().filter_map(|path| path.0.iter_attribute_values::(ATTR_ID)); - ids.map(|mut id| id.next_id()).unwrap_or(SegmentId::ZERO) + ids.flatten().copied().max() } impl Vector { /// Weaves a bezpath's contours onto this pool and the given paths, naming the new anchors and spans /// by continuing the ID sequences. Handles take `PointId::UNNAMED`. pub fn append_bezpath(&mut self, paths: &mut List, bezpath: &BezPath) { - let (first_new_point, first_new_path) = (self.0.len(), paths.len()); - let anchors = weave_bezpath(&mut self.0, paths, bezpath); + self.append_bezpaths(paths, [bezpath]); + } - // Pool order is traversal order, so anchors and free points take IDs in the order they were drawn - if !anchors.is_empty() { - let mut point_id = next_point_id(&self.0); - let ids = self.0.iter_attribute_values_mut_or_default::(ATTR_ID).skip(first_new_point); - for (id, anchor) in ids.zip(anchors) { - *id = if anchor { point_id.next_id() } else { PointId::UNNAMED }; - } - } + /// Weaves each bezpath in turn as [`Self::append_bezpath`] would, in O(existing + appended) however many there are + /// since the IDs to continue from are found once. + pub fn append_bezpaths(&mut self, paths: &mut List, bezpaths: impl IntoIterator>) { + self.append_bezpaths_counting_spans(paths, bezpaths); + } - let mut segment_id = next_segment_id(paths); - for path_index in first_new_path..paths.len() { - let curve_type = curve_type_at(paths, path_index); - let Some(path) = paths.element_mut(path_index) else { continue }; - - let span_count = path.segment_count(curve_type); - if span_count == 0 { - continue; - } - - let mut span_ids = vec![SegmentId::default(); path.0.len()]; - for span in 0..span_count { - span_ids[span * curve_type.stride()] = segment_id.next_id(); - } - path.0.set_attribute_values(ATTR_ID, span_ids); - } + /// Weaves bezpaths as [`Self::append_bezpaths`] does, returning how many spans each of them added. + pub fn append_bezpaths_counting_spans(&mut self, paths: &mut List, bezpaths: impl IntoIterator>) -> Vec { + let (last_point, last_segment) = (largest_point_id(&self.0), largest_segment_id(paths)); + append_named_bezpaths(&mut self.0, paths, bezpaths, last_point, last_segment) } /// Builds a fresh pool and paths from a single bezpath. @@ -157,13 +139,14 @@ impl Vector { impl Vector { /// Every segment in span order as `(id, segment, start point ID, end point ID)`. pub fn segment_iter<'a>(&'a self, paths: &'a List) -> impl Iterator + 'a { - addressing::spans(paths).filter_map(|span| { - let path = paths.element(span.path as usize)?; - let segment = path.segment(&self.0, curve_type_at(paths, span.path as usize), span.index as usize)?; - let id = addressing::segment_id_of(paths, span).unwrap_or_default(); - let (start, end) = addressing::span_endpoints(paths, span)?; + let point_ids = self.0.iter_attribute_values::(ATTR_ID).map(|ids| ids.as_slice()).unwrap_or_default(); + let point_id = move |point: u32| point_ids.get(point as usize).copied().unwrap_or_default(); - Some((id, segment, self.point_id_at(start).unwrap_or_default(), self.point_id_at(end).unwrap_or_default())) + addressing::resolved_spans(paths).filter_map(move |resolved| { + let segment = resolved.path.segment(&self.0, resolved.curve_type, resolved.span.index as usize)?; + let (start, end) = resolved.endpoints; + + Some((resolved.id.unwrap_or_default(), segment, point_id(start), point_id(end))) }) } @@ -379,8 +362,8 @@ impl Vector { let mut roles = vec![UNREFERENCED; self.0.len()]; let mut handles_unshared = true; - for (path_index, path) in paths.iter_element_values().enumerate() { - let stride = curve_type_at(paths, path_index).stride(); + for (path, curve_type) in paths.iter_element_values().zip(curve_types_of(paths)) { + let stride = curve_type.stride(); for (reference_index, point) in path.references().enumerate() { let Some(role) = roles.get_mut(point as usize) else { continue }; if reference_index.is_multiple_of(stride) { @@ -697,12 +680,12 @@ impl Vector { return; } - // Each closing segment's ID skips one after the previous, as the IDs of a newly appended bezpath do - let mut base = next_segment_id(paths); + // Each closing segment's ID skips one after the latest, as the IDs of a newly appended bezpath do + let mut latest = largest_segment_id(paths); let mut closing_paths = Vec::with_capacity(closings.len()); for (before, backward, references) in closings { - let id = base.next_id(); - base.next_id(); + let id = latest.map_or(SegmentId::ZERO, |mut latest| latest.next_id()).next_id(); + latest = Some(id); let mut single = List::new(); push_path(&mut single, CurveType::Linear, references, [id]); @@ -795,15 +778,32 @@ impl Vector { } } -/// Edits a holder item's pool and paths together, taking the paths attribute out and restoring it. +/// Edits a holder item's pool and paths together, taking the paths attribute out and putting it back where it was, or last if absent. pub fn edit_item_geometry(item: &mut Item, edit: impl FnOnce(&mut Vector, &mut List) -> R) -> R { - let mut paths = item.remove_attribute::>(ATTR_PATHS).unwrap_or_default(); + let mut paths = item.attribute_mut::>(ATTR_PATHS).map(std::mem::take).unwrap_or_default(); let result = edit(item.element_mut(), &mut paths); - item.set_attribute(ATTR_PATHS, paths); + *item.attribute_mut_or_insert_default::>(ATTR_PATHS) = paths; result } +/// Edits an item's pool while only reading its paths, which stay shared with the item's clones instead of being copied. +pub fn edit_item_points(item: &mut Item, edit: impl FnOnce(&mut Vector, &List) -> R) -> R { + let paths = shared_paths_from_item_attributes(item); + let result = edit(item.element_mut(), &paths); + ensure_paths_attribute(item); + + result +} + +/// Gives an item without paths an empty paths attribute, placed last, as [`edit_item_geometry`] gives a point cloud. +pub fn ensure_paths_attribute(item: &mut Item) { + if item.attribute::>(ATTR_PATHS).is_none() { + item.remove_attribute::>(ATTR_PATHS); + item.set_attribute(ATTR_PATHS, List::::new()); + } +} + /// Edits one list row's pool and paths together, writing the paths attribute back afterwards. pub fn edit_list_row_geometry(list: &mut List, index: usize, edit: impl FnOnce(&mut Vector, &mut List) -> R) -> Option { let mut paths = list.attribute::>(ATTR_PATHS, index).cloned().unwrap_or_default(); @@ -863,7 +863,7 @@ impl RenderComplexity for Vector { fn segment_count(paths: Option<&List>) -> usize { let Some(paths) = paths else { return 0 }; - paths.iter_element_values().enumerate().map(|(index, path)| path.segment_count(curve_type_at(paths, index))).sum() + paths.iter_element_values().zip(curve_types_of(paths)).map(|(path, curve_type)| path.segment_count(curve_type)).sum() } // Note: BoundingBox for List is handled by blanket impl in core-types @@ -896,6 +896,54 @@ mod tests { assert_eq!(List::new_from_item(item).render_complexity(), 4); } + // Bezpaths appended together come out as they do appended one at a time, IDs included, with the spans each one added counted + #[test] + fn bezpaths_appended_together_match_one_at_a_time() { + let mut mixed = BezPath::new(); + mixed.move_to((0., 0.)); + mixed.line_to((4., 0.)); + mixed.quad_to((6., 2.), (4., 4.)); + mixed.close_path(); + let bezpaths = [ellipse_bezpath(DVec2::NEG_ONE, DVec2::ONE), BezPath::new(), mixed, open_curve_bezpath()]; + + let (mut together, mut together_paths) = (lone_anchor(DVec2::splat(9.)), List::new()); + let span_counts = together.append_bezpaths_counting_spans(&mut together_paths, &bezpaths); + assert_eq!(span_counts, [4, 0, 3, 1]); + + let (mut in_turn, mut in_turn_paths) = (lone_anchor(DVec2::splat(9.)), List::new()); + for bezpath in &bezpaths { + in_turn.append_bezpath(&mut in_turn_paths, bezpath); + } + + assert_eq!((together, together_paths), (in_turn, in_turn_paths)); + } + + // Each appended bezpath's IDs skip one after the largest before it, which documents saved with edits to such geometry rely on + #[test] + fn appended_bezpaths_continue_the_id_sequences_with_a_gap() { + let mut triangle = BezPath::new(); + triangle.move_to((0., 0.)); + triangle.line_to((4., 0.)); + triangle.line_to((0., 4.)); + triangle.close_path(); + let named = |vector: &Vector, paths: &List| { + let point_ids: Vec = vector.0.iter_attribute_values::(ATTR_ID).into_iter().flatten().map(|id| id.inner()).collect(); + let segment_ids: Vec = vector.segment_iter(paths).map(|(id, ..)| id.inner()).collect(); + (point_ids, segment_ids) + }; + + let (mut vector, mut paths) = (Vector::default(), List::new()); + vector.append_bezpaths(&mut paths, [&triangle, &triangle]); + assert_eq!(named(&vector, &paths), (vec![1, 2, 3, 5, 6, 7], vec![1, 2, 3, 5, 6, 7])); + + // A pool holding IDs that name nothing yet starts its sequence one further on + let mut unnamed = Vector::default(); + unnamed.0.set_attribute_values(ATTR_ID, Vec::::new()); + let mut unnamed_paths = List::new(); + unnamed.append_bezpath(&mut unnamed_paths, &triangle); + assert_eq!(named(&unnamed, &unnamed_paths).0, [2, 3, 4]); + } + // A lone anchor is named zero and only the later collisions are renamed, so stored edits keyed on zero still land #[test] fn lone_anchor_is_named_zero_and_collisions_rename_from_it() { @@ -923,7 +971,7 @@ mod tests { let index = vector.index_of_point_id(PointId::ZERO).unwrap(); assert_eq!(vector.position(index as usize), Some(DVec2::new(5., 5.))); assert!(vector.anchor_indices(&paths).contains(&(index as usize))); - assert_eq!(next_point_id(&vector.0).inner(), 3); + assert_eq!(largest_point_id(&vector.0).map(PointId::inner), Some(2)); } #[test] diff --git a/node-graph/nodes/path-bool/src/lib.rs b/node-graph/nodes/path-bool/src/lib.rs index 70c4216ddf..3af6a11db5 100644 --- a/node-graph/nodes/path-bool/src/lib.rs +++ b/node-graph/nodes/path-bool/src/lib.rs @@ -175,9 +175,8 @@ fn boolean_operation_on_vector_list(vector: &List, boolean_operation: Bo }; let contours = top.contours(|winding| winding.is_inside(boolean_operation)); let mut result_paths = List::new(); - for contour in contours.contours() { - row.element_mut().append_bezpath(&mut result_paths, &closed(contour.path.clone())); - } + let closed_contours = contours.contours().map(|contour| closed(contour.path.clone())); + row.element_mut().append_bezpaths(&mut result_paths, closed_contours); row.set_attribute(ATTR_PATHS, result_paths); list.push(row); diff --git a/node-graph/nodes/text/src/path_builder.rs b/node-graph/nodes/text/src/path_builder.rs index cd0720d603..1a9ba175b3 100644 --- a/node-graph/nodes/text/src/path_builder.rs +++ b/node-graph/nodes/text/src/path_builder.rs @@ -17,9 +17,8 @@ pub struct PathBuilder { pub vector_list: List, /// Whether each glyph becomes its own list item rather than merging into one vector. per_glyph_items: bool, - /// The single accumulated vector and its paths in merged mode, written to item 0 in `finalize()`. - merged_vector: Vector, - merged_paths: List, + /// Every glyph's outline in merged mode, woven into item 0 together in `finalize()`. + merged_glyphs: Vec, /// Per-glyph AABBs collected in single-item mode, published as `ATTR_EDITOR_CLICK_TARGET` in `finalize()`. merged_click_target_bboxes: Vec<[DVec2; 2]>, /// Per-glyph baselines, parallel to `merged_click_target_bboxes`. Groups glyphs by line for the widening pass. @@ -40,8 +39,7 @@ impl PathBuilder { glyph_bezpath: BezPath::new(), vector_list: if per_glyph_items { List::new() } else { List::new_from_element(Vector::default()) }, per_glyph_items, - merged_vector: Vector::default(), - merged_paths: List::new(), + merged_glyphs: Vec::new(), merged_click_target_bboxes: Vec::new(), merged_click_target_baselines: Vec::new(), per_glyph_bboxes: Vec::new(), @@ -94,7 +92,7 @@ impl PathBuilder { // Defer click target creation to `finalize()` where adjacent AABBs get widened self.per_glyph_bboxes.push(glyph_bbox); } else { - self.merged_vector.append_bezpath(&mut self.merged_paths, &core::mem::take(&mut self.glyph_bezpath)); + self.merged_glyphs.push(core::mem::take(&mut self.glyph_bezpath)); if let Some(bbox) = glyph_bbox { self.merged_click_target_bboxes.push(bbox); @@ -164,12 +162,14 @@ impl PathBuilder { } pub fn finalize(mut self) -> List { - // Merged mode accumulated into side fields, which item 0 takes over here + // Merged mode gathered every glyph's outline, which item 0 takes on here in one pass if !self.per_glyph_items && let Some(element) = self.vector_list.element_mut(0) { - *element = core::mem::take(&mut self.merged_vector); - let paths = core::mem::take(&mut self.merged_paths); + let (mut vector, mut paths) = (Vector::default(), List::::new()); + vector.append_bezpaths(&mut paths, &self.merged_glyphs); + + *element = vector; self.vector_list.set_attribute(core_types::list::ATTR_PATHS, 0, paths); } diff --git a/node-graph/nodes/vector/src/generator_nodes.rs b/node-graph/nodes/vector/src/generator_nodes.rs index e0860b03fa..4d03f9ab88 100644 --- a/node-graph/nodes/vector/src/generator_nodes.rs +++ b/node-graph/nodes/vector/src/generator_nodes.rs @@ -250,15 +250,13 @@ fn qr_code( true => { let (mut vector, mut paths) = (Vector::default(), List::new()); - let dimension = qr_code.size() as usize; - for y in 0..dimension { - for x in 0..dimension { - if qr_code.get_module(x as i32, y as i32) { - let corner1 = DVec2::new(x as f64, y as f64); - vector.append_bezpath(&mut paths, &shapes::rectangle_bezpath(corner1, corner1 + DVec2::splat(1.))); - } - } - } + let dimension = qr_code.size(); + let cells = (0..dimension).flat_map(|y| (0..dimension).map(move |x| (x, y))); + let squares = cells.filter(|&(x, y)| qr_code.get_module(x, y)).map(|(x, y)| { + let corner1 = DVec2::new(x as f64, y as f64); + shapes::rectangle_bezpath(corner1, corner1 + DVec2::splat(1.)) + }); + vector.append_bezpaths(&mut paths, squares); (vector, paths) } @@ -432,7 +430,7 @@ mod tests { use super::*; use kurbo::ParamCurve; use vector_types::vector::misc::point_to_dvec2; - use vector_types::vector::paths_from_item_attributes; + use vector_types::vector::shared_paths_from_item_attributes; fn item(value: T) -> Item { Item::new_from_element(value) @@ -446,7 +444,7 @@ mod tests { // Works properly let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_i64), item(5_i64), item((30., 30.).into()), item(true)); - let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&grid); assert_eq!(grid.element().anchor_points(&paths).count(), 5 * 5); assert_eq!(grid.element().segment_iter(&paths).count(), 4 * 5 + 4 * 9); for (_, segment, _, _) in grid.element().segment_iter(&paths) { @@ -459,7 +457,7 @@ mod tests { #[test] fn skew_isometric_grid_test() { let grid = grid((), (), item(GridType::Isometric), item(10.), item(5_i64), item(5_i64), item((40., 30.).into()), item(true)); - let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&grid); assert_eq!(grid.element().anchor_points(&paths).count(), 5 * 5); assert_eq!(grid.element().segment_iter(&paths).count(), 4 * 5 + 4 * 9); for (_, segment, _, _) in grid.element().segment_iter(&paths) { @@ -474,7 +472,7 @@ mod tests { #[test] fn grid_joins_segments_only_where_they_follow_each_other() { let grid = grid((), (), item(GridType::Rectangular), item(10.), item(3_i64), item(3_i64), item((30., 30.).into()), item(true)); - let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&grid); let vector = grid.element(); assert_eq!(vector.segment_ids(&paths).len(), 2 * 3 + 2 * 3); @@ -486,7 +484,7 @@ mod tests { fn grid_disconnected_cells_test() { // A 3x3 rectangular grid has a 2x2 arrangement of cells, each its own closed quad subpath. let grid = grid((), (), item(GridType::Rectangular), item(10.), item(3_i64), item(3_i64), item((30., 30.).into()), item(false)); - let paths = paths_from_item_attributes(&grid).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&grid); let vector = grid.element(); assert_eq!(vector.stroke_manipulator_groups(&paths).filter(|(_, closed)| *closed).count(), 4); assert_eq!(vector.anchor_points(&paths).count(), 4 * 4); @@ -512,7 +510,7 @@ mod tests { item(QRCodeErrorCorrectionLevel::Low), item(true), ); - let paths = paths_from_item_attributes(&qr).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&qr); assert!(qr.element().anchor_points(&paths).count() > 0); assert!(!qr.element().segment_ids(&paths).is_empty()); } diff --git a/node-graph/nodes/vector/src/merge_qr_squares.rs b/node-graph/nodes/vector/src/merge_qr_squares.rs index ee02a93426..65f5a70117 100644 --- a/node-graph/nodes/vector/src/merge_qr_squares.rs +++ b/node-graph/nodes/vector/src/merge_qr_squares.rs @@ -6,8 +6,7 @@ use vector_types::vector::Path; use vector_types::vector::algorithms::shapes; pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> (Vector, List) { - let mut vector = Vector::default(); - let mut paths = List::new(); + let mut outlines = Vec::new(); let size = qr_code.size() as usize; @@ -109,7 +108,7 @@ pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> (Vector, List) { } if !simplified.is_empty() { - vector.append_bezpath(&mut paths, &shapes::polyline_bezpath(simplified, true)); + outlines.push(shapes::polyline_bezpath(simplified, true)); } } } @@ -123,5 +122,8 @@ pub fn merge_qr_squares(qr_code: &qrcodegen::QrCode) -> (Vector, List) { } } + let (mut vector, mut paths) = (Vector::default(), List::new()); + vector.append_bezpaths(&mut paths, &outlines); + (vector, paths) } diff --git a/node-graph/nodes/vector/src/vector_modification_nodes.rs b/node-graph/nodes/vector/src/vector_modification_nodes.rs index f902f9fec8..c25257d99f 100644 --- a/node-graph/nodes/vector/src/vector_modification_nodes.rs +++ b/node-graph/nodes/vector/src/vector_modification_nodes.rs @@ -5,22 +5,35 @@ use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFOR use glam::{DAffine2, DVec2}; use graphic_types::Vector; use vector_types::kurbo::BezPath; -use vector_types::vector::{VectorModification, edit_item_geometry}; +use vector_types::vector::{VectorModification, edit_item_geometry, ensure_paths_attribute, shared_paths_from_item_attributes}; /// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments. #[node_macro::node(category(""))] async fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item>, node_path: Item) -> Item { let mut vector = vector; let modification = modification.into_element(); - edit_item_geometry(&mut vector, |element, paths| { - modification.apply(element, paths); - // Faces tell negative space apart by a loop's winding, which users draw in arbitrary directions. - // Every other fill follows the contours, which keep the direction each path was drawn in. - if element.use_face_fill(paths) { - element.normalize_winding_directions(paths); - } - }); + // Moving points leaves the paths as they are, so they stay shared with the incoming geometry instead of being copied + let paths = shared_paths_from_item_attributes(&vector); + let moved_in_place = modification.apply_in_place(vector.element_mut(), &paths); + let fills_by_face = moved_in_place && vector.element().use_face_fill(&paths); + drop(paths); + + if moved_in_place && !fills_by_face { + ensure_paths_attribute(&mut vector); + } else { + edit_item_geometry(&mut vector, |element, paths| { + if !moved_in_place { + modification.apply(element, paths); + } + + // Faces tell negative space apart by a loop's winding, which users draw in arbitrary directions. + // Every other fill follows the contours, which keep the direction each path was drawn in. + if fills_by_face || (!moved_in_place && element.use_face_fill(paths)) { + element.normalize_winding_directions(paths); + } + }); + } // Drop the stale click-target override so hit testing uses the geometry the user is now editing vector.remove_attribute::(ATTR_EDITOR_CLICK_TARGET); @@ -53,7 +66,8 @@ async fn bake_transform(_ctx: impl Ctx, #[cfg(test)] mod tests { use super::*; - use vector_types::vector::paths_from_item_attributes; + use core_types::list::{ATTR_ID, ATTR_PATHS}; + use vector_types::vector::{CurveType, PointId, SegmentId, VectorModificationType, paths_from_item_attributes, push_path}; // A lone loop fills by its contour alone, so it keeps the direction it was drawn in even when that winds backwards #[tokio::test] @@ -70,4 +84,71 @@ mod tests { assert_eq!(paths_from_item_attributes(&modified), paths_from_item_attributes(&drawn)); } + + // Moving a point of a mesh leaves its paths in place to begin with, and its loops still get their winding set for the face fill + #[tokio::test] + async fn a_mesh_moved_in_place_still_has_its_winding_set() { + // A reverse-wound square beside three spokes meeting at a hub, which makes the geometry branch + let positions = [(0., 0.), (0., 10.), (10., 10.), (10., 0.), (30., 0.), (40., 0.), (30., 10.), (20., 10.)]; + let (mut vector, mut paths) = (Vector::default(), List::new()); + let (mut point_id, mut segment_id) = (PointId::ZERO, SegmentId::ZERO); + for (x, y) in positions { + vector.0.push(Item::new_from_element(DVec2::new(x, y)).with_attribute(ATTR_ID, point_id.next_id())); + } + for references in [vec![0, 1, 2, 3, 0], vec![4, 5], vec![4, 6], vec![4, 7]] { + let ids: Vec = (1..references.len()).map(|_| segment_id.next_id()).collect(); + push_path(&mut paths, CurveType::Linear, references, ids); + } + assert!(vector.use_face_fill(&paths)); + let hub = vector.point_id_at(4).unwrap(); + let drawn = Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths); + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::ApplyPointDelta { point: hub, delta: DVec2::X }); + let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()).await; + + let first_path = |item: &Item| paths_from_item_attributes(item).unwrap().element(0).unwrap().0.iter_element_values().copied().collect::>(); + assert_eq!(first_path(&drawn), [0, 1, 2, 3, 0]); + assert_eq!(first_path(&modified), [0, 3, 2, 1, 0]); + } + + // Moving points leaves the paths shared with the incoming geometry, and where they sat among its attributes + #[tokio::test] + async fn moving_points_leaves_the_paths_shared_and_in_place() { + let mut bezpath = BezPath::new(); + bezpath.move_to((0., 0.)); + bezpath.line_to((10., 0.)); + bezpath.line_to((10., 10.)); + let drawn = Vector::item_from_bezpath(&bezpath).with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY); + let corner = drawn.element().point_id_at(1).unwrap(); + + let mut modification = VectorModification::default(); + modification.modify(&VectorModificationType::ApplyPointDelta { point: corner, delta: DVec2::X }); + let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()).await; + + assert_eq!(modified.element().0.element(1), Some(&DVec2::new(11., 0.))); + assert!(std::ptr::eq(paths_from_item_attributes(&drawn).unwrap(), paths_from_item_attributes(&modified).unwrap())); + assert_eq!(modified.attributes().keys().collect::>(), [ATTR_PATHS, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH]); + } + + // A point cloud comes out with an empty paths attribute placed last, whether the edit is made in place or by reweaving + #[tokio::test] + async fn a_point_cloud_gains_an_empty_paths_attribute() { + let mut cloud = Vector::default(); + cloud.0.push(Item::new_from_element(DVec2::ZERO).with_attribute(ATTR_ID, PointId::ZERO)); + let drawn = Item::new_from_element(cloud).with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY); + + let mut adds_a_point = VectorModification::default(); + adds_a_point.modify(&VectorModificationType::InsertPoint { + id: PointId::generate(), + position: DVec2::ONE, + }); + + for modification in [VectorModification::default(), adds_a_point] { + let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()).await; + + assert_eq!(paths_from_item_attributes(&modified).map(List::len), Some(0)); + assert_eq!(modified.attributes().keys().collect::>(), [ATTR_TRANSFORM, ATTR_PATHS, ATTR_EDITOR_LAYER_PATH]); + } + } } diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index 033a63a51d..4c50ed81a1 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -34,8 +34,8 @@ use vector_types::vector::misc::{ }; use vector_types::vector::style::{DashPattern, Gradient, GradientSettings, Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use vector_types::vector::{ - CurveType, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, handle_point, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, push_path, - span_endpoints, spans, + CurveType, Path, PointId, SegmentId, WorkingVector, curve_type_at, edit_item_geometry, edit_item_points, handle_point, no_paths, paths_from_item_attributes, paths_from_list_row_attributes, + push_path, shared_paths_from_item_attributes, span_endpoints, spans, }; /// Appends one point to the working form, returning the index that names it. @@ -129,7 +129,7 @@ trait VectorItemMut { impl VectorItemMut for Item { fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, &List, DAffine2)) { - let paths = paths_from_item_attributes(self).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(self); let transform = self.attribute_cloned_or_default::(ATTR_TRANSFORM); f(self.element_mut(), &paths, transform); } @@ -139,7 +139,7 @@ impl VectorItemMut for Item { fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, &List, DAffine2)) { match self.element_mut() { Graphic::Vector(item) => { - let paths = paths_from_item_attributes(item).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(item); let transform = item.attribute_cloned_or_default::(ATTR_TRANSFORM); f(item.element_mut(), &paths, transform); } @@ -571,7 +571,7 @@ async fn copy_to_points( let do_rotation = random_rotation.abs() > 1e-6; let points_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM); - let row_paths = paths_from_item_attributes(&row).cloned().unwrap_or_default(); + let row_paths = shared_paths_from_item_attributes(&row); for point in row.element().anchor_positions(&row_paths) { let translation = points_transform.transform_point2(point); @@ -638,7 +638,7 @@ async fn round_corners( let (radius, roundness, edge_length_limit, min_angle_threshold) = (*radius.element(), *roundness.element(), *edge_length_limit.element(), *min_angle_threshold.element()); let source_transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); let source_transform_inverse = source_transform.inverse(); - let source_paths = paths_from_item_attributes(&source).cloned().unwrap_or_default(); + let source_paths = shared_paths_from_item_attributes(&source); let (source, mut attributes) = source.into_parts(); // Flip the roundness to help with user intuition @@ -646,7 +646,7 @@ async fn round_corners( // Convert 0-100 to 0-0.5 let edge_length_limit = edge_length_limit * 0.005; - let (mut result, mut result_paths) = (Vector::default(), List::new()); + let mut rounded_subpaths = Vec::new(); for bezpath in source.stroke_bezpath_iter(&source_paths) { // The radius is measured after the transform, so scaling the layer doesn't scale its rounding @@ -655,14 +655,17 @@ async fn round_corners( // A subpath without corners to round passes through as it was let Some(mut rounded_subpath) = round_subpath_corners(&document_bezpath, radius, roundness, edge_length_limit, min_angle_threshold.to_radians()) else { - result.append_bezpath(&mut result_paths, &bezpath); + rounded_subpaths.push(bezpath); continue; }; rounded_subpath.apply_affine(Affine::new(source_transform_inverse.to_cols_array())); - result.append_bezpath(&mut result_paths, &rounded_subpath); + rounded_subpaths.push(rounded_subpath); } + let (mut result, mut result_paths) = (Vector::default(), List::new()); + result.append_bezpaths(&mut result_paths, &rounded_subpaths); + attributes.insert(ATTR_PATHS, result_paths); Item::from_parts(result, attributes) }) @@ -1032,14 +1035,14 @@ async fn extrude(_: impl Ctx, #[implementations(G #[node_macro::node(category("Vector: Modifier"), icon("NodeBoxWarp"), path(core_types::vector))] async fn box_warp(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item, #[expose] rectangle: Item) -> Item { let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM); - let target_paths = paths_from_item_attributes(&rectangle).cloned().unwrap_or_default(); + let target_paths = shared_paths_from_item_attributes(&rectangle); let target = rectangle.into_element(); V::map_vector_items(content, |content| { let mut row = content; { let transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM); - let paths = paths_from_item_attributes(&row).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&row); let vector = std::mem::take(row.element_mut()); // Get the bounding box of the source vector geometry @@ -1240,19 +1243,12 @@ async fn auto_tangents( let (spread, preserve_existing) = (*spread.element(), *preserve_existing.element()); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); - let source_paths = paths_from_item_attributes(&source).cloned().unwrap_or_default(); + let source_paths = shared_paths_from_item_attributes(&source); let (source, mut attributes) = source.into_parts(); - let (mut result, mut result_paths) = (Vector::default(), List::new()); - - // Each auto-tangented anchor is found as the end of its incoming segment, counted across all subpaths - let mut segment_offset = 0; - let mut smooth_segment_ends = Vec::new(); - let segments_after = |paths: &List, first_path: usize| -> usize { - (first_path..paths.len()) - .filter_map(|index| Some(paths.element(index)?.segment_count(curve_type_at(paths, index)))) - .sum() - }; + // Each subpath's softened bezpath, beside which of its manipulators were given auto-tangents + let mut softened_bezpaths = Vec::new(); + let mut auto_tangented_manipulators = Vec::new(); for (mut manipulators_list, is_closed) in source.stroke_manipulator_groups(&source_paths) { for manipulator in &mut manipulators_list { @@ -1266,9 +1262,8 @@ async fn auto_tangents( let mut unchanged = bezpath_from_manipulator_groups(&manipulators_list, is_closed); unchanged.apply_affine(Affine::new(transform.inverse().to_cols_array())); - let first_path = result_paths.len(); - result.append_bezpath(&mut result_paths, &unchanged); - segment_offset += segments_after(&result_paths, first_path); + softened_bezpaths.push(unchanged); + auto_tangented_manipulators.push(Vec::new()); continue; } @@ -1363,12 +1358,20 @@ async fn auto_tangents( let mut softened_bezpath = bezpath_from_manipulator_groups(&new_manipulators_list, is_closed); softened_bezpath.apply_affine(Affine::new(transform.inverse().to_cols_array())); - let first_path = result_paths.len(); - result.append_bezpath(&mut result_paths, &softened_bezpath); - let appended_segments = segments_after(&result_paths, first_path); + softened_bezpaths.push(softened_bezpath); + auto_tangented_manipulators.push(auto_tangented); + } + // Weaving every subpath at once costs O(points) rather than a pass over everything woven so far per subpath + let (mut result, mut result_paths) = (Vector::default(), List::new()); + let span_counts = result.append_bezpaths_counting_spans(&mut result_paths, &softened_bezpaths); + + // Each auto-tangented anchor is found as the end of its incoming segment, counted across all subpaths + let mut segment_offset = 0; + let mut smooth_segment_ends = Vec::new(); + for (auto_tangented, appended_segments) in auto_tangented_manipulators.iter().zip(span_counts) { // Mark auto-tangented points as having colinear handles - let num_manipulators = new_manipulators_list.len(); + let num_manipulators = auto_tangented.len(); for (i, _) in auto_tangented.iter().enumerate().filter(|&(_, &tangented)| tangented) { // For interior point i, the incoming segment is (i - 1) and the outgoing one is i, counted within this subpath. // For closed paths, point 0's incoming segment is the last one. For open paths, endpoints are never @@ -1398,7 +1401,7 @@ async fn auto_tangents( async fn bounding_box(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { V::map_vector_items(content, |content| { let mut content = content; - let paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&content); let (result, result_paths) = content .element() .bounding_box_rect(&paths) @@ -1658,11 +1661,11 @@ async fn offset_path( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let transform = Affine::new(transform_attribute.to_cols_array()); - let source_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let source_paths = shared_paths_from_item_attributes(&content); let vector = std::mem::take(content.element_mut()); let bezpaths = vector.stroke_bezpath_iter(&source_paths).collect::>(); - let (mut result, mut result_paths) = (Vector::default(), List::new()); + let mut offset_bezpaths = Vec::with_capacity(bezpaths.len()); // Perform operation on all subpaths in this shape. for mut bezpath in bezpaths { @@ -1683,9 +1686,12 @@ async fn offset_path( bezpath_out.apply_affine(transform.inverse()); // One closed subpath, open path. - result.append_bezpath(&mut result_paths, &bezpath_out); + offset_bezpaths.push(bezpath_out); } + let (mut result, mut result_paths) = (Vector::default(), List::new()); + result.append_bezpaths(&mut result_paths, &offset_bezpaths); + *content.element_mut() = result; content.set_attribute(ATTR_PATHS, result_paths); content @@ -1774,8 +1780,8 @@ fn solidify_stroke_list(content: List) -> List { .first_index_of(Cover::Stroke) .zip(appearance.first_index_of(Cover::Fill)) .is_some_and(|(stroke_index, fill_index)| stroke_index < fill_index); - let paths = attributes.get::>(ATTR_PATHS).cloned().unwrap_or_default(); - let bezpaths = vector.stroke_bezpath_iter(&paths).collect::>(); + let paths = attributes.get::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); + let bezpaths = vector.stroke_bezpath_iter(paths).collect::>(); let (mut solidified_stroke, mut solidified_stroke_paths) = (Vector::default(), List::new()); // Taking the existing stroke data and passing it to kurbo::stroke to generate new fill paths. @@ -1806,7 +1812,7 @@ fn solidify_stroke_list(content: List) -> List { // 0.25 is balanced between performance and accuracy of the curve. const STROKE_TOLERANCE: f64 = 0.25; - for mut path in bezpaths { + let solidified_bezpaths = bezpaths.into_iter().map(|mut path| { path.apply_affine(Affine::new(stroke.transform.to_cols_array())); let is_closed = matches!(path.elements().last(), Some(kurbo::PathEl::ClosePath)); @@ -1817,8 +1823,9 @@ fn solidify_stroke_list(content: List) -> List { solidified.apply_affine(Affine::new(stroke.transform.inverse().to_cols_array())); } - solidified_stroke.append_bezpath(&mut solidified_stroke_paths, &solidified); - } + solidified + }); + solidified_stroke.append_bezpaths(&mut solidified_stroke_paths, solidified_bezpaths); // If the original vector has a fill, preserve it as a separate item with the stroke coverages dropped let fill_row = has_fill.then(|| { @@ -1859,7 +1866,7 @@ async fn solidify_stroke(_: impl Ctx, #[implement #[node_macro::node(category("Vector: Modifier"), icon("NodeSeparateSubpaths"), path(core_types::vector))] async fn separate_subpaths(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> List { V::expand_vector_items(content, |content| { - let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let content_paths = shared_paths_from_item_attributes(&content); let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::>(); // Pass the original element through unchanged when it has no subpaths, so its attributes @@ -2004,9 +2011,9 @@ async fn sample_polyline( } }; - let (mut result, mut result_paths) = (Vector::default(), List::new()); + let mut sample_bezpaths = Vec::new(); - let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let content_paths = shared_paths_from_item_attributes(&content); for local_bezpath in content.element().stroke_bezpath_iter(&content_paths).collect::>() { // Apply the transform to compute sample locations in world space (for correct distance-based spacing) let mut world_bezpath = local_bezpath.clone(); @@ -2042,9 +2049,12 @@ async fn sample_polyline( if was_closed { sample_bezpath.close_path(); } - result.append_bezpath(&mut result_paths, &sample_bezpath); + sample_bezpaths.push(sample_bezpath); } + let (mut result, mut result_paths) = (Vector::default(), List::new()); + result.append_bezpaths(&mut result_paths, &sample_bezpaths); + *content.element_mut() = result; content.set_attribute(ATTR_PATHS, result_paths); content @@ -2077,17 +2087,18 @@ async fn simplify( let transform = Affine::new(transform_attribute.to_cols_array()); let inverse_transform = transform.inverse(); - let (mut result, mut result_paths) = (Vector::default(), List::new()); - - let item_paths = paths_from_item_attributes(&item).cloned().unwrap_or_default(); - for mut bezpath in item.element().stroke_bezpath_iter(&item_paths).collect::>() { + let item_paths = shared_paths_from_item_attributes(&item); + let simplified_bezpaths = item.element().stroke_bezpath_iter(&item_paths).map(|mut bezpath| { bezpath.apply_affine(transform); let mut simplified = simplify_bezpath(bezpath, tolerance, &options); simplified.apply_affine(inverse_transform); - result.append_bezpath(&mut result_paths, &simplified); - } + simplified + }); + + let (mut result, mut result_paths) = (Vector::default(), List::new()); + result.append_bezpaths(&mut result_paths, simplified_bezpaths); *item.element_mut() = result; item.set_attribute(ATTR_PATHS, result_paths); @@ -2174,9 +2185,9 @@ async fn decimate( let transform = Affine::new(transform_attribute.to_cols_array()); let inverse_transform = transform.inverse(); - let (mut result, mut result_paths) = (Vector::default(), List::new()); + let mut decimated_bezpaths = Vec::new(); - let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let content_paths = shared_paths_from_item_attributes(&content); for mut bezpath in content.element().stroke_bezpath_iter(&content_paths).collect::>() { bezpath.apply_affine(transform); @@ -2213,9 +2224,12 @@ async fn decimate( } new_bezpath.apply_affine(inverse_transform); - result.append_bezpath(&mut result_paths, &new_bezpath); + decimated_bezpaths.push(new_bezpath); } + let (mut result, mut result_paths) = (Vector::default(), List::new()); + result.append_bezpaths(&mut result_paths, &decimated_bezpaths); + *content.element_mut() = result; content.set_attribute(ATTR_PATHS, result_paths); content @@ -2245,7 +2259,7 @@ async fn cut_path( let euclidean = !parameterized_distance; - let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let content_paths = shared_paths_from_item_attributes(&content); let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::>(); let bezpath_count = bezpaths.len() as f64; @@ -2254,20 +2268,19 @@ async fn cut_path( let index = if t_value >= bezpath_count { (bezpath_count - 1.) as usize } else { t_value as usize }; if let Some(bezpath) = bezpaths.get(index).cloned() { - let (mut result_vector, mut result_paths) = (Vector::default(), List::new()); - - for (_, bezpath) in bezpaths.iter().enumerate().filter(|&(i, _)| i != index) { - result_vector.append_bezpath(&mut result_paths, bezpath); - } let t = if t_value == bezpath_count { 1. } else { t_value.fract() }; let t = if euclidean { TValue::Euclidean(t) } else { TValue::Parametric(t) }; - if let Some((first, second)) = split_bezpath(&bezpath, t) { - result_vector.append_bezpath(&mut result_paths, &first); - result_vector.append_bezpath(&mut result_paths, &second); - } else { - result_vector.append_bezpath(&mut result_paths, &bezpath); - } + // Every other bezpath comes first, then the two halves of the one being split, or all of it where it cannot be + let halves = split_bezpath(&bezpath, t); + let split = match &halves { + Some((first, second)) => vec![first, second], + None => vec![&bezpath], + }; + let others = bezpaths.iter().enumerate().filter(|&(i, _)| i != index).map(|(_, bezpath)| bezpath); + + let (mut result_vector, mut result_paths) = (Vector::default(), List::new()); + result_vector.append_bezpaths(&mut result_paths, others.chain(split)); *content.element_mut() = result_vector; content.set_attribute(ATTR_PATHS, result_paths); @@ -2437,7 +2450,7 @@ async fn scatter_points( let mut cloud = List::new(); - let content_paths = paths_from_item_attributes(&content).cloned().unwrap_or_default(); + let content_paths = shared_paths_from_item_attributes(&content); let path_with_bounding_boxes: Vec<_> = content .element() .stroke_bezpath_iter(&content_paths) @@ -2460,6 +2473,7 @@ async fn scatter_points( } // The scattered points replace the source shape entirely, leaving no paths + drop(content_paths); edit_item_geometry(&mut content, |vector, paths| { *vector = Vector(cloud); *paths = List::new(); @@ -2630,12 +2644,13 @@ async fn jitter_points( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2); - edit_item_geometry(&mut content, |vector, paths| { + edit_item_points(&mut content, |vector, paths| { + let tangents = if along_normals { vector.anchor_tangents(paths) } else { Vec::new() }; let anchors = vector.anchor_indices(paths); let deltas: Vec<_> = anchors .iter() .map(|&point_index| { - let normal = if along_normals { vector.point_tangent(paths, point_index).map(|t| -t.perp()) } else { None }; + let normal = tangents.get(point_index).copied().flatten().map(|tangent| -tangent.perp()); let offset = if let Some(normal) = normal { normal * (rng.random::() * 2. - 1.) @@ -2673,12 +2688,13 @@ async fn offset_points( let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM); let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2); - edit_item_geometry(&mut content, |vector, paths| { + edit_item_points(&mut content, |vector, paths| { + let tangents = vector.anchor_tangents(paths); let anchors = vector.anchor_indices(paths); let deltas: Vec<_> = anchors .iter() .map(|&point_index| { - let Some(normal) = vector.point_tangent(paths, point_index).map(|t| -t.perp()) else { + let Some(normal) = tangents.get(point_index).copied().flatten().map(|tangent| -tangent.perp()) else { return DVec2::ZERO; }; @@ -3868,7 +3884,7 @@ mod test { #[test] fn points_to_vector_keeps_positions_in_order_and_unconnected() { let result = vector_item_from_points(&SQUARE_WITH_CENTER); - let paths = paths_from_item_attributes(&result).cloned().unwrap_or_default(); + let paths = shared_paths_from_item_attributes(&result); assert_eq!(result.element().anchor_positions(&paths), SQUARE_WITH_CENTER); assert_eq!(result.element().segment_iter(&paths).count(), 0); } From 58b8aeb0e249af0c2279fdec3ffc23cdad63180c Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 18 Oct 2026 08:32:51 +0000 Subject: [PATCH 34/47] Fix viewport zoom perf regression caused by #3848 (#4749) When zooming in graphite the intermediate render cache is unused even when not using the outline node. This fixes that regression --- node-graph/libraries/rendering/src/renderer.rs | 5 +++-- node-graph/nodes/gstd/src/render_background.rs | 8 ++++---- node-graph/nodes/gstd/src/render_cache.rs | 7 +++++-- node-graph/nodes/gstd/src/render_node.rs | 2 +- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 14ad6b4b02..1ba2a4186f 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -355,7 +355,7 @@ pub struct RenderParams { pub inside_pattern: bool, pub artboard_background: Option, /// Viewport zoom level (document-space scale). Used to compute constant viewport-pixel stroke widths in Outline mode. - pub viewport_zoom: f64, + pub viewport_zoom: Option, /// The nearest ancestor's appearance, cascading to items that lack their own. pub inherited_appearance: Option, } @@ -450,8 +450,9 @@ fn to_point(p: DVec2) -> kurbo::Point { fn get_outline_styles(render_params: &RenderParams) -> (kurbo::Stroke, peniko::Color) { use core_types::consts::LAYER_OUTLINE_STROKE_WEIGHT; + let zoom = render_params.viewport_zoom.unwrap_or(1.); let outline_stroke = kurbo::Stroke { - width: LAYER_OUTLINE_STROKE_WEIGHT / if render_params.viewport_zoom > 0. { render_params.viewport_zoom } else { 1. }, + width: LAYER_OUTLINE_STROKE_WEIGHT / if zoom > 0. { zoom } else { 1. }, miter_limit: 4., join: Join::Miter, start_cap: Cap::Butt, diff --git a/node-graph/nodes/gstd/src/render_background.rs b/node-graph/nodes/gstd/src/render_background.rs index 45abc4429e..ae60d18974 100644 --- a/node-graph/nodes/gstd/src/render_background.rs +++ b/node-graph/nodes/gstd/src/render_background.rs @@ -24,7 +24,7 @@ async fn render_background<'a: 'n>( .downcast_ref::() .expect("Downcasting render params yielded invalid type"); - if !render_params.to_canvas() || render_params.viewport_zoom <= 0.0 { + if !render_params.to_canvas() || render_params.viewport_zoom.unwrap_or(1.) <= 0.0 { return data; } @@ -41,7 +41,7 @@ async fn render_background<'a: 'n>( foreground: foreground_texture.as_ref(), backgrounds: &metadata.backgrounds, document_to_screen: doc_to_screen, - zoom: render_params.viewport_zoom.to_f32(), + zoom: render_params.viewport_zoom.unwrap_or(1.).to_f32(), }) .await; @@ -55,10 +55,10 @@ async fn render_background<'a: 'n>( let logical_transform = glam::DAffine2::from_scale(glam::DVec2::splat(1.0 / render_params.scale)) * render_params.footprint.transform; - if render_params.viewport_zoom > 0. { + if render_params.viewport_zoom.unwrap_or_default() > 0. { let draw_checkerboard = |render: &mut SvgRender, rect: vello::kurbo::Rect, pattern_origin: glam::DVec2, checker_id_prefix: &str| { let checker_id = format!("{checker_id_prefix}-{}", generate_uuid()); - let cell_size = 8. / render_params.viewport_zoom; + let cell_size = 8. / render_params.viewport_zoom.unwrap_or(1.); let pattern_size = cell_size * 2.; write!( diff --git a/node-graph/nodes/gstd/src/render_cache.rs b/node-graph/nodes/gstd/src/render_cache.rs index e2a92f0ff2..a87c5689d2 100644 --- a/node-graph/nodes/gstd/src/render_cache.rs +++ b/node-graph/nodes/gstd/src/render_cache.rs @@ -12,6 +12,7 @@ use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams}; use std::collections::HashSet; use std::hash::Hash; use std::sync::{Arc, Mutex}; +use vector_types::vector::style::RenderMode; use wgpu_executor::WgpuExecutor; pub const TILE_SIZE: u32 = 256; @@ -330,12 +331,14 @@ pub async fn render_output_cache<'a: 'n>( #[data] tile_cache: TileCache, ) -> Item { let footprint = ctx.footprint(); - let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::()) else { + let Some(mut render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::().cloned()) else { log::warn!("render_output_cache: missing or invalid render params, falling back to direct render"); let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint); return data.eval(context.into_context()).await; }; + render_params.viewport_zoom = if let RenderMode::Outline = render_params.render_mode { render_params.viewport_zoom } else { None }; + // Fall back to direct render for non-Vello or zero-size viewports let physical_resolution = footprint.resolution; if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 { @@ -376,7 +379,7 @@ pub async fn render_output_cache<'a: 'n>( if missing_region.tiles.is_empty() { continue; } - let region = render_missing_region(missing_region, |ctx| data.eval(ctx), ctx.clone(), render_params, &footprint.transform, &device_origin_offset).await; + let region = render_missing_region(missing_region, |ctx| data.eval(ctx), ctx.clone(), &render_params, &footprint.transform, &device_origin_offset).await; new_regions.push(region); } diff --git a/node-graph/nodes/gstd/src/render_node.rs b/node-graph/nodes/gstd/src/render_node.rs index 58d2354284..094041fb41 100644 --- a/node-graph/nodes/gstd/src/render_node.rs +++ b/node-graph/nodes/gstd/src/render_node.rs @@ -173,7 +173,7 @@ async fn create_context<'a: 'n>( for_export: render_config.for_export, render_output_type, scale: render_config.scale, - viewport_zoom: logical_viewport.scale_magnitudes().x, + viewport_zoom: Some(logical_viewport.scale_magnitudes().x), ..Default::default() }; From 713b50c2a9e991d2fd05496ff70f1a5a3c05fcb1 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 18 Oct 2026 12:18:17 +0000 Subject: [PATCH 35/47] Add async execution RFC (#4556) * Add async execution rfc * Remove measurement * Update rfc --- node-graph/rfcs/async-execution-model.md | 269 +++++++++++++++++++++++ 1 file changed, 269 insertions(+) create mode 100644 node-graph/rfcs/async-execution-model.md diff --git a/node-graph/rfcs/async-execution-model.md b/node-graph/rfcs/async-execution-model.md new file mode 100644 index 0000000000..dd9b7c11d5 --- /dev/null +++ b/node-graph/rfcs/async-execution-model.md @@ -0,0 +1,269 @@ +- RFC PR: [#4556](https://github.com/GraphiteEditor/Graphite/pull/4556) +- Implementation PR: [#4731](https://github.com/GraphiteEditor/Graphite/pull/4731) + +# Summary + +Replace the boxed-future execution model with synchronous, poll-based evaluation. Nodes return a `Poll` state instead of a future. Async work runs on an executor outside of the graph, and when a task finishes it bumps a per-source generation counter. The counters are part of the `Context`, so the memo nodes downstream of a finished task see a new context and miss, while everything else stays cached. Deciding which part of the graph observes which counter reuses the context nullification pass from the [fine-grained context caching RFC](fine-grained-context-caching.md). + +# Motivation + +Currently every node's `eval` returns a `DynFuture` (`Pin>`), even a node that adds two numbers. A full graph evaluation is one large future which we drive once per render request. This has several costs: + +- Every eval boxes a future, so pure nodes pay for async machinery they never use. +- There is no progressive rendering. One slow async operation stalls the whole evaluation and there is nothing to show in the meantime. +- Driving async work by re-evaluating the graph costs a full traversal per poll. +- Errors are propagated as panics which we catch with `catch_unwind` at the root. +- A precompiled graph (the graph emitted as Rust source and run against a small runtime) can't be built on a box per edge. + +Most nodes are not asynchronous at all. Only a handful of them (web requests, resource loading, rasterization on the web) actually wait on something, so the model should make the common case cheap and give the few async nodes a way to report "not done yet". + +# Guide-level explanation + +## Evaluation states + +Evaluating a node is synchronous and always returns immediately. Instead of a value, a node returns a `Poll`: + +```rs +enum Poll { + /// Waiting on at least one future, with no placeholder to compute with. + Pending, + Final(T), + /// Computed from provisional data; recomputed once the source generation bumps. + Partial(T), + /// An error occurred; the boxed value is a stand-in, downstream keeps computing. + Fallback(Box<(T, NodeError)>), + /// An error occurred and no stand-in exists; the cone cannot compute this frame. + Error(Box), +} +``` + +Three of the variants carry a value (`Final`, `Partial`, `Fallback`) and two don't (`Pending`, `Error`). A value keeps flowing through the graph: a node that receives `Partial` computes as usual and marks its own output as `Partial`, and a node that receives `Fallback` computes on the stand-in value and passes the error along. Without a value there is nothing to compute with, so `Pending` and `Error` stop evaluation of everything that depends on them for this frame. + +When a node has several inputs, their states are combined with a meet: the result is `Final` only if all inputs are `Final`, and `Error` wins over `Pending`. + +## Writing nodes + +Node authors keep writing plain Rust functions, and the node macro generates the status handling. A function can return one of four things: + +- `-> T` for a pure kernel. The macro combines the input states and the author never sees them. +- `-> Result` for kernels that can fail or that evaluate lazy inputs themselves. `Interrupt` is either `Pending` or `Error(Box)` and implements `From`, so input bail-outs and the node's own errors both work with `?`. +- `-> Result` for an error with a stand-in value. +- `-> Poll` for full manual control. + +A lazy input (`content: impl Node`) is evaluated with `content.eval(ctx)?`. The `?` bails out of the kernel if the input is `Pending` or `Error`, which is the only sensible thing to do without a value. `Partial` and `Fallback` inputs return `Ok(value)`, and the macro remembers that one of the inputs was provisional or had failed. + +```rs +#[node_macro::node(category("Debug"))] +fn error(_: impl Ctx, value: Item, fail: Item) -> Result, Interrupt> { + match *fail.element() { + true => Err(NodeError::new("debug error").into()), + false => Ok(value), + } +} +``` + +Only inputs that were actually evaluated affect the result, so the branch a `switch` did not take does not turn its output `Partial`. Nodes for which placeholder data makes no sense can opt out with `#[node(no_partial)]`, which treats a `Partial` input like a `Pending` one. + +Migrating an existing node that is only async because it awaits its inputs is mechanical: remove `async`, replace `.eval(ctx).await` with `.eval(ctx)?`, and return `Result`. + +## Async nodes + +An `async fn` node is a *source*: it starts work that runs outside of the graph. The macro evaluates its inputs, spawns the future onto the runtime, and returns a placeholder right away: + +```rs +#[node_macro::node(category("Web Request"), placeholder = pending_text)] +async fn get_request(_: impl Ctx, url: Item) -> Item { ... } + +fn pending_text(_url: &Item) -> Item { + Item::default() +} +``` + +The placeholder function receives references to the node's inputs. While the request is in flight, the node returns `Partial(placeholder)`. Without a placeholder function it returns `Pending`. Once the request has finished, the node returns its result as `Final`. + +The future has to be `'static`, so the async body cannot borrow the context or evaluate inputs lazily. It gets clones of everything it needs. If any input is still `Partial`, the node returns its placeholder without spawning, so no request is sent based on placeholder data. + +## How a finished task reaches the graph + +Every async node has a `SourceId`, which is a hash of its document node path. For each source, the runtime keeps a generation counter that is incremented when one of the source's tasks finishes. Before every evaluation, the editor puts a snapshot of all counters into the root `Context`. + +Memo nodes already hash the context to decide whether they can reuse their cached value. With the generations in the context, a finished task changes the hash for exactly the memo nodes that depend on that source, and the next evaluation recomputes them with the real value. Everything else still hits its cache. Nothing walks the graph at runtime to find the affected nodes. + +Which sources a part of the graph depends on is known at compile time, using the same analysis that decides which context features a branch needs. Where branches with different sources meet, the compiler inserts a context modification node that drops the generations of the other sources, just like it already drops unused features. + +## Partial results in the editor + +A `Partial` frame is shown in the viewport like a `Final` one, so the rest of the document stays visible while a request is pending. If the whole graph is `Pending`, the viewport keeps showing the last frame. An export waits until the result is `Final`. + +Errors are shown on the node they came from. Errors that are only produced because some input was still a placeholder are never shown, since they would disappear once the real value arrives. + +# Reference-level explanation + +## Node trait + +```rs +pub trait Node { + type Output; + fn eval(&self, input: &Input) -> Poll; +} +``` + +Some decisions about the shape of this trait: + +- **Plain `&self` receiver.** An `&'i self` receiver requires the forwarding impl `impl Node for &'i N`, which ties the borrow of the node to the eval lifetime, and shared references then can't satisfy higher-ranked bounds. With `&self`, sharing and type erasure compose. In exchange, nodes cannot lend their own storage and values cross edges owned. +- **No lifetime parameter on the trait.** With a plain `&self`, a lifetime in the output can only come from the input type, so the trait doesn't need one. `Poll` is part of the signature the same way `std::task::Poll` is part of `Future::poll`. +- **Input by reference.** `Input` is the owned context type and callers pass `&Context`. A node that modifies the context keeps one local copy, changes it between calls, and passes `&local` down. This is sound because nodes never store their input. + +`Node::reset` is removed, and so is `Type::Future`, because no node returns a future anymore. The type-erased form is `dyn Node>`: the input is downcast by reference and only the output value is boxed. Node constructors are plain functions. + +## Status cell + +The generated `eval` owns a `Status` cell on the stack. Lazy inputs are passed to the kernel as `LazyInput` handles that hold a reference to the cell and their input index, and value inputs are evaluated through the same cell before the kernel runs. `LazyInput::eval` maps the input state as follows: + +- `Final(v)` returns `Ok(v)`. +- `Partial(v)` returns `Ok(v)` and marks the cell as partial. +- `Fallback(v, e)` returns `Ok(v)` and stores `e` if it is the first input error. +- `Pending` and `Error(e)` return `Err(Interrupt)`. The cell remembers the strongest interrupt. + +After the kernel returns, the generated code folds the cell into the result. `Poll`-tier kernels get their lazy inputs as plain `&impl Node` handles that only add trace indices, and their returned state is merged with the cell. + +Finality is tracked as a separate `Finality` (`Final | Partial`) in the cell instead of a sixth `Poll` variant. The reason is that `meet(Partial, Fallback)` would otherwise be `Fallback`, and an error that only exists because of a placeholder would look like a real document error. With the separate flag, partiality wins: + +- A node with any `Partial` input returns `Partial`, and stand-in errors from its inputs are dropped. +- An error the node raises itself on provisional data is withheld. A stand-in error is dropped, and an `Err` from the kernel becomes `Pending`. +- An `Error` coming from an input still propagates, because it was computed from final data further upstream. + +The layout is one tag and one payload word for pointer-sized values: `Poll>` and `Poll` are both 16 bytes. The stand-in and its error share a box, and `Error` boxes the error alone. Progress percentages are deliberately not part of `Poll`. They change often and must not invalidate the dataflow, so they belong in the monitor side channel. + +## Errors + +`NodeError` wraps an `Arc`, so nodes can return any error type. It records a trace of input indices from the node that raised it up to the output. We use indices instead of names because a node can have two inputs of the same type. The handles push the indices, so node code never does. + +If a node raises its own error while one of its inputs has already failed, the input's error is kept in the new error's `upstream` list. + +The editor resolves a trace by walking the input indices through the executor's node tree, starting at the output node, and then maps the resulting proto node to its document node paths. `upstream` errors are resolved starting from the node that raised the outer error. Rank promotion adapters are inserted between nodes at build time and add their own entry to the trace, so the walk currently skips them by hand. + +Panics are not part of this model. The editor runtime still wraps evaluation in `catch_unwind` and reports a panic separately from node errors. + +## Async node code generation + +For an `async fn` node, the macro adds two hidden inputs: the `RuntimeHandle` from the `runtime` scope and the node's `SourceId`, which is injected as a reflection input like the document node path is. The `SourceId` is a hash of the document node path, so it stays the same across recompiles. + +The struct gets a `Slots`, an `Arc>>>`: + +```rs +enum Slot { + Ready(Poll), + Pending(AbortHandle), +} +``` + +The slots are keyed by a hash of the node's context with the node's own source removed from the generations, so the generation bump caused by its own task does not change the key. Evaluation goes like this: + +1. Evaluate the inputs through the status cell. Bail on `Pending` or `Error`, and return the placeholder (or `Pending`) if any input is `Partial`. +2. A `Ready` slot returns its stored state. A `Pending` slot returns the placeholder. +3. Otherwise build the future and poll it once inline with a no-op waker. A future that is ready immediately is stored as `Ready` without spawning a task or bumping a generation. +4. Otherwise spawn it onto the runtime, store a `Pending` slot with the task's abort handle, and return the placeholder. + +The spawned task holds a weak reference to the slot map. A node that `BorrowTree` keeps across a recompile still gets its result. When the last owner of a slot map is dropped, its `Pending` slots are dropped too, and that aborts their tasks. Since the mutex around the map also publishes the result to the next `eval`, the slot needs no additional synchronization. + +Async nodes don't get the element-wise variants over lists that other nodes get. + +## Generations and context nullification + +The runtime keeps a `HashMap` of generations. The task wrapper bumps the generation after the task has finished: + +```rs +task.await; +if let Some(generation) = generations.lock().get_mut(&source) { + *generation += 1; +} +``` + +A missing entry means the source was removed in a recompile, and then the bump does nothing. + +Before every evaluation the editor takes a snapshot of the generations, sorted by `SourceId` so that hashing is deterministic, and puts it into the root context. `OwnedContextImpl` has a new `generations` field which is part of its hash. + +`find_context_dependencies` now tracks a `ContextModification` for each node instead of only `ContextFeatures`: + +```rs +pub struct ContextModification { + pub features: ContextFeatures, + pub sources: BTreeSet, +} +``` + +The `SourceId` value node of an async node contributes that source, and a node's set of sources is the union of its children's. Unlike features, sources are never removed on the way to the root, because only the root injects generations. When the branches of a node have different modifications, the existing rule inserts a `context_modification` node with the branch's `ContextModification` as payload. It nullifies the unused features as before and also drops the generations of all sources outside the set. + +Context dependencies are no longer stored on document nodes. The preprocessor fills them in from the node registry metadata. + +## Caching + +A memo node keeps a single entry. It caches `Final`, `Partial`, and `Fallback` results and never caches `Pending` or `Error`. Caching `Partial` is fine because the generation bump that finalizes the value also changes the key. + +The render output cache includes the generation snapshot in its tile key. Tiles store their `Poll` state. Partial tiles are composited into a `Partial` frame, and a `Pending` or `Error` tile stops the whole frame. + +## Runtime + +The runtime is split into a host-facing and a node-facing trait: + +```rs +/// Host-provided task executor with no graph knowledge. +pub trait Spawn { + fn spawn(&self, task: Task); +} + +/// Node-facing scope input. +pub trait Runtime { + fn spawn(&self, source: SourceId, task: Task); +} +``` + +`Task` is a boxed `'static` future that is `Send` on native targets only. The editor owns an `AsyncRuntime`, which updates the live sources (`retain_sources`) and takes snapshots of the generations (`snapshot`). Nodes get a cloneable `RuntimeHandle` to the same state through the `runtime` scope input, which is always present. Graphs without async nodes never read it. + +The host provides the `Spawn` implementation: a tokio runtime on desktop and `spawn_local` on the web. The editor wraps it so that a finished task sets a dirty flag and calls the runtime's wake callback (a channel send on desktop, a queued runtime run on the web). + +Executor construction, update, and execution are plain functions, and `execute` returns `Poll`. The only await left in the editor runtime is the GPU readback for exports and the eyedropper, which can't block on the web. On desktop, the runtime runs on its own thread under `block_on`, and the readback polls the device until the copy is done. + +We don't use wakers to notify the graph. A waker resumes a suspended computation, and graph evaluations never suspend: every evaluation is a fresh call. A wake also doesn't mean that the task has finished, and wakers don't compose across host executors. + +## Scheduling + +- Generations are read once per evaluation. A task that finishes during an evaluation takes effect in the next one. +- The dirty flag is checked once per runtime run, so N finished tasks cause one re-render of the last viewport request. +- On recompile, `retain_sources` removes sources that no longer exist and adds new ones at generation zero. Nodes that were removed drop their slots, which aborts their tasks. + +The editor maps the top-level `Poll` to an `ExecutionResult`: `Pending`, `Value`, `Fallback(value, errors)`, `Error(errors)`, or `Panic`. A `Pending` result keeps the last frame and its errors on screen. An export treats `Partial` like `Pending`: it is parked and re-run on every dirty wake until the result is final, and the runtime doesn't process other requests until then. + +## Overhead + +Three properties keep the status handling cheap: the stand-in and its error share a box, the status is a single enum instead of a value plus a separate state (which brings `Poll` from 48 down to 16 bytes), and the status functions are `#[inline(always)]`. A plain `#[inline]` hint loses to the inliner's cost model because of the drop glue in the error branches. This lets statically composed nodes fold the `Pending` checks and meets away. In the interpreter, a type-erased edge costs an indirect call, an input downcast, and one boxed output, but there is no boxed future per evaluation anymore. + +# Drawbacks + +- Everything downstream of an async node is computed twice: once with the placeholder and once with the real value. That is the price of progressive rendering, and `#[node(no_partial)]` avoids it where it isn't wanted. +- `'static` futures cannot evaluate their inputs lazily. Everything a future needs is evaluated and cloned before it is spawned. +- The migration is a single cutover. The macro, the registry, and the executor change together, so even though node bodies migrate mechanically, it lands as one large PR. +- Slot maps keep every finished result per context hash for as long as the node lives. Nothing evicts them yet. +- An async node without a placeholder serializes its requests inside nodes that evaluate a lazy input several times, like `repeat`. The first in-flight iteration returns `Pending`, the `?` leaves the loop, and the later iterations are only spawned after the earlier ones have finished, one re-render each. With a placeholder, every iteration returns `Partial` and all futures are spawned in the first frame. + +# Rationale and alternatives + +- **Inline pinned futures.** We could store each node's future unboxed and poll it once per graph evaluation. That needs soundness arguments for `Pin` through a `Mutex`, splits the trait in two, conflicts with `BorrowTree` moving nodes around, and still turns every graph evaluation into a polling iteration. +- **Poll-once compatibility shims** for existing `async fn` bodies. Real IO has to move into source nodes anyway, since a body that is polled once per frame would send its request again every frame. The remaining async bodies only awaited their inputs and are easy to migrate by hand. +- **Bail on `Partial` and `Fallback` too**, treating every non-final state as `Err`. This would remove progressive rendering and stand-in values, and a single error type carrying a value doesn't work across inputs of different types. It remains available per node as `no_partial`. +- **Wakers as completion signal.** A wake doesn't mean completion, wakers don't compose across host executors, and there is no suspended computation to resume. +- **Clearing downstream caches when a task finishes.** This needs the graph topology at runtime and extra logic to track caches. Putting the generation into the hash has the same effect, is set up entirely by the compiler pass, and works the same way for a precompiled graph. + +# Unresolved questions + +- Futures that publish intermediate results (streams, progressive image decoding) would want a weaker kind of invalidation than "finished". +- How slot maps should evict old entries, and whether memo nodes need more than one entry for contexts that alternate between evaluations. +- Spawned futures need `Send` on native targets but can't be `Send` on the web. +- Whether async nodes should require a placeholder, or whether looping nodes should evaluate all iterations before bailing on `Pending`, so that requests inside a loop are spawned in parallel. + +# Future possibilities + +- A borrowed context with a stack-based lifetime instead of the current `Arc` allocation. +- Type-erased edges with unboxed values. In the prototype, these cost 1.8ns per edge compared to roughly 9ns for the box-and-downcast model. +- Resolving error traces through rank promotion adapters inside the runtime instead of in the editor. From c7e9d79f7ed715b8bf5195d1d1379018cd775d11 Mon Sep 17 00:00:00 2001 From: Timon Date: Sun, 18 Oct 2026 18:25:10 +0000 Subject: [PATCH 36/47] Implement async refactor (#4731) * Add editor task module, drop NodeGraphUpdateSender * Remove Node::reset and unused value nodes * Remove unneeded async from vector nodes * Remove unneeded async from graphic nodes * Remove unneeded async from raster nodes * Remove unneeded async from the remaining nodes * Make most node fns private * Make node construction sync * Remove block_on around node construction * Move GPU readback into ConvertAsync * Make Convert sync * Make wgpu pipelines and vello rendering sync * Make convert, brush and render nodes sync * Pass editor API as owned Arc * Take scope inputs by value * Move Spawn and Task into core-types * Add Poll type and status tracking * Add source generations to context * Stop storing context features in the document * Track source ids in context modification * Add async runtime and memo table * Pass runtime through scope, expose source ids * Set up async runtime in editor, CLI and benches * Give async nodes runtime and source id inputs * Classify node return types in the macro * Make Node eval sync and return Poll * Make lazy input nodes, tests and benches sync * Rerender when a spawned task finishes * Rerender in CLI until all tasks are done * Abort pending tasks when node is dropped * Trace errors through Poll node inputs * Let node errors carry upstream errors * Resolve error traces to the origin node * Show evaluation errors in the node graph * Default unmapped item primaries to a value * Add debug nodes * Memoize fallback results too * Show multiple node graph errors * Report node errors in CLI * Attach input fallback error as upstream * Keep input fallback error when node fails * Keep Poll status in render cache * Keep last frame while graph is pending * Treat partial export output as pending * Move environment from global to dispatcher * Add editor builder, drop global node runtime * Add Wake message, rerun graph when tasks finish * Add source generation tests * Add test for node error origin * Add render status overlay * Replace error artwork with render status * Poll node graph through portfolio message * Minor review fixups * Remove future type and macro --------- Co-authored-by: Dennis Kobert --- Cargo.lock | 6 +- desktop/src/app.rs | 72 +-- desktop/src/event.rs | 4 +- desktop/src/lib.rs | 1 + desktop/src/render/state.rs | 2 +- desktop/src/spawner.rs | 13 + .../src/handle_desktop_wrapper_message.rs | 3 +- desktop/wrapper/src/lib.rs | 44 +- desktop/wrapper/src/message_dispatcher.rs | 12 - desktop/wrapper/src/messages.rs | 1 - document/graph-storage/src/attributes/attr.rs | 1 - document/graph-storage/src/from_runtime.rs | 9 - .../graph-storage/src/tests/round_trip.rs | 15 - document/graph-storage/src/to_runtime.rs | 2 +- editor/Cargo.toml | 4 - editor/src/application.rs | 83 +--- editor/src/builder.rs | 215 +++++++++ editor/src/dispatcher.rs | 105 +++-- editor/src/lib.rs | 2 + .../app_window/app_window_message_handler.rs | 4 +- .../src/messages/frontend/frontend_message.rs | 9 +- editor/src/messages/frontend/utility_types.rs | 9 + editor/src/messages/future/future_message.rs | 3 +- .../messages/future/future_message_handler.rs | 129 +----- editor/src/messages/future/mod.rs | 2 +- .../input_mapper_message_handler.rs | 12 +- .../messages/input_mapper/input_mappings.rs | 16 +- .../key_mapping_message_handler.rs | 20 +- .../input_mapper/utility_types/keyboard.rs | 51 +-- .../input_mapper/utility_types/macros.rs | 4 +- .../input_mapper/utility_types/misc.rs | 25 +- .../input_preprocessor_message_handler.rs | 34 +- .../messages/layout/layout_message_handler.rs | 23 +- .../layout/utility_types/layout_widget.rs | 52 ++- editor/src/messages/message.rs | 1 + .../portfolio/document/document_diff.rs | 4 +- .../document/document_message_handler.rs | 10 +- .../navigation/navigation_message_handler.rs | 6 +- .../document_node_derive.rs | 2 - .../document/node_graph/node_graph_message.rs | 5 +- .../node_graph/node_graph_message_handler.rs | 74 ++- .../document/node_graph/node_inspector.rs | 5 +- .../document/node_graph/utility_types.rs | 6 + .../document/storage_tests/lifecycle_tests.rs | 2 +- .../utility_types/network_interface.rs | 1 - .../utility_types/network_interface/apply.rs | 10 - .../network_interface/editor_delta.rs | 11 - .../network_interface/mutations.rs | 8 - .../network_interface/store/cursor.rs | 15 - .../network_interface/template.rs | 9 +- .../messages/portfolio/document_migration.rs | 9 - .../messages/portfolio/portfolio_message.rs | 1 + .../portfolio/portfolio_message_handler.rs | 83 ++-- editor/src/messages/prelude.rs | 2 +- editor/src/messages/tool/utility_types.rs | 16 +- editor/src/node_graph_executor.rs | 150 ++++-- editor/src/node_graph_executor/runtime.rs | 359 ++++++++------- editor/src/node_graph_executor/runtime_io.rs | 44 -- editor/src/task.rs | 4 + editor/src/test_utils.rs | 65 ++- .../src/components/panels/Document.svelte | 46 +- frontend/src/components/views/Graph.svelte | 16 +- frontend/src/stores/document.ts | 12 +- frontend/src/stores/node-graph.ts | 10 +- frontend/wrapper/Cargo.toml | 3 +- frontend/wrapper/src/editor_wrapper.rs | 24 +- frontend/wrapper/src/helpers.rs | 88 +--- frontend/wrapper/src/lib.rs | 26 +- node-graph/README.md | 4 +- node-graph/graph-craft/src/document.rs | 19 +- node-graph/graph-craft/src/document/value.rs | 111 +++-- .../graph-craft/src/graphene_compiler.rs | 4 +- node-graph/graph-craft/src/proto.rs | 155 +++++-- node-graph/graph-craft/src/runtime_delta.rs | 8 +- node-graph/graphene-cli/Cargo.toml | 1 - node-graph/graphene-cli/src/export.rs | 63 ++- node-graph/graphene-cli/src/main.rs | 52 ++- .../benches/benchmark_util.rs | 12 +- .../benches/run_cached.rs | 4 +- .../benches/run_cached_gungraun.rs | 4 +- .../benches/run_demo_art_criterion.rs | 8 +- .../interpreted-executor/benches/run_once.rs | 2 +- .../benches/run_once_gungraun.rs | 2 +- .../benches/update_executor.rs | 4 +- .../benches/update_executor_gungraun.rs | 4 +- .../src/dynamic_executor.rs | 151 +++--- .../src/dynamic_executor/test.rs | 260 ++++++++--- node-graph/interpreted-executor/src/lib.rs | 3 +- .../interpreted-executor/src/node_registry.rs | 160 +++---- node-graph/interpreted-executor/src/util.rs | 37 +- .../libraries/application-io/src/lib.rs | 28 +- node-graph/libraries/core-types/Cargo.toml | 2 +- .../libraries/core-types/src/context.rs | 78 +++- .../libraries/core-types/src/generic.rs | 11 +- node-graph/libraries/core-types/src/lib.rs | 82 ++-- node-graph/libraries/core-types/src/ops.rs | 52 ++- node-graph/libraries/core-types/src/poll.rs | 429 ++++++++++++++++++ .../libraries/core-types/src/registry.rs | 127 ++---- .../libraries/core-types/src/runtime.rs | 362 +++++++++++++++ node-graph/libraries/core-types/src/types.rs | 43 -- node-graph/libraries/core-types/src/value.rs | 208 +-------- node-graph/libraries/graphene-hash/src/lib.rs | 11 + node-graph/libraries/wgpu-executor/src/lib.rs | 7 +- .../libraries/wgpu-executor/src/pipeline.rs | 32 +- .../per_pixel_adjust_runtime.rs | 6 +- .../wgpu-executor/src/texture_conversion.rs | 34 +- node-graph/node-macro/src/codegen.rs | 342 +++++++++----- node-graph/node-macro/src/parsing.rs | 146 +++++- .../src/shader_nodes/per_pixel_adjust.rs | 8 +- node-graph/node-macro/src/validation.rs | 13 +- node-graph/nodes/brush/src/basic_brush/mod.rs | 8 +- .../nodes/brush/src/basic_brush/pipeline.rs | 6 +- node-graph/nodes/gcore/src/animation.rs | 18 +- node-graph/nodes/gcore/src/context.rs | 4 +- .../nodes/gcore/src/context_modification.rs | 53 ++- node-graph/nodes/gcore/src/memo.rs | 87 +++- node-graph/nodes/gcore/src/ops.rs | 8 +- node-graph/nodes/graphic/src/artboard.rs | 12 +- node-graph/nodes/graphic/src/graphic.rs | 46 +- node-graph/nodes/gstd/src/any.rs | 14 +- node-graph/nodes/gstd/src/lib.rs | 1 + .../nodes/gstd/src/platform_application_io.rs | 76 ++-- node-graph/nodes/gstd/src/poll_debug.rs | 131 ++++++ .../nodes/gstd/src/render_background.rs | 27 +- node-graph/nodes/gstd/src/render_cache.rs | 111 +++-- node-graph/nodes/gstd/src/render_node.rs | 24 +- .../nodes/gstd/src/render_pixel_preview.rs | 39 +- node-graph/nodes/math/src/lib.rs | 12 +- node-graph/nodes/path-bool/src/lib.rs | 2 +- node-graph/nodes/raster/src/adjustments.rs | 6 +- node-graph/nodes/raster/src/blending_nodes.rs | 4 +- node-graph/nodes/raster/src/dehaze.rs | 2 +- node-graph/nodes/raster/src/filter.rs | 4 +- .../nodes/raster/src/image_color_palette.rs | 4 +- node-graph/nodes/raster/src/std_nodes.rs | 16 +- node-graph/nodes/repeat/src/repeat_nodes.rs | 151 +++--- node-graph/nodes/text/src/lib.rs | 9 +- .../nodes/transform/src/transform_nodes.rs | 20 +- .../vector/src/vector_modification_nodes.rs | 28 +- node-graph/nodes/vector/src/vector_nodes.rs | 320 +++++++------ node-graph/preprocessor/src/lib.rs | 105 ++++- 141 files changed, 4077 insertions(+), 2474 deletions(-) create mode 100644 desktop/src/spawner.rs create mode 100644 editor/src/builder.rs delete mode 100644 editor/src/node_graph_executor/runtime_io.rs create mode 100644 editor/src/task.rs create mode 100644 node-graph/libraries/core-types/src/poll.rs create mode 100644 node-graph/libraries/core-types/src/runtime.rs create mode 100644 node-graph/nodes/gstd/src/poll_debug.rs diff --git a/Cargo.lock b/Cargo.lock index 28be754b33..f75eda47ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -913,6 +913,7 @@ dependencies = [ "color", "ctor", "dyn-any", + "futures", "glam 0.33.10", "graphene-hash", "image", @@ -932,7 +933,6 @@ dependencies = [ "serde_json", "skrifa 0.42.1", "tinyvec", - "tokio", "tsify", "wasm-bindgen", ] @@ -2132,7 +2132,6 @@ dependencies = [ "document-container", "document-format", "fern", - "futures", "graph-craft", "graphene-std", "image", @@ -2424,7 +2423,6 @@ dependencies = [ "serde_json", "simplecss", "snapping", - "spin", "thiserror 2.0.18", "tokio", "tsify", @@ -2432,7 +2430,6 @@ dependencies = [ "usvg", "vello", "wasm-bindgen", - "wasm-bindgen-futures", "web-sys", "wgpu-executor", "zip", @@ -2464,6 +2461,7 @@ dependencies = [ "serde-wasm-bindgen", "serde_bytes", "serde_json", + "spin", "tsify", "wasm-bindgen", "wasm-bindgen-futures", diff --git a/desktop/src/app.rs b/desktop/src/app.rs index 96cfbb1b56..6b0ea29583 100644 --- a/desktop/src/app.rs +++ b/desktop/src/app.rs @@ -22,10 +22,11 @@ use crate::input::InputState; use crate::persist; use crate::preferences; use crate::render::{RenderError, RenderState}; +use crate::spawner::TokioSpawner; use crate::ui::{InputEvent, UiCommand, UiInstance}; use crate::window::Window; use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences}; -use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages}; +use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, serialize_frontend_messages}; pub(crate) struct App { render_state: Option, @@ -77,14 +78,40 @@ impl App { let exiting = Arc::new(AtomicBool::new(false)); - let rendering_app_event_scheduler = app_event_scheduler.clone(); let (start_render_sender, start_render_receiver) = std::sync::mpsc::sync_channel(1); + + let async_runtime = tokio::runtime::Builder::new_multi_thread() + .thread_name("graphite-async") + .enable_all() + .build() + .expect("failed to construct tokio runtime"); + + let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage"); + + let wake_scheduler = app_event_scheduler.clone(); + let editor_wake = move || { + wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake)); + }; + let runtime_wake_sender = start_render_sender.clone(); + let runtime_wake = move || { + let _ = runtime_wake_sender.try_send(()); + }; + let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new( + rand::rng().random(), + Arc::new(resource_storage), + Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())), + wgpu_context.clone(), + TokioSpawner::new(async_runtime.handle().clone()), + editor_wake, + runtime_wake, + ); + + let rendering_app_event_scheduler = app_event_scheduler.clone(); let exiting_clone = exiting.clone(); std::thread::spawn(move || { - let runtime = tokio::runtime::Runtime::new().unwrap(); loop { - let result = runtime.block_on(DesktopWrapper::execute_node_graph()); - rendering_app_event_scheduler.schedule(AppEvent::NodeGraphExecutionResult(result)); + let texture = async_runtime.block_on(node_runtime.run()); + rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture)); let _ = start_render_receiver.recv_timeout(Duration::from_millis(10)); if exiting_clone.load(Ordering::Relaxed) { break; @@ -92,21 +119,6 @@ impl App { } }); - let resource_storage = MmapResourceStorage::new(dirs::app_resources_dir()).expect("Failed to initialize on-disk resource storage"); - - // Wake the winit event loop when an editor future completes. - let wake_scheduler = app_event_scheduler.clone(); - let wake = Arc::new(move || { - wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake)); - }); - let desktop_wrapper = DesktopWrapper::new( - rand::rng().random(), - Arc::new(resource_storage), - Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())), - wgpu_context.clone(), - wake, - ); - Self { render_state: None, wgpu_context, @@ -436,19 +448,15 @@ impl App { } } AppEvent::DesktopWrapperMessage(message) => self.dispatch_desktop_wrapper_message(message), - AppEvent::NodeGraphExecutionResult(result) => match result { - NodeGraphExecutionResult::HasRun(texture) => { - self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::PollNodeGraphEvaluation); - if let Some(texture) = texture - && let Some(render_state) = self.render_state.as_mut() - && let Some(window) = self.window.as_ref() - { - render_state.bind_viewport_texture(texture); - window.request_redraw(); - } + AppEvent::ViewportTexture(texture) => { + if let Some(texture) = texture + && let Some(render_state) = self.render_state.as_mut() + && let Some(window) = self.window.as_ref() + { + render_state.bind_viewport_texture(texture); + window.request_redraw(); } - NodeGraphExecutionResult::NotRun => {} - }, + } AppEvent::UiUpdate(texture) => { if let Some(render_state) = self.render_state.as_mut() { render_state.bind_ui_texture(texture); diff --git a/desktop/src/event.rs b/desktop/src/event.rs index cbe0f77f3b..87ae4ce8c7 100644 --- a/desktop/src/event.rs +++ b/desktop/src/event.rs @@ -1,5 +1,5 @@ use crate::ui::Cursor; -use crate::wrapper::NodeGraphExecutionResult; +use crate::wrapper::Texture; use crate::wrapper::messages::DesktopWrapperMessage; pub(crate) enum AppEvent { @@ -7,7 +7,7 @@ pub(crate) enum AppEvent { CursorChange(Cursor), WebCommunicationInitialized, DesktopWrapperMessage(DesktopWrapperMessage), - NodeGraphExecutionResult(NodeGraphExecutionResult), + ViewportTexture(Option), ClipboardRead, ClipboardWrite { content: String, diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs index cfff56cd5b..d4e241dd43 100644 --- a/desktop/src/lib.rs +++ b/desktop/src/lib.rs @@ -22,6 +22,7 @@ mod persist; mod preferences; mod render; mod socket; +mod spawner; mod window; pub(crate) mod consts; diff --git a/desktop/src/render/state.rs b/desktop/src/render/state.rs index 3958b8cd3c..c3395c16a4 100644 --- a/desktop/src/render/state.rs +++ b/desktop/src/render/state.rs @@ -228,7 +228,7 @@ impl RenderState { return; }; let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height()); - let result = futures::executor::block_on(self.executor.render_vello_scene(&scene, size, &Default::default(), None)); + let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None); match result { Ok(texture) => { self.overlays_texture = Some(texture); diff --git a/desktop/src/spawner.rs b/desktop/src/spawner.rs new file mode 100644 index 0000000000..afdfd077fa --- /dev/null +++ b/desktop/src/spawner.rs @@ -0,0 +1,13 @@ +use crate::wrapper::{Spawn, Task}; + +pub(crate) struct TokioSpawner(tokio::runtime::Handle); +impl TokioSpawner { + pub(crate) fn new(handle: tokio::runtime::Handle) -> Self { + Self(handle) + } +} +impl Spawn for TokioSpawner { + fn spawn(&self, task: Task) { + self.0.spawn(task); + } +} diff --git a/desktop/wrapper/src/handle_desktop_wrapper_message.rs b/desktop/wrapper/src/handle_desktop_wrapper_message.rs index df3237623a..5c4bbcc257 100644 --- a/desktop/wrapper/src/handle_desktop_wrapper_message.rs +++ b/desktop/wrapper/src/handle_desktop_wrapper_message.rs @@ -10,7 +10,7 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess dispatcher.queue_editor_message(*message); } DesktopWrapperMessage::Wake => { - dispatcher.queue_editor_message(EditorMessage::Future(FutureMessage::Wake)); + dispatcher.queue_editor_message(EditorMessage::Wake); } DesktopWrapperMessage::Input(message) => { dispatcher.queue_editor_message(EditorMessage::InputPreprocessor(message)); @@ -35,7 +35,6 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content }); } }, - DesktopWrapperMessage::PollNodeGraphEvaluation => dispatcher.poll_node_graph_evaluation(), DesktopWrapperMessage::UpdateMaximized { maximized } => { let message = FrontendMessage::UpdateMaximized { maximized }; dispatcher.queue_editor_message(message); diff --git a/desktop/wrapper/src/lib.rs b/desktop/wrapper/src/lib.rs index e84e5e7288..216a3a1be3 100644 --- a/desktop/wrapper/src/lib.rs +++ b/desktop/wrapper/src/lib.rs @@ -1,8 +1,9 @@ use graph_craft::application_io::PlatformApplicationIo; use graph_craft::application_io::resource::ResourceStorage; use graphite_editor::application::{Editor, Environment, Host, Platform}; +use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder}; use graphite_editor::messages::frontend::FrontendMessage; -use graphite_editor::messages::prelude::Wake; +use graphite_editor::node_graph_executor::NodeRuntime; use message_dispatcher::DesktopWrapperMessageDispatcher; use messages::{DesktopFrontendMessage, DesktopWrapperMessage}; @@ -11,6 +12,7 @@ use std::sync::Arc; pub use graph_craft::application_io::resource::MmapResourceStorage; pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION}; pub use graphite_editor::document_store::{DocumentStore, FolderStore}; +pub use graphite_editor::task::{Spawn, Task}; pub use wgpu_executor::Texture; pub use wgpu_executor::WgpuBackends; pub use wgpu_executor::WgpuContext; @@ -33,7 +35,15 @@ pub struct DesktopWrapper { } impl DesktopWrapper { - pub fn new(uuid_random_seed: u64, resource_storage: Arc, document_store: Arc, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self { + pub fn new( + random_seed: u64, + resource_storage: Arc, + document_store: Arc, + wgpu_context: WgpuContext, + spawner: impl Spawn + Send + Sync + 'static, + editor_wake: impl Fn() + Send + Sync + 'static, + runtime_wake: impl Fn() + Send + Sync + 'static, + ) -> (Self, NodeRuntime) { #[cfg(target_os = "windows")] let host = Host::Windows; #[cfg(target_os = "macos")] @@ -43,9 +53,20 @@ impl DesktopWrapper { let env = Environment { platform: Platform::Desktop, host }; let application_io = PlatformApplicationIo::new_with_context(wgpu_context); - Self { - editor: Editor::new(env, uuid_random_seed, resource_storage, document_store, application_io, schedule_wake), - } + let (editor, runtime) = Builder::new() + .with_editor( + EditorBuilder::new() + .with_wake(editor_wake) + .with_environment(env) + .with_resource_storage(resource_storage) + .with_document_store(document_store), + ) + .with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io)) + .with_spawner(spawner) + .with_random_seed(random_seed) + .build(); + + (Self { editor }, runtime) } pub fn dispatch(&mut self, message: DesktopWrapperMessage) -> Vec { @@ -53,19 +74,6 @@ impl DesktopWrapper { executor.queue_desktop_wrapper_message(message); executor.execute() } - - pub async fn execute_node_graph() -> NodeGraphExecutionResult { - let result = graphite_editor::node_graph_executor::run_node_graph().await; - match result { - (true, texture) => NodeGraphExecutionResult::HasRun(texture), - (false, _) => NodeGraphExecutionResult::NotRun, - } - } -} - -pub enum NodeGraphExecutionResult { - HasRun(Option), - NotRun, } pub fn deserialize_editor_message(data: &[u8]) -> Option { diff --git a/desktop/wrapper/src/message_dispatcher.rs b/desktop/wrapper/src/message_dispatcher.rs index 11ac36c90f..9f35fb3f2d 100644 --- a/desktop/wrapper/src/message_dispatcher.rs +++ b/desktop/wrapper/src/message_dispatcher.rs @@ -42,18 +42,6 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> { self.responses.push(response); } - pub(super) fn poll_node_graph_evaluation(&mut self) { - let mut responses = VecDeque::new(); - if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses) - && e != "No active document" - { - tracing::error!("Error polling node graph: {}", e); - } - while let Some(message) = responses.pop_front() { - self.queue_editor_message(message); - } - } - fn process_queue(&mut self) { let mut frontend_messages = Vec::new(); diff --git a/desktop/wrapper/src/messages.rs b/desktop/wrapper/src/messages.rs index b3663ea87e..382e662246 100644 --- a/desktop/wrapper/src/messages.rs +++ b/desktop/wrapper/src/messages.rs @@ -79,7 +79,6 @@ pub enum DesktopWrapperMessage { Input(InputMessage), IngestFile { path: PathBuf, content: Vec, action: IngestAction }, SaveFileDialogResult { path: PathBuf, context: SaveFileDialogContext }, - PollNodeGraphEvaluation, UpdateMaximized { maximized: bool }, UpdateFullscreen { fullscreen: bool }, LoadPersistedState { state: PersistedState }, diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index 281d916d67..edf58496dd 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -1,6 +1,5 @@ pub mod node { pub const CALL_ARGUMENT: &str = "call_argument"; - pub const CONTEXT_FEATURES: &str = "context_features"; pub const VISIBLE: &str = "visible"; pub const SKIP_DEDUPLICATION: &str = "skip_deduplication"; pub const REFLECTION_METADATA: &str = "reflection_metadata"; diff --git a/document/graph-storage/src/from_runtime.rs b/document/graph-storage/src/from_runtime.rs index d9593738bf..1f3f54fc1a 100644 --- a/document/graph-storage/src/from_runtime.rs +++ b/document/graph-storage/src/from_runtime.rs @@ -1,7 +1,6 @@ use std::collections::HashMap; use core_types::Context; -use core_types::context::ContextDependencies; use core_types::uuid::NodeId as RuntimeNodeId; use graph_craft::concrete; use graph_craft::document::value::TaggedValue; @@ -447,9 +446,6 @@ fn convert_node( attributes .set_if_not_default(node::CALL_ARGUMENT, &doc_node.call_argument, &concrete!(Context), timestamp) .map_err(map_serialization_error(node::CALL_ARGUMENT))?; - attributes - .set_if_not_default(node::CONTEXT_FEATURES, &doc_node.context_features, &ContextDependencies::default(), timestamp) - .map_err(map_serialization_error(node::CONTEXT_FEATURES))?; attributes .set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp) .map_err(map_serialization_error(node::VISIBLE))?; @@ -477,11 +473,6 @@ pub fn encode_call_argument(call_argument: &core_types::Type) -> Result Result { - encode_if_not_default(node::CONTEXT_FEATURES, context_features, &ContextDependencies::default()) -} - fn encode_if_not_default(key: &str, value: &T, default: &T) -> Result { let value = if value == default { None } else { Some(to_value(value).map_err(map_serialization_error(key))?) }; diff --git a/document/graph-storage/src/tests/round_trip.rs b/document/graph-storage/src/tests/round_trip.rs index be511b4c3b..3d2540082b 100644 --- a/document/graph-storage/src/tests/round_trip.rs +++ b/document/graph-storage/src/tests/round_trip.rs @@ -1,7 +1,6 @@ use std::borrow::Cow; use std::collections::HashMap; -use core_types::context::ContextDependencies; use core_types::uuid::NodeId; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork}; use graph_craft::graphene_compiler::Compiler; @@ -244,11 +243,6 @@ fn test_nested_network_flattening() { #[test] fn test_metadata_preservation() { // Create a network with nodes that have non-default metadata - let context_features = ContextDependencies { - extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME, - ..Default::default() - }; - let network = NodeNetwork { exports: vec![NodeInput::node(NodeId(1), 0)], nodes: [ @@ -258,7 +252,6 @@ fn test_metadata_preservation() { inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)], implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")), call_argument: concrete!(String), - context_features, visible: false, // Non-default value skip_deduplication: true, // Non-default value ..Default::default() @@ -292,9 +285,6 @@ fn test_metadata_preservation() { let conv_node_1 = converted.nodes.get(&NodeId(1)).unwrap(); assert_eq!(orig_node_1.call_argument, conv_node_1.call_argument, "call_argument for node 1 should be preserved"); - // Verify context_features is preserved - assert_eq!(orig_node_0.context_features, conv_node_0.context_features, "context_features should be preserved"); - // Verify visible is preserved assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved"); @@ -353,11 +343,6 @@ fn test_demo_artwork_round_trip() { "{}: call_argument should be preserved for node {:?}", artwork_name, node_id ); - assert_eq!( - orig_node.context_features, conv_node.context_features, - "{}: context_features should be preserved for node {:?}", - artwork_name, node_id - ); assert_eq!(orig_node.visible, conv_node.visible, "{}: visible should be preserved for node {:?}", artwork_name, node_id); assert_eq!( orig_node.skip_deduplication, conv_node.skip_deduplication, diff --git a/document/graph-storage/src/to_runtime.rs b/document/graph-storage/src/to_runtime.rs index 00fbfb6a7a..b4f121232c 100644 --- a/document/graph-storage/src/to_runtime.rs +++ b/document/graph-storage/src/to_runtime.rs @@ -334,8 +334,8 @@ fn convert_node( implementation: convert_implementation(context, &node.implementation, metadata_path, runtime_node_id, node_collector, network_collector)?, visible: node.attributes.get_or(node::VISIBLE, true), skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false), - context_features: node.attributes.get_or_default(node::CONTEXT_FEATURES), // Regenerated during compilation; not stored. + context_dependencies: None, original_location: Default::default(), }) } diff --git a/editor/Cargo.toml b/editor/Cargo.toml index 4806931fc9..ef03f79c11 100644 --- a/editor/Cargo.toml +++ b/editor/Cargo.toml @@ -53,7 +53,6 @@ once_cell = { workspace = true } web-sys = { workspace = true } vello = { workspace = true } base64 = { workspace = true } -spin = { workspace = true } image = { workspace = true } color = { workspace = true } zip = { workspace = true } @@ -69,9 +68,6 @@ wasm-bindgen = { workspace = true, optional = true } [target.'cfg(not(target_family = "wasm"))'.dependencies] tokio = { workspace = true } -[target.'cfg(target_family = "wasm")'.dependencies] -wasm-bindgen-futures = { workspace = true } - [dev-dependencies] # Workspace dependencies env_logger = { workspace = true } diff --git a/editor/src/application.rs b/editor/src/application.rs index cd2f2c3f41..3d60214569 100644 --- a/editor/src/application.rs +++ b/editor/src/application.rs @@ -1,76 +1,17 @@ use crate::dispatcher::Dispatcher; use crate::messages::prelude::*; -use graph_craft::application_io::PlatformApplicationIo; -use graph_craft::application_io::resource::ResourceStorage; pub use graphene_std::uuid::*; -use std::sync::{Arc, OnceLock}; pub struct Editor { pub dispatcher: Dispatcher, } impl Editor { - pub fn new( - environment: Environment, - uuid_random_seed: u64, - resource_storage: Arc, - document_store: Arc, - mut application_io: PlatformApplicationIo, - wake: Wake, - ) -> Self { - ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once"); - graphene_std::uuid::set_uuid_seed(uuid_random_seed); - - let mut dispatcher = Dispatcher::new(resource_storage, document_store); - dispatcher.message_handlers.future_message_handler.set_wake(wake); - application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources()); - crate::node_graph_executor::replace_application_io(application_io); - - Self { dispatcher } - } - - #[cfg(test)] - pub(crate) fn new_local_executor() -> (Self, crate::node_graph_executor::NodeRuntime) { - let _ = ENVIRONMENT.set(*Editor::environment()); - graphene_std::uuid::set_uuid_seed(0); - - let (mut runtime, executor) = crate::node_graph_executor::NodeGraphExecutor::new_with_local_runtime(); - let editor = Self { - dispatcher: Dispatcher::with_executor(executor), - }; - - let mut application_io = PlatformApplicationIo::default(); - application_io.inject_resource_proxy(editor.dispatcher.message_handlers.resource_storage_message_handler.resources()); - runtime.replace_application_io(application_io); - - (editor, runtime) - } - pub fn handle_message>(&mut self, message: T) -> Vec { self.dispatcher.handle_message(message, true); std::mem::take(&mut self.dispatcher.responses) } - - pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque) -> Result<(), String> { - self.dispatcher.poll_node_graph_evaluation(responses) - } -} - -static ENVIRONMENT: OnceLock = OnceLock::new(); -impl Editor { - #[cfg(not(test))] - pub fn environment() -> &'static Environment { - ENVIRONMENT.get().expect("Editor environment accessed before initialization") - } - - #[cfg(test)] - pub fn environment() -> &'static Environment { - &Environment { - platform: Platform::Desktop, - host: Host::Linux, - } - } } #[derive(Clone, Copy, Debug)] @@ -78,6 +19,11 @@ pub struct Environment { pub platform: Platform, pub host: Host, } +#[cfg(test)] +pub(crate) const DEFAULT_ENVIRONMENT: Environment = Environment { + platform: Platform::Desktop, + host: Host::Linux, +}; #[derive(Clone, Copy, Debug)] pub enum Platform { Desktop, @@ -107,6 +53,25 @@ impl Environment { } } +pub trait EnvironmentDisplay { + fn fmt(&self, f: &mut std::fmt::Formatter, environment: Environment) -> std::fmt::Result; + + fn display(&self, environment: Environment) -> WithEnvironment<'_, Self> { + WithEnvironment { value: self, environment } + } +} + +pub struct WithEnvironment<'a, T: ?Sized> { + value: &'a T, + environment: Environment, +} + +impl std::fmt::Display for WithEnvironment<'_, T> { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + self.value.fmt(f, self.environment) + } +} + pub const GRAPHITE_RELEASE_SERIES: &str = env!("GRAPHITE_RELEASE_SERIES"); pub const GRAPHITE_GIT_COMMIT_BRANCH: Option<&str> = option_env!("GRAPHITE_GIT_COMMIT_BRANCH"); pub const GRAPHITE_GIT_COMMIT_HASH: &str = env!("GRAPHITE_GIT_COMMIT_HASH"); diff --git a/editor/src/builder.rs b/editor/src/builder.rs new file mode 100644 index 0000000000..f3bb6fe513 --- /dev/null +++ b/editor/src/builder.rs @@ -0,0 +1,215 @@ +use crate::application::{Editor, Environment}; +use crate::dispatcher::Dispatcher; +use crate::messages::prelude::*; +use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime}; +use crate::task::{Spawn, Spawner}; +use document_container::store::DocumentStore; +use graph_craft::application_io::PlatformApplicationIo; +use graph_craft::application_io::resource::ResourceStorage; +use std::sync::Arc; + +pub type ReadyEditorBuilder = EditorBuilder, Arc>; +pub type ReadyRuntimeBuilder = RuntimeBuilder; + +pub struct Builder { + editor: E, + runtime: R, + spawner: S, + random_seed: N, +} + +impl Builder { + pub fn new() -> Self { + Self { + editor: (), + runtime: (), + spawner: (), + random_seed: (), + } + } +} + +impl Default for Builder { + fn default() -> Self { + Self::new() + } +} + +impl Builder<(), R, S, N> { + pub fn with_editor(self, editor: ReadyEditorBuilder) -> Builder { + Builder { + editor, + runtime: self.runtime, + spawner: self.spawner, + random_seed: self.random_seed, + } + } +} + +impl Builder { + pub fn with_runtime(self, runtime: ReadyRuntimeBuilder) -> Builder { + Builder { + editor: self.editor, + runtime, + spawner: self.spawner, + random_seed: self.random_seed, + } + } +} + +impl Builder { + pub fn with_spawner(self, spawner: impl Spawn + Send + Sync + 'static) -> Builder { + Builder { + editor: self.editor, + runtime: self.runtime, + spawner: Arc::new(spawner), + random_seed: self.random_seed, + } + } +} + +impl Builder { + pub fn with_random_seed(self, random_seed: u64) -> Builder { + Builder { + editor: self.editor, + runtime: self.runtime, + spawner: self.spawner, + random_seed, + } + } +} + +impl Builder { + pub fn build(self) -> (Editor, NodeRuntime) { + let Self { + editor, + runtime, + spawner, + random_seed, + } = self; + let EditorBuilder { + wake: editor_wake, + environment, + resource_storage, + document_store, + } = editor; + let RuntimeBuilder { + wake: runtime_wake, + mut application_io, + } = runtime; + + graphene_std::uuid::set_uuid_seed(random_seed); + + let (executor, mut node_runtime) = NodeGraphExecutor::new(editor_wake.clone()); + + let future_message_handler = FutureMessageHandler::new(spawner.clone(), editor_wake); + let dispatcher = Dispatcher::new(environment, resource_storage, document_store, executor, future_message_handler); + + application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources()); + node_runtime.replace_application_io(application_io); + node_runtime.replace_task_executor(spawner, runtime_wake); + + (Editor { dispatcher }, node_runtime) + } +} + +pub struct EditorBuilder { + wake: W, + environment: E, + resource_storage: R, + document_store: D, +} + +impl EditorBuilder { + pub fn new() -> Self { + Self { + wake: (), + environment: (), + resource_storage: (), + document_store: (), + } + } +} + +impl Default for EditorBuilder { + fn default() -> Self { + Self::new() + } +} + +impl EditorBuilder<(), E, R, D> { + pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> EditorBuilder { + EditorBuilder { + wake: Arc::new(wake), + environment: self.environment, + resource_storage: self.resource_storage, + document_store: self.document_store, + } + } +} + +impl EditorBuilder { + pub fn with_environment(self, environment: Environment) -> EditorBuilder { + EditorBuilder { + wake: self.wake, + environment, + resource_storage: self.resource_storage, + document_store: self.document_store, + } + } +} + +impl EditorBuilder { + pub fn with_resource_storage(self, resource_storage: Arc) -> EditorBuilder, D> { + EditorBuilder { + wake: self.wake, + environment: self.environment, + resource_storage, + document_store: self.document_store, + } + } +} + +impl EditorBuilder { + pub fn with_document_store(self, document_store: Arc) -> EditorBuilder> { + EditorBuilder { + wake: self.wake, + environment: self.environment, + resource_storage: self.resource_storage, + document_store, + } + } +} + +pub struct RuntimeBuilder { + wake: W, + application_io: A, +} + +impl RuntimeBuilder { + pub fn new() -> Self { + Self { wake: (), application_io: () } + } +} + +impl Default for RuntimeBuilder { + fn default() -> Self { + Self::new() + } +} + +impl RuntimeBuilder<(), A> { + /// Called from any thread when a graph task has completed, to run the runtime again as soon as possible. + pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> RuntimeBuilder { + RuntimeBuilder { + wake: Arc::new(wake), + application_io: self.application_io, + } + } +} + +impl RuntimeBuilder { + pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder { + RuntimeBuilder { wake: self.wake, application_io } + } +} diff --git a/editor/src/dispatcher.rs b/editor/src/dispatcher.rs index 9a257a9d6d..3df013f05a 100644 --- a/editor/src/dispatcher.rs +++ b/editor/src/dispatcher.rs @@ -1,3 +1,4 @@ +use crate::application::Environment; use crate::messages::debug::utility_types::MessageLoggingVerbosity; use crate::messages::defer::DeferMessageContext; use crate::messages::dialog::DialogMessageContext; @@ -7,18 +8,20 @@ use crate::messages::portfolio::utility_types::PanelType; use crate::messages::preferences::preferences_message_handler::PreferencesMessageContext; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed; +use crate::node_graph_executor::NodeGraphExecutor; use graph_craft::application_io::resource::ResourceStorage; use std::sync::Arc; -#[derive(Debug, Default)] +#[derive(Debug)] pub struct Dispatcher { + environment: Environment, message_queues: Vec>, pub responses: Vec, pub frontend_update_messages: Vec, pub message_handlers: DispatcherMessageHandlers, } -#[derive(Debug, Default)] +#[derive(Debug)] pub struct DispatcherMessageHandlers { animation_message_handler: AnimationMessageHandler, app_window_message_handler: AppWindowMessageHandler, @@ -42,17 +45,27 @@ pub struct DispatcherMessageHandlers { } impl DispatcherMessageHandlers { - pub fn with_resource_storage(resource_storage: Arc) -> Self { + fn new(environment: Environment, executor: NodeGraphExecutor, document_store: Arc, future_message_handler: FutureMessageHandler) -> Self { Self { - resource_storage_message_handler: ResourceStorageMessageHandler::new(resource_storage), - ..Self::default() - } - } - - pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self { - Self { - portfolio_message_handler: PortfolioMessageHandler::with_executor(executor), - ..Self::default() + animation_message_handler: Default::default(), + app_window_message_handler: Default::default(), + future_message_handler, + broadcast_message_handler: Default::default(), + clipboard_message_handler: Default::default(), + color_picker_message_handler: Default::default(), + debug_message_handler: Default::default(), + defer_message_handler: Default::default(), + dialog_message_handler: Default::default(), + input_preprocessor_message_handler: Default::default(), + key_mapping_message_handler: KeyMappingMessageHandler::new(environment), + layout_message_handler: Default::default(), + menu_bar_message_handler: Default::default(), + network_message_handler: Default::default(), + portfolio_message_handler: PortfolioMessageHandler::new(executor, document_store), + preferences_message_handler: Default::default(), + resource_storage_message_handler: Default::default(), + tool_message_handler: Default::default(), + viewport_message_handler: Default::default(), } } } @@ -102,20 +115,21 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[ const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"]; impl Dispatcher { - pub fn new(resource_storage: Arc, document_store: Arc) -> Self { - let mut s = Self::default(); + pub fn new( + environment: Environment, + resource_storage: Arc, + document_store: Arc, + executor: NodeGraphExecutor, + future_message_handler: FutureMessageHandler, + ) -> Self { + let mut s = Self { + environment, + message_queues: Vec::new(), + responses: Vec::new(), + frontend_update_messages: Vec::new(), + message_handlers: DispatcherMessageHandlers::new(environment, executor, document_store, future_message_handler), + }; s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage); - s.message_handlers.portfolio_message_handler.set_document_store(document_store); - s - } - - #[cfg(test)] - pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self { - let mut s = Self::new( - Arc::new(graph_craft::application_io::resource::HashMapResourceStorage::new()), - Arc::new(document_container::store::MemoryStore::default()), - ); - s.message_handlers.portfolio_message_handler = PortfolioMessageHandler::with_executor(executor); s } @@ -144,13 +158,6 @@ impl Dispatcher { pub fn handle_message>(&mut self, message: T, process_after_all_current: bool) { let message = message.into(); - // Drain async results into the queue before processing the new message. - let mut async_results = VecDeque::new(); - self.message_handlers.future_message_handler.drain_results(&mut async_results); - if !async_results.is_empty() { - Self::schedule_execution(&mut self.message_queues, true, async_results); - } - // If we are not maintaining the buffer, simply add to the current queue Self::schedule_execution(&mut self.message_queues, process_after_all_current, [message]); @@ -201,7 +208,7 @@ impl Dispatcher { self.message_handlers.app_window_message_handler.process_message(message, &mut queue, ()); } Message::Future(message) => { - self.message_handlers.future_message_handler.process_message(message, &mut queue, FutureMessageContext {}); + self.message_handlers.future_message_handler.process_message(message, &mut queue, ()); } Message::Broadcast(message) => self.message_handlers.broadcast_message_handler.process_message(message, &mut queue, ()), Message::Clipboard(message) => { @@ -237,6 +244,7 @@ impl Dispatcher { message, &mut queue, InputPreprocessorMessageContext { + environment: self.environment, viewport: &self.message_handlers.viewport_message_handler, }, ); @@ -245,13 +253,22 @@ impl Dispatcher { let input = &self.message_handlers.input_preprocessor_message_handler; let actions = self.collect_actions(); - self.message_handlers - .key_mapping_message_handler - .process_message(message, &mut queue, KeyMappingMessageContext { input, actions }); + self.message_handlers.key_mapping_message_handler.process_message( + message, + &mut queue, + KeyMappingMessageContext { + environment: self.environment, + input, + actions, + }, + ); } Message::Layout(message) => { - let action_input_mapping = &|action_to_find: &MessageDiscriminant| self.message_handlers.key_mapping_message_handler.action_input_mapping(action_to_find); - let context = LayoutMessageContext { action_input_mapping }; + let action_input_mapping = &|action_to_find: &MessageDiscriminant| self.message_handlers.key_mapping_message_handler.action_input_mapping(action_to_find, self.environment); + let context = LayoutMessageContext { + environment: self.environment, + action_input_mapping, + }; self.message_handlers.layout_message_handler.process_message(message, &mut queue, context); } @@ -268,6 +285,7 @@ impl Dispatcher { message, &mut queue, PortfolioMessageContext { + environment: self.environment, ipp: &self.message_handlers.input_preprocessor_message_handler, preferences: &self.message_handlers.preferences_message_handler, current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type, @@ -377,10 +395,15 @@ impl Dispatcher { Message::Viewport(message) => { self.message_handlers.viewport_message_handler.process_message(message, &mut queue, ()); } - Message::NoOp => {} + // Messages + Message::Wake => { + queue.add(PortfolioMessage::PollNodeGraphEvaluation); + queue.add(FutureMessage::Drain); + } Message::Batched { messages } => { messages.into_iter().for_each(|message| self.handle_message(message, false)); } + Message::NoOp => {} } // If there are child messages, append the queue to the list of queues @@ -411,10 +434,6 @@ impl Dispatcher { list } - pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque) -> Result<(), String> { - self.message_handlers.portfolio_message_handler.poll_node_graph_evaluation(responses) - } - /// Create the tree structure for logging the messages as a tree fn create_indents(queues: &[VecDeque]) -> String { String::from_iter(queues.iter().enumerate().skip(1).map(|(index, queue)| { diff --git a/editor/src/lib.rs b/editor/src/lib.rs index 56e89e7f4e..1a1cb35c32 100644 --- a/editor/src/lib.rs +++ b/editor/src/lib.rs @@ -11,10 +11,12 @@ mod macros; extern crate log; pub mod application; +pub mod builder; pub mod consts; pub mod dispatcher; pub mod messages; pub mod node_graph_executor; +pub mod task; #[cfg(test)] pub mod test_utils; pub mod utility_traits; diff --git a/editor/src/messages/app_window/app_window_message_handler.rs b/editor/src/messages/app_window/app_window_message_handler.rs index e09ad3c19c..dee5f8ea69 100644 --- a/editor/src/messages/app_window/app_window_message_handler.rs +++ b/editor/src/messages/app_window/app_window_message_handler.rs @@ -86,8 +86,8 @@ pub enum AppWindowPlatform { Linux, } -impl From<&Environment> for AppWindowPlatform { - fn from(environment: &Environment) -> Self { +impl From for AppWindowPlatform { + fn from(environment: Environment) -> Self { match (environment.platform, environment.host) { (Platform::Web, _) => AppWindowPlatform::Web, (Platform::Desktop, Host::Linux) => AppWindowPlatform::Linux, diff --git a/editor/src/messages/frontend/frontend_message.rs b/editor/src/messages/frontend/frontend_message.rs index 2ea0dd74c5..876755dcbe 100644 --- a/editor/src/messages/frontend/frontend_message.rs +++ b/editor/src/messages/frontend/frontend_message.rs @@ -1,5 +1,5 @@ use super::IconName; -use super::utility_types::{MouseCursorIcon, PersistedState}; +use super::utility_types::{MouseCursorIcon, PersistedState, RenderStatus}; use crate::messages::app_window::app_window_message_handler::AppWindowPlatform; use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, FileDialogOptions, FileFilter, FileType, RasterizedImage}; use crate::messages::input_mapper::utility_types::misc::ActionShortcut; @@ -246,6 +246,9 @@ pub enum FrontendMessage { UpdateDocumentArtwork { svg: String, }, + UpdateRenderStatus { + status: RenderStatus, + }, UpdateImageData { image_data: Vec, }, @@ -291,8 +294,8 @@ pub enum FrontendMessage { UpdateNodeGraphNodes { nodes: Vec, }, - UpdateNodeGraphErrorDiagnostic { - error: Option, + UpdateNodeGraphErrorDiagnostics { + errors: Vec, }, UpdateVisibleNodes { nodes: Vec, diff --git a/editor/src/messages/frontend/utility_types.rs b/editor/src/messages/frontend/utility_types.rs index 27e2791ac8..37ad351ee2 100644 --- a/editor/src/messages/frontend/utility_types.rs +++ b/editor/src/messages/frontend/utility_types.rs @@ -42,6 +42,15 @@ pub enum MouseCursorIcon { Rotate, } +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)] +pub enum RenderStatus { + #[default] + Rendering, + Error, + Panic, +} + #[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))] #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum FileType { diff --git a/editor/src/messages/future/future_message.rs b/editor/src/messages/future/future_message.rs index 99ccb6052e..612e371314 100644 --- a/editor/src/messages/future/future_message.rs +++ b/editor/src/messages/future/future_message.rs @@ -11,6 +11,5 @@ pub enum FutureMessage { #[derivative(Debug = "ignore", PartialEq = "ignore")] future: MessageFuture, }, - /// Sent by a wake callback to nudge an idle event loop into a dispatch tick. - Wake, + Drain, } diff --git a/editor/src/messages/future/future_message_handler.rs b/editor/src/messages/future/future_message_handler.rs index 10731e65ef..cc766c2aa9 100644 --- a/editor/src/messages/future/future_message_handler.rs +++ b/editor/src/messages/future/future_message_handler.rs @@ -6,19 +6,16 @@ use dyn_any::WasmNotSend; use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded}; use crate::messages::prelude::*; +use crate::task::Spawner; #[cfg(not(target_family = "wasm"))] type InnerMessageFuture = Pin + Send + 'static>>; #[cfg(target_family = "wasm")] type InnerMessageFuture = Pin + 'static>>; -/// Invoked by the spawner after a result is sent, to wake the platform event loop. +/// Invoked after a result is sent, to wake the platform event loop. pub type Wake = Arc; -fn noop_wake() -> Wake { - Arc::new(|| {}) -} - /// One-shot async work whose result re-enters the dispatcher as a [`Message`]. /// Resolves to [`Message::NoOp`] if polled after the inner future has already been taken. #[derive(Clone, Default)] @@ -62,52 +59,24 @@ where } } -/// Platform-specific async-task executor. -/// Runs `future`, sends the resolved message on `results`, then calls `wake`. -pub trait MessageSpawner: Send + Sync { - fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender, wake: Wake); -} - -#[derive(ExtractField)] -pub struct FutureMessageContext {} - #[derive(ExtractField)] pub struct FutureMessageHandler { - #[cfg_attr(test, expect(dead_code))] - spawner: Arc, + spawner: Spawner, wake: Wake, - #[cfg_attr(test, expect(dead_code))] results_sender: UnboundedSender, results_receiver: UnboundedReceiver, } impl FutureMessageHandler { - pub fn with_wake(wake: Wake) -> Self { + pub fn new(spawner: Spawner, wake: Wake) -> Self { let (results_sender, results_receiver) = unbounded(); Self { - spawner: default_spawner(), + spawner, wake, results_sender, results_receiver, } } - - pub fn set_wake(&mut self, wake: Wake) { - self.wake = wake; - } - - /// Pull every resolved async result into `out`. - pub fn drain_results(&mut self, out: &mut VecDeque) { - while let Ok(Some(message)) = self.results_receiver.try_next() { - out.push_back(message); - } - } -} - -impl Default for FutureMessageHandler { - fn default() -> Self { - Self::with_wake(noop_wake()) - } } impl std::fmt::Debug for FutureMessageHandler { @@ -117,87 +86,25 @@ impl std::fmt::Debug for FutureMessageHandler { } #[message_handler_data] -impl MessageHandler for FutureMessageHandler { - fn process_message(&mut self, message: FutureMessage, _responses: &mut VecDeque, _context: FutureMessageContext) { +impl MessageHandler for FutureMessageHandler { + fn process_message(&mut self, message: FutureMessage, responses: &mut VecDeque, _context: ()) { match message { FutureMessage::Await { future } => { - #[cfg(not(test))] - self.spawner.spawn(future.into_future(), self.results_sender.clone(), self.wake.clone()); - - // For tests, block on the future to ensure the result is available when validating editor state afterwards. - #[cfg(test)] - { - let message = futures::executor::block_on(future.into_future()); - _responses.push_back(message); - } + let results = self.results_sender.clone(); + let wake = self.wake.clone(); + self.spawner.spawn(Box::pin(async move { + let message = future.await; + let _ = results.unbounded_send(message); + wake(); + })); } - FutureMessage::Wake => { - // Tick-only message: the dispatcher's top-of-tick drain handles the real work. + FutureMessage::Drain => { + while let Ok(Some(message)) = self.results_receiver.try_next() { + responses.push_back(message); + } } } } advertise_actions!(FutureMessageDiscriminant;); } - -#[cfg(not(target_family = "wasm"))] -fn default_spawner() -> Arc { - Arc::new(TokioSpawner::default()) -} - -#[cfg(target_family = "wasm")] -fn default_spawner() -> Arc { - Arc::new(WasmSpawner) -} - -#[cfg(not(target_family = "wasm"))] -struct TokioSpawner { - /// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver. - runtime: std::sync::OnceLock, -} - -#[cfg(not(target_family = "wasm"))] -impl Default for TokioSpawner { - fn default() -> Self { - Self { runtime: std::sync::OnceLock::new() } - } -} - -#[cfg(not(target_family = "wasm"))] -impl TokioSpawner { - fn runtime(&self) -> &tokio::runtime::Runtime { - self.runtime.get_or_init(|| { - tokio::runtime::Builder::new_multi_thread() - .worker_threads(1) - .thread_name("graphite-async") - .enable_all() - .build() - .expect("failed to construct async-message tokio runtime") - }) - } -} - -#[cfg(not(target_family = "wasm"))] -impl MessageSpawner for TokioSpawner { - fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender, wake: Wake) { - self.runtime().spawn(async move { - let message = future.await; - let _ = results.unbounded_send(message); - wake(); - }); - } -} - -#[cfg(target_family = "wasm")] -struct WasmSpawner; - -#[cfg(target_family = "wasm")] -impl MessageSpawner for WasmSpawner { - fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender, wake: Wake) { - wasm_bindgen_futures::spawn_local(async move { - let message = future.await; - let _ = results.unbounded_send(message); - wake(); - }); - } -} diff --git a/editor/src/messages/future/mod.rs b/editor/src/messages/future/mod.rs index 912d28c29f..8767de3b6f 100644 --- a/editor/src/messages/future/mod.rs +++ b/editor/src/messages/future/mod.rs @@ -4,4 +4,4 @@ mod future_message_handler; #[doc(inline)] pub use future_message::{FutureMessage, FutureMessageDiscriminant}; #[doc(inline)] -pub use future_message_handler::{FutureMessageContext, FutureMessageHandler, MessageFuture, MessageSpawner, Wake}; +pub use future_message_handler::{FutureMessageHandler, MessageFuture, Wake}; diff --git a/editor/src/messages/input_mapper/input_mapper_message_handler.rs b/editor/src/messages/input_mapper/input_mapper_message_handler.rs index 145b75d073..be58b44e63 100644 --- a/editor/src/messages/input_mapper/input_mapper_message_handler.rs +++ b/editor/src/messages/input_mapper/input_mapper_message_handler.rs @@ -1,6 +1,6 @@ use super::utility_types::keyboard::KeysGroup; use super::utility_types::misc::Mapping; -use crate::application::Editor; +use crate::application::Environment; use crate::messages::input_mapper::utility_types::keyboard::{self, Key}; use crate::messages::input_mapper::utility_types::misc::MappingEntry; use crate::messages::prelude::*; @@ -11,7 +11,7 @@ pub struct InputMapperMessageContext<'a> { pub actions: ActionList, } -#[derive(Debug, Default, ExtractField)] +#[derive(Debug, ExtractField)] pub struct InputMapperMessageHandler { mapping: Mapping, } @@ -29,11 +29,15 @@ impl MessageHandler> for Input } impl InputMapperMessageHandler { + pub fn new(mapping: Mapping) -> Self { + Self { mapping } + } + pub fn set_mapping(&mut self, mapping: Mapping) { self.mapping = mapping; } - pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option { + pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option { let all_key_mapping_entries = std::iter::empty() .chain(self.mapping.key_up.iter()) .chain(self.mapping.key_down.iter()) @@ -49,7 +53,7 @@ impl InputMapperMessageHandler { let found_actions = all_mapping_entries.filter(|entry| entry.action.to_discriminant() == *action_to_find); // Get the `Key` for this platform's accelerator key - let platform_accel_key = if Editor::environment().is_mac() { Key::Command } else { Key::Control }; + let platform_accel_key = if environment.is_mac() { Key::Command } else { Key::Control }; let entry_to_key = |entry: &MappingEntry| { // Get the modifier keys for the entry (and convert them to Key) diff --git a/editor/src/messages/input_mapper/input_mappings.rs b/editor/src/messages/input_mapper/input_mappings.rs index 3765b0ed8f..eecf69e0b7 100644 --- a/editor/src/messages/input_mapper/input_mappings.rs +++ b/editor/src/messages/input_mapper/input_mappings.rs @@ -1,4 +1,4 @@ -use crate::application::Editor; +use crate::application::Environment; use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT}; use crate::messages::input_mapper::key_mapping::MappingVariant; use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates}; @@ -13,20 +13,20 @@ use crate::messages::tool::tool_messages::brush_tool::BrushToolMessageOptionsUpd use crate::messages::tool::tool_messages::select_tool::SelectToolPointerKeys; use glam::DVec2; -impl From for Mapping { - fn from(value: MappingVariant) -> Self { - match value { - MappingVariant::Default => input_mappings(false), - MappingVariant::ZoomWithScroll => input_mappings(true), +impl Mapping { + pub fn new(variant: MappingVariant, environment: Environment) -> Self { + match variant { + MappingVariant::Default => input_mappings(false, environment), + MappingVariant::ZoomWithScroll => input_mappings(true, environment), } } } -pub fn input_mappings(zoom_with_scroll: bool) -> Mapping { +pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mapping { use InputMapperMessage::*; use Key::*; - let is_mac = Editor::environment().is_mac(); + let is_mac = environment.is_mac(); // NOTICE: // If a new mapping you added here isn't working (and perhaps another lower-precedence one is instead), make sure to advertise diff --git a/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs b/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs index 5f70b8df7d..02511b1061 100644 --- a/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs +++ b/editor/src/messages/input_mapper/key_mapping/key_mapping_message_handler.rs @@ -1,14 +1,18 @@ +use crate::application::Environment; use crate::messages::input_mapper::input_mapper_message_handler::InputMapperMessageContext; +use crate::messages::input_mapper::key_mapping::MappingVariant; use crate::messages::input_mapper::utility_types::keyboard::KeysGroup; +use crate::messages::input_mapper::utility_types::misc::Mapping; use crate::messages::prelude::*; #[derive(ExtractField)] pub struct KeyMappingMessageContext<'a> { + pub environment: Environment, pub input: &'a InputPreprocessorMessageHandler, pub actions: ActionList, } -#[derive(Debug, Default, ExtractField)] +#[derive(Debug, ExtractField)] pub struct KeyMappingMessageHandler { mapping_handler: InputMapperMessageHandler, } @@ -16,21 +20,27 @@ pub struct KeyMappingMessageHandler { #[message_handler_data] impl MessageHandler> for KeyMappingMessageHandler { fn process_message(&mut self, message: KeyMappingMessage, responses: &mut VecDeque, context: KeyMappingMessageContext) { - let KeyMappingMessageContext { input, actions } = context; + let KeyMappingMessageContext { environment, input, actions } = context; match message { // Sub-messages KeyMappingMessage::Lookup(input_message) => self.mapping_handler.process_message(input_message, responses, InputMapperMessageContext { input, actions }), // Messages - KeyMappingMessage::ModifyMapping { mapping } => self.mapping_handler.set_mapping(mapping.into()), + KeyMappingMessage::ModifyMapping { mapping } => self.mapping_handler.set_mapping(Mapping::new(mapping, environment)), } } advertise_actions!(); } impl KeyMappingMessageHandler { - pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant) -> Option { - self.mapping_handler.action_input_mapping(action_to_find) + pub fn new(environment: Environment) -> Self { + Self { + mapping_handler: InputMapperMessageHandler::new(Mapping::new(MappingVariant::Default, environment)), + } + } + + pub fn action_input_mapping(&self, action_to_find: &MessageDiscriminant, environment: Environment) -> Option { + self.mapping_handler.action_input_mapping(action_to_find, environment) } } diff --git a/editor/src/messages/input_mapper/utility_types/keyboard.rs b/editor/src/messages/input_mapper/utility_types/keyboard.rs index 041edb4ca0..1f9e66c2a5 100644 --- a/editor/src/messages/input_mapper/utility_types/keyboard.rs +++ b/editor/src/messages/input_mapper/utility_types/keyboard.rs @@ -1,4 +1,4 @@ -use crate::application::Editor; +use crate::application::{Environment, EnvironmentDisplay}; use crate::messages::prelude::*; use bitflags::bitflags; use std::fmt::{self, Display, Formatter}; @@ -243,9 +243,9 @@ pub enum Key { _KeysVariantCount, // This has to be the last element in the enum } -impl fmt::Display for Key { +impl EnvironmentDisplay for Key { // TODO: Relevant key labels should be localized when we get around to implementing localization/internationalization - fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter, environment: Environment) -> std::fmt::Result { let key_name = format!("{self:?}"); // Writing system keys @@ -258,7 +258,7 @@ impl fmt::Display for Key { return write!(f, "{}", key_name.chars().skip(KEY_PREFIX.len()).collect::()); } - let is_mac = Editor::environment().is_mac(); + let is_mac = environment.is_mac(); let name = match self { // Writing system keys @@ -345,36 +345,10 @@ pub const NUMBER_OF_KEYS: usize = Key::_KeysVariantCount as usize - 1; // ========= /// Only `Key`s that exist on a physical keyboard should be used. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct KeysGroup(pub Vec); -impl fmt::Display for KeysGroup { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - const JOINER_MARK: &str = " "; - - let mut joined = self - .0 - .iter() - .map(|key| { - let key_is_modifier = matches!(*key, Key::Control | Key::Command | Key::Alt | Key::Shift | Key::Meta | Key::Accel); - - if Editor::environment().is_mac() && key_is_modifier { - key.to_string() - } else { - key.to_string() + JOINER_MARK - } - }) - .collect::(); - - // Cut the joining character off the end, if present - if joined.ends_with(JOINER_MARK) { - joined.truncate(joined.len() - JOINER_MARK.len()); - } - - write!(f, "{joined}") - } -} - // ========== // LabeledKey // ========== @@ -425,13 +399,16 @@ pub enum LabeledKeyOrMouseMotion { MouseMotion(MouseMotion), } -impl From for LabeledKeyOrMouseMotion { - fn from(key: Key) -> Self { +impl LabeledKeyOrMouseMotion { + pub fn new(key: Key, environment: Environment) -> Self { match key { Key::MouseLeft => Self::MouseMotion(MouseMotion::Lmb), Key::MouseRight => Self::MouseMotion(MouseMotion::Rmb), Key::MouseMiddle => Self::MouseMotion(MouseMotion::Mmb), - _ => Self::Key(LabeledKey { key, label: key.to_string() }), + _ => Self::Key(LabeledKey { + key, + label: key.display(environment).to_string(), + }), } } } @@ -444,9 +421,9 @@ impl From for LabeledKeyOrMouseMotion { #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LabeledShortcut(pub Vec); -impl From for LabeledShortcut { - fn from(keys_group: KeysGroup) -> Self { - Self(keys_group.0.into_iter().map(|key| key.into()).collect()) +impl LabeledShortcut { + pub fn new(keys_group: KeysGroup, environment: Environment) -> Self { + Self(keys_group.0.into_iter().map(|key| LabeledKeyOrMouseMotion::new(key, environment)).collect()) } } diff --git a/editor/src/messages/input_mapper/utility_types/macros.rs b/editor/src/messages/input_mapper/utility_types/macros.rs index 2d0a5d6cf5..ec5767eeb9 100644 --- a/editor/src/messages/input_mapper/utility_types/macros.rs +++ b/editor/src/messages/input_mapper/utility_types/macros.rs @@ -163,8 +163,8 @@ macro_rules! action_shortcut { macro_rules! action_shortcut_manual { ($($keys:expr),*) => { - Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Shortcut( - crate::messages::input_mapper::utility_types::keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(), + Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Keys( + crate::messages::input_mapper::utility_types::keyboard::KeysGroup(vec![$($keys),*]), )) }; } diff --git a/editor/src/messages/input_mapper/utility_types/misc.rs b/editor/src/messages/input_mapper/utility_types/misc.rs index 8dcf77369f..6ffda83d1d 100644 --- a/editor/src/messages/input_mapper/utility_types/misc.rs +++ b/editor/src/messages/input_mapper/utility_types/misc.rs @@ -1,5 +1,5 @@ use super::keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed}; -use crate::messages::input_mapper::key_mapping::MappingVariant; +use crate::application::Environment; use crate::messages::input_mapper::utility_types::keyboard::{KeyStates, NUMBER_OF_KEYS}; use crate::messages::input_mapper::utility_types::pointer::NUMBER_OF_MOUSE_BUTTONS; use crate::messages::prelude::*; @@ -18,12 +18,6 @@ pub struct Mapping { pub pointer_shake: KeyMappingEntries, } -impl Default for Mapping { - fn default() -> Self { - MappingVariant::Default.into() - } -} - impl Mapping { pub fn match_input_message(&self, message: InputMapperMessage, keyboard_state: &KeyStates, actions: ActionList) -> Option { let list = self.associated_entries(&message); @@ -113,19 +107,20 @@ pub struct MappingEntry { pub enum ActionShortcut { #[serde(skip)] Action(MessageDiscriminant), + #[serde(skip)] + Keys(KeysGroup), #[serde(rename = "shortcut")] Shortcut(LabeledShortcut), } impl ActionShortcut { - pub fn realize_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option) { - if let Self::Action(action) = self { - if let Some(keys) = action_input_mapping(action) { - *self = Self::Shortcut(keys.into()); - } else { - *self = Self::Shortcut(KeysGroup::default().into()); - } - } + pub fn realize_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, environment: Environment) { + let keys = match self { + Self::Action(action) => action_input_mapping(action).unwrap_or_default(), + Self::Keys(keys) => std::mem::take(keys), + Self::Shortcut(_) => return, + }; + *self = Self::Shortcut(LabeledShortcut::new(keys, environment)); } } diff --git a/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs b/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs index 14a5526a94..b8f6399f35 100644 --- a/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs +++ b/editor/src/messages/input_preprocessor/input_preprocessor_message_handler.rs @@ -1,4 +1,4 @@ -use crate::application::Editor; +use crate::application::Environment; use crate::consts::DOUBLE_TAP_MILLISECONDS; use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys}; use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo; @@ -8,6 +8,7 @@ use std::time::Duration; #[derive(ExtractField)] pub struct InputPreprocessorMessageContext<'a> { + pub environment: Environment, pub viewport: &'a ViewportMessageHandler, } @@ -35,12 +36,12 @@ enum DoubleTapState { #[message_handler_data] impl<'a> MessageHandler> for InputPreprocessorMessageHandler { fn process_message(&mut self, message: InputPreprocessorMessage, responses: &mut VecDeque, context: InputPreprocessorMessageContext<'a>) { - let InputPreprocessorMessageContext { viewport } = context; + let InputPreprocessorMessageContext { environment, viewport } = context; match message { InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => { self.double_tap_state = DoubleTapState::Idle; - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); let pointer_state = editor_mouse_state.to_pointer_state(viewport); self.mouse.position = pointer_state.position; @@ -57,7 +58,7 @@ impl<'a> MessageHandler { - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); self.keyboard.set(key as usize); if !key_repeat { @@ -80,7 +81,7 @@ impl<'a> MessageHandler { - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); self.keyboard.unset(key as usize); if !key_repeat { responses.add(InputMapperMessage::KeyUpNoRepeat(key)); @@ -101,7 +102,7 @@ impl<'a> MessageHandler { self.double_tap_state = DoubleTapState::Idle; - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); let pointer_state = editor_mouse_state.to_pointer_state(viewport); self.mouse.position = pointer_state.position; @@ -109,7 +110,7 @@ impl<'a> MessageHandler { - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); let pointer_state = editor_mouse_state.to_pointer_state(viewport); self.mouse.position = pointer_state.position; @@ -121,7 +122,7 @@ impl<'a> MessageHandler { self.double_tap_state = DoubleTapState::Idle; - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); let pointer_state = editor_mouse_state.to_pointer_state(viewport); self.mouse.position = pointer_state.position; @@ -129,7 +130,7 @@ impl<'a> MessageHandler { - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); let pointer_state = editor_mouse_state.to_pointer_state(viewport); self.mouse.position = pointer_state.position; @@ -143,7 +144,7 @@ impl<'a> MessageHandler { self.double_tap_state = DoubleTapState::Idle; - self.update_states_of_modifier_keys(modifier_keys, responses); + self.update_states_of_modifier_keys(modifier_keys, environment, responses); let pointer_state = editor_mouse_state.to_pointer_state(viewport); self.mouse.position = pointer_state.position; @@ -199,7 +200,7 @@ impl InputPreprocessorMessageHandler { self.mouse = new_state; } - fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, responses: &mut VecDeque) { + fn update_states_of_modifier_keys(&mut self, pressed_modifier_keys: ModifierKeys, environment: Environment, responses: &mut VecDeque) { let is_key_pressed = |key_to_check: ModifierKeys| pressed_modifier_keys.contains(key_to_check); // Update the state of the concrete modifier keys based on the source state @@ -208,14 +209,14 @@ impl InputPreprocessorMessageHandler { self.update_modifier_key(Key::Control, is_key_pressed(ModifierKeys::CONTROL), responses); // Update the state of either the concrete Meta or the Command keys based on which one is applicable for this platform - let meta_or_command = match Editor::environment().is_mac() { + let meta_or_command = match environment.is_mac() { true => Key::Command, false => Key::Meta, }; self.update_modifier_key(meta_or_command, is_key_pressed(ModifierKeys::META_OR_COMMAND), responses); // Update the state of the virtual Accel key (the primary accelerator key) based on the source state of the Control or Command key, whichever is relevant on this platform - let accel_virtual_key_state = match Editor::environment().is_mac() { + let accel_virtual_key_state = match environment.is_mac() { true => is_key_pressed(ModifierKeys::META_OR_COMMAND), false => is_key_pressed(ModifierKeys::CONTROL), }; @@ -238,6 +239,7 @@ impl InputPreprocessorMessageHandler { #[cfg(test)] mod test { use super::DoubleTapState; + use crate::application::DEFAULT_ENVIRONMENT; use crate::consts::DOUBLE_TAP_MILLISECONDS; use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys}; use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys}; @@ -257,6 +259,7 @@ mod test { let mut responses = VecDeque::new(); let context = InputPreprocessorMessageContext { + environment: DEFAULT_ENVIRONMENT, viewport: &ViewportMessageHandler::default(), }; input_preprocessor.process_message(message, &mut responses, context); @@ -276,6 +279,7 @@ mod test { let mut responses = VecDeque::new(); let context = InputPreprocessorMessageContext { + environment: DEFAULT_ENVIRONMENT, viewport: &ViewportMessageHandler::default(), }; input_preprocessor.process_message(message, &mut responses, context); @@ -295,6 +299,7 @@ mod test { let mut responses = VecDeque::new(); let context = InputPreprocessorMessageContext { + environment: DEFAULT_ENVIRONMENT, viewport: &ViewportMessageHandler::default(), }; input_preprocessor.process_message(message, &mut responses, context); @@ -316,6 +321,7 @@ mod test { let mut responses = VecDeque::new(); let context = InputPreprocessorMessageContext { + environment: DEFAULT_ENVIRONMENT, viewport: &ViewportMessageHandler::default(), }; input_preprocessor.process_message(message, &mut responses, context); @@ -336,6 +342,7 @@ mod test { let mut responses = VecDeque::new(); let context = InputPreprocessorMessageContext { + environment: DEFAULT_ENVIRONMENT, viewport: &ViewportMessageHandler::default(), }; input_preprocessor.process_message(message, &mut responses, context); @@ -381,6 +388,7 @@ mod test { message, responses, InputPreprocessorMessageContext { + environment: DEFAULT_ENVIRONMENT, viewport: &ViewportMessageHandler::default(), }, ); diff --git a/editor/src/messages/layout/layout_message_handler.rs b/editor/src/messages/layout/layout_message_handler.rs index afd26eda4b..0b5c530dcb 100644 --- a/editor/src/messages/layout/layout_message_handler.rs +++ b/editor/src/messages/layout/layout_message_handler.rs @@ -1,3 +1,4 @@ +use crate::application::Environment; use crate::messages::input_mapper::utility_types::keyboard::KeysGroup; use crate::messages::layout::utility_types::math_expression::{ MathExpressionTokens, math_expression_completions, math_expression_error, math_expression_error_ranges, math_expression_number, math_expression_tokens, @@ -12,6 +13,7 @@ use std::collections::HashMap; #[derive(ExtractField)] pub struct LayoutMessageContext<'a> { + pub environment: Environment, pub action_input_mapping: &'a dyn Fn(&MessageDiscriminant) -> Option, } @@ -23,6 +25,7 @@ pub struct LayoutMessageHandler { #[message_handler_data] impl MessageHandler> for LayoutMessageHandler { fn process_message(&mut self, message: LayoutMessage, responses: &mut std::collections::VecDeque, context: LayoutMessageContext) { + let environment = context.environment; let action_input_mapping = &context.action_input_mapping; match message { @@ -36,7 +39,7 @@ impl MessageHandler> for LayoutMessageHa return; }; // Resend that diff - self.send_diff(vec![diff], layout_target, responses, action_input_mapping); + self.send_diff(vec![diff], layout_target, responses, action_input_mapping, environment); } LayoutMessage::ResendAllLayouts => { // Collect non-empty layouts and their indices, then clear the stored copies so diffs compute as full re-sends @@ -49,11 +52,11 @@ impl MessageHandler> for LayoutMessageHa .collect(); for (layout_target, layout) in layouts_to_resend { - self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping); + self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping, environment); } } LayoutMessage::SendLayout { layout, layout_target } => { - self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping); + self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping, environment); } LayoutMessage::DestroyLayout { layout_target } => { if let Some(layout) = self.layouts.get_mut(layout_target as usize) { @@ -575,6 +578,7 @@ impl LayoutMessageHandler { mut new_layout: Layout, responses: &mut VecDeque, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, + environment: Environment, ) { // Collect CheckboxId mappings from new layout let mut checkbox_map = HashMap::new(); @@ -605,12 +609,19 @@ impl LayoutMessageHandler { }]; } - self.send_diff(widget_diffs, layout_target, responses, action_input_mapping); + self.send_diff(widget_diffs, layout_target, responses, action_input_mapping, environment); } /// Send a diff to the frontend based on the layout target. - fn send_diff(&self, mut diff: Vec, layout_target: LayoutTarget, responses: &mut VecDeque, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option) { - diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping)); + fn send_diff( + &self, + mut diff: Vec, + layout_target: LayoutTarget, + responses: &mut VecDeque, + action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, + environment: Environment, + ) { + diff.iter_mut().for_each(|diff| diff.new_value.apply_keyboard_shortcut(action_input_mapping, environment)); if matches!(layout_target, LayoutTarget::_LayoutTargetLength) { panic!("`_LayoutTargetLength` is not a valid `LayoutTarget` and is used for array indexing"); diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 549cb4628d..0dc7a14c07 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -1,7 +1,7 @@ use super::widgets::button_widgets::*; use super::widgets::input_widgets::*; use super::widgets::label_widgets::*; -use crate::application::generate_uuid; +use crate::application::{Environment, generate_uuid}; use crate::messages::frontend::IconName; use crate::messages::input_mapper::utility_types::keyboard::KeysGroup; use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType; @@ -996,7 +996,7 @@ pub enum DiffUpdate { impl DiffUpdate { /// Append the keyboard shortcut to the tooltip where applicable - pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option) { + pub fn apply_keyboard_shortcut(&mut self, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, environment: Environment) { // Go through each widget to convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` and append the key combination to the widget tooltip let convert_tooltip = |widget_instance: &mut WidgetInstance| { // Handle all the widgets that have tooltips @@ -1033,7 +1033,7 @@ impl DiffUpdate { // Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` if let Some(tooltip_shortcut) = tooltip_shortcut { - tooltip_shortcut.realize_shortcut(action_input_mapping); + tooltip_shortcut.realize_shortcut(action_input_mapping, environment); } // Handle RadioInput separately because its tooltips are children of the widget @@ -1041,23 +1041,23 @@ impl DiffUpdate { for radio_entry_data in &mut radio_input.entries { // Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` if let Some(tooltip_shortcut) = radio_entry_data.tooltip_shortcut.as_mut() { - tooltip_shortcut.realize_shortcut(action_input_mapping); + tooltip_shortcut.realize_shortcut(action_input_mapping, environment); } } } }; // Recursively fill menu list entries with their realized shortcut keys specific to the current bindings and platform - fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option) { + fn apply_action_shortcut_to_menu_lists(entry_sections: &mut MenuListEntrySections, action_input_mapping: &impl Fn(&MessageDiscriminant) -> Option, environment: Environment) { for entries in entry_sections { for entry in entries { // Convert `ActionShortcut::Action` to `ActionShortcut::Shortcut` if let Some(tooltip_shortcut) = &mut entry.tooltip_shortcut { - tooltip_shortcut.realize_shortcut(action_input_mapping); + tooltip_shortcut.realize_shortcut(action_input_mapping, environment); } // Recursively call this function on the menu's children - apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping); + apply_action_shortcut_to_menu_lists(&mut entry.children, action_input_mapping, environment); } } } @@ -1065,29 +1065,39 @@ impl DiffUpdate { // Apply shortcut conversions to all widgets that have menu lists let convert_menu_lists = |widget_instance: &mut WidgetInstance| match &mut *widget_instance.widget { Widget::DropdownInput(dropdown_input) => { - apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping); + apply_action_shortcut_to_menu_lists(&mut dropdown_input.entries, action_input_mapping, environment); dropdown_input.entries_hash = hash_menu_list_entry_sections(&dropdown_input.entries); } Widget::TextButton(text_button) => { - apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping); + apply_action_shortcut_to_menu_lists(&mut text_button.menu_list_children, action_input_mapping, environment); text_button.menu_list_children_hash = hash_menu_list_entry_sections(&text_button.menu_list_children); } _ => {} }; - match self { - Self::Layout(layout) => layout.0.iter_mut().flat_map(|layout_group| layout_group.iter_mut()).for_each(|widget_instance| { - convert_tooltip(widget_instance); - convert_menu_lists(widget_instance); - }), - Self::LayoutGroup(layout_group) => layout_group.iter_mut().for_each(|widget_instance| { - convert_tooltip(widget_instance); - convert_menu_lists(widget_instance); - }), - Self::Widget(widget_instance) => { - convert_tooltip(widget_instance); - convert_menu_lists(widget_instance); + let convert = |widget_instance: &mut WidgetInstance| { + convert_tooltip(widget_instance); + convert_menu_lists(widget_instance); + }; + + fn convert_layout_group(layout_group: &mut LayoutGroup, convert: &impl Fn(&mut WidgetInstance)) { + match layout_group { + LayoutGroup::Column(WidgetColumn { widgets }) | LayoutGroup::Row(WidgetRow { widgets }) => widgets.iter_mut().for_each(|widget_instance| convert_widget(widget_instance, convert)), + LayoutGroup::Table(WidgetTable { rows, .. }) => rows.iter_mut().flatten().flatten().for_each(|widget_instance| convert_widget(widget_instance, convert)), + LayoutGroup::NodeSection(NodeSection { layout, .. }) => layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, convert)), } } + fn convert_widget(widget_instance: &mut WidgetInstance, convert: &impl Fn(&mut WidgetInstance)) { + convert(widget_instance); + if let Widget::PopoverButton(popover_button) = &mut *widget_instance.widget { + popover_button.popover_layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, convert)); + } + } + + match self { + Self::Layout(layout) => layout.0.iter_mut().for_each(|layout_group| convert_layout_group(layout_group, &convert)), + Self::LayoutGroup(layout_group) => convert_layout_group(layout_group, &convert), + Self::Widget(widget_instance) => convert_widget(widget_instance, &convert), + } } } diff --git a/editor/src/messages/message.rs b/editor/src/messages/message.rs index e3e3e6ec3a..2233f05be9 100644 --- a/editor/src/messages/message.rs +++ b/editor/src/messages/message.rs @@ -47,6 +47,7 @@ pub enum Message { Viewport(ViewportMessage), // Messages + Wake, Batched { messages: Box<[Message]>, }, diff --git a/editor/src/messages/portfolio/document/document_diff.rs b/editor/src/messages/portfolio/document/document_diff.rs index a128a975d3..3f5f2938b4 100644 --- a/editor/src/messages/portfolio/document/document_diff.rs +++ b/editor/src/messages/portfolio/document/document_diff.rs @@ -266,8 +266,8 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume if expected.skip_deduplication != actual.skip_deduplication { let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication); } - if expected.context_features != actual.context_features { - let _ = writeln!(out, " context_features: expected={:?} actual={:?}", expected.context_features, actual.context_features); + if expected.context_dependencies != actual.context_dependencies { + let _ = writeln!(out, " context_dependencies: expected={:?} actual={:?}", expected.context_dependencies, actual.context_dependencies); } if expected.original_location != actual.original_location { let _ = writeln!(out, " original_location differs (recomputed at load, not stored):"); diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index f99f053197..ba8505e16e 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -5,7 +5,7 @@ use super::utility_types::misc::{ANGLE_STEP_MAX, ANGLE_STEP_MIN, GroupFolderType use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus}; use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes}; use super::{CursorMoveError, DocumentHistory}; -use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid}; +use crate::application::{Environment, GRAPHITE_GIT_COMMIT_HASH, generate_uuid}; use crate::consts::{ ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING, }; @@ -58,6 +58,7 @@ use std::time::Duration; #[derive(ExtractField)] pub struct DocumentMessageContext<'a> { pub document_id: DocumentId, + pub environment: Environment, pub ipp: &'a InputPreprocessorMessageHandler, pub executor: &'a mut NodeGraphExecutor, pub current_tool: &'a ToolType, @@ -246,6 +247,7 @@ impl MessageHandler> for DocumentMes fn process_message(&mut self, message: DocumentMessage, responses: &mut VecDeque, context: DocumentMessageContext) { let DocumentMessageContext { document_id, + environment, ipp, executor, viewport, @@ -263,6 +265,7 @@ impl MessageHandler> for DocumentMes // Sub-messages DocumentMessage::Navigation(message) => { let context = NavigationMessageContext { + environment, network_interface: &mut self.network_interface, breadcrumb_network_path: &self.breadcrumb_network_path, ipp, @@ -4336,6 +4339,7 @@ fn deserialize_collapsed_layers<'de, D: serde::Deserializer<'de>>(deserializer: mod document_message_handler_tests { use super::*; use crate::consts::{BIG_NUDGE_AMOUNT, NUDGE_AMOUNT}; + use crate::messages::frontend::utility_types::RenderStatus; use crate::messages::portfolio::document::utility_types::misc::GridType; use crate::test_utils::test_prelude::*; @@ -4576,8 +4580,8 @@ mod document_message_handler_tests { .unwrap(); editor.runtime.run().await; - let mut messages = VecDeque::new(); - editor.editor.poll_node_graph_evaluation(&mut messages).unwrap(); + let frontend_messages = editor.editor.handle_message(Message::Wake); + assert!(!frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error })); } #[tokio::test] diff --git a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs index 09db062282..e03e9745d3 100644 --- a/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs +++ b/editor/src/messages/portfolio/document/navigation/navigation_message_handler.rs @@ -1,4 +1,4 @@ -use crate::application::Editor; +use crate::application::Environment; use crate::consts::{ VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR, @@ -16,6 +16,7 @@ use graph_craft::document::NodeId; #[derive(ExtractField)] pub struct NavigationMessageContext<'a> { + pub environment: Environment, pub network_interface: &'a mut NodeNetworkInterface, pub breadcrumb_network_path: &'a [NodeId], pub ipp: &'a InputPreprocessorMessageHandler, @@ -39,6 +40,7 @@ pub struct NavigationMessageHandler { impl MessageHandler> for NavigationMessageHandler { fn process_message(&mut self, message: NavigationMessage, responses: &mut VecDeque, context: NavigationMessageContext) { let NavigationMessageContext { + environment, network_interface, breadcrumb_network_path, ipp, @@ -189,7 +191,7 @@ impl MessageHandler> for Navigat } NavigationMessage::CanvasPanMouseWheel { use_y_as_x, .. } => { // On Mac, the OS already converts Shift+scroll into horizontal scrolling - let delta = if use_y_as_x && !Editor::environment().is_mac() { + let delta = if use_y_as_x && !environment.is_mac() { (ipp.mouse.scroll_delta.y, 0.).into() } else { ipp.mouse.scroll_delta.as_dvec2() diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs index 0a6c87069c..b3d7021c6f 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions/document_node_derive.rs @@ -42,7 +42,6 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap fields, description, inspector, - context_features, output_fields, .. } = metadata; @@ -90,7 +89,6 @@ pub(super) fn post_process_nodes(custom: Vec) -> HashMap inputs, call_argument: input_type.clone(), implementation: NodeTemplateImplementation::ProtoNode(id.clone()), - context_features: ContextDependencies::from(context_features.as_slice()), // TODO: Store information for input overrides in the node macro input_metadata: fields .iter() diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs index 60d26bfb0f..a3be59a0da 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message.rs @@ -1,4 +1,4 @@ -use super::utility_types::Direction; +use super::utility_types::{Direction, NodeEvaluationError}; use crate::messages::input_mapper::utility_types::keyboard::Key; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; @@ -305,6 +305,9 @@ pub enum NodeGraphMessage { #[serde(skip)] node_graph_errors: GraphErrors, }, + UpdateEvaluationErrors { + errors: Vec, + }, UpdateActionButtons, UpdateGraphBarRight, UpdateInSelectedNetwork, diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index 8a0db8caec..c4228ccc68 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -8,7 +8,7 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Modify use crate::messages::portfolio::document::node_graph::document_node_definitions::{ DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type, resolve_proto_node_type, }; -use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeGraphErrorDiagnostic}; +use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic}; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::network_interface::{ @@ -118,6 +118,7 @@ pub struct NodeGraphMessageHandler { frontend_nodes: Vec, /// Used to keep track of what wires are sent to the front end so the old ones can be removed frontend_wires: HashSet<(NodeId, usize)>, + evaluation_errors: Vec, } /// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network. @@ -1972,6 +1973,9 @@ impl<'a> MessageHandler> for NodeG nodes.push(*node_id); } } + if self.evaluation_errors.iter().any(|error| error.node_path.contains(node_id)) { + nodes.push(*node_id); + } } responses.add(FrontendMessage::UpdateVisibleNodes { nodes }); @@ -1986,8 +1990,8 @@ impl<'a> MessageHandler> for NodeG self.frontend_nodes = nodes.iter().map(|node| node.id).collect(); responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes }); - let error = self.node_graph_error(network_interface, breadcrumb_network_path); - responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostic { error }); + let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); + responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path); responses.add(NodeGraphMessage::UpdateImportsExports); @@ -2452,6 +2456,16 @@ impl<'a> MessageHandler> for NodeG responses.add(NodeGraphMessage::SendGraph); } + NodeGraphMessage::UpdateEvaluationErrors { errors } => { + if self.evaluation_errors != errors { + self.evaluation_errors = errors; + if breadcrumb_network_path == selection_network_path && graph_view_overlay_open { + let errors = self.node_graph_errors(network_interface, breadcrumb_network_path); + responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors }); + responses.add(NodeGraphMessage::UpdateVisibleNodes); + } + } + } NodeGraphMessage::UpdateActionButtons => { if selection_network_path == breadcrumb_network_path { self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses); @@ -3191,28 +3205,47 @@ impl NodeGraphMessageHandler { Some(subgraph_names) } - fn node_graph_error(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Option { - let graph_error = network_interface + fn node_graph_errors(&self, network_interface: &mut NodeNetworkInterface, breadcrumb_network_path: &[NodeId]) -> Vec { + let depth = breadcrumb_network_path.len(); + let inside = |path: &[NodeId]| path.starts_with(breadcrumb_network_path) && path.len() > depth; + let graph_errors: Vec<_> = network_interface .resolved_types .node_graph_errors .iter() - .find(|error| error.node_path.starts_with(breadcrumb_network_path) && error.node_path.len() > breadcrumb_network_path.len())?; - let error = if graph_error.node_path.len() == breadcrumb_network_path.len() + 1 { - format!("{:?}", graph_error.error) - } else { - "Node graph type error within this node".to_string() + .filter(|error| inside(&error.node_path)) + .map(|error| match error.node_path.len() == depth + 1 { + true => (error.node_path[depth], format!("{:?}", error.error)), + false => (error.node_path[depth], "Node graph type error within this node".to_string()), + }) + .collect(); + // Evaluation errors come from the last graph that compiled, so a type error hides them + let errors = match graph_errors.is_empty() { + true => self + .evaluation_errors + .iter() + .filter(|error| inside(&error.node_path)) + .map(|error| match error.node_path.len() == depth + 1 { + true => (error.node_path[depth], error.message.clone()), + false => (error.node_path[depth], "Node graph error within this node".to_string()), + }) + .collect(), + false => graph_errors, }; - let error_node = graph_error.node_path[breadcrumb_network_path.len()]; - let mut position = network_interface.position(&error_node, breadcrumb_network_path)?; - // Convert to graph space - position *= 24; - if network_interface.is_layer(&error_node, breadcrumb_network_path) { - position += IVec2::new(12, -12) - } - let position = position.into(); - - Some(NodeGraphErrorDiagnostic { position, error }) + let mut shown = HashSet::new(); + errors + .into_iter() + .filter(|(node, _)| shown.insert(*node)) + .filter_map(|(node, error)| { + let mut position = network_interface.position(&node, breadcrumb_network_path)?; + // Convert to graph space + position *= 24; + if network_interface.is_layer(&node, breadcrumb_network_path) { + position += IVec2::new(12, -12) + } + Some(NodeGraphErrorDiagnostic { position: position.into(), error }) + }) + .collect() } fn update_layer_panel( @@ -3411,6 +3444,7 @@ impl Default for NodeGraphMessageHandler { end_index: None, frontend_nodes: Vec::new(), frontend_wires: HashSet::new(), + evaluation_errors: Vec::new(), } } } diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index 09fe85c553..bca938a149 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -448,7 +448,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, }, Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(), Type::Fn(_, out) => return inspector_row_from_type(node_id, index, out, options, context), - Type::Future(out) => return inspector_row_from_type(node_id, index, out, options, context), }; extra_widgets.push(widgets); @@ -3867,8 +3866,8 @@ mod tests { #[test] fn wire_element_reads_every_spelling_down_to_the_element() { // A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element - let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64))))); - let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64))))); + let row = Type::Fn(Box::new(concrete!(())), Box::new(item!(f64))); + let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(list!(f64))); for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] { assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element"); } diff --git a/editor/src/messages/portfolio/document/node_graph/utility_types.rs b/editor/src/messages/portfolio/document/node_graph/utility_types.rs index 549df5797c..33453dd639 100644 --- a/editor/src/messages/portfolio/document/node_graph/utility_types.rs +++ b/editor/src/messages/portfolio/document/node_graph/utility_types.rs @@ -193,6 +193,12 @@ pub struct NodeGraphErrorDiagnostic { pub error: String, } +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct NodeEvaluationError { + pub node_path: Vec, + pub message: String, +} + #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)] pub struct FrontendClickTargets { diff --git a/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs b/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs index fa6e4ec817..7031a686d4 100644 --- a/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs +++ b/editor/src/messages/portfolio/document/storage_tests/lifecycle_tests.rs @@ -7,7 +7,7 @@ use crate::test_utils::EditorTestUtils; use document_container::{AnyContainer, AsyncContainer}; fn dispatch(editor: &mut EditorTestUtils, message: impl Into) -> Vec { - editor.editor.handle_message(message) + editor.dispatch(message) } fn portfolio(editor: &EditorTestUtils) -> &PortfolioMessageHandler { diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface.rs b/editor/src/messages/portfolio/document/utility_types/network_interface.rs index a5ce50be69..462b1295a3 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface.rs @@ -53,7 +53,6 @@ use graph_craft::application_io::resource::ResourceId; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork}; use graphene_std::Appearance; -use graphene_std::ContextDependencies; use graphene_std::math::quad::Quad; use graphene_std::registry::MULTI_OUTPUT_NODES; use graphene_std::transform::Footprint; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs index 49e48770f5..9f517e885f 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/apply.rs @@ -73,16 +73,6 @@ impl NodeNetworkInterface { } } - EditorDelta::Graph(RuntimeDelta::SetContextFeatures { - network_path, - node_id, - context_features, - }) => { - if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { - node.set_context_features(*context_features); - } - } - EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => { if let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) { node.replace_metadata((**metadata).clone()); diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs index 1f9b986715..0debcf67d4 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/editor_delta.rs @@ -211,17 +211,6 @@ impl EditorDelta { }); } - EditorDelta::Graph(RuntimeDelta::SetContextFeatures { - network_path, - node_id, - context_features, - }) => { - ops.push(RegistryDelta::ChangeNodeAttribute { - id: context.resolver.node_id(network_path, *node_id), - delta: document_graph_storage::from_runtime::encode_context_features(context_features)?, - }); - } - EditorDelta::NodeMetadataSnapshot { network_path, node_id, metadata } => { construct_metadata_snapshot(network_path, *node_id, metadata, batch, &context.resolver, ops)?; } diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs index 905d1accd5..395e76b980 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/mutations.rs @@ -515,14 +515,6 @@ impl NodeNetworkInterface { node.set_call_argument(call_argument); } - pub fn set_context_features(&mut self, node_id: &NodeId, network_path: &[NodeId], context_features: ContextDependencies) { - let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { - log::error!("Could not get node {node_id} in set_context_features"); - return; - }; - node.set_context_features(context_features); - } - /// Lightweight version of `set_input` for bulk import operations. /// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions, /// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs index f75929b676..b5ad0a23f3 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/store/cursor.rs @@ -193,21 +193,6 @@ impl NodeMut<'_> { changed } - /// The Extract and Inject annotations the node declares for the Context. - pub(crate) fn set_context_features(&mut self, context_features: ContextDependencies) -> bool { - let changed = self.node.context_features != context_features; - self.node.context_features = context_features; - if changed { - let delta = RuntimeDelta::SetContextFeatures { - network_path: self.deltas.network_path(), - node_id: self.deltas.node_id(), - context_features: self.node.context_features, - }; - self.deltas.graph(delta); - } - changed - } - /// The user-chosen name for this instance, empty when it has none. pub(crate) fn set_display_name(&mut self, display_name: String) -> bool { let changed = self.metadata.display_name != display_name; diff --git a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs index ea551eb932..3d572f5f8e 100644 --- a/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs +++ b/editor/src/messages/portfolio/document/utility_types/network_interface/template.rs @@ -23,8 +23,6 @@ pub struct NodeTemplate { pub visible: bool, /// Prevents identical proto nodes from being deduplicated during compilation, e.g. for monitor nodes. pub skip_deduplication: bool, - /// List of Extract and Inject annotations for the Context. - pub context_features: ContextDependencies, /// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed in italics. pub display_name: String, /// Metadata to override the Inspector widgets for each input. Kept the same length as `inputs`. @@ -60,7 +58,6 @@ impl Default for NodeTemplate { implementation: NodeTemplateImplementation::default(), visible: true, skip_deduplication: false, - context_features: ContextDependencies::default(), display_name: String::new(), input_metadata: Vec::new(), output_names: Vec::new(), @@ -117,7 +114,7 @@ impl NodeTemplate { implementation, visible, skip_deduplication, - context_features, + context_dependencies: _, original_location: _, } = document_node; let DocumentNodePersistentMetadata { @@ -163,7 +160,6 @@ impl NodeTemplate { implementation, visible, skip_deduplication, - context_features, display_name, input_metadata, output_names, @@ -182,7 +178,6 @@ impl NodeTemplate { implementation, visible, skip_deduplication, - context_features, display_name, mut input_metadata, output_names, @@ -203,7 +198,7 @@ impl NodeTemplate { implementation, visible, skip_deduplication, - context_features, + context_dependencies: None, original_location: Default::default(), }; let persistent_node_metadata = DocumentNodePersistentMetadata { diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 668dc412e7..0853692785 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -3214,15 +3214,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], } } - // Add context features to nodes that don't have them (fine-grained context caching migration) - if node.context_features == graphene_std::ContextDependencies::default() - && let Some(reference) = document.network_interface.reference(node_id, network_path).clone() - && let Some(node_definition) = resolve_document_node_type(&reference) - { - let context_features = node_definition.node_template.context_features; - document.network_interface.set_context_features(node_id, network_path, context_features); - } - // Add the "Scale Type" parameter to the "Decompose Scale" node if reference == DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::decompose_scale::IDENTIFIER) && inputs_count == 1 { let mut node_template = resolve_document_node_type(&reference)?.default_node_template(); diff --git a/editor/src/messages/portfolio/portfolio_message.rs b/editor/src/messages/portfolio/portfolio_message.rs index 0f7cb3915c..d65451beab 100644 --- a/editor/src/messages/portfolio/portfolio_message.rs +++ b/editor/src/messages/portfolio/portfolio_message.rs @@ -149,6 +149,7 @@ pub enum PortfolioMessage { ignore_hash: bool, }, SubmitEyedropperPreviewRender, + PollNodeGraphEvaluation, ToggleResetNodesToDefinitionsOnOpen, ToggleRulers, UpdateDocumentWidgets, diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index 5ae23bea9d..00c50133d4 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -1,13 +1,14 @@ use super::document::utility_types::document_metadata::LayerNodeIdentifier; use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler}; use super::utility_types::PanelType; -use crate::application::{Editor, generate_uuid}; +use crate::application::{Environment, generate_uuid}; use crate::consts::DEFAULT_DOCUMENT_NAME; use crate::messages::animation::TimingInformation; use crate::messages::dialog::simple_dialogs; use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState}; -use crate::messages::input_mapper::utility_types::keyboard::Key; -use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual}; +use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledShortcut}; +use crate::messages::input_mapper::utility_types::macros::action_shortcut; +use crate::messages::input_mapper::utility_types::misc::ActionShortcut; use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::portfolio::document::DocumentMessageContext; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; @@ -34,6 +35,7 @@ use std::vec; #[derive(ExtractField)] pub struct PortfolioMessageContext<'a> { + pub environment: Environment, pub ipp: &'a InputPreprocessorMessageHandler, pub preferences: &'a PreferencesMessageHandler, pub animation: &'a AnimationMessageHandler, @@ -45,7 +47,7 @@ pub struct PortfolioMessageContext<'a> { pub resource_storage: &'a ResourceStorageMessageHandler, } -#[derive(Debug, Default, ExtractField)] +#[derive(Debug, ExtractField)] pub struct PortfolioMessageHandler { pub documents: HashMap, loading_documents: HashMap, @@ -69,6 +71,7 @@ pub struct PortfolioMessageHandler { impl MessageHandler> for PortfolioMessageHandler { fn process_message(&mut self, message: PortfolioMessage, responses: &mut VecDeque, context: PortfolioMessageContext) { let PortfolioMessageContext { + environment, ipp, preferences, animation, @@ -88,6 +91,7 @@ impl MessageHandler> for Portfolio { let document_inputs = DocumentMessageContext { document_id, + environment, ipp, fonts: &self.fonts, executor: &mut self.executor, @@ -143,9 +147,7 @@ impl MessageHandler> for Portfolio responses.add(PersistentStateMessage::ReadState); // Initialize the frontend with environment information - responses.add(FrontendMessage::UpdatePlatform { - platform: Editor::environment().into(), - }); + responses.add(FrontendMessage::UpdatePlatform { platform: environment.into() }); // Before loading any documents, initially prepare the welcome screen buttons layout responses.add(PortfolioMessage::RequestWelcomeScreenButtonsLayout); @@ -162,16 +164,17 @@ impl MessageHandler> for Portfolio // Request status bar info layout responses.add(PortfolioMessage::RequestStatusBarInfoLayout); - // Send shortcuts for widgets created in the frontend which need shortcut tooltips + // Send shortcuts for widgets created in the frontend which need shortcut tooltips, labeled here since they bypass the layout system + let shortcut = |keys: &[Key]| Some(ActionShortcut::Shortcut(LabeledShortcut::new(KeysGroup(keys.to_vec()), environment))); responses.add(FrontendMessage::SendShortcutFullscreen { - shortcut: action_shortcut_manual!(Key::F11), - shortcut_mac: action_shortcut_manual!(Key::Control, Key::Command, Key::KeyF), + shortcut: shortcut(&[Key::F11]), + shortcut_mac: shortcut(&[Key::Control, Key::Command, Key::KeyF]), }); responses.add(FrontendMessage::SendShortcutAltClick { - shortcut: action_shortcut_manual!(Key::Alt, Key::MouseLeft), + shortcut: shortcut(&[Key::Alt, Key::MouseLeft]), }); responses.add(FrontendMessage::SendShortcutShiftClick { - shortcut: action_shortcut_manual!(Key::Shift, Key::MouseLeft), + shortcut: shortcut(&[Key::Shift, Key::MouseLeft]), }); // Send the information for tooltips and categories for each node/input. @@ -185,6 +188,7 @@ impl MessageHandler> for Portfolio if let Some(document) = self.documents.get_mut(&document_id) { let document_inputs = DocumentMessageContext { document_id, + environment, ipp, fonts: &self.fonts, executor: &mut self.executor, @@ -994,6 +998,12 @@ impl MessageHandler> for Portfolio Ok(message) => responses.add_front(message), } } + PortfolioMessage::PollNodeGraphEvaluation => { + let Some(document_id) = self.active_document_id else { return }; + let Some(active_document) = self.documents.get_mut(&document_id) else { return }; + + self.executor.poll_node_graph_evaluation(active_document, document_id, responses); + } PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => { self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open; responses.add(MenuBarMessage::SendLayout); @@ -1050,12 +1060,25 @@ impl MessageHandler> for Portfolio } impl PortfolioMessageHandler { - pub fn with_executor(executor: crate::node_graph_executor::NodeGraphExecutor) -> Self { - Self { executor, ..Default::default() } - } - - pub fn set_document_store(&mut self, store: Arc) { - self.document_store = DocumentStoreHandle::new(store); + pub fn new(executor: NodeGraphExecutor, document_store: Arc) -> Self { + Self { + documents: Default::default(), + loading_documents: Default::default(), + document_ids: Default::default(), + active_document_id: Default::default(), + failed_documents: Default::default(), + persistent_state: Default::default(), + fonts: Default::default(), + ingest: Default::default(), + executor, + selection_mode: Default::default(), + reset_node_definitions_on_open: Default::default(), + workspace: Default::default(), + document_store: DocumentStoreHandle::new(document_store), + pending_opens: Default::default(), + restore_select: Default::default(), + store_unavailable: Default::default(), + } } #[cfg(test)] @@ -1224,30 +1247,6 @@ impl PortfolioMessageHandler { self.document_ids.iter().position(|id| id == &document_id).expect("Active document is missing from document ids") } - pub fn poll_node_graph_evaluation(&mut self, responses: &mut VecDeque) -> Result<(), String> { - let Some(document_id) = self.active_document_id else { - return Err("No active document".to_string()); - }; - let Some(active_document) = self.documents.get_mut(&document_id) else { - return Err("No active document".to_string()); - }; - - let result = self.executor.poll_node_graph_evaluation(active_document, document_id, responses); - if result.is_err() { - let error = r#" - - - The document cannot render in its current state. - Undo to go back, if available, or check for error details - by clicking the Node Graph button up at the top right. - /text>"# - // It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed. - .to_string(); - responses.add(FrontendMessage::UpdateDocumentArtwork { svg: error }); - } - result - } - fn document_details(&self, document_id: DocumentId) -> Option { if let Some(document) = self.documents.get(&document_id) { Some(DocumentInfo { diff --git a/editor/src/messages/prelude.rs b/editor/src/messages/prelude.rs index a4f555dc20..766da5b616 100644 --- a/editor/src/messages/prelude.rs +++ b/editor/src/messages/prelude.rs @@ -16,7 +16,7 @@ pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler}; pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler}; pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant}; -pub use crate::messages::future::{FutureMessage, FutureMessageContext, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, MessageSpawner, Wake}; +pub use crate::messages::future::{FutureMessage, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, Wake}; pub use crate::messages::input_mapper::key_mapping::{KeyMappingMessage, KeyMappingMessageContext, KeyMappingMessageDiscriminant, KeyMappingMessageHandler}; pub use crate::messages::input_mapper::{InputMapperMessage, InputMapperMessageContext, InputMapperMessageDiscriminant, InputMapperMessageHandler}; pub use crate::messages::input_preprocessor::{InputPreprocessorMessage, InputPreprocessorMessageContext, InputPreprocessorMessageDiscriminant, InputPreprocessorMessageHandler}; diff --git a/editor/src/messages/tool/utility_types.rs b/editor/src/messages/tool/utility_types.rs index a23a0610f3..811cdc1155 100644 --- a/editor/src/messages/tool/utility_types.rs +++ b/editor/src/messages/tool/utility_types.rs @@ -556,7 +556,7 @@ impl HintData { } for shortcut in &hint.key_groups { - widgets.push(ShortcutLabel::new(Some(ActionShortcut::Shortcut(shortcut.clone()))).widget_instance()); + widgets.push(ShortcutLabel::new(Some(ActionShortcut::Keys(shortcut.clone()))).widget_instance()); } if let Some(mouse_movement) = hint.mouse { let mouse_movement = LabeledShortcut(vec![LabeledKeyOrMouseMotion::MouseMotion(mouse_movement)]); @@ -598,10 +598,10 @@ pub struct HintInfo { /// A `KeysGroup` specifies all the keys pressed simultaneously to perform an action (like "Ctrl C" to copy). /// Usually at most one is given, but less commonly, multiple can be used to describe additional hotkeys not used simultaneously (like the four different arrow keys to nudge a layer). #[serde(rename = "keyGroups")] - pub key_groups: Vec, + pub key_groups: Vec, /// `None` means that the regular `key_groups` should be used for all platforms, `Some` is an override for a Mac-only input hint. #[serde(rename = "keyGroupsMac")] - pub key_groups_mac: Option>, + pub key_groups_mac: Option>, /// An optional `MouseMotion` that can indicate the mouse action, like which mouse button is used and whether a drag occurs. /// No such icon is shown if `None` is given, and it can be combined with `key_groups` if desired. pub mouse: Option, @@ -621,7 +621,7 @@ impl HintInfo { pub fn keys(keys: impl IntoIterator, label: impl Into>) -> Self { let keys = keys.into_iter().collect(); Self { - key_groups: vec![KeysGroup(keys).into()], + key_groups: vec![KeysGroup(keys)], key_groups_mac: None, mouse: None, label: label.into(), @@ -635,7 +635,7 @@ impl HintInfo { /// - The four arrow keys can be used to nudge a layer in different directions /// - The G, R, and S keys can be used to enter GRS transformation mode pub fn multi_keys(multi_keys: impl IntoIterator>, label: impl Into>) -> Self { - let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect()).into()).collect(); + let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect())).collect(); Self { key_groups, key_groups_mac: None, @@ -671,7 +671,7 @@ impl HintInfo { pub fn keys_and_mouse(keys: impl IntoIterator, mouse_motion: MouseMotion, label: impl Into>) -> Self { let keys = keys.into_iter().collect(); Self { - key_groups: vec![KeysGroup(keys).into()], + key_groups: vec![KeysGroup(keys)], key_groups_mac: None, mouse: Some(mouse_motion), label: label.into(), @@ -681,7 +681,7 @@ impl HintInfo { } pub fn multi_keys_and_mouse(multi_keys: impl IntoIterator>, mouse_motion: MouseMotion, label: impl Into>) -> Self { - let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect()).into()).collect(); + let key_groups = multi_keys.into_iter().map(|keys| KeysGroup(keys.into_iter().collect())).collect(); Self { key_groups, key_groups_mac: None, @@ -709,7 +709,7 @@ impl HintInfo { pub fn add_mac_keys(mut self, keys: impl IntoIterator) -> Self { let mac_keys = keys.into_iter().collect(); - self.key_groups_mac = Some(vec![KeysGroup(mac_keys).into()]); + self.key_groups_mac = Some(vec![KeysGroup(mac_keys)]); self } } diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index ecb9ba72d6..71b37dad40 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -1,4 +1,5 @@ -use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage}; +use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; +use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError; use crate::messages::portfolio::document::utility_types::network_interface::InputConnector; use crate::messages::prelude::*; use glam::{DAffine2, DVec2, UVec2}; @@ -6,7 +7,7 @@ use graph_craft::application_io::EditorPreferences; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; use graph_craft::proto::GraphErrors; -use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderConfig, TimingInformation}; +use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::color::SRGBA8; use graphene_std::list::List; @@ -19,14 +20,12 @@ use graphene_std::{ATTR_TRANSFORM, Context, Graphic}; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use std::any::Any; use std::sync::Arc; - -mod runtime_io; -pub use runtime_io::NodeRuntimeIO; +use std::sync::mpsc::{Receiver, Sender}; mod runtime; pub use runtime::*; -#[derive(Debug, serde::Serialize, serde::Deserialize)] +#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct ExecutionRequest { execution_id: u64, render_config: RenderConfig, @@ -34,13 +33,24 @@ pub struct ExecutionRequest { pub struct ExecutionResponse { execution_id: u64, - result: Result, + result: ExecutionResult, responses: VecDeque, vector_modify: HashMap, /// The resulting value from the temporary inspected during execution inspect_result: Option, } +#[derive(Debug)] +pub enum ExecutionResult { + Pending, + Value(TaggedValue), + Fallback(TaggedValue, EvaluationError), + Error(EvaluationError), + Panic(Box), +} + +pub type EvaluationError = Box<[(Arc, Box<[NodeId]>)]>; + #[derive(serde::Serialize, serde::Deserialize)] pub struct CompilationResponse { result: Result, @@ -51,14 +61,15 @@ pub enum NodeGraphUpdate { ExecutionResponse(Box), CompilationResponse(CompilationResponse), EyedropperPreview(Raster), - NodeGraphUpdateMessage(NodeGraphUpdateMessage), } -#[derive(Debug, Default)] +#[derive(Debug)] pub struct NodeGraphExecutor { - runtime_io: NodeRuntimeIO, + sender: Sender, + receiver: Receiver, current_execution_id: u64, futures: VecDeque<(u64, ExecutionContext)>, + pending: Option<(u64, ExecutionContext)>, node_graph_hash: u64, /// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected. /// The last element is the inspect target itself; preceding elements identify the nested subnetwork the node lives in, @@ -100,23 +111,23 @@ struct GradientMigration { } impl NodeGraphExecutor { - /// A local runtime is useful on threads since having global state causes flakes - #[cfg(test)] - pub(crate) fn new_with_local_runtime() -> (NodeRuntime, Self) { + pub(crate) fn new(editor_wake: Wake) -> (Self, NodeRuntime) { let (request_sender, request_receiver) = std::sync::mpsc::channel(); let (response_sender, response_receiver) = std::sync::mpsc::channel(); - let node_runtime = NodeRuntime::new(request_receiver, response_sender); + let node_runtime = NodeRuntime::new(request_receiver, response_sender, editor_wake); let node_executor = Self { futures: Default::default(), - runtime_io: NodeRuntimeIO::with_channels(request_sender, response_receiver), + sender: request_sender, + receiver: response_receiver, node_graph_hash: 0, current_execution_id: 0, previous_node_to_inspect: Vec::new(), gradient_migration: None, gradient_migration_attempted: HashSet::new(), + pending: None, }; - (node_runtime, node_executor) + (node_executor, node_runtime) } /// Allows the test runner to see if any more executions have been queued. @@ -130,13 +141,13 @@ impl NodeGraphExecutor { let execution_id = self.current_execution_id; self.current_execution_id += 1; let request = ExecutionRequest { execution_id, render_config }; - self.runtime_io.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); + self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); execution_id } pub fn update_editor_preferences(&self, editor_preferences: EditorPreferences) { - self.runtime_io + self.sender .send(GraphRuntimeRequest::EditorPreferencesUpdate(editor_preferences)) .expect("Failed to send editor preferences"); } @@ -151,7 +162,7 @@ impl NodeGraphExecutor { let resources = document.resources.registry.clone(); - self.runtime_io + self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, @@ -172,7 +183,7 @@ impl NodeGraphExecutor { let resources = document.resources.registry.clone(); - self.runtime_io + self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, node_to_inspect })) .map_err(|e| e.to_string())?; } @@ -338,7 +349,7 @@ impl NodeGraphExecutor { export_config.size = resolution; // Execute the node graph - self.runtime_io + self.sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, @@ -359,14 +370,14 @@ impl NodeGraphExecutor { Ok(()) } - pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque) -> Result<(), String> { + pub fn poll_node_graph_evaluation(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque) { // TODO: Eventually remove this document upgrade code // A gradient migration belongs to one document; if the active document changed away from it, cancel so its stale in-flight response is ignored and revisiting restarts a fresh pass if self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id != document_id) { self.cancel_gradient_migration(); } - let results = self.runtime_io.receive().collect::>(); + let results = self.receiver.try_iter().collect::>(); for response in results { match response { NodeGraphUpdate::ExecutionResponse(execution_response) => { @@ -386,42 +397,77 @@ impl NodeGraphExecutor { } } - let Some((queued_execution_id, execution_context)) = self.futures.pop_front() else { - panic!("InvalidGenerationId") + 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() { + self.pending = Some((execution_id, execution_context.clone())); + } + execution_context + } else if let Some((rendered_execution_id, execution_context)) = &self.pending + && *rendered_execution_id == execution_id + { + execution_context.clone() + } else { + continue; }; - assert_eq!(queued_execution_id, execution_id, "Missmatch in execution id"); // TODO: Eventually remove this document upgrade code // Gradient-migration measurement runs only read back the fill's evaluated geometry; they never render to the artwork. // Apply only to the active document's in-progress migration, dropping responses left over from a document switch. if let Some(bake_target) = execution_context.measure_fill { if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) { - self.handle_gradient_measurement(document, document_id, bake_target, result.ok().and(inspect_result), responses); + let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten(); + self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses); } continue; } 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) { + let errors = match &result { + ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => errors + .iter() + .map(|(error, node_path)| NodeEvaluationError { + node_path: node_path.to_vec(), + message: error.to_string(), + }) + .collect(), + ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) => Vec::new(), + }; + responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors }); + } + let node_graph_output = match result { + ExecutionResult::Pending => Ok(None), + ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Ok(Some(value)), + ExecutionResult::Error(errors) => Err(errors.iter().map(|(error, _)| error.to_string()).collect::>().join("\n")), + ExecutionResult::Panic(payload) => { + let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::().map(String::as_str)); + Err(format!("Panicked: {}", message.unwrap_or("no message"))) + } + }; + let node_graph_output = match node_graph_output { Ok(output) => output, Err(e) => { // Clear the click targets while the graph is in an un-renderable state document.network_interface.update_click_targets(HashMap::new()); document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new()); - return Err(format!("Node graph evaluation failed:\n{e}")); + log::error!("Node graph evaluation failed:\n{e}"); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + return; } }; responses.extend(existing_responses.into_iter().map(Into::into)); document.network_interface.update_vector_modify(vector_modify); - if let Some(export_config) = execution_context.export_config { - // Special handling for exporting the artwork - self.process_export(node_graph_output, export_config, document, responses)?; - } else { - self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, responses)?; + 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, responses), + (None, _) => {} } responses.add(DeferMessage::TriggerGraphRun { execution_id, @@ -462,7 +508,8 @@ impl NodeGraphExecutor { node_graph_errors, }); - return Err(format!("Node graph evaluation failed:\n{e}")); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + return; } Ok(result) => result, }; @@ -476,11 +523,8 @@ impl NodeGraphExecutor { let (data, width, height) = raster.to_flat_u8(); responses.add(EyedropperToolMessage::PreviewImage { data, width, height }); } - NodeGraphUpdate::NodeGraphUpdateMessage(_) => {} } } - - Ok(()) } // TODO: Eventually remove this document upgrade code @@ -548,7 +592,7 @@ impl NodeGraphExecutor { let resources = document.resources.registry.clone(); if self - .runtime_io + .sender .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, @@ -667,9 +711,11 @@ impl NodeGraphExecutor { self.node_graph_hash = 0; } - fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque) -> Result<(), String> { + fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque) { let TaggedValue::RenderOutput(render_output) = node_graph_output else { - return Err(format!("Invalid node graph output type: {node_graph_output:#?}")); + log::error!("Invalid node graph output type: {node_graph_output:#?}"); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + return; }; match render_output.data { @@ -697,7 +743,11 @@ impl NodeGraphExecutor { responses.add(FrontendMessage::UpdateDocumentArtwork { svg }); } RenderOutputType::Texture { .. } => {} - _ => return Err(format!("Invalid node graph output type: {:#?}", render_output.data)), + _ => { + log::error!("Invalid node graph output type: {:#?}", render_output.data); + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); + return; + } } let RenderMetadata { @@ -730,10 +780,10 @@ impl NodeGraphExecutor { responses.add(DocumentMessage::RenderRulers); responses.add(OverlaysMessage::Draw); - Ok(()) + responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Rendering }); } - fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque) -> Result<(), String> { + fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque) { let ExportConfig { file_type, name, @@ -773,15 +823,19 @@ impl NodeGraphExecutor { data: RenderOutputType::Buffer { data, width, height }, .. }) if file_type != FileType::Svg => { - let content = file_type.encode(width, height, data)?.into(); + let content = match file_type.encode(width, height, data) { + Ok(content) => content.into(), + Err(e) => { + log::error!("Failed to encode image: {e}"); + return; + } + }; responses.add(FrontendMessage::TriggerSaveFile { name, folder, filters, content }); } _ => { - return Err(format!("Incorrect render type for exporting to an SVG ({file_type:?}, {node_graph_output})")); + log::error!("Incorrect render type for exporting to an SVG ({file_type:?}, {node_graph_output})"); } - }; - - Ok(()) + } } } diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 26f1307866..b9884efc91 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -1,5 +1,6 @@ use super::*; use crate::messages::frontend::utility_types::{ExportBounds, FileType}; +use crate::task::{Spawn, Spawner, Task}; use glam::{DAffine2, DVec2, UVec2}; use graph_craft::application_io::resource::ResourceRegistry; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; @@ -8,23 +9,24 @@ use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::graphene_compiler::Compiler; use graph_craft::proto::GraphErrors; -use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture}; +use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig, Texture}; use graphene_std::bounds::RenderBoundingBox; use graphene_std::list::{Item, List}; use graphene_std::memo::IORecord; -use graphene_std::ops::Convert; +use graphene_std::ops::ConvertAsync; #[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))] use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle}; use graphene_std::raster_types::Raster; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment}; +use graphene_std::runtime::AsyncRuntime; use graphene_std::transform::RenderQuality; use graphene_std::vector::style::RenderMode; use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes}; -use graphene_std::{Artboard, Context, Graphic}; -use interpreted_executor::dynamic_executor::{DynamicExecutor, IntrospectError, ResolvedDocumentNodeTypesDelta}; +use graphene_std::{Artboard, Context, Graphic, NodeError, Poll}; +use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::util::wrap_network_in_scope; -use spin::Mutex; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender}; /// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`. @@ -36,10 +38,15 @@ pub struct NodeRuntime { #[cfg(not(test))] executor: DynamicExecutor, receiver: Receiver, - sender: InternalNodeGraphUpdateSender, + sender: Sender, + editor_wake: Wake, + dirty: Arc, + pending: Option, + pending_export: Option, editor_preferences: EditorPreferences, old_graph: Option, update_thumbnails: bool, + async_runtime: Option, editor_api: Arc, resources: ResourceRegistry, @@ -93,46 +100,24 @@ pub struct ExportConfig { pub artboard_count: usize, } -#[derive(Clone)] -struct InternalNodeGraphUpdateSender(Sender); - -impl InternalNodeGraphUpdateSender { - fn send_compilation_response(&self, response: CompilationResponse) { - self.0.send(NodeGraphUpdate::CompilationResponse(response)).expect("Failed to send response") - } - - fn send_execution_response(&self, response: ExecutionResponse) { - self.0.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response") - } - - fn send_eyedropper_preview(&self, raster: Raster) { - self.0.send(NodeGraphUpdate::EyedropperPreview(raster)).expect("Failed to send response") - } -} - -impl NodeGraphUpdateSender for InternalNodeGraphUpdateSender { - fn send(&self, message: NodeGraphUpdateMessage) { - self.0.send(NodeGraphUpdate::NodeGraphUpdateMessage(message)).expect("Failed to send response") - } -} - -// TODO: Replace with `core::cell::LazyCell` () or similar -pub static NODE_RUNTIME: once_cell::sync::Lazy>> = once_cell::sync::Lazy::new(|| Mutex::new(None)); - impl NodeRuntime { - pub fn new(receiver: Receiver, sender: Sender) -> Self { + pub fn new(receiver: Receiver, sender: Sender, editor_wake: Wake) -> Self { Self { executor: DynamicExecutor::default(), receiver, - sender: InternalNodeGraphUpdateSender(sender.clone()), + sender, + editor_wake, + dirty: Default::default(), + pending: None, + pending_export: None, editor_preferences: EditorPreferences::default(), old_graph: None, resources: ResourceRegistry::default(), update_thumbnails: true, + async_runtime: None, editor_api: PlatformEditorApi { editor_preferences: Box::new(EditorPreferences::default()), - node_graph_message_sender: Box::new(InternalNodeGraphUpdateSender(sender)), #[cfg(not(test))] application_io: None, @@ -158,17 +143,23 @@ impl NodeRuntime { } pub async fn run(&mut self) -> Option { + let texture = self.handle_requests().await; + (self.editor_wake)(); + texture + } + + async fn handle_requests(&mut self) -> Option { let mut preferences = None; let mut graph = None; let mut eyedropper = None; let mut execution = None; - for request in self.receiver.try_iter() { + + for request in self.pending_export.is_none().then_some(&self.receiver).into_iter().flat_map(Receiver::try_iter) { match request { GraphRuntimeRequest::GraphUpdate(_) => graph = Some(request), GraphRuntimeRequest::ExecutionRequest(ref execution_request) => { if execution_request.render_config.for_eyedropper { eyedropper = Some(request); - continue; } @@ -185,6 +176,10 @@ impl NodeRuntime { } } + if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() { + execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest); + } + // Eydropper should use the same time and pointer to not invalidate the cache if let Some(GraphRuntimeRequest::ExecutionRequest(eyedropper)) = &mut eyedropper && let Some(GraphRuntimeRequest::ExecutionRequest(execution)) = &execution @@ -201,13 +196,12 @@ impl NodeRuntime { self.editor_preferences = preferences.clone(); self.editor_api = PlatformEditorApi { application_io: self.editor_api.application_io.clone(), - node_graph_message_sender: Box::new(self.sender.clone()), editor_preferences: Box::new(preferences), } .into(); if let Some(graph) = self.old_graph.clone() { // We ignore this result as compilation errors should have been reported in an earlier iteration - let _ = self.update_network(graph).await; + let _ = self.update_network(graph); } } GraphRuntimeRequest::GraphUpdate(GraphUpdate { @@ -222,14 +216,23 @@ impl NodeRuntime { self.resources = resources; self.node_graph_errors.clear(); - let result = self.update_network(network).await; + let result = self.update_network(network); let node_graph_errors = self.node_graph_errors.clone(); self.update_thumbnails = true; - self.sender.send_compilation_response(CompilationResponse { result, node_graph_errors }); + self.sender + .send(NodeGraphUpdate::CompilationResponse(CompilationResponse { result, node_graph_errors })) + .expect("Failed to send response"); } - GraphRuntimeRequest::ExecutionRequest(ExecutionRequest { execution_id, mut render_config, .. }) => { + GraphRuntimeRequest::ExecutionRequest(request @ ExecutionRequest { execution_id, mut render_config, .. }) => { + if !render_config.for_export && !render_config.for_eyedropper { + self.pending = Some(request); + } + if render_config.for_export { + self.pending_export = None; + } + // We may want to render via the SVG pipeline even though raster was requested, if SVG Preview render mode is active or WebGPU/Vello is unavailable if render_config.export_format == ExportFormat::Raster && (render_config.render_mode == RenderMode::SvgPreview || self.editor_api.application_io.as_ref().unwrap().gpu_executor().is_none()) @@ -237,7 +240,38 @@ impl NodeRuntime { render_config.export_format = ExportFormat::Svg; } - let result = self.execute_network(render_config).await; + let mut result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.execute_network(render_config))) { + Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, + Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending, + Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value), + Ok(Ok(Poll::Fallback(boxed))) => { + let (value, error) = *boxed; + ExecutionResult::Fallback(value, self.resolve_errors(&error)) + } + Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)), + Ok(Err(error)) => ExecutionResult::Error(Box::new([(Arc::clone(NodeError::new(error).error()), Box::default())])), + Err(payload) => { + let response = ExecutionResponse { + execution_id, + result: ExecutionResult::Panic(payload), + responses: VecDeque::new(), + vector_modify: HashMap::new(), + inspect_result: None, + }; + self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); + return None; + } + }; + + match (render_config.for_export, &result) { + (true, ExecutionResult::Pending) => { + self.pending_export = Some(request); + return None; + } + (true, _) => self.dirty.store(true, Ordering::Release), + _ => {} + } + let mut responses = VecDeque::new(); // TODO: Only process monitor nodes if the graph has changed, not when only the Footprint changes if !render_config.for_eyedropper { @@ -248,96 +282,71 @@ impl NodeRuntime { // Resolve the result from the inspection by accessing the monitor node let inspect_result = self.inspect_state.as_ref().and_then(|state| state.access(&self.executor)); - let (result, texture) = match result { - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata, - })) if render_config.for_export => { - let executor = self - .editor_api - .application_io - .as_ref() - .unwrap() - .gpu_executor() - .expect("GPU executor should be available when we receive a texture"); - - let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; - - let (data, width, height) = raster_cpu.to_flat_u8(); - - ( - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Buffer { data, width, height }, - metadata, - })), - None, - ) - } - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata: _, - })) if render_config.for_eyedropper => { - let executor = self - .editor_api - .application_io - .as_ref() - .unwrap() - .gpu_executor() - .expect("GPU executor should be available when we receive a texture"); - - let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor).await; - - self.sender.send_eyedropper_preview(raster_cpu); - continue; - } - // Eyedropper render that didn't produce a texture (e.g., SVG fallback when GPU is unavailable); discard it - _ if render_config.for_eyedropper => { - continue; - } - #[cfg(all(target_family = "wasm", feature = "gpu"))] - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata, - })) if !render_config.for_export => { - self.current_viewport_texture = Some(texture.clone()); - - let app_io = self.editor_api.application_io.as_ref().unwrap(); - let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture"); - - self.wasm_canvas_cache.present(&texture, executor); - - let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale; - ( - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::CanvasFrame { - canvas_id: self.wasm_canvas_cache.id(), - resolution: logical_resolution, - }, - metadata, - })), - None, - ) - } - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture), - metadata, - })) => ( - Ok(TaggedValue::RenderOutput(RenderOutput { - data: RenderOutputType::Texture(texture.clone()), - metadata, - })), - Some(texture), - ), - r => (r, None), + let output = match &mut result { + ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Some(value), + ExecutionResult::Pending | ExecutionResult::Error(_) | ExecutionResult::Panic(_) => None, }; + let texture = if let Some(TaggedValue::RenderOutput(RenderOutput { data, .. })) = output + && let RenderOutputType::Texture(texture) = data + { + let texture = texture.clone(); + if render_config.for_export || render_config.for_eyedropper { + let executor = self + .editor_api + .application_io + .as_ref() + .unwrap() + .gpu_executor() + .expect("GPU executor should be available when we receive a texture"); - self.sender.send_execution_response(ExecutionResponse { + let raster_cpu = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await; + + if render_config.for_eyedropper { + self.sender.send(NodeGraphUpdate::EyedropperPreview(raster_cpu)).expect("Failed to send response"); + continue; + } + + let (buffer, width, height) = raster_cpu.to_flat_u8(); + *data = RenderOutputType::Buffer { data: buffer, width, height }; + None + } else { + #[cfg(all(target_family = "wasm", feature = "gpu"))] + { + self.current_viewport_texture = Some(texture.clone()); + + let app_io = self.editor_api.application_io.as_ref().unwrap(); + let executor = app_io.gpu_executor().expect("GPU executor should be available when we receive a texture"); + + self.wasm_canvas_cache.present(&texture, executor); + + let logical_resolution = render_config.viewport.resolution.as_dvec2() / render_config.scale; + *data = RenderOutputType::CanvasFrame { + canvas_id: self.wasm_canvas_cache.id(), + resolution: logical_resolution, + }; + None + } + #[cfg(not(all(target_family = "wasm", feature = "gpu")))] + { + Some(texture) + } + } + } else { + None + }; + // Eyedropper render that didn't produce a texture (e.g., SVG fallback when GPU is unavailable); discard it + if render_config.for_eyedropper { + continue; + } + + let response = ExecutionResponse { execution_id, result, responses, vector_modify: self.vector_modify.clone(), inspect_result, - }); + }; + self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); return texture; } } @@ -345,8 +354,8 @@ impl NodeRuntime { None } - async fn update_network(&mut self, graph: NodeNetwork) -> Result { - let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone()); + fn update_network(&mut self, graph: NodeNetwork) -> Result { + let mut scoped_network = wrap_network_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)) { return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string())); @@ -368,25 +377,48 @@ impl NodeRuntime { .collect::>(); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); - self.executor.update(proto_network).await.map_err(|(types, e)| { + let result = self.executor.update(proto_network).map_err(|(types, e)| { self.node_graph_errors.clone_from(&e); (types, format!("{e:?}")) - }) + }); + self.async_runtime().retain_sources(self.executor.sources()); + result } - async fn execute_network(&mut self, render_config: RenderConfig) -> Result { + fn execute_network(&mut self, render_config: RenderConfig) -> Result, String> { use graph_craft::graphene_compiler::Executor; match self.executor.input_type() { - Some(t) if t == concrete!(Context) => (&self.executor).execute(render_config.into_context()).await.map_err(|e| e.to_string()), - Some(t) if t == concrete!(()) => (&self.executor).execute(()).await.map_err(|e| e.to_string()), + Some(t) if t == concrete!(Context) => (&self.executor) + .execute(render_config.into_context_with_generations(self.async_runtime().snapshot())) + .map_err(|e| e.to_string()), + Some(t) if t == concrete!(()) => (&self.executor).execute(()).map_err(|e| e.to_string()), Some(t) => Err(format!("Invalid input type {t:?}")), _ => Err(format!("No input type:\n{:?}", self.node_graph_errors)), } } + fn resolve_errors(&self, error: &NodeError) -> EvaluationError { + let source_map = self.executor.tree().source_map(); + let mut errors = Vec::new(); + let mut pending = vec![(Some(self.executor.output()), error)]; + while let Some((node, error)) = pending.pop() { + let origin = node.and_then(|node| self.executor.find_origin(node, error)); + let start = errors.len(); + if let Some(origin) = origin { + errors.extend(source_map.iter().filter(|(_, (node, _))| *node == origin).map(|(path, _)| (Arc::clone(error.error()), path.clone()))); + errors[start..].sort_unstable_by(|(_, a), (_, b)| a.cmp(b)); + } + if errors.len() == start { + errors.push((Arc::clone(error.error()), Box::default())); + } + pending.extend(error.upstream().iter().rev().map(|upstream| (origin, upstream))); + } + errors.into_boxed_slice() + } + /// Updates state data - pub fn process_monitor_nodes(&mut self, responses: &mut VecDeque, update_thumbnails: bool) { + fn process_monitor_nodes(&mut self, responses: &mut VecDeque, update_thumbnails: bool) { // TODO: Consider optimizing this since it's currently O(m*n^2), with a sort it could be made O(m * n*log(n)) self.thumbnail_renders.retain(|id, _| self.monitor_nodes.iter().any(|monitor_node_path| monitor_node_path.contains(id))); @@ -570,42 +602,45 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] { [center - half, center + half] } -pub async fn introspect_node(path: &[NodeId]) -> Result, IntrospectError> { - let runtime = NODE_RUNTIME.lock(); - if let Some(ref mut runtime) = runtime.as_ref() { - return runtime.executor.introspect(path); - } - Err(IntrospectError::RuntimeNotReady) -} - -pub async fn run_node_graph() -> (bool, Option) { - let Some(mut runtime) = NODE_RUNTIME.try_lock() else { return (false, None) }; - if let Some(ref mut runtime) = runtime.as_mut() { - return (true, runtime.run().await); - } - (false, None) -} - -pub fn replace_node_runtime(runtime: NodeRuntime) -> Option { - let mut node_runtime = NODE_RUNTIME.lock(); - node_runtime.replace(runtime) -} -pub(crate) fn replace_application_io(application_io: PlatformApplicationIo) { - let mut node_runtime = NODE_RUNTIME.lock(); - if let Some(node_runtime) = &mut *node_runtime { - node_runtime.replace_application_io(application_io); - } -} - impl NodeRuntime { pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) { self.editor_api = PlatformEditorApi { application_io: Some(application_io.into()), - node_graph_message_sender: Box::new(self.sender.clone()), editor_preferences: Box::new(self.editor_preferences.clone()), } .into(); } + + pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) { + let spawn = NodeTaskExecutor { + spawner, + dirty: self.dirty.clone(), + wake, + }; + self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn))); + } + + fn async_runtime(&self) -> &AsyncRuntime { + self.async_runtime.as_ref().expect("the task executor is installed before the first graph update") + } +} + +struct NodeTaskExecutor { + spawner: Spawner, + dirty: Arc, + wake: Wake, +} + +impl Spawn for NodeTaskExecutor { + fn spawn(&self, task: Task) { + let dirty = self.dirty.clone(); + let wake = self.wake.clone(); + self.spawner.spawn(Box::pin(async move { + task.await; + dirty.store(true, Ordering::Release); + wake(); + })); + } } /// Which node is inspected and which monitor node is used (if any) for the current execution diff --git a/editor/src/node_graph_executor/runtime_io.rs b/editor/src/node_graph_executor/runtime_io.rs deleted file mode 100644 index 5b2235ae5e..0000000000 --- a/editor/src/node_graph_executor/runtime_io.rs +++ /dev/null @@ -1,44 +0,0 @@ -use super::*; -use std::sync::mpsc::{Receiver, Sender}; - -/// Handles communication with the NodeRuntime -#[derive(Debug)] -pub struct NodeRuntimeIO { - // Send to - sender: Sender, - receiver: Receiver, -} - -impl Default for NodeRuntimeIO { - fn default() -> Self { - Self::new() - } -} - -impl NodeRuntimeIO { - /// Creates a new NodeRuntimeIO instance - pub fn new() -> Self { - let (response_sender, response_receiver) = std::sync::mpsc::channel(); - let (request_sender, request_receiver) = std::sync::mpsc::channel(); - replace_node_runtime(NodeRuntime::new(request_receiver, response_sender)); - - Self { - sender: request_sender, - receiver: response_receiver, - } - } - #[cfg(test)] - pub fn with_channels(sender: Sender, receiver: Receiver) -> Self { - Self { sender, receiver } - } - - /// Sends a message to the NodeRuntime - pub fn send(&self, message: GraphRuntimeRequest) -> Result<(), String> { - self.sender.send(message).map_err(|e| e.to_string()) - } - - /// Receives any pending updates from the NodeRuntime - pub fn receive(&self) -> impl Iterator + use<'_> { - self.receiver.try_iter() - } -} diff --git a/editor/src/task.rs b/editor/src/task.rs new file mode 100644 index 0000000000..f571fb1c94 --- /dev/null +++ b/editor/src/task.rs @@ -0,0 +1,4 @@ +pub use graphene_std::runtime::{Spawn, Task}; +use std::sync::Arc; + +pub type Spawner = Arc; diff --git a/editor/src/test_utils.rs b/editor/src/test_utils.rs index add951a6a8..8c9cdb5adc 100644 --- a/editor/src/test_utils.rs +++ b/editor/src/test_utils.rs @@ -1,4 +1,6 @@ -use crate::application::Editor; +use crate::application::{DEFAULT_ENVIRONMENT, Editor}; +use crate::builder::{Builder, EditorBuilder, RuntimeBuilder}; +use crate::messages::frontend::utility_types::RenderStatus; use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys; use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ViewportPosition}; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; @@ -8,30 +10,59 @@ use crate::messages::tool::tool_messages::tool_prelude::Key; use crate::messages::tool::utility_types::ToolType; use crate::node_graph_executor::Instrumented; use crate::node_graph_executor::NodeRuntime; +use crate::task::{Spawn, Task}; use crate::test_utils::test_prelude::LayerNodeIdentifier; +use document_container::store::MemoryStore; use glam::{DVec2, UVec2}; +use graph_craft::application_io::PlatformApplicationIo; +use graph_craft::application_io::resource::HashMapResourceStorage; use graphene_std::raster::color::Color; use graphene_std::uuid::NodeId; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; /// A set of utility functions to make the writing of editor test more declarative pub struct EditorTestUtils { pub editor: Editor, pub runtime: NodeRuntime, + woken: Arc, } impl EditorTestUtils { pub fn create() -> Self { init_test_logger(); - let (mut editor, runtime) = Editor::new_local_executor(); + let woken = Arc::new(AtomicBool::new(false)); + let wake = woken.clone(); + let (editor, runtime) = Builder::new() + .with_editor( + EditorBuilder::new() + .with_wake(move || wake.store(true, Ordering::Relaxed)) + .with_environment(DEFAULT_ENVIRONMENT) + .with_resource_storage(Arc::new(HashMapResourceStorage::new())) + .with_document_store(Arc::new(MemoryStore::default())), + ) + .with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(PlatformApplicationIo::default())) + .with_spawner(BlockingSpawner) + .with_random_seed(0) + .build(); + let mut editor = Self { editor, runtime, woken }; - editor.handle_message(PortfolioMessage::Init); + editor.dispatch(PortfolioMessage::Init); // Tests run with `.gdd` storage on and the dual-write soak validation enabled, so storage round-trip drift fails loud. - editor.handle_message(PreferencesMessage::SaveAsGdd { enabled: true }); - editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: true }); + editor.dispatch(PreferencesMessage::SaveAsGdd { enabled: true }); + editor.dispatch(PreferencesMessage::ValidateStorageRoundTrip { enabled: true }); - Self { editor, runtime } + editor + } + + pub fn dispatch(&mut self, message: impl Into) -> Vec { + let mut responses = self.editor.handle_message(message); + while self.woken.swap(false, Ordering::Relaxed) { + responses.extend(self.editor.handle_message(Message::Wake)); + } + responses } /// Submit an evaluation to the executor, run the runtime, and process the results. @@ -53,11 +84,10 @@ impl EditorTestUtils { } self.runtime.run().await; - let mut messages = VecDeque::new(); - if let Err(e) = self.editor.poll_node_graph_evaluation(&mut messages) { - return Err(format!("Graph should render\n\n{e}")); + let frontend_messages = self.dispatch(Message::Wake); + if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) { + return Err("Graph should render".to_string()); } - let frontend_messages = messages.into_iter().flat_map(|message| self.editor.handle_message(message)); for message in frontend_messages { message.check_node_graph_error(); @@ -81,7 +111,7 @@ impl EditorTestUtils { } pub async fn handle_message(&mut self, message: impl Into) -> Vec { - let frontend_messages_from_msg = self.editor.handle_message(message); + let frontend_messages_from_msg = self.dispatch(message); // Required to process any buffered messages if let Err(e) = self.eval_graph_until_finished().await { @@ -379,9 +409,9 @@ pub trait FrontendMessageTestUtils { impl FrontendMessageTestUtils for FrontendMessage { fn check_node_graph_error(&self) { - let FrontendMessage::UpdateNodeGraphErrorDiagnostic { error } = self else { return }; - if let Some(error) = error { - panic!("error: {:?}", error); + let FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors } = self else { return }; + if !errors.is_empty() { + panic!("errors: {errors:?}"); } } } @@ -440,6 +470,13 @@ pub fn capture_logged_errors(operation: impl FnOnce() -> T) -> (T, Vec {/if} - {#if isWeb} + {#if isWeb && $document.renderStatus === "Rendering"} Initializing Renderer… {/if} + {#if $document.renderStatus === "Error"} + + +

+ The document cannot render in its current state.
+ Undo to go back, if available, or check for error details
+ by clicking the Node Graph button up at the top right. +

+
+
+ {:else if $document.renderStatus === "Panic"} + + +

+ The document crashed while being rendered in its current state.
+ The editor is now unstable! Undo your last action to restore the artwork,
+ then save your document and restart the editor before continuing work. +

+
+
+ {/if}
@@ -961,6 +982,29 @@ } } + .render-status-overlay { + position: absolute; + inset: 0; + align-items: center; + justify-content: center; + background: var(--color-2-mildblack); + pointer-events: none; + + .text-label { + padding: 14px 20px; + border-radius: 4px; + background: var(--color-warning-yellow); + color: var(--color-2-mildblack); + font-size: 18px; + line-height: 24px; + text-align: center; + } + + &.panic .text-label { + background: var(--color-error-red); + } + } + .text-input div { cursor: text; background: none; diff --git a/frontend/src/components/views/Graph.svelte b/frontend/src/components/views/Graph.svelte index 35eeb69735..2d276ee745 100644 --- a/frontend/src/components/views/Graph.svelte +++ b/frontend/src/components/views/Graph.svelte @@ -420,14 +420,16 @@ {/if} - {#if $nodeGraph.error} + {#if $nodeGraph.errors.length > 0}
- - {$nodeGraph.error.error} - - - {$nodeGraph.error.error} - + {#each $nodeGraph.errors as error} + + {error.error} + + + {error.error} + + {/each}
{/if} diff --git a/frontend/src/stores/document.ts b/frontend/src/stores/document.ts index 491a191d0f..905c481bd5 100644 --- a/frontend/src/stores/document.ts +++ b/frontend/src/stores/document.ts @@ -3,7 +3,7 @@ import { writable } from "svelte/store"; import type { Writable } from "svelte/store"; import type { SubscriptionsRouter } from "/src/subscriptions-router"; import { patchLayout } from "/src/utility-functions/widgets"; -import type { Layout } from "/wrapper/pkg/graphite_wasm_wrapper"; +import type { Layout, RenderStatus } from "/wrapper/pkg/graphite_wasm_wrapper"; export type DocumentStore = ReturnType; @@ -15,6 +15,7 @@ type DocumentStoreState = { nodeGraphControlBarLayout: Layout; graphViewOverlayOpen: boolean; fadeArtwork: number; + renderStatus: RenderStatus; }; const initialState: DocumentStoreState = { toolOptionsLayout: [], @@ -24,6 +25,7 @@ const initialState: DocumentStoreState = { nodeGraphControlBarLayout: [], graphViewOverlayOpen: false, fadeArtwork: 100, + renderStatus: "Rendering", }; let subscriptionsRouter: SubscriptionsRouter | undefined = undefined; @@ -97,6 +99,13 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) { }); }); + subscriptions.subscribeFrontendMessage("UpdateRenderStatus", (data) => { + update((state) => { + state.renderStatus = data.status; + return state; + }); + }); + return { subscribe }; } @@ -106,6 +115,7 @@ export function destroyDocumentStore() { subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork"); subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay"); + subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus"); subscriptions.unsubscribeLayoutUpdate("ToolOptions"); subscriptions.unsubscribeLayoutUpdate("DocumentBar"); subscriptions.unsubscribeLayoutUpdate("ToolShelf"); diff --git a/frontend/src/stores/node-graph.ts b/frontend/src/stores/node-graph.ts index 79fd0e191b..be47cfe39a 100644 --- a/frontend/src/stores/node-graph.ts +++ b/frontend/src/stores/node-graph.ts @@ -13,7 +13,7 @@ type NodeGraphStoreState = { box: BoxSelection | undefined; clickTargets: FrontendClickTargets | undefined; contextMenuInformation: ContextMenuInformation | undefined; - error: NodeGraphErrorDiagnostic | undefined; + errors: NodeGraphErrorDiagnostic[]; layerWidths: Map; chainWidths: Map; hasLeftInputWire: Map; @@ -32,7 +32,7 @@ const initialState: NodeGraphStoreState = { box: undefined, clickTargets: undefined, contextMenuInformation: undefined, - error: undefined, + errors: [], layerWidths: new Map(), chainWidths: new Map(), hasLeftInputWire: new Map(), @@ -150,9 +150,9 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) { }); }); - subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostic", (data) => { + subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics", (data) => { update((state) => { - state.error = data.error; + state.errors = data.errors; return state; }); }); @@ -244,7 +244,7 @@ export function destroyNodeGraphStore() { subscriptions.unsubscribeFrontendMessage("UpdateInSelectedNetwork"); subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes"); - subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostic"); + subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics"); subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes"); subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires"); subscriptions.unsubscribeFrontendMessage("ClearAllNodeGraphWires"); diff --git a/frontend/wrapper/Cargo.toml b/frontend/wrapper/Cargo.toml index 6b9fca2fa9..8574c2b23c 100644 --- a/frontend/wrapper/Cargo.toml +++ b/frontend/wrapper/Cargo.toml @@ -13,7 +13,7 @@ readme = "./README.md" [features] default = ["gpu", "shader-nodes", "web"] web = ["editor", "editor?/wasm"] -editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:wgpu"] +editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:spin", "dep:wgpu"] gpu = ["editor?/gpu"] shader-nodes = ["graphene-std?/shader-nodes", "gpu"] native = [] @@ -38,6 +38,7 @@ wasm-bindgen-futures = { workspace = true } wgpu = { workspace = true, optional = true } web-sys = { workspace = true } serde_json = { workspace = true } +spin = { workspace = true, optional = true } tsify = { workspace = true } [dev-dependencies] diff --git a/frontend/wrapper/src/editor_wrapper.rs b/frontend/wrapper/src/editor_wrapper.rs index 4126d6c8a5..071fb9992c 100644 --- a/frontend/wrapper/src/editor_wrapper.rs +++ b/frontend/wrapper/src/editor_wrapper.rs @@ -8,7 +8,7 @@ use crate::MESSAGE_BUFFER; #[cfg(all(feature = "native", target_family = "wasm"))] use crate::editor_commands::EditorCommand; #[cfg(not(feature = "native"))] -use crate::helpers::poll_node_graph_evaluation; +use crate::helpers::run_node_runtime; #[cfg(any(not(feature = "native"), target_family = "wasm"))] use crate::helpers::wrapper; #[cfg(feature = "editor")] @@ -16,7 +16,7 @@ use crate::helpers::{calculate_hash, render_image_data_to_canvases}; use crate::helpers::{request_animation_frame, set_timeout}; use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY}; #[cfg(all(not(feature = "native"), target_family = "wasm"))] -use editor::application::{Editor, Environment, Host, Platform}; +use editor::application::{Environment, Host, Platform}; #[cfg(feature = "editor")] use editor::messages::prelude::*; #[cfg(feature = "editor")] @@ -54,6 +54,7 @@ impl EditorWrapper { impl EditorWrapper { #[cfg(all(not(feature = "native"), target_family = "wasm"))] pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper { + use editor::builder::{Builder, EditorBuilder, RuntimeBuilder}; use graph_craft::application_io::PlatformApplicationIo; use graph_craft::application_io::resource::*; @@ -73,13 +74,24 @@ impl EditorWrapper { }; let application_io = PlatformApplicationIo::new().await; - let wake = crate::helpers::async_wake_callback(); let document_store = std::sync::Arc::new(editor::document_store::OpfsStore::new("documents")); - let editor = Editor::new(Environment { platform: Platform::Web, host }, uuid_random_seed, storage, document_store, application_io, wake); + let (editor, runtime) = Builder::new() + .with_editor( + EditorBuilder::new() + .with_wake(crate::helpers::wake_editor) + .with_environment(Environment { platform: Platform::Web, host }) + .with_resource_storage(storage) + .with_document_store(document_store), + ) + .with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io)) + .with_spawner(crate::helpers::WasmSpawner) + .with_random_seed(uuid_random_seed) + .build(); if EDITOR.with(|slot| slot.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() { log::error!("Attempted to initialize the editor more than once"); } + *crate::NODE_RUNTIME.lock() = Some(runtime); Self::initialize_wrapper(frontend_message_handler_callback) } @@ -177,14 +189,14 @@ impl EditorWrapper { #[cfg(target_family = "wasm")] self.init_portfolio(); - // Poll node graph evaluation on `requestAnimationFrame` + // Run the node runtime on `requestAnimationFrame` { let f = std::rc::Rc::new(RefCell::new(None)); let g = f.clone(); *g.borrow_mut() = Some(Closure::new(move |_timestamp| { #[cfg(not(feature = "native"))] - wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation()); + wasm_bindgen_futures::spawn_local(run_node_runtime()); #[cfg(any(not(feature = "native"), target_family = "wasm"))] wrapper(|wrapper| { diff --git a/frontend/wrapper/src/helpers.rs b/frontend/wrapper/src/helpers.rs index d8f5adf86f..e39a040081 100644 --- a/frontend/wrapper/src/helpers.rs +++ b/frontend/wrapper/src/helpers.rs @@ -1,16 +1,14 @@ #[cfg(not(feature = "native"))] -use crate::EDITOR; -#[cfg(not(feature = "native"))] use crate::EDITOR_HAS_CRASHED; use crate::EDITOR_WRAPPER; use crate::editor_wrapper::EditorWrapper; use crate::native_communication::RasterizedImage; -#[cfg(not(feature = "native"))] -use editor::application::Editor; #[cfg(feature = "editor")] use editor::messages::input_mapper::utility_types::keyboard::Key; -#[cfg(not(feature = "native"))] +#[cfg(all(not(feature = "native"), target_family = "wasm"))] use editor::messages::prelude::*; +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +use editor::task::{Spawn, Task}; use js_sys::{Object, Reflect}; use std::cell::RefCell; use std::collections::HashSet; @@ -38,30 +36,6 @@ pub(crate) fn set_timeout(f: &Closure, delay: Duration) { .expect("Failed to call `setTimeout`"); } -/// Provides access to the `Editor` by calling the given closure with it as an argument. -#[cfg(not(feature = "native"))] -fn editor(callback: impl FnOnce(&mut editor::application::Editor) -> T) -> T { - EDITOR.with(|editor| { - let mut guard = editor.try_lock(); - let Ok(Some(editor)) = guard.as_deref_mut() else { - log::error!("Failed to borrow editor"); - return T::default(); - }; - - callback(editor) - }) -} - -/// Provides access to the `Editor` and its `EditorWrapper` by calling the given closure with them as arguments. -#[cfg(not(feature = "native"))] -pub(crate) fn editor_and_wrapper(callback: impl FnOnce(&mut Editor, &mut EditorWrapper)) { - wrapper(|wrapper| { - editor(|editor| { - // Call the closure with the editor and its wrapper - callback(editor, wrapper); - }) - }); -} /// Provides access to the `EditorWrapper` by calling the given closure with them as arguments. pub(crate) fn wrapper(callback: impl FnOnce(&mut EditorWrapper)) { EDITOR_WRAPPER.with(|wrapper| { @@ -77,52 +51,38 @@ pub(crate) fn wrapper(callback: impl FnOnce(&mut EditorWrapper)) { } #[cfg(not(feature = "native"))] -pub(crate) async fn poll_node_graph_evaluation() { +pub(crate) async fn run_node_runtime() { // Process no further messages after a crash to avoid spamming the console if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) { return; } - if !editor::node_graph_executor::run_node_graph().await.0 { - return; + let Some(mut runtime) = crate::NODE_RUNTIME.try_lock() else { return }; + let Some(runtime) = runtime.as_mut() else { return }; + runtime.run().await; +} + +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +pub(crate) struct WasmSpawner; +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +impl Spawn for WasmSpawner { + fn spawn(&self, task: Task) { + wasm_bindgen_futures::spawn_local(task); } +} - editor_and_wrapper(|editor, wrapper| { - let mut messages = VecDeque::new(); - if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) { - // TODO: This is a hacky way to suppress the error, but it shouldn't be generated in the first place - if e != "No active document" { - error!("Error evaluating node graph:\n{e}"); - } - } - - // Clear the error display if there are no more errors - if !messages.is_empty() { - crate::NODE_GRAPH_ERROR_DISPLAYED.store(false, Ordering::SeqCst); - } - - // Batch responses to pool frontend updates - let batched = Message::Batched { - messages: messages.into_iter().collect(), - }; - // Send each `FrontendMessage` to the JavaScript frontend - for response in editor.handle_message(batched) { - wrapper.send_frontend_message_to_js(response); - } - - // If the editor cannot be borrowed then it has encountered a panic - we should just ignore new dispatches +/// Web editor wake: queues a microtask that dispatches [`Message::Wake`]. +#[cfg(all(not(feature = "native"), target_family = "wasm"))] +pub(crate) fn wake_editor() { + wasm_bindgen_futures::spawn_local(async { + wrapper(|wrapper| wrapper.dispatch(Message::Wake)); }); } -/// Web wake callback: queues a microtask that dispatches [`FutureMessage::Wake`]. +/// Web runtime wake: queues a run of the node runtime. Used to wake the runtime on async task completion. #[cfg(all(not(feature = "native"), target_family = "wasm"))] -pub(crate) fn async_wake_callback() -> Wake { - use std::sync::Arc; - Arc::new(|| { - wasm_bindgen_futures::spawn_local(async { - wrapper(|wrapper| wrapper.dispatch(FutureMessage::Wake)); - }); - }) +pub(crate) fn wake_runtime() { + wasm_bindgen_futures::spawn_local(run_node_runtime()); } thread_local! { diff --git a/frontend/wrapper/src/lib.rs b/frontend/wrapper/src/lib.rs index 0785d8efab..b953256c0d 100644 --- a/frontend/wrapper/src/lib.rs +++ b/frontend/wrapper/src/lib.rs @@ -16,6 +16,8 @@ pub use editor_commands::EditorCommand; #[cfg(feature = "editor")] use crate::helpers::wrapper; #[cfg(feature = "editor")] +use editor::messages::frontend::utility_types::RenderStatus; +#[cfg(feature = "editor")] use editor::messages::prelude::*; use std::panic; use std::sync::Mutex; @@ -25,8 +27,9 @@ use wasm_bindgen::prelude::*; // Set up the persistent editor backend state pub static EDITOR_HAS_CRASHED: AtomicBool = AtomicBool::new(false); pub static FRONTEND_READY: AtomicBool = AtomicBool::new(false); -pub static NODE_GRAPH_ERROR_DISPLAYED: AtomicBool = AtomicBool::new(false); pub static LOGGER: WasmLog = WasmLog; +#[cfg(not(feature = "native"))] +pub static NODE_RUNTIME: spin::Mutex> = spin::Mutex::new(None); thread_local! { #[cfg(not(feature = "native"))] @@ -60,25 +63,12 @@ pub fn panic_hook(info: &panic::PanicHookInfo) { log::error!("Node graph evaluation panicked {info}"); // When the graph panics, the node runtime lock may not be released properly - if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() { - unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() }; + #[cfg(not(feature = "native"))] + if NODE_RUNTIME.try_lock().is_none() { + unsafe { NODE_RUNTIME.force_unlock() }; } - if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) { - NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst); - wrapper(|wrapper| { - let error = r#" - - - The document crashed while being rendered in its current state. - The editor is now unstable! Undo your last action to restore the artwork, - then save your document and restart the editor before continuing work. - /text>"# - // It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed. - .to_string(); - wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error }); - }); - } + wrapper(|wrapper| wrapper.send_frontend_message_to_js(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Panic })); return; } diff --git a/node-graph/README.md b/node-graph/README.md index addc4f772c..11312e94de 100644 --- a/node-graph/README.md +++ b/node-graph/README.md @@ -73,13 +73,13 @@ To test this: #[test] fn test_opacity_node() { let opacity_node = OpacityNode { - opacity_multiplier: crate::value::CopiedNode(10_f64), // set opacity to 10% + opacity_multiplier: crate::value::ClonedNode(10_f64), // set opacity to 10% }; assert_eq!(opacity_node.eval(Color::WHITE), Color::from_rgbaf32_unchecked(1., 1., 1., 0.1)); } ``` -The `graphene_core::value::CopiedNode` is a node that, when evaluated, copies `10_f64` and returns it. +The `graphene_core::value::ClonedNode` is a node that, when evaluated, clones `10_f64` and returns it. ## Creating a new node diff --git a/node-graph/graph-craft/src/document.rs b/node-graph/graph-craft/src/document.rs index 6297ceab3e..c0228aedec 100644 --- a/node-graph/graph-craft/src/document.rs +++ b/node-graph/graph-craft/src/document.rs @@ -57,9 +57,8 @@ pub struct DocumentNode { /// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph. #[serde(default)] pub skip_deduplication: bool, - /// List of Extract and Inject annotations for the Context. - #[serde(default)] - pub context_features: ContextDependencies, + #[serde(skip)] + pub context_dependencies: Option, /// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called. #[serde(skip)] pub original_location: OriginalLocation, @@ -93,7 +92,7 @@ impl Default for DocumentNode { visible: true, skip_deduplication: Default::default(), original_location: OriginalLocation::default(), - context_features: Default::default(), + context_dependencies: Default::default(), } } } @@ -167,7 +166,7 @@ impl DocumentNode { construction_args, original_location: self.original_location, skip_deduplication: self.skip_deduplication, - context_features: self.context_features, + context_dependencies: self.context_dependencies.unwrap_or_default(), } } } @@ -216,12 +215,14 @@ impl InlineRust { #[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)] pub enum DocumentNodeMetadata { DocumentNodePath, + SourceId, } impl DocumentNodeMetadata { pub fn ty(&self) -> Type { match self { DocumentNodeMetadata::DocumentNodePath => item!(core_types::list::NodeIdPath), + DocumentNodeMetadata::SourceId => item!(core_types::SourceId), } } } @@ -958,6 +959,11 @@ impl NodeNetwork { self.nodes.insert(id, node); return; }; + debug_assert!( + node.context_dependencies.is_none(), + "Network {id} should not have context dependencies: {deps:#?}", + deps = node.context_dependencies + ); // Replace value and reflection imports with value nodes, added inside nested network Self::replace_value_inputs_with_nodes( @@ -1077,6 +1083,7 @@ impl NodeNetwork { NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed), NodeInput::Reflection(reflect) => match reflect { DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false), + DocumentNodeMetadata::SourceId => (TaggedValue::SourceId(core_types::SourceId::from_path(path)).into(), false), }, previous_export => { *export = previous_export; @@ -1329,7 +1336,7 @@ impl core_types::graphene_hash::CacheHash for DocumentNode { self.implementation.cache_hash(state); self.visible.cache_hash(state); self.skip_deduplication.cache_hash(state); - self.context_features.cache_hash(state); + self.context_dependencies.cache_hash(state); } } diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 729dcebbae..27b6b437e0 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -1,14 +1,13 @@ use super::DocumentNode; use crate::application_io::PlatformEditorApi; use crate::application_io::resource::Resource; -use crate::proto::{Any as DAny, FutureAny}; +use crate::proto::{Any as DAny, AnyInput}; use brush_nodes::{BrushCache, Stroke}; use core_types::color::SRGBA8; use core_types::list::{Item, List, NodeIdPath}; use core_types::transfer_curve::TransferCurve; use core_types::transform::Footprint; -use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDescriptor}; -use dyn_any::DynAny; +use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor}; pub use dyn_any::StaticType; pub use glam::{DAffine2, DVec2, IVec2, UVec2}; use graphene_animation::AnimationCurve; @@ -23,7 +22,6 @@ use graphic_types::{Artboard, Graphic, Vector}; use rendering::RenderMetadata; use std::fmt::Display; use std::hash::Hash; -use std::marker::PhantomData; use std::str::FromStr; pub use std::sync::Arc; use text_nodes::Font; @@ -116,7 +114,11 @@ macro_rules! tagged_value { DocumentNode(DocumentNode), /// Carried by context nullification proto nodes constructed at proto node compilation time in `insert_context_nullification_nodes`. #[serde(skip)] - ContextFeatures(ContextFeatures), + ContextModification(ContextModification), + #[serde(skip)] + SourceId(SourceId), + #[serde(skip)] + Runtime(RuntimeHandle), #[serde(skip)] EditorApi(Arc), /// Only used by the `resource` node, should never be serialized @@ -149,7 +151,9 @@ macro_rules! tagged_value { // ======================= Self::NodeIdPath(path) => path.cache_hash(state), Self::DocumentNode(node) => node.cache_hash(state), - Self::ContextFeatures(features) => features.cache_hash(state), + Self::ContextModification(modification) => modification.cache_hash(state), + Self::SourceId(source) => source.cache_hash(state), + Self::Runtime(runtime) => runtime.cache_hash(state), Self::RenderOutput(x) => x.cache_hash(state), Self::EditorApi(x) => x.cache_hash(state), Self::ResourceHash(x) => x.cache_hash(state), @@ -157,9 +161,9 @@ macro_rules! tagged_value { } } - impl<'a> TaggedValue { - /// Converts to a Box - pub fn to_dynany(self) -> DAny<'a> { + impl TaggedValue { + /// Converts to a `Box` + pub fn to_dynany(self) -> DAny { match self { // =============== // MANUAL VARIANTS @@ -222,8 +226,10 @@ macro_rules! tagged_value { Self::RenderOutput(x) => Box::new(Item::new_from_element(x)), Self::NodeIdPath(path) => Box::new(Item::new_from_element(path)), Self::DocumentNode(node) => Box::new(node), - Self::ContextFeatures(features) => Box::new(Item::new_from_element(features)), - Self::EditorApi(x) => Box::new(x), + Self::ContextModification(modification) => Box::new(Item::new_from_element(modification)), + Self::SourceId(source) => Box::new(Item::new_from_element(source)), + Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)), + Self::EditorApi(x) => Box::new(Item::new_from_element(x)), Self::ResourceHash(x) => Box::new(Item::new_from_element(x)), } } @@ -290,8 +296,10 @@ macro_rules! tagged_value { Self::RenderOutput(x) => Arc::new(Item::new_from_element(x)), Self::NodeIdPath(path) => Arc::new(Item::new_from_element(path)), Self::DocumentNode(node) => Arc::new(node), - Self::ContextFeatures(features) => Arc::new(Item::new_from_element(features)), - Self::EditorApi(x) => Arc::new(x), + Self::ContextModification(modification) => Arc::new(Item::new_from_element(modification)), + Self::SourceId(source) => Arc::new(Item::new_from_element(source)), + Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)), + Self::EditorApi(x) => Arc::new(Item::new_from_element(x)), Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)), } } @@ -321,8 +329,10 @@ macro_rules! tagged_value { Self::RenderOutput(_) => item!(RenderOutput), Self::NodeIdPath(_) => item!(NodeIdPath), Self::DocumentNode(_) => concrete!(DocumentNode), - Self::ContextFeatures(_) => item!(ContextFeatures), - Self::EditorApi(_) => item!(&PlatformEditorApi), + Self::ContextModification(_) => item!(ContextModification), + Self::SourceId(_) => item!(SourceId), + Self::Runtime(_) => item!(RuntimeHandle), + Self::EditorApi(_) => item!(Arc), Self::ResourceHash(_) => item!(ResourceHash), }; @@ -331,39 +341,38 @@ macro_rules! tagged_value { } /// Attempts to downcast the dynamic type to a tagged value - pub fn try_from_any(input: Box + 'a>) -> Result { - use dyn_any::downcast; + pub fn try_from_any(input: DAny) -> Result { use std::any::TypeId; - match DynAny::type_id(input.as_ref()) { + match (*input).type_id() { // =============== // MANUAL VARIANTS // =============== // The manual variants convert from both their payload and wire forms, with the newtypes flattening to their stored `Vec` form x if x == TypeId::of::<()>() => Ok(TaggedValue::None), - x if x == TypeId::of::>() => Ok(TaggedValue::Numbers(*downcast(input).unwrap())), - x if x == TypeId::of::>() => Ok(TaggedValue::Numbers(downcast::>(input).unwrap().iter_element_values().copied().collect())), - x if x == TypeId::of::() => Ok(TaggedValue::DashPattern(downcast::(input).unwrap().0.iter_element_values().copied().collect())), - x if x == TypeId::of::>() => Ok(TaggedValue::DashPattern(downcast::>(input).unwrap().into_element().0.iter_element_values().copied().collect())), - x if x == TypeId::of::() => Ok(TaggedValue::BoxCorners(downcast::(input).unwrap().0.iter_element_values().copied().collect())), - x if x == TypeId::of::>() => Ok(TaggedValue::BoxCorners(downcast::>(input).unwrap().into_element().0.iter_element_values().copied().collect())), - x if x == TypeId::of::() => Ok(TaggedValue::TransferCurve(downcast::(input).unwrap().points().to_vec())), - x if x == TypeId::of::>() => Ok(TaggedValue::TransferCurve(downcast::>(input).unwrap().into_element().points().to_vec())), - x if x == TypeId::of::() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*downcast::(input).unwrap()))), - x if x == TypeId::of::>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*downcast::>(input).unwrap()))), - x if x == TypeId::of::>() => Ok(TaggedValue::Strokes(downcast::>(input).unwrap().into_iter().map(Item::into_element).collect())), - x if x == TypeId::of::>() => Ok(TaggedValue::BrushCache(downcast::>(input).unwrap().into_element())), + x if x == TypeId::of::>() => Ok(TaggedValue::Numbers(*input.downcast().unwrap())), + x if x == TypeId::of::>() => Ok(TaggedValue::Numbers(input.downcast::>().unwrap().iter_element_values().copied().collect())), + x if x == TypeId::of::() => Ok(TaggedValue::DashPattern(input.downcast::().unwrap().0.iter_element_values().copied().collect())), + x if x == TypeId::of::>() => Ok(TaggedValue::DashPattern(input.downcast::>().unwrap().into_element().0.iter_element_values().copied().collect())), + x if x == TypeId::of::() => Ok(TaggedValue::BoxCorners(input.downcast::().unwrap().0.iter_element_values().copied().collect())), + x if x == TypeId::of::>() => Ok(TaggedValue::BoxCorners(input.downcast::>().unwrap().into_element().0.iter_element_values().copied().collect())), + x if x == TypeId::of::() => Ok(TaggedValue::TransferCurve(input.downcast::().unwrap().points().to_vec())), + x if x == TypeId::of::>() => Ok(TaggedValue::TransferCurve(input.downcast::>().unwrap().into_element().points().to_vec())), + x if x == TypeId::of::() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*input.downcast::().unwrap()))), + x if x == TypeId::of::>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*input.downcast::>().unwrap()))), + x if x == TypeId::of::>() => Ok(TaggedValue::Strokes(input.downcast::>().unwrap().into_iter().map(Item::into_element).collect())), + x if x == TypeId::of::>() => Ok(TaggedValue::BrushCache(input.downcast::>().unwrap().into_element())), // ======================= // AUTO-GENERATED VARIANTS // ======================= - $( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*downcast(input).unwrap())), )* - $( x if x == TypeId::of::>() => Ok(TaggedValue::$identifier(downcast::>(input).unwrap().into_element())), )* + $( x if x == TypeId::of::<$ty>() => Ok(TaggedValue::$identifier(*input.downcast().unwrap())), )* + $( x if x == TypeId::of::>() => Ok(TaggedValue::$identifier(input.downcast::>().unwrap().into_element())), )* // ======================= // NON-SERIALIZED VARIANTS // ======================= - x if x == TypeId::of::>() => Ok(TaggedValue::RenderOutput(downcast::>(input).unwrap().into_element())), + x if x == TypeId::of::>() => Ok(TaggedValue::RenderOutput(input.downcast::>().unwrap().into_element())), - _ => Err(format!("Cannot convert {:?} to TaggedValue", DynAny::type_name(input.as_ref()))), + _ => Err(format!("Cannot convert {:?} to TaggedValue", (*input).type_id())), } } @@ -429,7 +438,6 @@ macro_rules! tagged_value { None } Type::Fn(_, output) => TaggedValue::from_type(output), - Type::Future(output) => TaggedValue::from_type(output), // Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type Type::Item(element) => TaggedValue::from_type(element).or_else(|| { macro_rules! check { @@ -487,7 +495,9 @@ macro_rules! tagged_value { Self::RenderOutput(_) => "RenderOutput".to_string(), Self::NodeIdPath(path) => format!("NodeIdPath({path:?})"), Self::DocumentNode(node) => format!("DocumentNode({node:?})"), - Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"), + Self::ContextModification(modification) => format!("ContextModification({modification:?})"), + Self::SourceId(source) => format!("SourceId({source:?})"), + Self::Runtime(_) => "Runtime".to_string(), Self::EditorApi(_) => "PlatformEditorApi".to_string(), Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"), } @@ -718,7 +728,6 @@ impl TaggedValue { Some(ty) } Type::Fn(_, output) => TaggedValue::from_primitive_string(string, output), - Type::Future(fut) => TaggedValue::from_primitive_string(string, fut), Type::Item(element) => TaggedValue::from_primitive_string(string, element), Type::List(element) => TaggedValue::from_primitive_string(string, element), } @@ -898,12 +907,11 @@ impl Display for TaggedValue { pub struct UpcastNode { value: MemoHash, } -impl<'input> Node<'input, DAny<'input>> for UpcastNode { - type Output = FutureAny<'input>; +impl Node for UpcastNode { + type Output = DAny; - fn eval(&'input self, _: DAny<'input>) -> Self::Output { - let memo_clone = MemoHash::clone(&self.value); - Box::pin(async move { memo_clone.into_inner().as_ref().clone().to_dynany() }) + fn eval(&self, _: &AnyInput) -> Poll { + Poll::Final((*self.value).clone().to_dynany()) } } impl UpcastNode { @@ -911,23 +919,6 @@ impl UpcastNode { Self { value } } } -#[derive(Default, Debug, Clone, Copy)] -pub struct UpcastAsRefNode + Sync + Send, U: Sync + Send>(pub T, PhantomData); - -impl<'i, T: 'i + AsRef + Sync + Send, U: 'i + StaticType + Sync + Send> Node<'i, DAny<'i>> for UpcastAsRefNode { - type Output = FutureAny<'i>; - #[inline(always)] - fn eval(&'i self, _: DAny<'i>) -> Self::Output { - Box::pin(async move { Box::new(Item::new_from_element(self.0.as_ref())) as DAny<'i> }) - } -} - -impl + Sync + Send, U: Sync + Send> UpcastAsRefNode { - pub const fn new(value: T) -> UpcastAsRefNode { - UpcastAsRefNode(value, PhantomData) - } -} - #[derive(Debug, Clone, PartialEq, dyn_any::DynAny, serde::Serialize, serde::Deserialize)] pub struct RenderOutput { pub data: RenderOutputType, @@ -1002,7 +993,7 @@ mod typedefault_dispatch { let expected_type_id = std::any::TypeId::of::<$type_default>(); let dyn_value = TaggedValue::TypeDefault(ty.clone()).to_dynany(); assert_eq!( - DynAny::type_id(&*dyn_value), + (*dyn_value).type_id(), expected_type_id, "`to_dynany(TypeDefault({0}))` did not produce a `{0}` — the type-default lists cover this type but the unwrap site doesn't handle it. Without a match, `to_dynany` falls back to `from_type_or_none`, which returns `TypeDefault({0})` again and recurses forever.", std::any::type_name::<$type_default>(), diff --git a/node-graph/graph-craft/src/graphene_compiler.rs b/node-graph/graph-craft/src/graphene_compiler.rs index 702c4f8835..325b6e2a69 100644 --- a/node-graph/graph-craft/src/graphene_compiler.rs +++ b/node-graph/graph-craft/src/graphene_compiler.rs @@ -1,5 +1,5 @@ use crate::document::NodeNetwork; -use crate::proto::{LocalFuture, ProtoNetwork}; +use crate::proto::ProtoNetwork; use std::error::Error; pub struct Compiler {} @@ -33,5 +33,5 @@ impl Compiler { } pub trait Executor { - fn execute(&self, input: I) -> LocalFuture<'_, Result>>; + fn execute(&self, input: I) -> Result>; } diff --git a/node-graph/graph-craft/src/proto.rs b/node-graph/graph-craft/src/proto.rs index 9dd4e8dbe8..e185573ee1 100644 --- a/node-graph/graph-craft/src/proto.rs +++ b/node-graph/graph-craft/src/proto.rs @@ -133,7 +133,7 @@ pub struct ProtoNode { pub identifier: ProtoNodeIdentifier, pub original_location: OriginalLocation, pub skip_deduplication: bool, - pub(crate) context_features: ContextDependencies, + pub(crate) context_dependencies: ContextDependencies, } impl Default for ProtoNode { @@ -144,7 +144,7 @@ impl Default for ProtoNode { call_argument: concrete!(()), original_location: OriginalLocation::default(), skip_deduplication: false, - context_features: Default::default(), + context_dependencies: Default::default(), } } } @@ -179,7 +179,7 @@ impl ProtoNode { ..Default::default() }, skip_deduplication: false, - context_features: Default::default(), + context_dependencies: Default::default(), } } @@ -288,7 +288,7 @@ impl ProtoNetwork { Ok(()) } - fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId { + fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId { let (_, node) = &self.nodes[node_id.0 as usize]; let mut path = node.original_location.path.clone(); @@ -318,7 +318,7 @@ impl ProtoNetwork { self.nodes.push(( nullification_value_node_id, ProtoNode { - construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))), + construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextModification(context_deps))), call_argument: concrete!(Context), identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"), original_location: OriginalLocation { @@ -345,60 +345,80 @@ impl ProtoNetwork { nullification_node_id } - fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option) { + pub fn source_ids(&self) -> impl Iterator { + self.nodes.iter().filter_map(|(_, node)| match &node.construction_args { + ConstructionArgs::Value(value) => match &**value { + TaggedValue::SourceId(source) => Some(source), + _ => None, + }, + _ => None, + }) + } + + fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option) { let mut branch_dependencies = Vec::new(); - let mut combined_deps = ContextFeatures::default(); + let mut combined_deps = ContextModification::default(); let node_index = id.0 as usize; - let context_features = self.nodes[node_index].1.context_features; + let dependencies = self.nodes[node_index].1.context_dependencies; let mut inputs = match &self.nodes[node_index].1.construction_args { - // We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached - ConstructionArgs::Value(_) => return (context_features.extract, Some(id)), ConstructionArgs::Nodes(items) => items.clone(), - ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)), + // We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached + ConstructionArgs::Value(value) if let TaggedValue::SourceId(source) = **value => { + return ( + ContextModification { + features: dependencies.extract, + sources: [source].into(), + }, + Some(id), + ); + } + ConstructionArgs::Value(_) | ConstructionArgs::Inline(_) => return (dependencies.extract.into(), Some(id)), }; // Compute the dependencies for each branch and combine all of them for &node in &inputs { let branch = self.find_context_dependencies(node); + combined_deps.features |= branch.0.features; + combined_deps.sources.extend(&branch.0.sources); branch_dependencies.push(branch); - combined_deps |= branch.0; } - let mut new_deps = combined_deps; - - // Remove requirements which this node provides - new_deps &= !context_features.inject; - // Add requirements we have - new_deps |= context_features.extract; + // Remove requirements which this node provides and add requirements we have + let features = (combined_deps.features & !dependencies.inject) | dependencies.extract; // If we either introduce new dependencies, we can cache all children which don't yet need that dependency - let we_introduce_new_deps = !combined_deps.contains(new_deps); + let we_introduces_new_deps = !combined_deps.features.contains(features); // For diverging branches, we can add a cache node for all branches which don't reqire all dependencies for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies) { if let Some(new_id) = new_id { *child_node = new_id; - } else if we_introduce_new_deps || deps != combined_deps { + } else if we_introduces_new_deps || deps != combined_deps { *child_node = self.insert_context_nullification_node(*child_node, deps); } } self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs); // Which dependencies do we supply (and don't need ourselves)? - let net_injections = context_features.inject.difference(context_features.extract); + let net_injections = dependencies.inject.difference(dependencies.extract); // Which dependencies still need to be met after this node? - let remaining_deps_from_children = combined_deps.difference(net_injections); + let remaining_deps_from_children = combined_deps.features.difference(net_injections); // Do we satisfy any existing dependencies? - let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty(); + let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty(); + + let new_deps = ContextModification { + features, + sources: combined_deps.sources, + }; let mut new_id = None; if we_supply_existing_deps { // Our set of context dependencies has shrunk so we can add a cache node after the current node - new_id = Some(self.insert_context_nullification_node(id, new_deps)); + new_id = Some(self.insert_context_nullification_node(id, new_deps.clone())); } (new_deps, new_id) @@ -700,7 +720,7 @@ impl TypingContext { // If the node has a value input we can infer the return type from it ConstructionArgs::Value(ref v) => { // TODO: This should return a reference to the value - let types = NodeIOTypes::new(concrete!(Context), Type::Future(Box::new(v.ty())), vec![]); + let types = NodeIOTypes::new(concrete!(Context), v.ty(), vec![]); self.inferred.insert(node_id, types.clone()); return Ok(types); } @@ -734,8 +754,6 @@ impl TypingContext { match (from, to) { // Direct comparison of two concrete types. (Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2, - // Check inner type for futures - (Type::Future(type1), Type::Future(type2)) => valid_type(type1, type2), // Direct comparison of two function types. // Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality. // That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature. @@ -1045,6 +1063,89 @@ mod test { ); } + #[test] + fn retain_filter_placement_on_source_free_branch() { + let mut network = source_branch_network(&[SourceId(1)], &[]); + network.insert_context_nullification_nodes().unwrap(); + + let filters = nullification_filters(&network); + assert_eq!(filters.len(), 1); + let (filter_id, wrapped, retained) = &filters[0]; + assert_eq!(wrapped, "source_b"); + assert!(retained.is_empty()); + + let (source_a_id, _) = find_node(&network, "source_a"); + let (_, join) = find_node(&network, "join"); + let ConstructionArgs::Nodes(join_args) = &join.construction_args else { unreachable!() }; + assert_eq!(join_args, &vec![source_a_id, *filter_id]); + } + + #[test] + fn diverging_source_sets_filter_each_branch() { + let mut network = source_branch_network(&[SourceId(1)], &[SourceId(2)]); + network.insert_context_nullification_nodes().unwrap(); + + let mut filters = nullification_filters(&network); + filters.sort_by(|(_, a, _), (_, b, _)| a.cmp(b)); + let summary: Vec<_> = filters.iter().map(|(_, wrapped, retained)| (wrapped.as_str(), retained.as_slice())).collect(); + assert_eq!(summary, vec![("source_a", &[SourceId(1)][..]), ("source_b", &[SourceId(2)][..])]); + } + + #[test] + fn matching_source_sets_insert_no_filter() { + let mut network = source_branch_network(&[SourceId(1)], &[SourceId(1)]); + network.insert_context_nullification_nodes().unwrap(); + + assert!(nullification_filters(&network).is_empty()); + assert_eq!(network.source_ids().copied().collect::>(), vec![SourceId(1), SourceId(1)]); + } + + fn find_node<'a>(network: &'a ProtoNetwork, name: &str) -> (NodeId, &'a ProtoNode) { + network.nodes.iter().find(|(_, node)| node.identifier.as_str() == name).map(|(id, node)| (*id, node)).unwrap() + } + + fn nullification_filters(network: &ProtoNetwork) -> Vec<(NodeId, String, Vec)> { + let node = |id: NodeId| &network.nodes[id.0 as usize].1; + network + .nodes + .iter() + .filter(|(_, candidate)| candidate.identifier == graphene_core::context_modification::context_modification::IDENTIFIER) + .map(|(id, candidate)| { + let ConstructionArgs::Nodes(args) = &candidate.construction_args else { unreachable!() }; + let ConstructionArgs::Nodes(memoized) = &node(args[0]).construction_args else { unreachable!() }; + let ConstructionArgs::Value(value) = &node(args[1]).construction_args else { unreachable!() }; + let TaggedValue::ContextModification(modification) = &**value else { unreachable!() }; + (*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources.iter().copied().collect()) + }) + .collect() + } + + fn source_branch_network(branch_a_sources: &[SourceId], branch_b_sources: &[SourceId]) -> ProtoNetwork { + let node = |name: &'static str, construction_args: ConstructionArgs| ProtoNode { + identifier: ProtoNodeIdentifier::new(name), + call_argument: concrete!(()), + construction_args, + ..Default::default() + }; + let mut nodes = vec![(NodeId(0), node("value", ConstructionArgs::Value(TaggedValue::Integer(2).into())))]; + let mut branch = |name: &'static str, sources: &[SourceId]| { + let mut inputs = vec![NodeId(0)]; + for &source in sources { + inputs.push(NodeId(nodes.len() as u64)); + nodes.push((NodeId(nodes.len() as u64), node("source_id", ConstructionArgs::Value(TaggedValue::SourceId(source).into())))); + } + let id = NodeId(nodes.len() as u64); + nodes.push((id, node(name, ConstructionArgs::Nodes(inputs)))); + id + }; + let branch_a = branch("source_a", branch_a_sources); + let branch_b = branch("source_b", branch_b_sources); + + let output = NodeId(nodes.len() as u64); + nodes.push((output, node("join", ConstructionArgs::Nodes(vec![branch_a, branch_b])))); + ProtoNetwork { inputs: vec![], output, nodes } + } + fn test_network() -> ProtoNetwork { ProtoNetwork { inputs: vec![NodeId(10)], diff --git a/node-graph/graph-craft/src/runtime_delta.rs b/node-graph/graph-craft/src/runtime_delta.rs index f29ca97443..88dcb2fdc0 100644 --- a/node-graph/graph-craft/src/runtime_delta.rs +++ b/node-graph/graph-craft/src/runtime_delta.rs @@ -1,5 +1,5 @@ use crate::document::{DocumentNode, NodeId, NodeInput}; -use core_types::{ContextDependencies, Type}; +use core_types::Type; /// One mutation's worth of structural graph change, carrying its post-change data as plain runtime /// types. Constructed by the mutation itself; a compound mutation emits several. Consumed typed and @@ -60,10 +60,4 @@ pub enum RuntimeDelta { node_id: NodeId, call_argument: Type, }, - /// The Extract and Inject annotations the node declares for the Context, as [`ContextDependencies`]. - SetContextFeatures { - network_path: Vec, - node_id: NodeId, - context_features: ContextDependencies, - }, } diff --git a/node-graph/graphene-cli/Cargo.toml b/node-graph/graphene-cli/Cargo.toml index 652f635eaf..67e432f22a 100644 --- a/node-graph/graphene-cli/Cargo.toml +++ b/node-graph/graphene-cli/Cargo.toml @@ -30,7 +30,6 @@ document-container = { workspace = true, features = ["zip", "xz"] } # Workspace dependencies log = { workspace = true } -futures = { workspace = true } fern = { workspace = true } chrono = { workspace = true } wgpu = { workspace = true } diff --git a/node-graph/graphene-cli/src/export.rs b/node-graph/graphene-cli/src/export.rs index 0ffafbea05..60e000b08a 100644 --- a/node-graph/graphene-cli/src/export.rs +++ b/node-graph/graphene-cli/src/export.rs @@ -1,9 +1,12 @@ +use crate::TokioSpawner; use graph_craft::document::value::{RenderOutputType, TaggedValue, UVec2}; use graph_craft::graphene_compiler::Executor; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; -use graphene_std::core_types::ops::Convert; +use graphene_std::core_types::ops::ConvertAsync; use graphene_std::core_types::transform::Footprint; use graphene_std::raster_types::{CPU, GPU, Raster}; +use graphene_std::runtime::AsyncRuntime; +use graphene_std::{NodeError, Poll}; use image::ImageFormat; use interpreted_executor::dynamic_executor::DynamicExecutor; use std::error::Error; @@ -73,7 +76,14 @@ pub struct ExportSettings { } /// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type. -async fn render_frame(executor: &DynamicExecutor, wgpu_executor: &wgpu_executor::WgpuExecutor, settings: ExportSettings, animation_time: Duration) -> Result> { +async fn render_frame( + executor: &DynamicExecutor, + wgpu_executor: &wgpu_executor::WgpuExecutor, + settings: ExportSettings, + animation_time: Duration, + runtime: &AsyncRuntime, + spawner: &TokioSpawner, +) -> Result> { let ExportSettings { file_type, scale, @@ -100,13 +110,13 @@ async fn render_frame(executor: &DynamicExecutor, wgpu_executor: &wgpu_executor: } // Execute the graph and extract its output - match executor.execute(render_config.into_context()).await? { + match execute_until_settled(executor, runtime, spawner, render_config).await? { TaggedValue::RenderOutput(output) => match output.data { RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)), RenderOutputType::Texture(texture) => { // Convert GPU texture to CPU buffer let gpu_raster = Raster::::new_gpu(texture); - let cpu_raster: Raster = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor).await; + let cpu_raster: Raster = gpu_raster.convert(Footprint::BOUNDLESS, wgpu_executor.clone()).await; let (data, width, height) = cpu_raster.to_flat_u8(); Ok(RenderedFrame::Raster { data, width, height }) } @@ -174,8 +184,15 @@ fn encode_raster(file_type: FileType, data: Vec, width: u32, height: u32, tr Ok(cursor.into_inner()) } -pub async fn export_document(executor: &DynamicExecutor, wgpu_executor: &wgpu_executor::WgpuExecutor, output_path: PathBuf, settings: ExportSettings) -> Result<(), Box> { - let frame = render_frame(executor, wgpu_executor, settings, Duration::ZERO).await?; +pub async fn export_document( + executor: &DynamicExecutor, + wgpu_executor: &wgpu_executor::WgpuExecutor, + output_path: PathBuf, + settings: ExportSettings, + runtime: &AsyncRuntime, + spawner: &TokioSpawner, +) -> Result<(), Box> { + let frame = render_frame(executor, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?; write_frame(&output_path, settings, frame)?; log::info!("Exported to: {}", output_path.display()); @@ -217,6 +234,8 @@ pub async fn export_gif( output_path: PathBuf, settings: ExportSettings, animation: AnimationParams, + runtime: &AsyncRuntime, + spawner: &TokioSpawner, ) -> Result<(), Box> { use image::codecs::gif::{GifEncoder, Repeat}; use image::{Frame, RgbaImage}; @@ -238,7 +257,7 @@ pub async fn export_gif( log::debug!("Rendering frame {}/{} at time {:?}", frame_idx + 1, animation.frames, animation_time); - let RenderedFrame::Raster { data, width, height } = render_frame(executor, wgpu_executor, settings, animation_time).await? else { + let RenderedFrame::Raster { data, width, height } = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await? else { return Err("A GIF frame must render as pixels".into()); }; @@ -265,6 +284,8 @@ pub async fn export_image_sequence( output_path: PathBuf, settings: ExportSettings, animation: AnimationParams, + runtime: &AsyncRuntime, + spawner: &TokioSpawner, ) -> Result<(), Box> { log::info!("Exporting image sequence: {} frames at {} fps", animation.frames, animation.fps); @@ -280,7 +301,7 @@ pub async fn export_image_sequence( // Print progress to stderr (overwrites previous line) eprint!("\rRendering frame {}/{}...", frame_idx + 1, animation.frames); - let frame = render_frame(executor, wgpu_executor, settings, animation_time).await?; + let frame = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await?; let frame_path = directory.join(format!("{stem}_{frame_idx:0digits$}.{extension}")); write_frame(&frame_path, settings, frame)?; } @@ -292,6 +313,32 @@ pub async fn export_image_sequence( Ok(()) } +async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result> { + let execute = || executor.execute(render_config.into_context_with_generations(runtime.snapshot())); + let mut frame = execute()?; + while spawner.join().await { + frame = execute()?; + } + match frame { + Poll::Fallback(boxed) => { + let (value, error) = *boxed; + log::warn!("Exported fallback value due to node error: {}", messages(&error)); + Ok(value) + } + Poll::Error(error) => Err(format!("Node graph failed: {}", messages(&error)).into()), + frame => frame.value().ok_or_else(|| "Node graph produced no frame".into()), + } +} + +fn messages(error: &NodeError) -> String { + let mut text = error.to_string(); + for upstream in error.upstream() { + text.push('\n'); + text.push_str(&messages(upstream)); + } + text +} + #[cfg(test)] mod tests { use super::*; diff --git a/node-graph/graphene-cli/src/main.rs b/node-graph/graphene-cli/src/main.rs index 28655426bd..c42b596bc2 100644 --- a/node-graph/graphene-cli/src/main.rs +++ b/node-graph/graphene-cli/src/main.rs @@ -5,27 +5,19 @@ use document_container::AnyContainer; use document_container::backends::memory::MemoryBackend; use document_format::{GddV1, GddV1Layout}; use fern::colors::{Color, ColoredLevelConfig}; -use futures::executor::block_on; use graph_craft::application_io::EditorPreferences; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::document::*; use graph_craft::graphene_compiler::Compiler; use graph_craft::proto::ProtoNetwork; use graph_craft::util::load_network; -use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender}; +use graphene_std::application_io::ApplicationIo; +use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task}; use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::util::wrap_network_in_scope; use std::error::Error; use std::path::PathBuf; -use std::sync::Arc; - -struct UpdateLogger {} - -impl NodeGraphUpdateSender for UpdateLogger { - fn send(&self, message: NodeGraphUpdateMessage) { - println!("{message:?}"); - } -} +use std::sync::{Arc, Mutex}; #[derive(Debug, Parser)] #[clap(name = "graphene-cli", version)] @@ -183,10 +175,11 @@ async fn main() -> Result<(), Box> { }; let editor_api = Arc::new(PlatformEditorApi { application_io: Some(application_io_for_api), - node_graph_message_sender: Box::new(UpdateLogger {}), editor_preferences: Box::new(preferences), }); - let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref())?; + let spawner = Arc::new(TokioSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?; match app.command { Command::Compile { print_proto, .. } => { @@ -218,6 +211,7 @@ async fn main() -> Result<(), Box> { // Create executor let executor = create_executor(proto_graph)?; + runtime.retain_sources(executor.sources()); if fps <= 0. { return Err("Fps number must be positive".into()); @@ -232,14 +226,14 @@ async fn main() -> Result<(), Box> { }; let animation = export::AnimationParams::new(fps, frames, duration); if file_type == export::FileType::Gif { - export::export_gif(&executor, wgpu_executor_ref, output, settings, animation).await?; + export::export_gif(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?; } else if animation.frames > 1 { if file_type == export::FileType::Ico { return Err("ICO can't be exported as an image sequence".into()); } - export::export_image_sequence(&executor, wgpu_executor_ref, output, settings, animation).await?; + export::export_image_sequence(&executor, wgpu_executor_ref, output, settings, animation, &runtime, &spawner).await?; } else { - export::export_document(&executor, wgpu_executor_ref, output, settings).await?; + export::export_document(&executor, wgpu_executor_ref, output, settings, &runtime, &spawner).await?; } } _ => unreachable!("All other commands should be handled before this match statement is run"), @@ -277,10 +271,10 @@ fn init_logging(log_level: u8) { .unwrap(); } -fn compile_graph(network: NodeNetwork, editor_api: Arc, gdd: Option<&GddV1>) -> Result> { +fn compile_graph(network: NodeNetwork, editor_api: Arc, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result> { let preprocessor = preprocessor::Preprocessor::new(); - let mut network = wrap_network_in_scope(network, editor_api); + let mut network = wrap_network_in_scope(network, editor_api, runtime); // A `.gdd` resolves resource hashes from its registry; a legacy `.graphite` has no resource store, so it // preprocesses against an empty registry (matching the pre-`.gdd` CLI behavior). @@ -296,6 +290,26 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc, gdd: } fn create_executor(proto_network: ProtoNetwork) -> Result> { - let executor = block_on(DynamicExecutor::new(proto_network)).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?; + let executor = DynamicExecutor::new(proto_network).map_err(|errors| errors.iter().map(|e| format!("{e:?}")).reduce(|acc, e| format!("{acc}\n{e}")).unwrap_or_default())?; Ok(executor) } + +#[derive(Default)] +pub(crate) struct TokioSpawner(Mutex>>); + +impl Spawn for TokioSpawner { + fn spawn(&self, task: Task) { + self.0.lock().unwrap().push(tokio::spawn(task)); + } +} + +impl TokioSpawner { + pub(crate) async fn join(&self) -> bool { + let tasks = std::mem::take(&mut *self.0.lock().unwrap()); + let pending = !tasks.is_empty(); + for task in tasks { + let _ = task.await; + } + pending + } +} diff --git a/node-graph/interpreted-executor/benches/benchmark_util.rs b/node-graph/interpreted-executor/benches/benchmark_util.rs index 25c62f55f8..cad6af3acc 100644 --- a/node-graph/interpreted-executor/benches/benchmark_util.rs +++ b/node-graph/interpreted-executor/benches/benchmark_util.rs @@ -1,20 +1,20 @@ use criterion::BenchmarkGroup; use criterion::measurement::Measurement; -use futures::executor::block_on; use graph_craft::proto::ProtoNetwork; use graph_craft::util::{DEMO_ART, compile, load_from_name}; use graphene_std::application_io::EditorApi; +use graphene_std::runtime::{AsyncRuntime, Spawn, Task}; use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::util::wrap_network_in_scope; pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) { let network = load_from_name(name); let editor_api = std::sync::Arc::new(EditorApi::default()); - let mut network = wrap_network_in_scope(network, editor_api); + let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle()); let preprocessor = preprocessor::Preprocessor::new(); preprocessor.preprocess(&mut network, &|_| None).unwrap(); let proto_network = compile(network); - let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap(); + let executor = DynamicExecutor::new(proto_network.clone()).unwrap(); (executor, proto_network) } @@ -27,3 +27,9 @@ where f(name, group); } } + +// TODO: Consider replacing this with a real spawner and benchmarking async nodes +struct DummySpawner; +impl Spawn for DummySpawner { + fn spawn(&self, _task: Task) {} +} diff --git a/node-graph/interpreted-executor/benches/run_cached.rs b/node-graph/interpreted-executor/benches/run_cached.rs index 621a0c1df2..df9692aa0e 100644 --- a/node-graph/interpreted-executor/benches/run_cached.rs +++ b/node-graph/interpreted-executor/benches/run_cached.rs @@ -10,9 +10,7 @@ fn subsequent_evaluations(c: &mut Criterion) { bench_for_each_demo(&mut group, |name, g| { let (executor, _) = setup_network(name); let context = context.clone(); - g.bench_function(name, |b| { - b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap()) - }); + g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap())); }); group.finish(); } diff --git a/node-graph/interpreted-executor/benches/run_cached_gungraun.rs b/node-graph/interpreted-executor/benches/run_cached_gungraun.rs index a983525669..ce81e8eb74 100644 --- a/node-graph/interpreted-executor/benches/run_cached_gungraun.rs +++ b/node-graph/interpreted-executor/benches/run_cached_gungraun.rs @@ -11,7 +11,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor { // Warm up the cache by running once let context = RenderConfig::default().into_context(); - let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context)); + let _ = executor.tree().eval_tagged_value(executor.output(), &context); executor } @@ -20,7 +20,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor { #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)] pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor { let context = RenderConfig::default().into_context(); - black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap()); + black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap()); // Return the executor so its teardown happens outside the measured section executor diff --git a/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs b/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs index 7f58565665..048abcbda3 100644 --- a/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs +++ b/node-graph/interpreted-executor/benches/run_demo_art_criterion.rs @@ -11,12 +11,12 @@ fn update_executor(name: &str, c: &mut BenchmarkGroup) { let proto_network = compile(network); let empty = ProtoNetwork::default(); - let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); + let executor = DynamicExecutor::new(empty).unwrap(); c.bench_function(name, |b| { b.iter_batched( || (executor.clone(), proto_network.clone()), - |(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))), + |(mut executor, network)| executor.update(std::hint::black_box(network)), criterion::BatchSize::SmallInput, ) }); @@ -33,10 +33,10 @@ fn run_once(name: &str, c: &mut BenchmarkGroup) { let network = load_from_name(name); let proto_network = compile(network); - let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap(); + let executor = DynamicExecutor::new(proto_network).unwrap(); let footprint = Footprint::default(); - c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint)))); + c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint))); } fn run_once_demo(c: &mut Criterion) { let mut g = c.benchmark_group("Run Once no render"); diff --git a/node-graph/interpreted-executor/benches/run_once.rs b/node-graph/interpreted-executor/benches/run_once.rs index f63ca9df43..693cc11885 100644 --- a/node-graph/interpreted-executor/benches/run_once.rs +++ b/node-graph/interpreted-executor/benches/run_once.rs @@ -12,7 +12,7 @@ fn run_once(c: &mut Criterion) { g.bench_function(name, |b| { b.iter_batched( || setup_network(name), - |(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context.clone()))).unwrap(), + |(executor, _)| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap(), criterion::BatchSize::SmallInput, ) }); diff --git a/node-graph/interpreted-executor/benches/run_once_gungraun.rs b/node-graph/interpreted-executor/benches/run_once_gungraun.rs index 307dbb64fa..a748939301 100644 --- a/node-graph/interpreted-executor/benches/run_once_gungraun.rs +++ b/node-graph/interpreted-executor/benches/run_once_gungraun.rs @@ -15,7 +15,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor { #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)] pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor { let context = application_io::RenderConfig::default().into_context(); - black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap()); + black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap()); // Return the executor so its teardown happens outside the measured section executor diff --git a/node-graph/interpreted-executor/benches/update_executor.rs b/node-graph/interpreted-executor/benches/update_executor.rs index ca5f4c0a4a..081cba763a 100644 --- a/node-graph/interpreted-executor/benches/update_executor.rs +++ b/node-graph/interpreted-executor/benches/update_executor.rs @@ -13,10 +13,10 @@ fn update_executor(c: &mut Criterion) { || { let (_, proto_network) = setup_network(name); let empty = ProtoNetwork::default(); - let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); + let executor = DynamicExecutor::new(empty).unwrap(); (executor, proto_network) }, - |(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))), + |(mut executor, network)| executor.update(std::hint::black_box(network)), criterion::BatchSize::SmallInput, ) }); diff --git a/node-graph/interpreted-executor/benches/update_executor_gungraun.rs b/node-graph/interpreted-executor/benches/update_executor_gungraun.rs index 91017ee3b8..42dbbe508a 100644 --- a/node-graph/interpreted-executor/benches/update_executor_gungraun.rs +++ b/node-graph/interpreted-executor/benches/update_executor_gungraun.rs @@ -9,7 +9,7 @@ use std::hint::black_box; fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) { let (_, proto_network) = setup_network(name); let empty = ProtoNetwork::default(); - let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap(); + let executor = DynamicExecutor::new(empty).unwrap(); (executor, proto_network) } @@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) { #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)] pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor { let (mut executor, network) = setup; - let _ = black_box(futures::executor::block_on(executor.update(black_box(network)))); + let _ = black_box(executor.update(black_box(network))); // Return the executor so its teardown happens outside the measured section executor diff --git a/node-graph/interpreted-executor/src/dynamic_executor.rs b/node-graph/interpreted-executor/src/dynamic_executor.rs index ffa2c7ddb5..aa79de3492 100644 --- a/node-graph/interpreted-executor/src/dynamic_executor.rs +++ b/node-graph/interpreted-executor/src/dynamic_executor.rs @@ -1,10 +1,10 @@ use crate::node_registry; -use dyn_any::StaticType; +use core_types::{NodeError, Poll, SourceId, WasmNotSend}; use graph_craft::Type; use graph_craft::document::NodeId; -use graph_craft::document::value::{TaggedValue, UpcastAsRefNode, UpcastNode}; +use graph_craft::document::value::{TaggedValue, UpcastNode}; use graph_craft::graphene_compiler::Executor; -use graph_craft::proto::{ConstructionArgs, GraphError, LocalFuture, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext}; +use graph_craft::proto::{ConstructionArgs, GraphError, NodeContainer, ProtoNetwork, ProtoNode, SharedNodeContainer, TypeErasedBox, TypingContext}; use graph_craft::proto::{GraphErrorType, GraphErrors}; use std::collections::{HashMap, HashSet}; use std::error::Error; @@ -20,6 +20,7 @@ pub struct DynamicExecutor { typing_context: TypingContext, // This allows us to keep the nodes around for one more frame which is used for introspection orphaned_nodes: HashSet, + sources: Vec, } impl Default for DynamicExecutor { @@ -29,6 +30,7 @@ impl Default for DynamicExecutor { tree: Default::default(), typing_context: TypingContext::new(&node_registry::NODE_REGISTRY), orphaned_nodes: HashSet::new(), + sources: Vec::new(), } } } @@ -48,23 +50,29 @@ pub struct ResolvedDocumentNodeTypesDelta { } impl DynamicExecutor { - pub async fn new(proto_network: ProtoNetwork) -> Result { + pub fn new(proto_network: ProtoNetwork) -> Result { let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY); typing_context.update(&proto_network)?; let output = proto_network.output; - let tree = BorrowTree::new(proto_network, &typing_context).await?; + let sources = proto_network.source_ids().copied().collect(); + let tree = BorrowTree::new(proto_network, &typing_context)?; Ok(Self { tree, output, typing_context, orphaned_nodes: HashSet::new(), + sources, }) } + pub fn sources(&self) -> &[SourceId] { + &self.sources + } + /// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible. #[cfg_attr(debug_assertions, inline(never))] - pub async fn update(&mut self, proto_network: ProtoNetwork) -> Result { + pub fn update(&mut self, proto_network: ProtoNetwork) -> Result { self.output = proto_network.output; self.typing_context.update(&proto_network).map_err(|e| { // If there is an error then get types that have been resolved before the error @@ -87,11 +95,8 @@ impl DynamicExecutor { (ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e) })?; - let (add, orphaned) = self - .tree - .update(proto_network, &self.typing_context) - .await - .map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?; + self.sources = proto_network.source_ids().copied().collect(); + let (add, orphaned) = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?; 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 { @@ -133,29 +138,34 @@ impl DynamicExecutor { // TODO: https://github.com/GraphiteEditor/Graphite/issues/1767 // TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node. } -} -impl Executor for &DynamicExecutor -where - I: StaticType + 'static + Send + Sync, -{ - fn execute(&self, input: I) -> LocalFuture<'_, Result>> { - Box::pin(async move { - use futures::FutureExt; - - let result = self.tree.eval_tagged_value(self.output, input); - let wrapped_result = std::panic::AssertUnwindSafe(result).catch_unwind().await; - - match wrapped_result { - Ok(result) => result.map_err(|e| e.into()), - Err(e) => { - Box::leak(e); - Err("Node graph execution panicked".into()) - } + // TODO(Dennis and Timon): Remove this once rank promotion is fixed. + // Only really needed due to the runtime not knowing about rank adapters. + // Once we reworked that we should be able to move this resolution into the runtime. + // Also remember to remove `BorrowTree::nodes.3` at that point + pub fn find_origin(&self, mut node: NodeId, error: &NodeError) -> Option { + let mut trace = error.trace().iter().rev(); + while let Some(&index) = trace.next() { + // Hack to undo rank promotion while traversing the graph + if self.typing_context.promotions(node).is_some_and(|promotions| promotions.iter().any(|(argument, _)| *argument == index)) { + trace.next(); } - }) + + node = *self.tree.nodes.get(&node).map(|(_, _, inputs)| &**inputs)?.get(index)?; + } + Some(node) } } + +impl Executor> for &DynamicExecutor +where + I: 'static + WasmNotSend, +{ + fn execute(&self, input: I) -> Result, Box> { + self.tree.eval_tagged_value(self.output, &input).map_err(|error| error.into()) + } +} + pub struct InputMapping {} #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -188,8 +198,8 @@ impl std::fmt::Display for IntrospectError { /// /// # Fields /// -/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`] and [`Path`]. -/// This stores the actual node instances and their associated paths. +/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SharedNodeContainer`], [`Path`], and input [`NodeId`]s. +/// This stores the actual node instances, their associated paths, and the nodes connected to their inputs. /// /// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`]. /// This maps document paths to node IDs and their associated type information. @@ -197,30 +207,30 @@ impl std::fmt::Display for IntrospectError { /// A store of the dynamically typed nodes and also the source map. #[derive(Default, Clone)] pub struct BorrowTree { - /// A hashmap of node IDs and dynamically typed nodes. - nodes: HashMap, + /// A hashmap of node IDs and dynamically typed nodes, with their paths and input node IDs. + nodes: HashMap)>, /// A hashmap from the document path to the proto node ID. source_map: HashMap, } impl BorrowTree { - pub async fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result { + pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result { let mut nodes = BorrowTree::default(); for (id, node) in proto_network.nodes { - nodes.push_node(id, node, typing_context).await? + nodes.push_node(id, node, typing_context)? } Ok(nodes) } /// Pushes new nodes into the tree and return orphaned nodes - pub async fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec, HashSet), GraphErrors> { + pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec, HashSet), GraphErrors> { let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect(); let mut new_nodes: Vec<_> = Vec::new(); // TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type. for (id, node) in proto_network.nodes { if !self.nodes.contains_key(&id) { new_nodes.push(node.original_location.path.clone().unwrap_or_default().into()); - self.push_node(id, node, typing_context).await?; + self.push_node(id, node, typing_context)?; } else if self.update_source_map(id, typing_context, &node) { new_nodes.push(node.original_location.path.clone().unwrap_or_default().into()); } @@ -233,40 +243,48 @@ impl BorrowTree { nodes.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect() } - fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path) { - self.nodes.insert(id, (node, path)); + fn store_node(&mut self, node: SharedNodeContainer, id: NodeId, path: Path, inputs: Box<[NodeId]>) { + self.nodes.insert(id, (node, path, inputs)); } /// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path. pub fn introspect(&self, node_path: &[NodeId]) -> Result, IntrospectError> { let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?; - let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?; + let (node, _path, _) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?; node.serialize().ok_or(IntrospectError::NoData) } pub fn get(&self, id: NodeId) -> Option { - self.nodes.get(&id).map(|(node, _)| node.clone()) + self.nodes.get(&id).map(|(node, _, _)| node.clone()) } /// Evaluate the output node of the [`BorrowTree`]. - pub async fn eval<'i, I, O>(&'i self, id: NodeId, input: I) -> Option + pub fn eval(&self, id: NodeId, input: &I) -> Option where - I: StaticType + 'i + Send + Sync, - O: StaticType + 'i, + I: 'static + WasmNotSend, + O: 'static, { - let (node, _path) = self.nodes.get(&id).cloned()?; - let output = node.eval(Box::new(input)); - dyn_any::downcast::(output.await).ok().map(|o| *o) + let (node, _path, _) = self.nodes.get(&id)?; + node.eval(input).value().and_then(|output| output.downcast::().ok().map(|o| *o)) } + /// Evaluate the output node of the [`BorrowTree`] and cast it to a tagged value. /// This ensures that no borrowed data can escape the node graph. - pub async fn eval_tagged_value(&self, id: NodeId, input: I) -> Result + pub fn eval_tagged_value(&self, id: NodeId, input: &I) -> Result, String> where - I: StaticType + 'static + Send + Sync, + I: 'static + WasmNotSend, { - let (node, _path) = self.nodes.get(&id).cloned().ok_or("Output node not found in executor")?; - let output = node.eval(Box::new(input)); - TaggedValue::try_from_any(output.await) + let (node, _path, _) = self.nodes.get(&id).ok_or("Output node not found in executor")?; + Ok(match node.eval(input) { + Poll::Pending => Poll::Pending, + Poll::Final(output) => Poll::Final(TaggedValue::try_from_any(output)?), + Poll::Partial(output) => Poll::Partial(TaggedValue::try_from_any(output)?), + Poll::Fallback(boxed) => { + let (output, error) = *boxed; + Poll::Fallback(Box::new((TaggedValue::try_from_any(output)?, error))) + } + Poll::Error(error) => Poll::Error(error), + }) } /// Removes a node from the [`BorrowTree`] and returns its associated path. @@ -293,10 +311,10 @@ impl BorrowTree { /// use interpreted_executor::node_registry; /// /// - /// async fn example() -> Result<(), GraphErrors> { + /// fn example() -> Result<(), GraphErrors> { /// let (proto_network, node_id, proto_node) = ProtoNetwork::example(); /// let typing_context = TypingContext::new(&node_registry::NODE_REGISTRY); - /// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context).await?; + /// let mut borrow_tree = BorrowTree::new(proto_network, &typing_context)?; /// /// // Assert that the node exists in the BorrowTree /// assert!(borrow_tree.get(node_id).is_some(), "Node should exist before removal"); @@ -325,7 +343,7 @@ impl BorrowTree { /// - If the node is the primary node for its path in the `source_map`, it's also removed from there. /// - Returns `None` if the node is not found in the `nodes` HashMap. pub fn free_node(&mut self, id: NodeId) -> Option { - let (_, path) = self.nodes.remove(&id)?; + let (_, path, _) = self.nodes.remove(&id)?; if self.source_map.get(&path)?.0 == id { self.source_map.remove(&path); return Some(path); @@ -393,22 +411,15 @@ impl BorrowTree { /// - `Nodes`: Constructs a node using other nodes as dependencies. /// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments. /// - Returns an error if no constructor is found for the given node ID. - async fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> { + fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> { self.update_source_map(id, typing_context, &proto_node); let path = proto_node.original_location.path.clone().unwrap_or_default(); match &proto_node.construction_args { ConstructionArgs::Value(value) => { - let node = if let TaggedValue::EditorApi(api) = &**value { - let editor_api = UpcastAsRefNode::new(api.clone()); - let node = Box::new(editor_api) as TypeErasedBox<'_>; - NodeContainer::new(node) - } else { - let upcasted = UpcastNode::new(value.to_owned()); - let node = Box::new(upcasted) as TypeErasedBox<'_>; - NodeContainer::new(node) - }; - self.store_node(node, id, path.into()); + let upcasted = UpcastNode::new(value.to_owned()); + let node = NodeContainer::new(Box::new(upcasted) as TypeErasedBox<'_>); + self.store_node(node, id, path.into(), Box::default()); } ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"), ConstructionArgs::Nodes(ids) => { @@ -421,15 +432,15 @@ impl BorrowTree { let adapter_constructor = typing_context .adapter_constructor(&promotion.adapter_identifier()) .ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?; - let adapter = adapter_constructor(vec![construction_nodes[*argument_index].clone()]).await; + let adapter = adapter_constructor(vec![construction_nodes[*argument_index].clone()]); construction_nodes[*argument_index] = NodeContainer::new(adapter); } } let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?; - let node = constructor(construction_nodes).await; + let node = constructor(construction_nodes); let node = NodeContainer::new(node); - self.store_node(node, id, path.into()); + self.store_node(node, id, path.into(), ids.into()); } }; Ok(()) diff --git a/node-graph/interpreted-executor/src/dynamic_executor/test.rs b/node-graph/interpreted-executor/src/dynamic_executor/test.rs index 1b90375d53..adc40f81d6 100644 --- a/node-graph/interpreted-executor/src/dynamic_executor/test.rs +++ b/node-graph/interpreted-executor/src/dynamic_executor/test.rs @@ -11,10 +11,9 @@ fn push_node_sync() { let mut tree = BorrowTree::default(); let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]); let context = TypingContext::default(); - let future = tree.push_node(NodeId(0), val_1_protonode, &context); - futures::executor::block_on(future).unwrap(); + tree.push_node(NodeId(0), val_1_protonode, &context).unwrap(); let _node = tree.get(NodeId(0)).unwrap(); - let result: Option> = futures::executor::block_on(tree.eval(NodeId(0), ())); + let result: Option> = tree.eval(NodeId(0), &()); assert_eq!(result.map(|item| *item.element()), Some(2_i64)); } @@ -36,7 +35,7 @@ fn compile_bounding_box_network(content: TaggedValue) -> BorrowTree { let network = bounding_box_network(content); let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("The network should resolve against exactly one registered wire variant"); - futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The resolved variant's constructor should instantiate") + BorrowTree::new(network, &typing_context).expect("The resolved variant's constructor should instantiate") } #[test] @@ -44,10 +43,10 @@ fn item_wire_variant_resolves_and_executes() { let tree = compile_bounding_box_network(TaggedValue::TypeDefault(item!(Vector))); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context.clone())); + let result: Option> = tree.eval(NodeId(1), &context); assert!(result.is_some(), "The Item wire variant should downcast and execute end-to-end"); - let wrong_type: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let wrong_type: Option> = tree.eval(NodeId(1), &context); assert!(wrong_type.is_none(), "An Item wire should not downcast as a List"); } @@ -67,10 +66,10 @@ fn item_wire_promotes_to_list_connector() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An Item wire should resolve a List connector via promotion"); assert!(typing_context.promotions(NodeId(1)).is_some(), "The typing pass should record the promotion"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapter should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The promotion adapter should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert!(result.is_some(), "The promoted wire should execute end-to-end"); } @@ -97,10 +96,10 @@ fn rank_0_content_promotes_through_the_layer_coercion_path() { typing_context.update(&network).expect("A rank-0 content wire should resolve the layer coercion path via promotion"); assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 content should be raised at Into Group's List connector"); assert!(typing_context.promotions(NodeId(3)).is_some(), "The grouped Item should be raised at Extend's List connector"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The promotion adapters should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The promotion adapters should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(3), context)); + let result: Option> = tree.eval(NodeId(3), &context); let stack = result.expect("The layer coercion path should execute end-to-end"); assert_eq!(stack.len(), 1, "The rank-0 content should contribute exactly one graphic to the stack"); } @@ -131,10 +130,10 @@ fn mixed_rank_connectors_resolve_via_promotion() { .update(&network) .expect("A List primary with an Item parameter should resolve the mapped variant via promotion"); assert!(typing_context.promotions(NodeId(3)).is_some(), "The Item distance should be marked for promotion"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Construction should wrap the promoted argument"); + let tree = BorrowTree::new(network, &typing_context).expect("Construction should wrap the promoted argument"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(3), context)); + let result: Option> = tree.eval(NodeId(3), &context); assert!(result.is_some(), "The zipped mapped variant should execute end-to-end"); } @@ -144,10 +143,10 @@ fn all_item_connectors_resolve_without_promotion() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("All-Item connectors should resolve the rank-0 variant exactly"); assert!(typing_context.promotions(NodeId(3)).is_none(), "No promotion should be needed at rank 0"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The rank-0 variant should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The rank-0 variant should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(3), context)); + let result: Option> = tree.eval(NodeId(3), &context); assert!(result.is_some(), "The rank-0 variant should execute and stay rank 0"); } @@ -192,10 +191,10 @@ fn transform_composes_onto_item_wire() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("Transform should resolve its rank-0 variant"); assert!(typing_context.promotions(output).is_none(), "All-Item connectors should need no promotion"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("Transform's rank-0 variant should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("Transform's rank-0 variant should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(output, context)); + let result: Option> = tree.eval(output, &context); let item = result.expect("A rank-0 chain through Transform should stay rank 0"); let transform = item.attribute_cloned_or_default::(core_types::ATTR_TRANSFORM); assert_eq!(transform.translation, DVec2::new(5., 0.), "The translation should compose onto the item's transform attribute"); @@ -212,10 +211,10 @@ fn transform_broadcasts_item_content_across_a_framed_parameter() { .update(&network) .expect("A framed rotation should resolve the mapped variant via promotion of the other connectors"); assert!(typing_context.promotions(output).is_some(), "The Item-typed connectors should be raised into the frame"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped variant should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The mapped variant should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(output, context)); + let result: Option> = tree.eval(output, &context); let list = result.expect("The broadcast should produce a List"); assert_eq!(list.len(), 2, "One output item per frame slot"); @@ -245,10 +244,10 @@ fn generator_frames_over_a_list_parameter() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("A List radius should resolve Circle's mapped generator variant"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped generator variant should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The mapped generator variant should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(3), context)); + let result: Option> = tree.eval(NodeId(3), &context); let list = result.expect("The generator frame should produce a List"); assert_eq!(list.len(), 3, "One circle per radius slot"); } @@ -260,7 +259,7 @@ fn nullification_chain_network(value: TaggedValue) -> ProtoNetwork { let mut memoize_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]); memoize_node.identifier = graphene_core::memo::memoize::IDENTIFIER; - let features_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextFeatures(Default::default()).into()), vec![NodeId(2)]); + let features_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(Default::default()).into()), vec![NodeId(2)]); let mut nullification_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1), NodeId(2)]), vec![NodeId(3)]); nullification_node.identifier = graphene_core::context_modification::context_modification::IDENTIFIER; @@ -315,10 +314,10 @@ fn value_wires_materialize_as_items_at_resolution() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("Value wires should materialize as Items and resolve the all-Item variant"); assert!(typing_context.promotions(NodeId(5)).is_none(), "Already-Item value wires should need no promotion"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The all-Item variant should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The all-Item variant should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(5), context)); + let result: Option> = tree.eval(NodeId(5), &context); let item = result.expect("A value matrix should flow through Transform as an Item"); let transform = item.attribute_cloned_or_default::(core_types::ATTR_TRANSFORM); assert_eq!(transform.translation, DVec2::new(7., 0.), "The translation should compose onto the gained transform attribute"); @@ -339,10 +338,10 @@ fn position_value_converts_through_the_vector_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An Item wire should resolve the adapter's element conversion row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The conversion constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The conversion constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert!(result.is_some(), "The position should arrive as an Item single-anchor path"); } @@ -364,10 +363,10 @@ fn position_value_raises_into_the_into_group_reducer() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An Item wire should raise into Into Group's List row"); assert!(typing_context.promotions(NodeId(1)).is_some(), "The rank-0 position should be raised at Into Group's List connector"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The reducer constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The reducer constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); let grouped = result.expect("The position should arrive as an Item"); let Graphic::VectorList(anchors) = grouped.element() else { @@ -398,10 +397,10 @@ fn color_list_wraps_through_the_colors_to_gradient_node() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("A List wire should embed into the node's List connector"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The node constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The node constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(3), context)); + let result: Option> = tree.eval(NodeId(3), &context); let gradient = result.expect("The color list should arrive wrapped as a gradient"); assert_eq!(gradient.element().len(), 1, "The single color should become the gradient's one stop"); } @@ -443,10 +442,10 @@ fn as_graphic_converts_a_vector_list_element_wise() { typing_context .update(&network) .expect("A List wire should resolve As Graphic's mapped variant through the embedding adapter"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The mapped constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The mapped constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(5), context)); + let result: Option> = tree.eval(NodeId(5), &context); let graphics = result.expect("The vector list should arrive as a graphic list"); assert_eq!(graphics.len(), 2, "Each vector should become its own graphic rather than collapsing into one group"); @@ -479,10 +478,10 @@ fn gradient_value_embeds_through_the_graphic_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An Item wire should resolve the adapter's embedding row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The embedding constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The embedding constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); let embedded = result.expect("The gradient should arrive as an Item"); assert!(embedded.attributes().iter_any().next().is_none(), "The fresh outer envelope describes the graphic, so it starts empty"); @@ -509,10 +508,10 @@ fn number_value_splats_through_the_vec2_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An f64 wire should resolve the adapter's splat conversion row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The splat constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The splat constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert_eq!(result.map(|item| *item.element()), Some(glam::DVec2::splat(-60.)), "The scalar should splat into both axes"); } @@ -531,10 +530,10 @@ fn number_value_formats_through_the_string_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An f64 wire should resolve the adapter's formatting conversion row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The formatting constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The formatting constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert_eq!(result.map(|item| item.element().clone()), Some("42".to_string()), "The number should format as its text representation"); } @@ -554,10 +553,10 @@ fn bool_value_embeds_through_the_number_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("A bool wire should resolve the adapter's embedding conversion row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The embedding constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The embedding constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert_eq!(result.map(|item| *item.element()), Some(expected), "{value} should embed as exactly {expected}"); } } @@ -578,10 +577,10 @@ fn bool_value_formats_through_the_string_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("A bool wire should resolve the adapter's formatting conversion row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The formatting constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The formatting constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert_eq!(result.map(|item| item.element().clone()), Some(expected.to_string()), "{value} should format as `{expected}`"); } } @@ -603,10 +602,10 @@ fn list_wire_erases_through_the_list_dyn_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("A List wire should resolve the ListDyn erasure row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The erasure constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The erasure constructor should instantiate"); let context: Context = None; - let result: Option = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option = tree.eval(NodeId(1), &context); let erased = result.expect("The erased list should arrive as a ListDyn"); assert_eq!(erased.len(), 3, "The erased list should keep its row count"); } @@ -625,10 +624,10 @@ fn value_wire_passes_through_the_input_adapter_as_item() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An f64 value's Item wire should resolve the adapter's passthrough row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The passthrough constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); assert_eq!(result.map(|item| *item.element()), Some(3.), "The value should arrive as an Item"); } @@ -651,10 +650,10 @@ fn modification_value_rides_the_item_wire_through_its_input_adapter() { }; let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("A modification value's Item wire should resolve the adapter's passthrough row"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The passthrough constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The passthrough constructor should instantiate"); let context: Context = None; - let result: Option>> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option>> = tree.eval(NodeId(1), &context); assert!(result.is_some(), "The modification should arrive as an Item"); } @@ -675,10 +674,10 @@ fn item_wire_boxes_into_the_attribute_value_connector() { let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY); typing_context.update(&network).expect("An Item wire should resolve the attribute value boxing row"); assert!(typing_context.promotions(NodeId(1)).is_none(), "The already-Item value wire should need no promotion"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The boxing constructor should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The boxing constructor should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let result: Option> = tree.eval(NodeId(1), &context); let boxed = result.expect("The boxed attribute value should arrive as an Item"); assert_eq!( boxed.element().0.as_any().downcast_ref::(), @@ -692,10 +691,10 @@ fn list_wire_variant_resolves_and_executes() { let tree = compile_bounding_box_network(TaggedValue::TypeDefault(list!(Vector))); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(1), context.clone())); + let result: Option> = tree.eval(NodeId(1), &context); assert!(result.is_some(), "The mapped List wire variant should downcast and execute end-to-end"); - let wrong_type: Option> = futures::executor::block_on(tree.eval(NodeId(1), context)); + let wrong_type: Option> = tree.eval(NodeId(1), &context); assert!(wrong_type.is_none(), "A List wire should not downcast as an Item"); } @@ -733,10 +732,10 @@ fn expander_flattens_under_the_frame() { .update(&network) .expect("All-Item connectors should resolve the expander's direct `Item -> List` variant"); assert!(typing_context.promotions(output).is_none(), "No promotion should be needed when every connector is already an Item"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The expander variant should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The expander variant should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(output, context)); + let result: Option> = tree.eval(output, &context); let list = result.expect("An Item-wired expander should produce a List"); assert_eq!(list.len(), 2, "Splitting \"a,b\" on the comma should expand into two rows"); let substrings: Vec<_> = list.iter_element_values().map(|s| s.as_str()).collect(); @@ -779,9 +778,9 @@ fn whole_list_switches_as_one_bundle() { .count(); assert_eq!(branch_bundles, 2, "Both branches should bundle their whole list into one opaque cell"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The bundle, wrap, and unbundle adapters should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(4), context)); + let result: Option> = tree.eval(NodeId(4), &context); let list = result.expect("The whole stack should round-trip through the bundle switch back to a flat List"); let values: Vec = list.iter_element_values().copied().collect(); assert_eq!(values, [1., 2., 3.], "The taken branch's whole list should come through unchanged"); @@ -814,9 +813,9 @@ fn a_bundle_unbundles_into_a_list_connector() { "The base connector should unbundle the whole list" ); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The unbundle adapter should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The unbundle adapter should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(3), context)); + let result: Option> = tree.eval(NodeId(3), &context); assert!(result.is_some(), "The unbundled stack should flow into Extend as a List"); } @@ -856,9 +855,152 @@ fn a_whole_list_of_scalars_switches_as_one_bundle() { .count(); assert_eq!(branch_bundles, 2, "Both scalar-list branches should bundle into one opaque cell"); - let tree = futures::executor::block_on(BorrowTree::new(network, &typing_context)).expect("The bundle, wrap, and unbundle adapters should instantiate"); + let tree = BorrowTree::new(network, &typing_context).expect("The bundle, wrap, and unbundle adapters should instantiate"); let context: Context = None; - let result: Option> = futures::executor::block_on(tree.eval(NodeId(4), context)); + let result: Option> = tree.eval(NodeId(4), &context); let list = result.expect("The whole scalar list should round-trip through the bundle switch"); assert_eq!(list.len(), 2, "The true branch's whole list should be selected and preserved intact"); } + +fn error_traced_through(indices: &[usize]) -> NodeError { + let mut state = Poll::<()>::error("boom"); + for &index in indices { + let status = core_types::Status::new(); + let Err(interrupt) = status.record(index, state) else { unreachable!() }; + state = status.bail(interrupt); + } + let Poll::Error(error) = state else { unreachable!() }; + *error +} + +#[test] +fn a_trace_leads_to_the_node_that_raised_the_error() { + let executor = DynamicExecutor::new(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap(); + + assert_eq!(executor.find_origin(executor.output(), &error_traced_through(&[])), Some(NodeId(1))); + assert_eq!(executor.find_origin(executor.output(), &error_traced_through(&[0])), Some(NodeId(0))); + assert_eq!(executor.find_origin(executor.output(), &error_traced_through(&[0, 0])), None, "a value node has no inputs"); + assert_eq!(executor.find_origin(NodeId(0), &error_traced_through(&[])), Some(NodeId(0))); + assert_eq!(executor.find_origin(NodeId(0), &error_traced_through(&[0])), None, "an upstream trace starts at its parent's origin"); +} + +#[test] +fn a_trace_steps_over_the_index_of_a_promotion_adapter() { + let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::TypeDefault(item!(f64)).into()), vec![NodeId(0)]); + let mut box_corners_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]); + box_corners_node.identifier = graphene_std::vector::generator_nodes::box_corners::IDENTIFIER; + let executor = DynamicExecutor::new(ProtoNetwork { + inputs: vec![], + output: NodeId(1), + nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)], + }) + .unwrap(); + + assert_eq!(executor.find_origin(executor.output(), &error_traced_through(&[0, 0])), Some(NodeId(0))); +} + +#[test] +fn executor_panics_reach_the_host_with_the_original_payload() { + struct Panics; + impl core_types::Node for Panics { + type Output = core_types::registry::Any; + fn eval(&self, _: &core_types::registry::AnyInput) -> Poll { + std::panic::panic_any(42_u32); + } + } + + let mut executor = DynamicExecutor { + output: NodeId(0), + ..Default::default() + }; + let missing_output = (&executor).execute(()).unwrap_err(); + assert_eq!(missing_output.to_string(), "Output node not found in executor"); + + executor.tree.store_node(NodeContainer::new(Box::new(Panics)), NodeId(0), Box::default(), Box::default()); + let payload = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (&executor).execute(()))).unwrap_err(); + assert_eq!(*payload.downcast::().unwrap(), 42); +} + +#[test] +fn chained_fallbacks_both_reach_the_root() { + let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(1.).into()), vec![NodeId(0)]); + let fail_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(1)]); + let mut first = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1)]), vec![NodeId(2)]); + first.identifier = graphene_std::poll_debug::fallback::IDENTIFIER; + let mut second = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2), NodeId(1)]), vec![NodeId(3)]); + second.identifier = graphene_std::poll_debug::fallback::IDENTIFIER; + let executor = DynamicExecutor::new(ProtoNetwork { + inputs: vec![], + output: NodeId(3), + nodes: vec![(NodeId(0), value_node), (NodeId(1), fail_node), (NodeId(2), first), (NodeId(3), second)], + }) + .unwrap(); + + let context: Context = None; + let Ok(Poll::Fallback(boxed)) = (&executor).execute(context) else { + panic!("Both nodes fall back, so the root should too") + }; + let error = &boxed.1; + assert_eq!(executor.find_origin(executor.output(), error), Some(NodeId(3))); + let [upstream] = error.upstream() else { + panic!("The second node's error should carry the first node's error") + }; + assert_eq!(executor.find_origin(NodeId(3), upstream), Some(NodeId(2))); +} + +#[test] +fn an_error_after_a_fallback_keeps_both() { + let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(1.).into()), vec![NodeId(0)]); + let fail_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(1)]); + let mut fallback = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1)]), vec![NodeId(2)]); + fallback.identifier = graphene_std::poll_debug::fallback::IDENTIFIER; + let mut error = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2), NodeId(1)]), vec![NodeId(3)]); + error.identifier = graphene_std::poll_debug::error::IDENTIFIER; + let executor = DynamicExecutor::new(ProtoNetwork { + inputs: vec![], + output: NodeId(3), + nodes: vec![(NodeId(0), value_node), (NodeId(1), fail_node), (NodeId(2), fallback), (NodeId(3), error)], + }) + .unwrap(); + + let context: Context = None; + let Ok(Poll::Error(error)) = (&executor).execute(context) else { + panic!("The failing node should stop the frame") + }; + assert_eq!(executor.find_origin(executor.output(), &error), Some(NodeId(3))); + let [upstream] = error.upstream() else { + panic!("The failing node's error should carry the fallback before it") + }; + assert_eq!(executor.find_origin(NodeId(3), upstream), Some(NodeId(2))); +} + +#[test] +fn a_node_error_names_the_node_that_raised_it() { + let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(1.).into()), vec![NodeId(0)]); + let fail_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(1)]); + let mut error_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1)]), vec![NodeId(2)]); + error_node.identifier = graphene_std::poll_debug::error::IDENTIFIER; + let mut count_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(2)]), vec![NodeId(3)]); + count_node.identifier = graphene_std::poll_debug::evaluation_count::IDENTIFIER; + let executor = DynamicExecutor::new(ProtoNetwork { + inputs: vec![], + output: NodeId(3), + nodes: vec![(NodeId(0), value_node), (NodeId(1), fail_node), (NodeId(2), error_node), (NodeId(3), count_node)], + }) + .expect("The debug nodes should resolve"); + + let context: Context = None; + let Ok(Poll::Error(error)) = (&executor).execute(context) else { + panic!("The failing node should stop the frame") + }; + let origin = executor.find_origin(executor.output(), &error); + assert_eq!(origin, Some(NodeId(2)), "The error should name the failing node, not the root that forwarded it"); + let paths: Vec<_> = executor + .tree() + .source_map() + .iter() + .filter(|(_, (node, _))| Some(*node) == origin) + .map(|(path, _)| path.to_vec()) + .collect(); + assert_eq!(paths, [vec![NodeId(2)]]); +} diff --git a/node-graph/interpreted-executor/src/lib.rs b/node-graph/interpreted-executor/src/lib.rs index ddf05222e5..f0642d2f44 100644 --- a/node-graph/interpreted-executor/src/lib.rs +++ b/node-graph/interpreted-executor/src/lib.rs @@ -5,7 +5,6 @@ pub mod util; #[cfg(test)] mod tests { use core_types::*; - use futures::executor::block_on; #[test] fn double_number() { @@ -46,6 +45,6 @@ mod tests { let compiler = Compiler {}; let protograph = compiler.compile_single(network).expect("Graph should be generated"); - let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err(); + let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err(); } } diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index 7a23e20dd7..aff56cb4f3 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -27,9 +27,10 @@ use graphene_std::vector::misc::{ }; use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification}; -use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type_fut, future}; +use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type}; use node_registry_macros::async_node; use std::collections::HashMap; +use std::sync::Arc; // TODO: turn into hashmap fn node_registry() -> HashMap> { @@ -80,17 +81,19 @@ fn node_registry() -> HashMap, input: Context, fn_params: [Context => List]), // Context nullification #[cfg(feature = "gpu")] - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item>, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => Item]), #[cfg(target_family = "wasm")] - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<&wgpu_executor::WgpuExecutor>, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item>, Context => Item]), - async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item>, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item>, Context => Item]), + async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item, Context => Item]), // ========== // MEMO NODES // ========== @@ -135,13 +138,15 @@ fn node_registry() -> HashMap, input: Context, fn_params: [Context => Item]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<&PlatformEditorApi>]), + async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item>]), + async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), + async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), #[cfg(feature = "gpu")] async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List>]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), - async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<&wgpu_executor::WgpuExecutor>]), - async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item>]), + async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), + async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item>]), async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item]), ]; // The per-connector input adapter, registered per element type: an `Item` or `List` wire passes through unchanged. @@ -158,16 +163,14 @@ fn node_registry() -> HashMap"]), |mut args| { - Box::pin(async move { - let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::downcast_node::(args.pop().unwrap())); - let any: DynAnyNode = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::downcast_node::(args.pop().unwrap())); + let any: DynAnyNode = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { - let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::PanicNode:: + Send>>>::new()); - let params = vec![fn_type_fut!(Context, $ty)]; - let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); + let node = graphene_core::ops::PassthroughNode::new(graphene_std::any::PanicNode::::new()); + let params = vec![fn_type!(Context, $ty)]; + let node_io = NodeIO::::to_node_io(&node, params); node_io }, ) @@ -176,22 +179,20 @@ fn node_registry() -> HashMap"]), |mut args| { - Box::pin(async move { - let node = graphene_core::ops::IntoNode::new( - graphene_std::any::downcast_node::(args.pop().unwrap()), - graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)), - ); - let any: DynAnyNode = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = graphene_core::ops::IntoNode::new( + graphene_std::any::downcast_node::(args.pop().unwrap()), + graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>), + ); + let any: DynAnyNode = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { let node = graphene_core::ops::IntoNode::new( - graphene_std::any::PanicNode:: + Send>>>::new(), - graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>)), + graphene_std::any::PanicNode::::new(), + graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$to>), ); - let params = vec![fn_type_fut!(Context, $from)]; - let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); + let params = vec![fn_type!(Context, $from)]; + let node_io = NodeIO::::to_node_io(&node, params); node_io }, ) @@ -211,22 +212,20 @@ fn node_registry() -> HashMap"]), |mut args| { - Box::pin(async move { - let node = graphene_core::ops::$node::new( - graphene_std::any::downcast_node::(args.pop().unwrap()), - graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>)), - ); - let any: DynAnyNode = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = graphene_core::ops::$node::new( + graphene_std::any::downcast_node::(args.pop().unwrap()), + graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>), + ); + let any: DynAnyNode = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { let node = graphene_core::ops::$node::new( - graphene_std::any::PanicNode:: + Send>>>::new(), - graphene_std::any::FutureWrapperNode::new(graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>)), + graphene_std::any::PanicNode::::new(), + graphene_std::value::ClonedNode::new(std::marker::PhantomData::<$element>), ); - let params = vec![fn_type_fut!(Context, $from)]; - let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); + let params = vec![fn_type!(Context, $from)]; + let node_io = NodeIO::::to_node_io(&node, params); node_io }, ) @@ -238,19 +237,14 @@ fn node_registry() -> HashMap"]), |mut args| { - Box::pin(async move { - let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::downcast_node::>(args.pop().unwrap())); - let any: DynAnyNode, _> = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::downcast_node::>(args.pop().unwrap())); + let any: DynAnyNode, _> = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { - let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::PanicNode::< - Context, - core::pin::Pin> + Send>>, - >::new()); - let params = vec![fn_type_fut!(Context, Item<$element>)]; - let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); + let node = graphene_core::ops::ItemToListNode::new(graphene_std::any::PanicNode::>::new()); + let params = vec![fn_type!(Context, Item<$element>)]; + let node_io = NodeIO::::to_node_io(&node, params); node_io }, ) @@ -262,19 +256,14 @@ fn node_registry() -> HashMap"]), |mut args| { - Box::pin(async move { - let node = graphene_core::ops::BundleNode::new(graphene_std::any::downcast_node::>(args.pop().unwrap())); - let any: DynAnyNode>, _> = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = graphene_core::ops::BundleNode::new(graphene_std::any::downcast_node::>(args.pop().unwrap())); + let any: DynAnyNode>, _> = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { - let node = graphene_core::ops::BundleNode::new(graphene_std::any::PanicNode::< - Context, - core::pin::Pin> + Send>>, - >::new()); - let params = vec![fn_type_fut!(Context, List<$element>)]; - let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); + let node = graphene_core::ops::BundleNode::new(graphene_std::any::PanicNode::>::new()); + let params = vec![fn_type!(Context, List<$element>)]; + let node_io = NodeIO::::to_node_io(&node, params); node_io }, ) @@ -286,19 +275,14 @@ fn node_registry() -> HashMap"]), |mut args| { - Box::pin(async move { - let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::downcast_node::>>(args.pop().unwrap())); - let any: DynAnyNode, _> = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::downcast_node::>>(args.pop().unwrap())); + let any: DynAnyNode, _> = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { - let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::PanicNode::< - Context, - core::pin::Pin>> + Send>>, - >::new()); - let params = vec![fn_type_fut!(Context, Item>)]; - let node_io = NodeIO::<'_, Context>::to_async_node_io(&node, params); + let node = graphene_core::ops::UnbundleNode::new(graphene_std::any::PanicNode::>>::new()); + let params = vec![fn_type!(Context, Item>)]; + let node_io = NodeIO::::to_node_io(&node, params); node_io }, ) @@ -465,7 +449,7 @@ fn node_registry() -> HashMap = vec![ async_node!(identifier: graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => $value]), async_node!(identifier: graphene_core::memo::monitor::IDENTIFIER, graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => $value]), - async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item]), + async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item]), ]; entries }}; @@ -644,19 +628,17 @@ mod node_registry_macros { ( $identifier, |mut args| { - Box::pin(async move { - args.reverse(); - let node = <$path>::new($(graphene_std::any::downcast_node::<$arg, $type>(args.pop().expect("Not enough arguments provided to construct node"))),*); - let any: DynAnyNode<$input, _, _> = graphene_std::any::DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + args.reverse(); + let node = <$path>::new($(graphene_std::any::downcast_node::<$arg, $type>(args.pop().expect("Not enough arguments provided to construct node"))),*); + let any: DynAnyNode<$input, _, _> = graphene_std::any::DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }, { let node = <$path>::new($( - graphene_std::any::PanicNode::<$arg, core::pin::Pin + Send>>>::new() + graphene_std::any::PanicNode::<$arg, $type>::new() ),*); - let params = vec![$(fn_type_fut!($arg, $type)),*]; - let mut node_io = NodeIO::<'_, $input>::to_async_node_io(&node, params); + let params = vec![$(fn_type!($arg, $type)),*]; + let mut node_io = NodeIO::<$input>::to_node_io(&node, params); node_io.call_argument = concrete!(<$input as StaticType>::Static); node_io }, diff --git a/node-graph/interpreted-executor/src/util.rs b/node-graph/interpreted-executor/src/util.rs index 1c48c990cf..b8b1c720f4 100644 --- a/node-graph/interpreted-executor/src/util.rs +++ b/node-graph/interpreted-executor/src/util.rs @@ -5,10 +5,11 @@ use graph_craft::generic; use graph_craft::{concrete, item}; use graphene_std::Context; use graphene_std::ContextFeatures; +use graphene_std::RuntimeHandle; use graphene_std::uuid::NodeId; use std::sync::Arc; -pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc) -> NodeNetwork { +pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc, runtime: RuntimeHandle) -> NodeNetwork { let inner_network = DocumentNode { implementation: DocumentNodeImplementation::Network(network), inputs: vec![], @@ -30,20 +31,20 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc))), + ("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))), ]; - let scope_injections = vec![("editor-api".to_string(), (NodeId(2), item!(&PlatformEditorApi)))]; NodeNetwork { exports: vec![NodeInput::node(NodeId(1), 0)], diff --git a/node-graph/libraries/application-io/src/lib.rs b/node-graph/libraries/application-io/src/lib.rs index b3df3314d3..f06bb4eee1 100644 --- a/node-graph/libraries/application-io/src/lib.rs +++ b/node-graph/libraries/application-io/src/lib.rs @@ -1,5 +1,5 @@ use core_types::transform::Footprint; -use core_types::{Context, OwnedContextImpl}; +use core_types::{Context, Generations, OwnedContextImpl}; use dyn_any::{DynAny, StaticType, StaticTypeSized}; use glam::DVec2; use graphene_hash::CacheHash; @@ -38,20 +38,6 @@ impl ApplicationIo for &T { } } -#[derive(Debug, Clone)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum NodeGraphUpdateMessage {} - -pub trait NodeGraphUpdateSender { - fn send(&self, message: NodeGraphUpdateMessage); -} - -impl NodeGraphUpdateSender for std::sync::Mutex { - fn send(&self, message: NodeGraphUpdateMessage) { - self.lock().as_mut().unwrap().send(message) - } -} - pub trait GetEditorPreferences { fn max_render_region_area(&self) -> u32; } @@ -90,13 +76,9 @@ impl RenderConfig { pub fn into_context(self) -> Context<'static> { OwnedContextImpl::default().with_vararg(Box::new(self)).into_context() } -} -struct Logger; - -impl NodeGraphUpdateSender for Logger { - fn send(&self, message: NodeGraphUpdateMessage) { - log::warn!("dispatching message with fallback node graph update sender {message:?}"); + pub fn into_context_with_generations(self, generations: Generations) -> Context<'static> { + OwnedContextImpl::default().with_vararg(Box::new(self)).with_generations(generations).into_context() } } @@ -111,7 +93,6 @@ impl GetEditorPreferences for DummyPreferences { pub struct EditorApi { /// Gives access to APIs like resources. pub application_io: Option>, - pub node_graph_message_sender: Box, /// Editor preferences made available to the graph through the `PlatformEditorApi`. pub editor_preferences: Box, } @@ -122,7 +103,6 @@ impl Default for EditorApi { fn default() -> Self { Self { application_io: None, - node_graph_message_sender: Box::new(Logger), editor_preferences: Box::new(DummyPreferences), } } @@ -131,7 +111,6 @@ impl Default for EditorApi { impl Hash for EditorApi { fn hash(&self, state: &mut H) { self.application_io.as_ref().map_or(0, |io| io as *const _ as usize).hash(state); - (self.node_graph_message_sender.as_ref() as *const dyn NodeGraphUpdateSender).hash(state); (self.editor_preferences.as_ref() as *const dyn GetEditorPreferences).hash(state); } } @@ -145,7 +124,6 @@ impl CacheHash for EditorApi { impl PartialEq for EditorApi { fn eq(&self, other: &Self) -> bool { self.application_io.as_ref().map_or(0, |io| addr_of!(io) as usize) == other.application_io.as_ref().map_or(0, |io| addr_of!(io) as usize) - && std::ptr::eq(self.node_graph_message_sender.as_ref() as *const _, other.node_graph_message_sender.as_ref() as *const _) && std::ptr::eq(self.editor_preferences.as_ref() as *const _, other.editor_preferences.as_ref() as *const _) } } diff --git a/node-graph/libraries/core-types/Cargo.toml b/node-graph/libraries/core-types/Cargo.toml index c1e4daec7b..865e7f1b82 100644 --- a/node-graph/libraries/core-types/Cargo.toml +++ b/node-graph/libraries/core-types/Cargo.toml @@ -50,6 +50,7 @@ lyon_geom = { workspace = true } log = { workspace = true } base64 = { workspace = true } polycool = { workspace = true } +futures = { workspace = true } # Optional workspace dependencies serde = { workspace = true, optional = true } @@ -58,5 +59,4 @@ wasm-bindgen = { workspace = true, optional = true } [dev-dependencies] # Workspace dependencies -tokio = { workspace = true } serde_json = { workspace = true } diff --git a/node-graph/libraries/core-types/src/context.rs b/node-graph/libraries/core-types/src/context.rs index ab8b022239..2a573bdb50 100644 --- a/node-graph/libraries/core-types/src/context.rs +++ b/node-graph/libraries/core-types/src/context.rs @@ -1,8 +1,10 @@ +use crate::runtime::{Generations, SourceId}; use crate::transform::Footprint; use glam::DVec2; pub use no_std_types::context::{ArcCtx, Ctx}; use std::any::Any; use std::borrow::Borrow; +use std::collections::BTreeSet; use std::hash::{Hash, Hasher}; use std::panic::Location; use std::sync::Arc; @@ -45,6 +47,10 @@ pub trait ExtractVarArgs { fn hash_varargs(&self, hasher: &mut dyn Hasher); } +pub trait ExtractGenerations { + fn try_generations(&self) -> Option<&Generations>; +} + pub trait CloneVarArgs: ExtractVarArgs { // TODO: Consider returning a slice or something like that @@ -77,7 +83,8 @@ pub trait ExtractAll: ExtractPointerPosition + ExtractPosition + ExtractIndex + - ExtractVarArgs {} + ExtractVarArgs + + ExtractGenerations {} impl< T: ?Sized // Extract traits @@ -87,7 +94,8 @@ impl< + ExtractPointerPosition + ExtractPosition + ExtractIndex - + ExtractVarArgs, + + ExtractVarArgs + + ExtractGenerations, > ExtractAll for T { } @@ -125,6 +133,22 @@ impl ModifyPosition for T {} impl ModifyIndex for T {} impl ModifyVarArgs for T {} +// ==================== +// CONTEXT MODIFICATION +// ==================== + +#[derive(Debug, Clone, PartialEq, Eq, Default, graphene_hash::CacheHash, dyn_any::DynAny)] +pub struct ContextModification { + pub features: ContextFeatures, + pub sources: BTreeSet, +} + +impl From for ContextModification { + fn from(features: ContextFeatures) -> Self { + Self { features, sources: BTreeSet::new() } + } +} + // ================ // CONTEXT FEATURES // ================ @@ -292,6 +316,12 @@ impl CloneVarArgs for Option { } } +impl ExtractGenerations for Option { + fn try_generations(&self) -> Option<&Generations> { + self.as_ref().and_then(|x| x.try_generations()) + } +} + // ================================ // EXTRACT TRAIT IMPLS FOR `Arc` // ================================ @@ -346,6 +376,12 @@ impl CloneVarArgs for Arc { } } +impl ExtractGenerations for Arc { + fn try_generations(&self) -> Option<&Generations> { + (**self).try_generations() + } +} + // ============================ // EXTRACT TRAIT IMPLS FOR `&T` // ============================ @@ -425,6 +461,12 @@ impl ExtractVarArgs for ContextImpl<'_> { } } +impl ExtractGenerations for ContextImpl<'_> { + fn try_generations(&self) -> Option<&Generations> { + None + } +} + // ========================================== // EXTRACT TRAIT IMPLS FOR `OwnedContextImpl` // ========================================== @@ -497,6 +539,12 @@ impl ExtractVarArgs for OwnedContextImpl { } } +impl ExtractGenerations for OwnedContextImpl { + fn try_generations(&self) -> Option<&Generations> { + self.generations.as_ref() + } +} + impl CloneVarArgs for Arc { fn arc_clone(&self) -> Option> { Some(self.clone()) @@ -522,6 +570,7 @@ pub struct OwnedContextImpl { // This could be converted into a single enum to save extra bytes index: Option>, varargs: Option>, + generations: Option, } impl std::fmt::Debug for OwnedContextImpl { @@ -534,6 +583,7 @@ impl std::fmt::Debug for OwnedContextImpl { .field("pointer_position", &self.pointer_position) .field("index", &self.index) .field("varargs_len", &self.varargs.as_ref().map(|x| x.len())) + .field("generations", &self.generations) .finish() } } @@ -553,6 +603,7 @@ impl graphene_hash::CacheHash for OwnedContextImpl { self.pointer_position.cache_hash(state); self.position.cache_hash(state); self.index.cache_hash(state); + self.generations.cache_hash(state); self.hash_varargs(state); } } @@ -588,9 +639,20 @@ impl OwnedContextImpl { position, index, varargs: None, + generations: value.try_generations().cloned(), } } + #[track_caller] + pub fn from_modification(value: T, modification: &ContextModification) -> Self { + let mut context = Self::from_flags(value, modification.features); + context.generations = context + .generations + .map(|generations| generations.iter().filter(|(source, _)| modification.sources.contains(source)).copied().collect::()) + .filter(|generations| !generations.is_empty()); + context + } + pub const fn empty() -> Self { OwnedContextImpl { parent: None, @@ -601,6 +663,7 @@ impl OwnedContextImpl { position: None, index: None, varargs: None, + generations: None, } } } @@ -671,6 +734,17 @@ impl OwnedContextImpl { self.varargs = Some(Arc::new([value])); self } + pub fn with_generations(mut self, generations: Generations) -> Self { + self.generations = (!generations.is_empty()).then_some(generations); + self + } + pub fn without_source(mut self, source: SourceId) -> Self { + self.generations = self + .generations + .map(|generations| generations.iter().filter(|(id, _)| *id != source).copied().collect::()) + .filter(|generations| !generations.is_empty()); + self + } pub fn into_context(self) -> Option> { Some(Arc::new(self)) } diff --git a/node-graph/libraries/core-types/src/generic.rs b/node-graph/libraries/core-types/src/generic.rs index 055c0cb53d..8ebfc78ff4 100644 --- a/node-graph/libraries/core-types/src/generic.rs +++ b/node-graph/libraries/core-types/src/generic.rs @@ -1,16 +1,17 @@ use crate::Node; +use crate::poll::Poll; use std::marker::PhantomData; #[derive(Clone)] -pub struct FnNode O, I, O>(T, PhantomData<(I, O)>); +pub struct FnNode O, I, O>(T, PhantomData<(I, O)>); -impl<'i, T: Fn(I) -> O + 'i, O: 'i, I: 'i> Node<'i, I> for FnNode { +impl O, I, O> Node for FnNode { type Output = O; - fn eval(&'i self, input: I) -> Self::Output { - self.0(input) + fn eval(&self, input: &I) -> Poll { + Poll::Final(self.0(input)) } } -impl O, I, O> FnNode { +impl O, I, O> FnNode { pub fn new(f: T) -> Self { FnNode(f, PhantomData) } diff --git a/node-graph/libraries/core-types/src/lib.rs b/node-graph/libraries/core-types/src/lib.rs index 5de86b6f89..60fce46105 100644 --- a/node-graph/libraries/core-types/src/lib.rs +++ b/node-graph/libraries/core-types/src/lib.rs @@ -11,8 +11,10 @@ pub mod memo; pub mod misc; pub mod none; pub mod ops; +pub mod poll; pub mod registry; pub mod render_complexity; +pub mod runtime; pub mod transfer_curve; pub mod transform; pub mod uuid; @@ -39,22 +41,19 @@ pub use no_std_types::choice_type; pub use no_std_types::color; pub use no_std_types::shaders; pub use num_traits; +pub use poll::{Finality, Interrupt, LazyInput, NodeError, Poll, PollInput, Status}; +pub use runtime::{Generations, RuntimeHandle, SourceId}; use std::any::TypeId; -use std::future::Future; -use std::pin::Pin; #[cfg(feature = "wasm")] pub use tsify; pub use types::Cow; -// pub trait Node: for<'n> NodeIO<'n> { /// The node trait allows for defining any node. Nodes can only take one call argument input, however they can store references to other nodes inside the struct. /// See `node-graph/README.md` for information on how to define a new node. -pub trait Node<'i, Input> { - type Output: 'i; +pub trait Node { + type Output; /// Evaluates the node with the single specified input. - fn eval(&'i self, input: Input) -> Self::Output; - /// Resets the node, e.g. the LetNode's cache is set to None. - fn reset(&self) {} + fn eval(&self, input: &Input) -> Poll; /// Returns the name of the node for diagnostic purposes. fn node_name(&self) -> &'static str { std::any::type_name::() @@ -69,9 +68,9 @@ pub trait Node<'i, Input> { mod types; pub use types::*; -pub trait NodeIO<'i, Input>: Node<'i, Input> +pub trait NodeIO: Node where - Self::Output: 'i + StaticTypeSized, + Self::Output: StaticTypeSized, Input: StaticTypeSized, { fn input_type(&self) -> TypeId { @@ -93,56 +92,53 @@ where inputs, } } - fn to_async_node_io(&self, inputs: Vec) -> NodeIOTypes - where - ::Output: StaticTypeSized, - Self::Output: Future, - { - NodeIOTypes { - call_argument: concrete!(::Static), - return_value: future!(<::Output as StaticTypeSized>::Static), - inputs, - } - } } -impl<'i, N: Node<'i, I>, I> NodeIO<'i, I> for N +impl, I> NodeIO for N where - N::Output: 'i + StaticTypeSized, + N::Output: StaticTypeSized, I: StaticTypeSized, { } -impl<'i, I: 'i, N: Node<'i, I> + ?Sized> Node<'i, I> for &'i N { +impl + ?Sized> Node for &N { type Output = N::Output; - fn eval(&'i self, input: I) -> N::Output { - (*self).eval(input) - } -} -impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for Box { - type Output = O; - fn eval(&'i self, input: I) -> O { + #[inline(always)] + fn eval(&self, input: &I) -> Poll { (**self).eval(input) } -} -impl<'i, I: 'i, O: 'i, N: Node<'i, I, Output = O> + ?Sized> Node<'i, I> for std::sync::Arc { - type Output = O; - fn eval(&'i self, input: I) -> O { - (**self).eval(input) + fn node_name(&self) -> &'static str { + (**self).node_name() + } + fn serialize(&self) -> Option> { + (**self).serialize() } } - -impl<'i, I, O: 'i> Node<'i, I> for Pin + 'i>> { - type Output = O; - fn eval(&'i self, input: I) -> O { +impl + ?Sized> Node for Box { + type Output = N::Output; + #[inline(always)] + fn eval(&self, input: &I) -> Poll { (**self).eval(input) } + fn node_name(&self) -> &'static str { + (**self).node_name() + } + fn serialize(&self) -> Option> { + (**self).serialize() + } } -impl<'i, I, O: 'i> Node<'i, I> for Pin<&'i (dyn NodeIO<'i, I, Output = O> + 'i)> { - type Output = O; - fn eval(&'i self, input: I) -> O { +impl + ?Sized> Node for std::sync::Arc { + type Output = N::Output; + #[inline(always)] + fn eval(&self, input: &I) -> Poll { (**self).eval(input) } + fn node_name(&self) -> &'static str { + (**self).node_name() + } + fn serialize(&self) -> Option> { + (**self).serialize() + } } /// A compile-time symbol naming one parameter of one proto node. diff --git a/node-graph/libraries/core-types/src/ops.rs b/node-graph/libraries/core-types/src/ops.rs index 3fb436b015..f5c06e7feb 100644 --- a/node-graph/libraries/core-types/src/ops.rs +++ b/node-graph/libraries/core-types/src/ops.rs @@ -1,49 +1,51 @@ use crate::Node; use crate::math::float_noise::round_away_float_noise; +use crate::poll::Poll; use crate::transform::Footprint; use glam::{DAffine2, DVec2}; -use std::future::Future; use std::marker::PhantomData; // Type // TODO: Document this #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -pub struct TypeNode Node<'a, I>, I, O>(pub N, pub PhantomData<(I, O)>); -impl<'i, N, I: 'i, O: 'i> Node<'i, I> for TypeNode +pub struct TypeNode, I, O>(pub N, pub PhantomData<(I, O)>); +impl Node for TypeNode where - N: for<'n> Node<'n, I, Output = O>, + N: Node, { type Output = O; - fn eval(&'i self, input: I) -> Self::Output { + fn eval(&self, input: &I) -> Poll { self.0.eval(input) } - fn reset(&self) { - self.0.reset(); - } - fn serialize(&self) -> Option> { self.0.serialize() } } -impl<'i, N: for<'a> Node<'a, I>, I: 'i> TypeNode>::Output> { +impl, I> TypeNode>::Output> { pub fn new(node: N) -> Self { Self(node, PhantomData) } } -impl<'i, N: for<'a> Node<'a, I> + Clone, I: 'i> Clone for TypeNode>::Output> { +impl + Clone, I> Clone for TypeNode>::Output> { fn clone(&self) -> Self { Self(self.0.clone(), self.1) } } -impl<'i, N: for<'a> Node<'a, I> + Copy, I: 'i> Copy for TypeNode>::Output> {} +impl + Copy, I> Copy for TypeNode>::Output> {} /// The [`Convert`] trait allows for conversion between Rust primitive numeric types. /// Because number casting is lossy, we cannot use the normal [`Into`] trait like we do for other types. pub trait Convert: Sized { /// Converts this type into the (usually inferred) output type. #[must_use] - fn convert(self, footprint: Footprint, converter: C) -> impl Future + Send; + fn convert(self, footprint: Footprint, converter: C) -> T; +} + +/// Asynchronous version of [`Convert`] +pub trait ConvertAsync: Sized { + #[must_use] + fn convert(self, footprint: Footprint, converter: C) -> impl std::future::Future + Send + 'static; } /// Implements the [`Convert`] trait for formatting a type into a `String` via [`ToString`]. @@ -52,7 +54,7 @@ macro_rules! impl_convert_to_string { $( impl Convert for $from { #[inline] - async fn convert(self, _: Footprint, _converter: ()) -> String { + fn convert(self, _: Footprint, _converter: ()) -> String { self.to_string() } } @@ -64,7 +66,7 @@ impl_convert_to_string!(f32, u32, u64, i32, i64, bool, DVec2, DAffine2); // Denoised so 0.1 + 0.2 reaches the string as "0.3" rather than "0.30000000000000004" impl Convert for f64 { #[inline] - async fn convert(self, _: Footprint, _converter: ()) -> String { + fn convert(self, _: Footprint, _converter: ()) -> String { round_away_float_noise(self).to_string() } } @@ -81,14 +83,14 @@ pub trait FromAnchorPosition { macro_rules! impl_convert { ($from:ty => $to:ty) => { impl Convert<$to, ()> for $from { - async fn convert(self, _: Footprint, _: ()) -> $to { + fn convert(self, _: Footprint, _: ()) -> $to { self as $to } } }; ($from:ty => round $to:ty) => { impl Convert<$to, ()> for $from { - async fn convert(self, _: Footprint, _: ()) -> $to { + fn convert(self, _: Footprint, _: ()) -> $to { self.round() as $to } } @@ -108,7 +110,7 @@ macro_rules! impl_convert { impl_convert!(usize => $to); impl Convert for $to { - async fn convert(self, _: Footprint, _: ()) -> DVec2 { + fn convert(self, _: Footprint, _: ()) -> DVec2 { DVec2::splat(self as f64) } } @@ -145,7 +147,7 @@ macro_rules! impl_convert_from_bool { ($($to:ty),* $(,)?) => { $( impl Convert<$to, ()> for bool { - async fn convert(self, _: Footprint, _: ()) -> $to { + fn convert(self, _: Footprint, _: ()) -> $to { self as u8 as $to } } @@ -158,12 +160,12 @@ impl_convert_from_bool!(f32, f64, i8, u8, u16, i16, i32, u32, i64, u64, i128, u1 mod tests { use super::*; - #[tokio::test] - async fn a_float_narrows_to_the_nearest_integer() { + #[test] + fn a_float_narrows_to_the_nearest_integer() { let footprint = Footprint::default(); - assert_eq!(Convert::::convert(5.999_999_f64, footprint, ()).await, 6, "float noise rounds up to the whole number it meant"); - assert_eq!(Convert::::convert(2.5_f64, footprint, ()).await, 3, "ties round away from zero"); - assert_eq!(Convert::::convert(-1.5_f64, footprint, ()).await, -2); - assert_eq!(Convert::::convert(7_i64, footprint, ()).await, 7., "an integer widens exactly"); + assert_eq!(Convert::::convert(5.999_999_f64, footprint, ()), 6, "float noise rounds up to the whole number it meant"); + assert_eq!(Convert::::convert(2.5_f64, footprint, ()), 3, "ties round away from zero"); + assert_eq!(Convert::::convert(-1.5_f64, footprint, ()), -2); + assert_eq!(Convert::::convert(7_i64, footprint, ()), 7., "an integer widens exactly"); } } diff --git a/node-graph/libraries/core-types/src/poll.rs b/node-graph/libraries/core-types/src/poll.rs new file mode 100644 index 0000000000..6a9889afd0 --- /dev/null +++ b/node-graph/libraries/core-types/src/poll.rs @@ -0,0 +1,429 @@ +#![allow(clippy::inline_always)] + +use crate::Node; +use std::cell::Cell; +use std::error::Error; +use std::sync::Arc; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Poll { + Pending, + Final(T), + Partial(T), + Fallback(Box<(T, NodeError)>), + Error(Box), +} + +impl Poll { + pub fn fallback(value: T, error: impl Into>) -> Self { + Poll::Fallback(Box::new((value, NodeError::new(error)))) + } + + pub fn error(error: impl Into>) -> Self { + Poll::Error(Box::new(NodeError::new(error))) + } + + #[inline(always)] + pub fn map(self, f: impl FnOnce(T) -> U) -> Poll { + match self { + Poll::Pending => Poll::Pending, + Poll::Final(value) => Poll::Final(f(value)), + Poll::Partial(value) => Poll::Partial(f(value)), + Poll::Fallback(boxed) => { + let (value, error) = *boxed; + Poll::Fallback(Box::new((f(value), error))) + } + Poll::Error(error) => Poll::Error(error), + } + } + + pub fn value(self) -> Option { + match self { + Poll::Final(value) | Poll::Partial(value) => Some(value), + Poll::Fallback(boxed) => Some(boxed.0), + Poll::Pending | Poll::Error(_) => None, + } + } +} + +impl From for Poll { + fn from(interrupt: Interrupt) -> Self { + match interrupt { + Interrupt::Pending => Poll::Pending, + Interrupt::Error(error) => Poll::Error(error), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Interrupt { + Pending, + Error(Box), +} + +#[derive(Clone, Debug)] +pub struct NodeError { + error: Arc, + trace: Vec, + upstream: Vec, +} + +impl NodeError { + pub fn new(error: impl Into>) -> Self { + Self { + error: Arc::from(error.into()), + trace: Vec::new(), + upstream: Vec::new(), + } + } + + #[must_use] + pub fn with_upstream(mut self, upstream: Vec) -> Self { + self.upstream = upstream; + self + } + + pub fn track(&mut self, input: usize) { + self.trace.push(input); + } + + #[must_use] + pub fn trace(&self) -> &[usize] { + &self.trace + } + + #[must_use] + pub fn upstream(&self) -> &[NodeError] { + &self.upstream + } + + #[must_use] + pub fn error(&self) -> &Arc { + &self.error + } +} + +impl PartialEq for NodeError { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.error, &other.error) && self.trace == other.trace && self.upstream == other.upstream + } +} + +impl Eq for NodeError {} + +impl std::fmt::Display for NodeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.error.fmt(f) + } +} + +impl Error for NodeError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + self.error.source() + } +} + +impl From for Interrupt { + fn from(error: NodeError) -> Self { + Interrupt::Error(Box::new(error)) + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Finality { + #[default] + Final, + Partial, +} + +#[derive(Default)] +pub struct Status { + finality: Cell, + error: Cell>, + raised: Cell>, + interrupt: Cell>, + no_partial: bool, +} + +impl Status { + #[must_use] + pub fn new() -> Self { + Self::default() + } + + #[must_use] + pub fn no_partial() -> Self { + Self { no_partial: true, ..Self::default() } + } + + pub fn finality(&self) -> Finality { + self.finality.get() + } + + #[inline(always)] + pub fn record(&self, index: usize, state: Poll) -> Result { + match state { + Poll::Final(value) => Ok(value), + Poll::Partial(_) if self.no_partial => Err(self.interrupted(Interrupt::Pending)), + Poll::Partial(value) => { + self.finality.set(Finality::Partial); + Ok(value) + } + Poll::Fallback(boxed) => { + let (value, mut error) = *boxed; + error.track(index); + self.fail(error); + Ok(value) + } + Poll::Pending => Err(self.interrupted(Interrupt::Pending)), + Poll::Error(mut error) => { + error.track(index); + Err(self.interrupted(Interrupt::Error(error))) + } + } + } + + pub fn fail(&self, error: NodeError) { + let first = self.error.take(); + self.error.set(first.or(Some(error))); + } + + pub fn raise(&self, error: NodeError) { + let first = self.raised.take(); + self.raised.set(first.or(Some(error))); + } + + #[inline(always)] + pub fn run(self, kernel: impl FnOnce(&Self) -> Result) -> Poll { + match kernel(&self) { + Ok(value) => self.finish(value), + Err(interrupt) => self.bail(interrupt), + } + } + + #[inline(always)] + pub fn finish(self, value: T) -> Poll { + match (self.finality.get(), self.raised.take(), self.error.take()) { + (Finality::Partial, _, _) => Poll::Partial(value), + (Finality::Final, Some(mut raised), input) => { + raised.upstream.extend(input); + Poll::Fallback(Box::new((value, raised))) + } + (Finality::Final, None, Some(error)) => Poll::Fallback(Box::new((value, error))), + (Finality::Final, None, None) => Poll::Final(value), + } + } + + #[inline(always)] + pub fn merge(self, poll: Poll) -> Poll { + match poll { + Poll::Final(value) => self.finish(value), + Poll::Partial(_) if self.no_partial => self.bail(Interrupt::Pending), + Poll::Partial(value) => { + self.finality.set(Finality::Partial); + self.finish(value) + } + Poll::Fallback(boxed) => { + let (value, error) = *boxed; + self.fail(error); + self.finish(value) + } + Poll::Pending => self.bail(Interrupt::Pending), + Poll::Error(error) => self.bail(Interrupt::Error(error)), + } + } + + #[inline(always)] + pub fn bail(self, interrupt: Interrupt) -> Poll { + match (self.interrupt.take(), interrupt) { + (Some(Interrupt::Error(error)), _) => Poll::Error(error), + (_, Interrupt::Error(_)) if self.finality.get() == Finality::Partial => Poll::Pending, + (_, Interrupt::Error(mut error)) => { + if error.trace.is_empty() { + error.upstream.extend(self.error.take()); + } + Poll::Error(error) + } + (_, Interrupt::Pending) => Poll::Pending, + } + } + + fn interrupted(&self, interrupt: Interrupt) -> Interrupt { + let strongest = match (self.interrupt.take(), &interrupt) { + (Some(Interrupt::Error(error)), _) => Interrupt::Error(error), + _ => interrupt.clone(), + }; + self.interrupt.set(Some(strongest)); + interrupt + } +} + +pub struct LazyInput<'a, N> { + node: &'a N, + status: &'a Status, + index: usize, +} + +impl Clone for LazyInput<'_, N> { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for LazyInput<'_, N> {} + +impl<'a, N> LazyInput<'a, N> { + pub fn new(node: &'a N, status: &'a Status, index: usize) -> Self { + Self { node, status, index } + } + + #[inline(always)] + pub fn eval(&self, input: Input) -> Result + where + N: Node, + { + self.status.record(self.index, self.node.eval(&input)) + } +} + +pub struct PollInput<'a, N> { + node: &'a N, + index: usize, +} + +impl<'a, N> PollInput<'a, N> { + pub fn new(node: &'a N, index: usize) -> Self { + Self { node, index } + } +} + +impl> Node for PollInput<'_, N> { + type Output = N::Output; + + #[inline(always)] + fn eval(&self, input: &I) -> Poll { + let mut state = self.node.eval(input); + match &mut state { + Poll::Fallback(boxed) => boxed.1.track(self.index), + Poll::Error(error) => error.track(self.index), + Poll::Pending | Poll::Final(_) | Poll::Partial(_) => {} + } + state + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + fn add(a: Poll, b: Poll) -> Poll { + Status::new().run(|cell| { + let a = cell.record(0, a); + let b = cell.record(1, b); + Ok(a? + b?) + }) + } + + #[test] + fn a_pointer_payload_fits_one_tag_and_one_word() { + assert_eq!(size_of::>>(), 16); + assert_eq!(size_of::>(), 16); + } + + #[test] + fn statuses_meet_through_the_cell() { + assert_eq!(add(Poll::Final(1), Poll::Final(2)), Poll::Final(3)); + assert_eq!(add(Poll::Final(1), Poll::Partial(2)), Poll::Partial(3)); + assert_eq!(add(Poll::Pending, Poll::Final(2)), Poll::Pending); + + let Poll::Fallback(boxed) = add(Poll::Final(1), Poll::fallback(2, "boom")) else { unreachable!() }; + assert_eq!(boxed.0, 3); + assert_eq!(boxed.1.trace(), [1]); + + let Poll::Error(error) = add(Poll::Pending, Poll::error("boom")) else { unreachable!() }; + assert_eq!(error.trace(), [1]); + } + + #[test] + fn provisional_inputs_hold_kernel_errors_back() { + let parse = |text: Poll<&str>| { + Status::new().run(|cell| { + let text = cell.record(0, text)?; + text.parse::().map_err(|error| NodeError::new(error).into()) + }) + }; + assert_eq!(parse(Poll::Partial("")), Poll::Pending); + assert_eq!(parse(Poll::Partial("7")), Poll::Partial(7)); + assert!(matches!(parse(Poll::Final("")), Poll::Error(_))); + + assert_eq!(add(Poll::Partial(1), Poll::fallback(2, "boom")), Poll::Partial(3)); + + let Poll::Error(error) = add(Poll::Partial(1), Poll::error("boom")) else { unreachable!() }; + assert_eq!(error.trace(), [1]); + } + + #[test] + fn an_error_keeps_its_message() { + let Poll::Error(error) = add(Poll::Final(1), Poll::error(format!("no response from {}", "example.com"))) else { + unreachable!() + }; + assert_eq!(error.to_string(), "no response from example.com"); + + let parse_error = "x".parse::().unwrap_err(); + let Poll::Error(error) = add(Poll::error(parse_error), Poll::Final(2)) else { unreachable!() }; + assert_eq!(error.trace(), [0]); + let error: Box = error; + assert_eq!(error.to_string(), "invalid digit found in string"); + } + + #[test] + fn a_raised_error_carries_the_input_error_upstream() { + let Poll::Fallback(boxed) = Status::new().run(|cell| { + let value = cell.record(0, Poll::fallback(1, "input"))?; + cell.raise(NodeError::new("own")); + Ok(value) + }) else { + unreachable!() + }; + let error = boxed.1; + assert_eq!(error.to_string(), "own"); + assert!(error.trace().is_empty()); + let [upstream] = error.upstream() else { unreachable!() }; + assert_eq!(upstream.to_string(), "input"); + assert_eq!(upstream.trace(), [0]); + } + + #[test] + fn a_failing_node_carries_the_input_error_upstream() { + let Poll::Error(error) = Status::new().run(|cell| -> Result { + cell.record(0, Poll::fallback(1, "input"))?; + Err(NodeError::new("own").into()) + }) else { + unreachable!() + }; + assert_eq!(error.to_string(), "own"); + let [upstream] = error.upstream() else { unreachable!() }; + assert_eq!(upstream.to_string(), "input"); + assert_eq!(upstream.trace(), [0]); + + let Poll::Error(error) = add(Poll::fallback(1, "first"), Poll::error("second")) else { + unreachable!() + }; + assert!(error.upstream().is_empty(), "an input's error is passed on, not raised"); + } + + #[test] + fn an_unrecorded_input_does_not_touch_the_status() { + let switch = |take_first: bool| { + Status::new().run(|cell| { + let first = || cell.record(0, Poll::Final(1)); + let second = || cell.record(1, Poll::Partial(2)); + if take_first { first() } else { second() } + }) + }; + assert_eq!(switch(true), Poll::Final(1)); + assert_eq!(switch(false), Poll::Partial(2)); + assert_eq!(Status::no_partial().run(|cell| cell.record(0, Poll::Partial(1))), Poll::Pending); + } +} diff --git a/node-graph/libraries/core-types/src/registry.rs b/node-graph/libraries/core-types/src/registry.rs index cf2b57ea6c..870a5cae0a 100644 --- a/node-graph/libraries/core-types/src/registry.rs +++ b/node-graph/libraries/core-types/src/registry.rs @@ -1,9 +1,8 @@ -use crate::{Color, ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend}; -use dyn_any::{DynAny, StaticType}; +use crate::poll::Poll; +use crate::{Color, ContextFeature, Node, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend}; use std::collections::HashMap; use std::marker::PhantomData; use std::ops::Deref; -use std::pin::Pin; use std::sync::{LazyLock, Mutex}; // Translation struct between macro and definition @@ -18,6 +17,7 @@ pub struct NodeMetadata { pub context_features: Vec, pub memoize: bool, pub inject_scope: bool, + pub asynchronous: bool, pub output_fields: Option, } @@ -63,6 +63,7 @@ pub enum RegistryValueSource { None, Default(&'static str), Scope(&'static str), + SourceId, } #[derive(Clone, Debug)] @@ -174,28 +175,24 @@ pub static MULTI_OUTPUT_NODES: LazyLock = Pin + 'n + Send>>; +pub type Any = Box; #[cfg(target_family = "wasm")] -pub type DynFuture<'n, T> = Pin + 'n>>; -pub type LocalFuture<'n, T> = Pin + 'n>>; +pub type Any = Box; #[cfg(not(target_family = "wasm"))] -pub type Any<'n> = Box + 'n + Send>; +pub type AnyInput = dyn std::any::Any + Send; #[cfg(target_family = "wasm")] -pub type Any<'n> = Box + 'n>; -pub type FutureAny<'n> = DynFuture<'n, Any<'n>>; +pub type AnyInput = dyn std::any::Any; // TODO: is this safe? This is assumed to be send+sync. #[cfg(not(target_family = "wasm"))] -pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n + Send + Sync; +pub type TypeErasedNode<'n> = dyn Node + 'n + Send + Sync; #[cfg(target_family = "wasm")] -pub type TypeErasedNode<'n> = dyn for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + 'n; -pub type TypeErasedPinnedRef<'n> = Pin<&'n TypeErasedNode<'n>>; +pub type TypeErasedNode<'n> = dyn Node + 'n; pub type TypeErasedRef<'n> = &'n TypeErasedNode<'n>; pub type TypeErasedBox<'n> = Box>; -pub type TypeErasedPinned<'n> = Pin>>; pub type SharedNodeContainer = std::sync::Arc; -pub type NodeConstructor = fn(Vec) -> DynFuture<'static, TypeErasedBox<'static>>; +pub type NodeConstructor = fn(Vec) -> TypeErasedBox<'static>; #[derive(Clone)] pub struct NodeContainer { @@ -255,35 +252,27 @@ impl NodeContainer { } } -/// Boxes the input and downcasts the output. -/// Wraps around a node taking Box and returning Box +/// Erases the input and downcasts the output. +/// Wraps around a node taking `&dyn Any` and returning `Box` #[derive(Clone)] pub struct DowncastBothNode { node: SharedNodeContainer, _i: PhantomData, _o: PhantomData, } -impl<'input, O, I> Node<'input, I> for DowncastBothNode +impl Node for DowncastBothNode where - O: 'input + StaticType + WasmNotSend, - I: 'input + StaticType + WasmNotSend, + I: 'static + WasmNotSend, + O: 'static + WasmNotSend, { - type Output = DynFuture<'input, O>; + type Output = O; #[inline] - #[track_caller] - fn eval(&'input self, input: I) -> Self::Output { - { - let node_name = self.node.node_name(); - let input = Box::new(input); - let future = self.node.eval(input); - Box::pin(async move { - let out = dyn_any::downcast(future.await).unwrap_or_else(|e| panic!("DowncastBothNode wrong output type: {e} in: \n{node_name}")); - *out - }) - } - } - fn reset(&self) { - self.node.reset(); + fn eval(&self, input: &I) -> Poll { + self.node.eval(input).map(|output| { + *output + .downcast::() + .unwrap_or_else(|_| panic!("DowncastBothNode wrong output type: expected {} in: \n{}", std::any::type_name::(), self.node.node_name())) + }) } fn serialize(&self) -> Option> { @@ -299,36 +288,6 @@ impl DowncastBothNode { } } } -pub struct FutureWrapperNode { - node: Node, -} - -impl<'i, T: 'i + WasmNotSend, N> Node<'i, T> for FutureWrapperNode -where - N: Node<'i, T, Output: WasmNotSend> + WasmNotSend, -{ - type Output = DynFuture<'i, N::Output>; - #[inline(always)] - fn eval(&'i self, input: T) -> Self::Output { - let result = self.node.eval(input); - Box::pin(async move { result }) - } - #[inline(always)] - fn reset(&self) { - self.node.reset(); - } - - #[inline(always)] - fn serialize(&self) -> Option> { - self.node.serialize() - } -} - -impl FutureWrapperNode { - pub const fn new(node: N) -> Self { - Self { node } - } -} pub struct DynAnyNode { node: Node, @@ -336,40 +295,26 @@ pub struct DynAnyNode { _o: PhantomData, } -impl<'input, I, O, N> Node<'input, Any<'input>> for DynAnyNode +impl Node for DynAnyNode where - I: 'input + StaticType + WasmNotSend, - O: 'input + StaticType + WasmNotSend, - N: 'input + Node<'input, I, Output = DynFuture<'input, O>>, + I: 'static, + O: 'static + WasmNotSend, + N: Node, { - type Output = FutureAny<'input>; + type Output = Any; #[inline] - fn eval(&'input self, input: Any<'input>) -> Self::Output { - let node_name = std::any::type_name::(); - let output = |input| { - let result = self.node.eval(input); - async move { Box::new(result.await) as Any<'input> } - }; - match dyn_any::downcast(input) { - Ok(input) => Box::pin(output(*input)), - Err(e) => panic!("DynAnyNode Input, {e} in:\n{node_name}"), - } - } - - fn reset(&self) { - self.node.reset(); + fn eval(&self, input: &AnyInput) -> Poll { + let input = input + .downcast_ref::() + .unwrap_or_else(|| panic!("DynAnyNode Input: expected {} in:\n{}", std::any::type_name::(), std::any::type_name::())); + self.node.eval(input).map(|output| Box::new(output) as Any) } fn serialize(&self) -> Option> { self.node.serialize() } } -impl<'input, I, O, N> DynAnyNode -where - I: 'input + StaticType, - O: 'input + StaticType, - N: 'input + Node<'input, I, Output = DynFuture<'input, O>>, -{ +impl DynAnyNode { pub const fn new(node: N) -> Self { Self { node, @@ -380,9 +325,9 @@ where } pub struct PanicNode(PhantomData, PhantomData); -impl<'i, I: 'i + WasmNotSend, O: 'i + WasmNotSend> Node<'i, I> for PanicNode { +impl Node for PanicNode { type Output = O; - fn eval(&'i self, _: I) -> Self::Output { + fn eval(&self, _: &I) -> Poll { unimplemented!("This node should never be evaluated") } } diff --git a/node-graph/libraries/core-types/src/runtime.rs b/node-graph/libraries/core-types/src/runtime.rs new file mode 100644 index 0000000000..346cbabfdb --- /dev/null +++ b/node-graph/libraries/core-types/src/runtime.rs @@ -0,0 +1,362 @@ +use crate::poll::Poll; +use crate::uuid::NodeId; +use dyn_any::WasmNotSend; +use futures::future::{AbortHandle, Abortable}; +use std::collections::HashMap; +use std::future::Future; +use std::hash::{Hash, Hasher}; +use std::pin::Pin; +use std::sync::{Arc, Mutex, PoisonError}; +use std::task::{Context, Waker}; + +#[cfg(not(target_family = "wasm"))] +pub type Task = Pin + Send + 'static>>; +#[cfg(target_family = "wasm")] +pub type Task = Pin + 'static>>; + +pub trait Spawn { + fn spawn(&self, task: Task); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)] +pub struct SourceId(pub u64); + +impl SourceId { + #[must_use] + pub fn from_path(path: &[NodeId]) -> Self { + let mut hasher = rustc_hash::FxHasher::default(); + path.hash(&mut hasher); + Self(hasher.finish()) + } +} + +pub type Generations = Arc<[(SourceId, u64)]>; + +pub trait Runtime { + fn spawn(&self, source: SourceId, task: Task); +} + +#[derive(Clone, dyn_any::DynAny)] +pub struct RuntimeHandle(Arc); + +impl Runtime for RuntimeHandle { + fn spawn(&self, source: SourceId, task: Task) { + self.0.spawn(source, task); + } +} + +impl std::fmt::Debug for RuntimeHandle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RuntimeHandle").finish_non_exhaustive() + } +} + +impl PartialEq for RuntimeHandle { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +impl graphene_hash::CacheHash for RuntimeHandle { + fn cache_hash(&self, state: &mut H) { + state.write_usize(Arc::as_ptr(&self.0) as usize); + } +} + +pub struct AsyncRuntime(Arc); + +impl AsyncRuntime { + pub fn new(spawner: Arc) -> Self { + Self(Arc::new(RuntimeInner { + generations: Mutex::default(), + spawner, + })) + } + + pub fn retain_sources(&self, live: &[SourceId]) { + let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner); + generations.retain(|source, _| live.contains(source)); + for source in live { + generations.entry(*source).or_insert(0); + } + } + + pub fn snapshot(&self) -> Generations { + let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner); + let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect(); + snapshot.sort_unstable(); + snapshot.into() + } + + #[must_use] + pub fn handle(&self) -> RuntimeHandle { + RuntimeHandle(Arc::clone(&self.0)) + } +} + +impl Runtime for AsyncRuntime { + fn spawn(&self, source: SourceId, task: Task) { + self.0.spawn(source, task); + } +} + +struct RuntimeInner { + generations: Mutex>, + spawner: Arc, +} + +impl RuntimeInner { + fn spawn(self: &Arc, source: SourceId, task: Task) { + let inner = Arc::clone(self); + self.spawner.spawn(Box::pin(async move { + task.await; + if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) { + *generation += 1; + } + })); + } +} + +pub struct Slots(Arc>>>); + +enum Slot { + Ready(Poll), + Pending(AbortHandle), +} + +impl Drop for Slot { + fn drop(&mut self) { + if let Slot::Pending(task) = self { + task.abort(); + } + } +} + +impl Default for Slots { + fn default() -> Self { + Self(Arc::default()) + } +} + +impl Clone for Slots { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl std::fmt::Debug for Slots { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Slots").finish_non_exhaustive() + } +} + +impl Slots { + pub fn resolve(&self, key: u64, runtime: &dyn Runtime, source: SourceId, placeholder: Option, future: impl FnOnce() -> F) -> Poll + where + F: Future> + WasmNotSend + 'static, + { + match self.0.lock().unwrap_or_else(PoisonError::into_inner).get(&key) { + Some(Slot::Ready(landed)) => return landed.clone(), + Some(Slot::Pending(_)) => return placeholder.map_or(Poll::Pending, Poll::Partial), + None => {} + } + + // Fast path for futures that are ready immediately + // TODO(Timon): check if this would ever cause a problem; running a future on the graph executor thread might also be a bit wierd + let mut future = Box::pin(future()); + if let std::task::Poll::Ready(state) = future.as_mut().poll(&mut Context::from_waker(Waker::noop())) { + self.0.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state.clone())); + return state; + } + + let (handle, registration) = AbortHandle::new_pair(); + let slots = Arc::downgrade(&self.0); + runtime.spawn( + source, + Box::pin(async move { + if let Ok(state) = Abortable::new(future, registration).await + && let Some(slots) = slots.upgrade() + { + slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state)); + } + }), + ); + let mut slots = self.0.lock().unwrap_or_else(PoisonError::into_inner); + match slots.get(&key) { + Some(Slot::Ready(landed)) => landed.clone(), + _ => { + slots.insert(key, Slot::Pending(handle)); + placeholder.map_or(Poll::Pending, Poll::Partial) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + fn poll_once(task: &mut Task) -> bool { + task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready() + } + + #[derive(Default)] + struct CollectSpawner(Mutex>); + + impl Spawn for CollectSpawner { + fn spawn(&self, task: Task) { + self.0.lock().unwrap().push(task); + } + } + + impl CollectSpawner { + fn drain(&self) -> usize { + let tasks = std::mem::take(&mut *self.0.lock().unwrap()); + let count = tasks.len(); + for mut task in tasks { + while !poll_once(&mut task) {} + } + count + } + } + + struct BlockingSpawner; + + impl Spawn for BlockingSpawner { + fn spawn(&self, mut task: Task) { + while !poll_once(&mut task) {} + } + } + + struct YieldOnce(bool); + + impl Future for YieldOnce { + type Output = (); + fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> std::task::Poll<()> { + if self.0 { + return std::task::Poll::Ready(()); + } + self.0 = true; + context.waker().wake_by_ref(); + std::task::Poll::Pending + } + } + + const SOURCE: SourceId = SourceId(7); + + #[test] + fn a_completion_bumps_its_generation() { + let spawner = Arc::new(CollectSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.retain_sources(&[SOURCE]); + + runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false))); + assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]); + + assert_eq!(spawner.drain(), 1); + assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]); + } + + #[test] + fn retaining_sources_keeps_live_generations() { + let spawner = Arc::new(CollectSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.retain_sources(&[SOURCE]); + runtime.spawn(SOURCE, Box::pin(YieldOnce(false))); + spawner.drain(); + + runtime.retain_sources(&[SOURCE, SourceId(9)]); + assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1), (SourceId(9), 0)]); + + runtime.retain_sources(&[SourceId(9)]); + assert_eq!(&*runtime.snapshot(), &[(SourceId(9), 0)]); + } + + #[test] + fn an_inline_completion_and_a_dropped_source_bump_nothing() { + let spawner = Arc::new(CollectSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.retain_sources(&[SOURCE]); + + let slots = Slots::default(); + assert_eq!(slots.resolve(1, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1)); + assert_eq!(spawner.drain(), 0); + assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]); + + runtime.spawn(SOURCE, Box::pin(YieldOnce(false))); + runtime.retain_sources(&[]); + assert_eq!(spawner.drain(), 1); + assert!(runtime.snapshot().is_empty()); + } + + #[test] + fn a_slot_serves_the_placeholder_until_the_response_lands() { + let spawner = Arc::new(CollectSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + runtime.retain_sources(&[SOURCE]); + let slots = Slots::default(); + let fetch = || async { + YieldOnce(false).await; + Poll::Final(42u32) + }; + + assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Partial(0)); + assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending); + assert_eq!(spawner.drain(), 1, "an in-flight slot is not spawned twice"); + assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42)); + assert_eq!(slots.resolve(2, &runtime, SOURCE, None, || async { Poll::Final(1u32) }), Poll::Final(1)); + } + + #[test] + fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() { + let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner)); + runtime.retain_sources(&[SOURCE]); + let slots = Slots::default(); + let fetch = || async { + YieldOnce(false).await; + Poll::Final(42u32) + }; + + assert_eq!(slots.resolve(1, &runtime, SOURCE, Some(0), fetch), Poll::Final(42)); + assert_eq!(&*runtime.snapshot(), &[(SOURCE, 1)]); + } + + #[test] + fn a_clone_keeps_the_task_running() { + let spawner = Arc::new(CollectSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + let slots = Slots::default(); + let fetch = || async { + YieldOnce(false).await; + Poll::Final(42u32) + }; + + assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending); + let clone = slots.clone(); + drop(slots); + assert_eq!(spawner.drain(), 1); + assert_eq!(clone.resolve(1, &runtime, SOURCE, None, fetch), Poll::Final(42)); + } + + #[test] + fn dropping_the_last_clone_aborts_the_task() { + let spawner = Arc::new(CollectSpawner::default()); + let runtime = AsyncRuntime::new(spawner.clone()); + let slots = Slots::default(); + let finished = Arc::new(AtomicBool::new(false)); + let fetch = || { + let finished = Arc::clone(&finished); + async move { + YieldOnce(false).await; + finished.store(true, Ordering::Relaxed); + Poll::Final(42u32) + } + }; + + assert_eq!(slots.resolve(1, &runtime, SOURCE, None, fetch), Poll::Pending); + drop(slots); + assert_eq!(spawner.drain(), 1); + assert!(!finished.load(Ordering::Relaxed)); + } +} diff --git a/node-graph/libraries/core-types/src/types.rs b/node-graph/libraries/core-types/src/types.rs index bccf8c641a..2c27584124 100644 --- a/node-graph/libraries/core-types/src/types.rs +++ b/node-graph/libraries/core-types/src/types.rs @@ -60,19 +60,6 @@ macro_rules! list { }; } -// The `List<...>`/`Item<...>` rules must appear before the generic `$type:ty` rules, and in each macro that sees the literal tokens, -// because a type captured as `ty` becomes opaque to any inner macro's ranked pattern -#[macro_export] -macro_rules! future { - (List<$inner:ty>) => { - $crate::Type::Future(Box::new($crate::list!($inner))) - }; - (Item<$inner:ty>) => { - $crate::Type::Future(Box::new($crate::item!($inner))) - }; - ($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }}; -} - #[macro_export] macro_rules! fn_type { (List<$inner:ty>) => { @@ -94,27 +81,6 @@ macro_rules! fn_type { $crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type))) }; } -#[macro_export] -macro_rules! fn_type_fut { - (List<$inner:ty>) => { - $crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::list!($inner))))) - }; - (Item<$inner:ty>) => { - $crate::Type::Fn(Box::new(concrete!(())), Box::new($crate::Type::Future(Box::new($crate::item!($inner))))) - }; - ($type:ty) => { - $crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type))) - }; - ($in_type:ty, List<$inner:ty>) => { - $crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner))))) - }; - ($in_type:ty, Item<$inner:ty>) => { - $crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner))))) - }; - ($in_type:ty, $type:ty) => { - $crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type))) - }; -} // TODO: Rename to NodeSignatureMonomorphization #[derive(Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash, Default)] @@ -269,8 +235,6 @@ pub enum Type { Concrete(TypeDescriptor), /// Runtime type information for a function. Given some input, gives some output. Fn(Box, Box), - /// Represents a future which promises to return the inner type. - Future(Box), /// Represents a recursive [Type] allowing nested levels of types to represent the type of an Item. Item(Box), /// Represents a list of this recursive [Type] allowing nested levels of types to represent the type of a List. @@ -346,7 +310,6 @@ impl Type { Self::Generic(_) => None, Self::Concrete(ty) => Some(ty.size), Self::Fn(_, _) => None, - Self::Future(_) => None, Self::Item(_) => None, Self::List(_) => None, } @@ -357,7 +320,6 @@ impl Type { Self::Generic(_) => None, Self::Concrete(ty) => Some(ty.align), Self::Fn(_, _) => None, - Self::Future(_) => None, Self::Item(_) => None, Self::List(_) => None, } @@ -368,7 +330,6 @@ impl Type { Self::Generic(_) => self, Self::Concrete(_) => self, Self::Fn(_, output) => output.nested_type(), - Self::Future(output) => output.nested_type(), Self::Item(_) => self, Self::List(_) => self, } @@ -382,7 +343,6 @@ impl Type { Self::Generic(_) => None, Self::Concrete(_) => None, Self::Fn(_, output) => output.replace_nested(f), - Self::Future(output) => output.replace_nested(f), Self::Item(_) => None, Self::List(_) => None, } @@ -393,7 +353,6 @@ impl Type { Type::Generic(name) => name.to_string(), Type::Concrete(ty) => simplify_identifier_name(&ty.name), Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()), - Type::Future(ty) => ty.identifier_name(), Type::Item(element) => element.identifier_name(), Type::List(element) => format!("{}[]", element.identifier_name()), } @@ -445,7 +404,6 @@ impl Type { Type::Concrete(descriptor) } Type::Fn(input, output) => Type::Fn(Box::new(input.normalize_rank()), Box::new(output.normalize_rank())), - Type::Future(inner) => Type::Future(Box::new(inner.normalize_rank())), Type::Item(element) => Type::Item(Box::new(element.normalize_rank())), Type::List(element) => Type::List(Box::new(element.normalize_rank())), Type::Generic(_) => self, @@ -566,7 +524,6 @@ impl std::fmt::Display for Type { Type::Generic(name) => write!(f, "{}", make_type_user_readable(name)), Type::Concrete(ty) => write!(f, "{ty}"), Type::Fn(_, return_value) => write!(f, "{return_value}"), - Type::Future(ty) => write!(f, "{ty}"), Type::Item(element) => write!(f, "{element}"), Type::List(element) => write!(f, "{element}[]"), } diff --git a/node-graph/libraries/core-types/src/value.rs b/node-graph/libraries/core-types/src/value.rs index 51e9d5490c..26bdd4e62c 100644 --- a/node-graph/libraries/core-types/src/value.rs +++ b/node-graph/libraries/core-types/src/value.rs @@ -1,102 +1,15 @@ +use crate::Node; use crate::list::Item; -use crate::registry::DynFuture; -use crate::{Node, WasmNotSend}; -use std::cell::{Cell, RefCell, RefMut}; -use std::marker::PhantomData; - -#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub struct IntNode; - -impl<'i, const N: u32, I> Node<'i, I> for IntNode { - type Output = u32; - #[inline(always)] - fn eval(&'i self, _input: I) -> Self::Output { - N - } -} - -#[derive(Default, Debug, Clone, Copy)] -pub struct ValueNode(pub T); - -impl<'i, T: 'i, I> Node<'i, I> for ValueNode { - type Output = &'i T; - #[inline(always)] - fn eval(&'i self, _input: I) -> Self::Output { - &self.0 - } -} - -impl ValueNode { - pub const fn new(value: T) -> ValueNode { - ValueNode(value) - } -} - -impl From for ValueNode { - fn from(value: T) -> Self { - ValueNode::new(value) - } -} - -#[derive(Default, Debug, Clone, Copy)] -pub struct AsRefNode, U>(pub T, PhantomData); - -impl<'i, T: 'i + AsRef, U: 'i> Node<'i, ()> for AsRefNode { - type Output = &'i U; - #[inline(always)] - fn eval(&'i self, _input: ()) -> Self::Output { - self.0.as_ref() - } -} - -impl, U> AsRefNode { - pub const fn new(value: T) -> AsRefNode { - AsRefNode(value, PhantomData) - } -} - -#[derive(Default, Debug, Clone)] -pub struct RefCellMutNode(pub RefCell); - -impl<'i, T: 'i> Node<'i, ()> for RefCellMutNode { - type Output = RefMut<'i, T>; - #[inline(always)] - fn eval(&'i self, _input: ()) -> Self::Output { - self.0.borrow_mut() - } -} - -impl RefCellMutNode { - pub const fn new(value: T) -> RefCellMutNode { - RefCellMutNode(RefCell::new(value)) - } -} - -#[derive(Default)] -pub struct OnceCellNode(pub Cell); - -impl<'i, T: Default + 'i, I> Node<'i, I> for OnceCellNode { - type Output = T; - #[inline(always)] - fn eval(&'i self, _input: I) -> Self::Output { - self.0.replace(T::default()) - } -} - -impl OnceCellNode { - pub const fn new(value: T) -> OnceCellNode { - OnceCellNode(Cell::new(value)) - } -} +use crate::poll::Poll; #[derive(Clone, Copy)] pub struct ClonedNode(pub T); -impl<'i, T: Clone + 'i, I> Node<'i, I> for ClonedNode { +impl Node for ClonedNode { type Output = T; #[inline(always)] - fn eval(&'i self, _input: I) -> Self::Output { - self.0.clone() + fn eval(&self, _input: &I) -> Poll { + Poll::Final(self.0.clone()) } } @@ -112,17 +25,16 @@ impl From for ClonedNode { } } -/// Yields a precomputed `Item` as a ready future, ignoring its input context. +/// Yields a precomputed `Item`, ignoring its input context. /// Generated list-content variants feed each already-evaluated content slot through this so the kernel's own /// context modifications become no-ops (the slot was evaluated once, up front, at the ambient footprint). pub struct PrecomputedItemNode(pub Item); -impl<'i, T: Clone + WasmNotSend + 'i, I: 'i> Node<'i, I> for PrecomputedItemNode { - type Output = DynFuture<'i, Item>; +impl Node for PrecomputedItemNode { + type Output = Item; #[inline(always)] - fn eval(&'i self, _input: I) -> Self::Output { - let item = self.0.clone(); - Box::pin(async move { item }) + fn eval(&self, _input: &I) -> Poll> { + Poll::Final(self.0.clone()) } } @@ -131,103 +43,3 @@ impl PrecomputedItemNode { Self(item) } } - -#[derive(Clone, Copy)] -/// The DebugClonedNode logs every time it is evaluated. -/// This is useful for debugging. -pub struct DebugClonedNode(pub T); - -impl<'i, T: Clone + 'i> Node<'i, ()> for DebugClonedNode { - type Output = T; - #[inline(always)] - fn eval(&'i self, _input: ()) -> Self::Output { - // KEEP THIS `debug!()` - It acts as the output for the debug node itself - log::debug!("DebugClonedNode::eval"); - - self.0.clone() - } -} - -impl DebugClonedNode { - pub const fn new(value: T) -> DebugClonedNode { - DebugClonedNode(value) - } -} - -#[derive(Clone, Copy)] -pub struct CopiedNode(pub T); - -impl<'i, T: Copy + 'i, I> Node<'i, I> for CopiedNode { - type Output = T; - #[inline(always)] - fn eval(&'i self, _input: I) -> Self::Output { - self.0 - } -} - -impl CopiedNode { - pub const fn new(value: T) -> CopiedNode { - CopiedNode(value) - } -} - -#[derive(Default)] -pub struct DefaultNode(PhantomData); - -impl<'i, T: Default + 'i, I> Node<'i, I> for DefaultNode { - type Output = T; - fn eval(&'i self, _input: I) -> Self::Output { - T::default() - } -} - -impl DefaultNode { - pub fn new() -> Self { - Self(PhantomData) - } -} - -#[repr(C)] -/// Return the unit value -#[derive(Default, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub struct ForgetNode; - -impl<'i, T: 'i> Node<'i, T> for ForgetNode { - type Output = (); - fn eval(&'i self, _input: T) -> Self::Output {} -} - -impl ForgetNode { - pub const fn new() -> Self { - ForgetNode - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_int_node() { - let node = IntNode::<5>; - assert_eq!(node.eval(()), 5); - } - #[test] - fn test_value_node() { - let node = ValueNode::new(5); - assert_eq!(node.eval(()), &5); - let type_erased = &node as &dyn for<'a> Node<'a, (), Output = &'a i32>; - assert_eq!(type_erased.eval(()), &5); - } - #[test] - fn test_default_node() { - let node = DefaultNode::::new(); - assert_eq!(node.eval(42), 0); - } - #[test] - #[allow(clippy::unit_cmp)] - fn test_unit_node() { - let node = ForgetNode::new(); - assert_eq!(node.eval(()), ()); - } -} diff --git a/node-graph/libraries/graphene-hash/src/lib.rs b/node-graph/libraries/graphene-hash/src/lib.rs index 00be14c112..0e0acc8876 100644 --- a/node-graph/libraries/graphene-hash/src/lib.rs +++ b/node-graph/libraries/graphene-hash/src/lib.rs @@ -232,6 +232,17 @@ impl CacheHash for Vec { } } +#[cfg(feature = "std")] +impl CacheHash for std::collections::BTreeSet { + #[inline] + fn cache_hash(&self, state: &mut H) { + core::hash::Hash::hash(&self.len(), state); + for item in self { + item.cache_hash(state); + } + } +} + #[cfg(feature = "std")] impl CacheHash for Box { #[inline] diff --git a/node-graph/libraries/wgpu-executor/src/lib.rs b/node-graph/libraries/wgpu-executor/src/lib.rs index e363f31c2e..94e3e03c00 100644 --- a/node-graph/libraries/wgpu-executor/src/lib.rs +++ b/node-graph/libraries/wgpu-executor/src/lib.rs @@ -10,10 +10,10 @@ use crate::texture_cache::TextureCache; use anyhow::Result; use core_types::Color; use core_types::color::SRGBA8; -use futures::lock::Mutex; use glam::UVec2; use graphene_application_io::{ApplicationIo, EditorApi}; use std::sync::Arc; +use std::sync::Mutex; use vello::{AaConfig, AaSupport, RenderParams, Renderer, RendererOptions, Scene}; use wgpu::util::DeviceExt; use wgpu::{Origin3d, TextureAspect}; @@ -21,7 +21,6 @@ use wgpu::{Origin3d, TextureAspect}; pub use buffer::Buffer; pub use context::Context as WgpuContext; pub use context::ContextBuilder as WgpuContextBuilder; -pub use pipeline::AsyncPipeline as AsyncWgpuPipeline; pub use pipeline::Pipeline as WgpuPipeline; pub use pipeline::PipelineCache as WgpuPipelineCache; pub use raster_types::Texture; @@ -70,7 +69,7 @@ impl<'a, T: ApplicationIo> From<&'a EditorApi> for & } impl WgpuExecutor { - pub async fn render_vello_scene(&self, scene: &Scene, size: UVec2, context: &RenderContext, background: Option) -> Result { + pub fn render_vello_scene(&self, scene: &Scene, size: UVec2, context: &RenderContext, background: Option) -> Result { let texture = self.request_texture(size); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default()); @@ -84,7 +83,7 @@ impl WgpuExecutor { }; { - let mut renderer = self.inner.vello_renderer.lock().await; + let mut renderer = self.inner.vello_renderer.lock().unwrap(); for (image_brush, texture) in context.resource_overrides.iter() { let texture_view = wgpu::TexelCopyTextureInfoBase { texture: (**texture).clone(), diff --git a/node-graph/libraries/wgpu-executor/src/pipeline.rs b/node-graph/libraries/wgpu-executor/src/pipeline.rs index 281a8a9dfd..031d2b9dda 100644 --- a/node-graph/libraries/wgpu-executor/src/pipeline.rs +++ b/node-graph/libraries/wgpu-executor/src/pipeline.rs @@ -1,42 +1,16 @@ use dyn_any::DynAny; use std::any::Any; -use std::future::Future; -use std::pin::Pin; use std::sync::{Arc, OnceLock}; use crate::WgpuExecutor; -pub type PipelineFuture<'a, T> = Pin + Send + 'a>>; - pub trait Pipeline: Any + Send + Sync + Sized { type Args<'a>; type Out: Send; fn create(executor: &WgpuExecutor) -> Self; - fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> PipelineFuture<'a, Self::Out>; -} - -pub trait AsyncPipeline: Any + Send + Sync + Sized { - type Args<'a>; - type Out: Send; - - fn create(executor: &WgpuExecutor) -> Self; - - fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> impl Future + Send + 'a; -} - -impl Pipeline for P { - type Args<'a> =

::Args<'a>; - type Out =

::Out; - - fn create(executor: &WgpuExecutor) -> Self { -

::create(executor) - } - - fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> PipelineFuture<'a, Self::Out> { - Box::pin(

::run(self, executor, args)) - } + fn run(&self, executor: &WgpuExecutor, args: &Self::Args<'_>) -> Self::Out; } #[derive(Default, Clone, DynAny)] @@ -51,13 +25,13 @@ impl PipelineCache { self.pipeline.get_or_init(|| Box::new(P::create(executor))); } - pub async fn run(&self, args: &P::Args<'_>) -> P::Out { + pub fn run(&self, args: &P::Args<'_>) -> P::Out { let executor = self.executor.get().expect("PipelineCache not initialized"); let entry = self.pipeline.get().expect("PipelineCache not initialized"); let pipeline = (**entry) .downcast_ref::

() .unwrap_or_else(|| panic!("PipelineCache type mismatch: run::<{}>() but init used a different pipeline type", std::any::type_name::

(),)); - pipeline.run(executor, args).await + pipeline.run(executor, args) } } diff --git a/node-graph/libraries/wgpu-executor/src/shader_runtime/per_pixel_adjust_runtime.rs b/node-graph/libraries/wgpu-executor/src/shader_runtime/per_pixel_adjust_runtime.rs index 761fbcad25..ffb4406efa 100644 --- a/node-graph/libraries/wgpu-executor/src/shader_runtime/per_pixel_adjust_runtime.rs +++ b/node-graph/libraries/wgpu-executor/src/shader_runtime/per_pixel_adjust_runtime.rs @@ -2,11 +2,11 @@ use crate::shader_runtime::FULLSCREEN_VERTEX_SHADER_NAME; use crate::{Buffer, WgpuContext, WgpuExecutor}; use core_types::list::{Item, List}; use core_types::shaders::buffer_struct::BufferStruct; -use futures::lock::Mutex; use glam::UVec2; use raster_types::{GPU, Raster}; use std::borrow::Cow; use std::collections::HashMap; +use std::sync::Mutex; use wgpu::util::BufferInitDescriptor; use wgpu::{ BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face, @@ -34,8 +34,8 @@ impl PerPixelAdjustShaderRuntime { } impl WgpuExecutor { - pub async fn run_per_pixel_adjust(&self, shaders: &Shaders<'_>, textures: List>, args: Option<&T>) -> List> { - let mut cache = self.inner.shader_runtime.per_pixel_adjust.pipeline_cache.lock().await; + pub fn run_per_pixel_adjust(&self, shaders: &Shaders<'_>, textures: List>, args: Option<&T>) -> List> { + let mut cache = self.inner.shader_runtime.per_pixel_adjust.pipeline_cache.lock().unwrap(); let pipeline = cache .entry(shaders.fragment_shader_name.to_owned()) .or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(self.context(), shaders)); diff --git a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs index 93fb12da34..d94372bd51 100644 --- a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs +++ b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs @@ -2,7 +2,7 @@ use crate::{Buffer, WgpuExecutor}; use core_types::Color; use core_types::color::SRGBA8; use core_types::list::{Item, List}; -use core_types::ops::Convert; +use core_types::ops::{Convert, ConvertAsync}; use core_types::transform::Footprint; use raster_types::Image; use raster_types::{CPU, GPU, Raster, Texture}; @@ -133,21 +133,21 @@ impl RasterGpuToRasterCpuConverter { } /// Passthrough conversion for GPU `List`s - no conversion needed -impl<'i> Convert>, &'i WgpuExecutor> for List> { - async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List> { +impl Convert>, WgpuExecutor> for List> { + fn convert(self, _: Footprint, _converter: WgpuExecutor) -> List> { self } } /// Converts a `List>` to `List>` by uploading each image to a texture -impl<'i> Convert>, &'i WgpuExecutor> for List> { - async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List> { +impl Convert>, WgpuExecutor> for List> { + fn convert(self, _: Footprint, executor: WgpuExecutor) -> List> { let queue = executor.context().queue.lock(); let list = self .into_iter() .map(|row| { let (image, attributes) = row.into_parts(); - let texture = upload_to_texture(executor, &queue, &image); + let texture = upload_to_texture(&executor, &queue, &image); Item::from_parts(Raster::new_gpu(texture), attributes) }) @@ -159,10 +159,10 @@ impl<'i> Convert>, &'i WgpuExecutor> for List> { } /// Converts single CPU raster to GPU by uploading to texture -impl<'i> Convert, &'i WgpuExecutor> for Raster { - async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster { +impl Convert, WgpuExecutor> for Raster { + fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster { let queue = executor.context().queue.lock(); - let texture = upload_to_texture(executor, &queue, &self); + let texture = upload_to_texture(&executor, &queue, &self); queue.submit([]); Raster::new_gpu(texture) @@ -170,15 +170,15 @@ impl<'i> Convert, &'i WgpuExecutor> for Raster { } /// Passthrough conversion for CPU `List`s - no conversion needed -impl<'i> Convert>, &'i WgpuExecutor> for List> { - async fn convert(self, _: Footprint, _converter: &'i WgpuExecutor) -> List> { +impl Convert>, WgpuExecutor> for List> { + fn convert(self, _: Footprint, _converter: WgpuExecutor) -> List> { self } } /// Converts a `List>` to `List>` by downloading texture data in one go then asynchronously maps all buffers and processes the results. -impl<'i> Convert>, &'i WgpuExecutor> for List> { - async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> List> { +impl ConvertAsync>, WgpuExecutor> for List> { + async fn convert(self, _: Footprint, executor: WgpuExecutor) -> List> { let device = &executor.context().device; let queue = &executor.context().queue; @@ -191,7 +191,7 @@ impl<'i> Convert>, &'i WgpuExecutor> for List> { for row in self { let (element, attributes) = row.into_parts(); - converters.push(RasterGpuToRasterCpuConverter::new(executor, &mut encoder, element)); + converters.push(RasterGpuToRasterCpuConverter::new(&executor, &mut encoder, element)); rows_meta.push(Item::from_parts((), attributes)); } @@ -219,8 +219,8 @@ impl<'i> Convert>, &'i WgpuExecutor> for List> { } /// Converts single GPU raster to CPU by downloading texture data -impl<'i> Convert, &'i WgpuExecutor> for Raster { - async fn convert(self, _: Footprint, executor: &'i WgpuExecutor) -> Raster { +impl ConvertAsync, WgpuExecutor> for Raster { + async fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster { let device = &executor.context().device; let queue = &executor.context().queue; @@ -228,7 +228,7 @@ impl<'i> Convert, &'i WgpuExecutor> for Raster { label: Some("single_texture_download_encoder"), }); - let converter = RasterGpuToRasterCpuConverter::new(executor, &mut encoder, self); + let converter = RasterGpuToRasterCpuConverter::new(&executor, &mut encoder, self); queue.submit([encoder.finish()]); diff --git a/node-graph/node-macro/src/codegen.rs b/node-graph/node-macro/src/codegen.rs index 2f89c8e8b9..7f222c4544 100644 --- a/node-graph/node-macro/src/codegen.rs +++ b/node-graph/node-macro/src/codegen.rs @@ -41,8 +41,21 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }; let struct_name = format_ident!("{}Node", struct_name); + let async_hidden_fields = is_async.then(|| { + [ + ParsedField::hidden( + "_runtime", + parse_quote!(#core_types::list::Item<#core_types::RuntimeHandle>), + ParsedValueSource::Scope(Box::new(parse_quote!("runtime"))), + ), + ParsedField::hidden("_source", parse_quote!(#core_types::list::Item<#core_types::SourceId>), ParsedValueSource::SourceId), + ] + }); + + let fields_iter = fields.iter().chain(async_hidden_fields.iter().flatten()); + // Separate data fields from regular fields - let (data_fields, regular_fields): (Vec<_>, Vec<_>) = fields.iter().partition(|f| f.is_data_field); + let (data_fields, regular_fields): (Vec<_>, Vec<_>) = fields_iter.partition(|f| f.is_data_field); // The primary's position among the regular fields, which `#[scope]` fields may precede (`#[data]` fields are already partitioned out) let primary_regular_index = regular_fields.iter().position(|field| !field.is_environment()); @@ -59,6 +72,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn data_fields .iter() .any(|field| field.ty.regular().is_some_and(|regular| type_contains_ident(®ular.ty, generic_ident))) + || (parsed.is_async && type_contains_ident(&output_payload(output_type), generic_ident)) }) .cloned() .collect(); @@ -131,9 +145,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote! { pub(super) #name: #r#gen } }); - let struct_fields: Vec<_> = data_field_defs.chain(regular_field_defs).collect(); - - let mut future_idents = Vec::new(); + let tier = output_tier(output_type); + let output = output_payload(output_type); + let slots_field = parsed.is_async.then(|| quote! { pub(super) slots: #core_types::runtime::Slots<#output> }); + let struct_fields: Vec<_> = data_field_defs.chain(regular_field_defs).chain(slots_field).collect(); // Data fields get passed as references to the underlying function let data_field_idents: Vec<_> = data_fields.iter().map(|f| &f.pat_ident).collect(); @@ -152,9 +167,9 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let field_types: Vec<_> = regular_fields .iter() .map(|field| match &field.ty { - ParsedFieldType::Node(NodeParsedField { output_type, input_type, .. }) => match parsed.is_async { - true => parse_quote!(&'n impl #core_types::Node<'n, #input_type, Output = impl core::future::Future>), - false => parse_quote!(&'n impl #core_types::Node<'n, #input_type, Output = #output_type>), + ParsedFieldType::Node(NodeParsedField { output_type, input_type, .. }) => match tier { + NodeOutputTier::Poll => parse_quote!(&impl #core_types::Node<#input_type, Output = #output_type>), + _ => parse_quote!(#core_types::LazyInput<'_, impl #core_types::Node<#input_type, Output = #output_type>>), }, value => value.regular().expect("a non-node field is a value field").ty.clone(), }) @@ -200,6 +215,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote!(RegistryValueSource::Scope(#data.as_static_str())) } } + ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId), _ => quote!(RegistryValueSource::None), }, None => quote!(RegistryValueSource::None), @@ -229,7 +245,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }; match implementations.first() { // A primary's scalar `#[default]` parses as a bare element (unranked, promoted at resolution); without one it defaults to an empty List - Some(implementation_ty) if Some(index) == primary_regular_index && element_wise => match value_source { + Some(implementation_ty) if Some(index) == primary_regular_index && element_wise && mapped_variant => match value_source { ParsedValueSource::Default(_) => quote!(Some(concrete!(#implementation_ty))), _ => quote!(Some(#core_types::list!(#implementation_ty))), }, @@ -317,17 +333,20 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn .collect(); // Only eval regular fields (data fields are accessed directly as self.field_name) - let eval_args = regular_fields.iter().map(|field| { + let eval_args = regular_fields.iter().enumerate().map(|(index, field)| { let name = &field.pat_ident.ident; match &field.ty { - ParsedFieldType::Node { .. } => { - quote! { let #name = &self.#name; } - } - _ => { - quote! { let #name = self.#name.eval(__input.clone()).await; } - } + ParsedFieldType::Node { .. } => match tier { + NodeOutputTier::Poll => quote! { let #name = &#core_types::PollInput::new(&self.#name, #index); }, + _ => quote! { let #name = #core_types::LazyInput::new(&self.#name, __cell, #index); }, + }, + _ => quote! { let #name = __cell.record(#index, self.#name.eval(__input)); }, } }); + let unwrap_args = regular_fields.iter().filter(|field| !matches!(field.ty, ParsedFieldType::Node { .. })).map(|field| { + let name = &field.pat_ident.ident; + quote! { let #name = #name?; } + }); // Only regular fields can have min/max constraints let min_max_args = regular_fields.iter().map(|field| match field.ty.regular() { @@ -381,8 +400,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn }) .collect() }; - future_idents.extend((0..regular_fields.len()).map(|id| format_ident!("F{}", id))); - // Builds every field's where-clause bounds, wrapping each ranked connector's wire type for the element-wise variants // while environment fields keep their declared type. `list_content` additionally lifts a lazy primary connector's // `Item` output to `List` for the list-content variant. @@ -390,28 +407,21 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn regular_fields .iter() .zip(node_generics.iter()) - .zip(future_idents.iter()) .enumerate() - .map(|(index, ((field, name), fut_ident))| match &field.ty { + .map(|(index, (field, name))| match &field.ty { ParsedFieldType::Node(NodeParsedField { input_type, output_type, output_element, .. }) => { - if !*is_async { - unreachable!("Found node which takes an impl Node<> input but is not async") - } let output_type = if list_content && Some(index) == primary_regular_index { let element_ty = output_element.clone().unwrap_or_else(|| output_type.clone()); WireWrapper::List.apply(core_types, &element_ty) } else { output_type.clone() }; - quote!( - #fut_ident: core::future::Future + #core_types::WasmNotSend + 'n, - #name: #core_types::Node<'n, #input_type, Output = #fut_ident > + #core_types::WasmNotSync - ) + quote!(#name: #core_types::Node<#input_type, Output = #output_type>) } value => { let declared = &value.regular().expect("a non-node field is a value field").ty; @@ -420,12 +430,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn (ParsedFieldType::Item { element, .. }, Some(wrap)) if !field.is_environment() => wrap.apply(core_types, element), _ => declared.clone(), }; - let all_lifetime_ty = substitute_lifetimes(ty.clone(), "all"); - quote!( - #fut_ident: core::future::Future + #core_types::WasmNotSend + 'n, - for<'all> #all_lifetime_ty: #core_types::WasmNotSend, - #name: #core_types::Node<'n, #input_type, Output = #fut_ident> + #core_types::WasmNotSync - ) + quote!(#name: #core_types::Node<#input_type, Output = #ty>) } }) .collect() @@ -441,13 +446,28 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn #(#field_clauses,)* #(#clampable_clauses,)* #(#extra_clauses,)* - #output_type: 'n, ); struct_where_clause.predicates.extend(extra_where); struct_where_clause }; + + let source_clauses: Vec = if parsed.is_async { + let data_clones = data_fields.iter().filter_map(|field| field.ty.regular()).map(|regular| { + let ty = ®ular.ty; + quote!(#ty: Clone) + }); + [ + quote!(#output: Clone + #core_types::WasmNotSend + #core_types::WasmNotSync + 'static), + quote!(#input_type: #core_types::ExtractAll + #core_types::CloneVarArgs + 'static), + ] + .into_iter() + .chain(data_clones) + .collect() + } else { + Vec::new() + }; let primary_wire = element_wise.then_some(WireWrapper::Item); - let struct_where_clause = make_struct_where_clause(build_field_clauses(primary_wire, false), build_clampable_clauses(primary_wire), Vec::new()); + let struct_where_clause = make_struct_where_clause(build_field_clauses(primary_wire, false), build_clampable_clauses(primary_wire), source_clauses); // The mapped variant clones bare parameters and clones ranked connectors' items per frame slot, so both need Clone let param_clone_clauses: Vec = regular_fields @@ -494,13 +514,13 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let regular_inits = regular_field_names.iter().map(|name| { quote! { #name } }); - let all_field_inits: Vec<_> = data_inits.chain(regular_inits).collect(); + let slots_init = parsed.is_async.then(|| quote! { slots: Default::default() }); + let all_field_inits: Vec<_> = data_inits.chain(regular_inits).chain(slots_init).collect(); let async_keyword = is_async.then(|| quote!(async)); - let await_keyword = is_async.then(|| quote!(.await)); // Data fields may not implement Copy, PartialEq, etc., so only derive Debug and Clone - let struct_derives = if data_fields.is_empty() { + let struct_derives = if data_fields.is_empty() && !parsed.is_async { quote!(#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]) } else { quote!(#[derive(Debug, Clone)]) @@ -522,26 +542,119 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn use #core_types::misc::Clampable; #(#eval_args)* + #(#unwrap_args)* #(#min_max_args)* }; + let cell_ctor = match attributes.no_partial { + true => quote!(#core_types::Status::no_partial()), + false => quote!(#core_types::Status::new()), + }; - let eval_impl = quote! { - type Output = #core_types::registry::DynFuture<'n, #output_type>; - #[inline] - fn eval(&'n self, __input: #input_type) -> Self::Output { - Box::pin(async move { - #eval_prelude - self::#fn_name(__input #(, &self.#data_field_names)* #(, #regular_field_names)*) #await_keyword - }) + let lift = |call: TokenStream2| match tier { + NodeOutputTier::Plain | NodeOutputTier::Poll => quote!(Ok(#call)), + NodeOutputTier::Interrupt => call, + NodeOutputTier::Fallback => quote! { + match #call { + Ok(value) => Ok(value), + Err((value, error)) => { + __cell.raise(error); + Ok(value) + } + } + }, + }; + + let lift_slot = |call: TokenStream2| match tier { + NodeOutputTier::Plain | NodeOutputTier::Poll => call, + NodeOutputTier::Interrupt => quote!(#call?), + NodeOutputTier::Fallback => quote! { + match #call { + Ok(value) => value, + Err((value, error)) => { + __cell.raise(error); + value + } + } + }, + }; + + let fold = match tier { + NodeOutputTier::Poll => quote! { + match __kernel(&__cell) { + Ok(state) => __cell.merge(state), + Err(interrupt) => __cell.bail(interrupt), + } + }, + _ => quote!(__cell.run(__kernel)), + }; + + let kernel_call = lift(quote!(self::#fn_name(__input.clone() #(, &self.#data_field_names)* #(, #regular_field_names)*))); + + let eval_impl = if parsed.is_async { + let declared_field_names: Vec<_> = fields.iter().filter(|field| !field.is_data_field).map(|field| &field.pat_ident.ident).collect(); + let placeholder = match &attributes.placeholder { + Some(path) => quote!(Some(#path(#(&#declared_field_names),*))), + None => quote!(None), + }; + let data_clones = data_field_names.iter().map(|name| quote!(let #name = self.#name.clone();)); + quote! { + type Output = #output; + #[inline] + fn eval(&self, __input: &#input_type) -> #core_types::Poll { + let __cell = #cell_ctor; + let __kernel = |__cell: &#core_types::Status| -> Result<_, #core_types::Interrupt> { + #eval_prelude + Ok((#(#regular_field_names,)*)) + }; + let (#(#regular_field_names,)*) = match __kernel(&__cell) { + Ok(inputs) => inputs, + Err(interrupt) => return __cell.bail(interrupt), + }; + let __placeholder: Option = #placeholder; + if __cell.finality() == #core_types::Finality::Partial { + return match __placeholder { + Some(placeholder) => __cell.finish(placeholder), + None => #core_types::Poll::Pending, + }; + } + let __source = *_source.element(); + let __key = { + let mut __hasher = std::hash::DefaultHasher::new(); + #core_types::CacheHash::cache_hash(&#core_types::OwnedContextImpl::from(__input.clone()).without_source(__source), &mut __hasher); + std::hash::Hasher::finish(&__hasher) + }; + let __runtime = _runtime.element().clone(); + let __context = __input.clone(); + #(#data_clones)* + let __state = self.slots.resolve(__key, &__runtime, __source, __placeholder, move || async move { + #core_types::Poll::Final(self::#fn_name(__context #(, &#data_field_names)* #(, #regular_field_names)*).await) + }); + __cell.merge(__state) + } + + #serialize_impl } + } else { + quote! { + type Output = #output; + #[inline] + fn eval(&self, __input: &#input_type) -> #core_types::Poll { + let __cell = #cell_ctor; + let __kernel = |__cell: &#core_types::Status| -> Result<_, #core_types::Interrupt> { + #eval_prelude + #kernel_call + }; + #fold + } - #serialize_impl + #serialize_impl + } }; // The output a framed variant collects into. A map kernel pushes one item per frame slot and a `Destructure` struct appends its // fields to its mapped struct. An expander kernel, returning `List`, has its lists concatenated since nested lists aren't supported. let framed_output = || -> (TokenStream2, TokenStream2, TokenStream2, TokenStream2) { - match (parsed.output_element.as_ref(), peel_list(output_type)) { + match (parsed.output_element.as_ref(), peel_list(&output)) { (Some(element_ty), _) => ( quote!(#core_types::list::List<#element_ty>), quote!(#core_types::list::List::with_capacity(__frame_length)), @@ -549,13 +662,13 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn quote!(#core_types::list::List::new()), ), (None, Some(_)) => ( - quote!(#output_type), + quote!(#output), quote!(#core_types::list::List::new()), quote!(__output.extend(__result);), quote!(#core_types::list::List::new()), ), (None, None) => { - let destructure = quote!(<#output_type as #core_types::registry::Destructure>); + let destructure = quote!(<#output as #core_types::registry::Destructure>); ( quote!(#destructure::Mapped), quote!(#destructure::mapped_with_capacity(__frame_length)), @@ -598,28 +711,31 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let (mapped_output_type, initial_output, collect_result, empty_output) = framed_output(); + let slot_call = lift_slot(quote!(self::#fn_name(__slot_context #(, &self.#data_field_names)* #(, #per_slot_args)*))); quote! { - type Output = #core_types::registry::DynFuture<'n, #mapped_output_type>; + type Output = #mapped_output_type; #[inline] #[allow(clippy::clone_on_copy)] - fn eval(&'n self, __input: #input_type) -> Self::Output { - Box::pin(async move { + fn eval(&self, __input: &#input_type) -> #core_types::Poll { + let __cell = #cell_ctor; + let __kernel = |__cell: &#core_types::Status| -> Result<_, #core_types::Interrupt> { #eval_prelude let __frame_length = [#(#ranked_names.len()),*].into_iter().max().unwrap_or(0); if [#(#ranked_names.len()),*].into_iter().any(|length| length == 0) { - return #empty_output; + return Ok(#empty_output); } let mut __output = #initial_output; for __slot_index in 0..__frame_length { let __slot_context = #slot_context; - let __result = self::#fn_name(__slot_context #(, &self.#data_field_names)* #(, #per_slot_args)*) #await_keyword; + let __result = #slot_call; #collect_result } - __output - }) + Ok(__output) + }; + __cell.run(__kernel) } #serialize_impl @@ -644,7 +760,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn .map(|(index, field)| { let name = &field.pat_ident.ident; if index == primary_index { - return quote!(&__stub); + return match tier { + NodeOutputTier::Poll => quote!(&__stub), + _ => quote!(#core_types::LazyInput::new(&__stub, __cell, #primary_index)), + }; } match &field.ty { ParsedFieldType::Node(_) => quote!(#name), @@ -661,20 +780,22 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let empty_param_check = (!ranked_names.is_empty()).then(|| { quote! { if [#(#ranked_names.len()),*].into_iter().any(|__length| __length == 0) { - return #empty_output; + return Ok(#empty_output); } } }); + let slot_call = lift_slot(quote!(self::#fn_name(__input.clone() #(, &self.#data_field_names)* #(, #per_slot_args)*))); quote! { - type Output = #core_types::registry::DynFuture<'n, #list_content_output_type>; + type Output = #list_content_output_type; #[inline] #[allow(clippy::clone_on_copy)] - fn eval(&'n self, __input: #input_type) -> Self::Output { - Box::pin(async move { + fn eval(&self, __input: &#input_type) -> #core_types::Poll { + let __cell = #cell_ctor; + let __kernel = |__cell: &#core_types::Status| -> Result<_, #core_types::Interrupt> { #eval_prelude - let __content = #primary_name.eval(#core_types::OwnedContextImpl::from(__input.clone()).into_context()) #await_keyword; + let __content = #primary_name.eval(#core_types::OwnedContextImpl::from(__input.clone()).into_context())?; let __frame_length = __content.len(); #empty_param_check @@ -683,12 +804,13 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let __stub = #core_types::value::PrecomputedItemNode::new( __content.clone_item(__slot_index).expect("A content slot index is always within bounds") ); - let __result = self::#fn_name(__input.clone() #(, &self.#data_field_names)* #(, #per_slot_args)*) #await_keyword; + let __result = #slot_call; #collect_result } - __output - }) + Ok(__output) + }; + __cell.run(__kernel) } #serialize_impl @@ -706,17 +828,18 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn let mapped_struct_name = format_ident!("{}Mapped", struct_name); let list_content_struct_name = format_ident!("{}ListContent", struct_name); - let register_node_impl = generate_register_node_impl(parsed, &field_names, &struct_name, &mapped_struct_name, &list_content_struct_name, &identifier)?; + let register_node_impl = generate_register_node_impl(parsed, ®ular_fields, &field_names, &struct_name, &mapped_struct_name, &list_content_struct_name, &identifier)?; let import_name = format_ident!("_IMPORT_STUB_{}", mod_name.to_string().to_case(Case::UpperSnake)); let inspector = &attributes.inspector_string.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None)); let icon = &attributes.icon.as_ref().map(|value| quote!(Some(#value))).unwrap_or(quote!(None)); let memoize_flag = attributes.memoize; + let asynchronous_flag = parsed.is_async; let inject_scope_flag = attributes.inject_scope; // A node returning a `Destructure` struct records its fields as output connectors let output_fields = match may_return_destructure_struct(parsed) { true => { - let output_type = substitute_lifetimes(output_type.clone(), "static"); + let output_type = substitute_lifetimes(output_payload(output_type), "static"); quote! {{ use gcore::registry::{DestructureOutputFields as _, NoOutputFields as _}; (&gcore::registry::OutputFields::<#output_type>(core::marker::PhantomData)).output_fields() @@ -733,7 +856,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn (Some(mapped_where_clause), Some(mapped_eval)) => quote! { #cfg #[automatically_derived] - impl<'n, #(#fn_generics,)* #(#node_generics,)* #(#future_idents,)*> #core_types::Node<'n, #input_type> for #mod_name::#mapped_struct_name<#(#struct_type_params,)*> + impl<#(#fn_generics,)* #(#node_generics,)*> #core_types::Node<#input_type> for #mod_name::#mapped_struct_name<#(#struct_type_params,)*> #mapped_where_clause { #mapped_eval @@ -746,7 +869,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn (Some(list_content_where_clause), Some(list_content_eval)) => quote! { #cfg #[automatically_derived] - impl<'n, #(#fn_generics,)* #(#node_generics,)* #(#future_idents,)*> #core_types::Node<'n, #input_type> for #mod_name::#list_content_struct_name<#(#struct_type_params,)*> + impl<#(#fn_generics,)* #(#node_generics,)*> #core_types::Node<#input_type> for #mod_name::#list_content_struct_name<#(#struct_type_params,)*> #list_content_where_clause { #list_content_eval @@ -763,7 +886,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn } #[automatically_derived] - impl<'n, #(#struct_generic_params,)*> #mapped_struct_name<#(#struct_type_params,)*> + impl<#(#struct_generic_params,)*> #mapped_struct_name<#(#struct_type_params,)*> { #[allow(clippy::too_many_arguments)] pub fn new(#(#new_args,)*) -> Self { @@ -783,7 +906,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn } #[automatically_derived] - impl<'n, #(#struct_generic_params,)*> #list_content_struct_name<#(#struct_type_params,)*> + impl<#(#struct_generic_params,)*> #list_content_struct_name<#(#struct_type_params,)*> { #[allow(clippy::too_many_arguments)] pub fn new(#(#new_args,)*) -> Self { @@ -840,7 +963,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn #(#description_doc_attrs)* #[inline] #[allow(clippy::too_many_arguments)] - #vis #async_keyword fn #fn_name <'n, #(#fn_generics,)*> (#input_ident: #input_type #(, #data_field_idents: #data_field_types)* #(, #field_idents: #field_types)*) -> #output_type #where_clause #body + #vis #async_keyword fn #fn_name <#(#fn_generics,)*> (#input_ident: #input_type #(, #data_field_idents: #data_field_types)* #(, #field_idents: #field_types)*) -> #output_type #where_clause #body } }; // A shader node's fn is emitted twice from the one body: as declared, in f64, for the CPU, and with the f32 parameter @@ -864,7 +987,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn #cfg #[automatically_derived] - impl<'n, #(#fn_generics,)* #(#node_generics,)* #(#future_idents,)*> #core_types::Node<'n, #input_type> for #mod_name::#struct_name<#(#struct_type_params,)*> + impl<#(#fn_generics,)* #(#node_generics,)*> #core_types::Node<#input_type> for #mod_name::#struct_name<#(#struct_type_params,)*> #struct_where_clause { #eval_impl @@ -896,10 +1019,10 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn mod #mod_name { use super::*; use #core_types as gcore; - use gcore::{Node, NodeIOTypes, concrete, fn_type, fn_type_fut, future, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature}; + use gcore::{Node, NodeIOTypes, concrete, fn_type, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature}; use gcore::value::ClonedNode; use gcore::ops::TypeNode; - use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, DynFuture, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride}; + use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride}; use gcore::ctor::ctor; // Use the types specified in the implementation @@ -912,7 +1035,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn } #[automatically_derived] - impl<'n, #(#struct_generic_params,)*> #struct_name<#(#struct_type_params,)*> + impl<#(#struct_generic_params,)*> #struct_name<#(#struct_type_params,)*> { #[allow(clippy::too_many_arguments)] pub fn new(#(#new_args,)*) -> Self { @@ -939,6 +1062,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn context_features: vec![#(ContextFeature::#context_features,)*], memoize: #memoize_flag, inject_scope: #inject_scope_flag, + asynchronous: #asynchronous_flag, output_fields: #output_fields, fields: vec![ #( @@ -1084,6 +1208,14 @@ fn primary_item_element(parsed: &ParsedNodeFn) -> Option { /// Whether the element-wise node gets a mapped `List` wire variant: an eager primary is its own frame source, while a lazy primary (or a `()` generator) draws the frame from its ranked eager params, so it needs at least one. fn generates_mapped_variant(parsed: &ParsedNodeFn) -> bool { + if parsed.is_async { + return false; + } + + if output_tier(&parsed.output_type) == NodeOutputTier::Poll { + return false; + } + // A `()` generator frames over its ranked params exactly like a lazy primary, but generating fresh content per slot instead of transforming an upstream item if is_generator_frame(parsed) { return true; @@ -1126,7 +1258,7 @@ fn is_unit_type(ty: &syn::Type) -> bool { /// Whether the node's return type could be a `Destructure` struct, meaning a concrete type other than `()` or a ranked wrapper. fn may_return_destructure_struct(parsed: &ParsedNodeFn) -> bool { - let output_type = &parsed.output_type; + let output_type = &output_payload(&parsed.output_type); let ranked = peel_item(output_type).is_some() || peel_list(output_type).is_some() || matches!(output_type, Type::Path(path) if path.path.is_ident("ListDyn")); let generic = parsed .fn_generics @@ -1138,11 +1270,14 @@ fn may_return_destructure_struct(parsed: &ParsedNodeFn) -> bool { /// Whether the element-wise node gets a list-content `List` wire variant: only a lazy primary connector qualifies, since it draws its frame from the whole content `List` (an eager primary already maps over `List` content via the mapped variant). fn generates_list_content_variant(parsed: &ParsedNodeFn) -> bool { - primary_item_element(parsed).is_some() && matches!(parsed.primary_input_field().map(|(_, field)| &field.ty), Some(ParsedFieldType::Node(_))) + !(output_tier(&parsed.output_type) == NodeOutputTier::Poll) + && primary_item_element(parsed).is_some() + && matches!(parsed.primary_input_field().map(|(_, field)| &field.ty), Some(ParsedFieldType::Node(_))) } fn generate_register_node_impl( parsed: &ParsedNodeFn, + regular_fields: &[&ParsedField], field_names: &[&Ident], struct_name: &Ident, mapped_struct_name: &Ident, @@ -1170,7 +1305,6 @@ fn generate_register_node_impl( let mut constructors = Vec::new(); let unit = parse_quote!(gcore::Context); - let regular_fields: Vec<_> = parsed.fields.iter().filter(|f| !f.is_data_field).collect(); let primary_regular_index = regular_fields.iter().position(|field| !field.is_environment()); let parameter_types: Vec<_> = regular_fields @@ -1206,23 +1340,19 @@ fn generate_register_node_impl( let max_implementations = parameter_types.iter().map(|x| x.len()).chain([parsed.input.implementations.len().max(1)]).max(); - // Element-wise nodes register a variant per wire shape per implementations row; all other nodes register one let gcore = quote!(gcore); - let variants: Vec = if primary_item_element(parsed).is_some() { - let mut variants = vec![RegisterVariant::Item]; - if generates_mapped_variant(parsed) { - variants.push(RegisterVariant::Mapped); - } - if generates_list_content_variant(parsed) { - variants.push(RegisterVariant::ListContent); - } - variants - } else if is_generator_frame(parsed) { - // A `()` generator registers an Item form (single generation) plus a mapped form framed over its ranked params - vec![RegisterVariant::Item, RegisterVariant::Mapped] + let mut variants = Vec::new(); + if primary_item_element(parsed).is_some() || is_generator_frame(parsed) { + variants.push(RegisterVariant::Item); } else { - vec![RegisterVariant::Plain] + variants.push(RegisterVariant::Plain); }; + if generates_mapped_variant(parsed) { + variants.push(RegisterVariant::Mapped); + } + if generates_list_content_variant(parsed) { + variants.push(RegisterVariant::ListContent); + } for i in 0..max_implementations.unwrap_or(0) { for &variant in &variants { @@ -1237,7 +1367,7 @@ fn generate_register_node_impl( let field_is_ranked = !regular_fields[j].is_environment() && matches!(®ular_fields[j].ty, ParsedFieldType::Item { .. }); let is_lazy_primary = Some(j) == primary_regular_index && matches!(regular_fields[j].ty, ParsedFieldType::Node { .. }); // The list-content variant lifts its lazy primary connector's `Item` content to `List`; ranked params follow the variant's param wrap. - // A ranked signature is spelled with bare `Item<...>`/`List<...>` tokens, which `fn_type_fut!` matches syntactically to construct the structural form. + // A ranked signature is spelled with bare `Item<...>`/`List<...>` tokens, which `fn_type!` matches syntactically to construct the structural form. let (output_type, signature_type) = if is_lazy_primary && variant == RegisterVariant::ListContent { let element_ty = peel_item(output_type).unwrap_or_else(|| output_type.clone()); (WireWrapper::List.apply(&gcore, &element_ty), Some(quote!(List<#element_ty>))) @@ -1258,17 +1388,12 @@ fn generate_register_node_impl( }; let signature_type = signature_type.unwrap_or_else(|| quote!(#output_type)); - let node = matches!(regular_fields[j].ty, ParsedFieldType::Node { .. }); - let downcast_node = quote!( let #field_name: DowncastBothNode<#input_type, #output_type> = DowncastBothNode::new(args[#j].clone()); ); - if node && !parsed.is_async { - return Err(Error::new_spanned(&parsed.fn_name, "Node needs to be async if you want to use lambda parameters")); - } temp_constructors.push(downcast_node); - temp_node_io.push(quote!(fn_type_fut!(#input_type, #signature_type))); - panic_node_types.push(quote!(#input_type, DynFuture<'static, #output_type>)); + temp_node_io.push(quote!(fn_type!(#input_type, #signature_type))); + panic_node_types.push(quote!(#input_type, #output_type)); } let input_type = match parsed.input.implementations.is_empty() { true => parsed.input.ty.clone(), @@ -1282,19 +1407,14 @@ fn generate_register_node_impl( constructors.push(quote!( ( |args| { - Box::pin(async move { - #(#temp_constructors;)* - let node = #variant_struct_name::new(#(#field_names,)*); - // try polling futures - let any: DynAnyNode<#input_type, _, _> = DynAnyNode::new(node); - Box::new(any) as TypeErasedBox<'_> - }) + #(#temp_constructors;)* + let node = #variant_struct_name::new(#(#field_names,)*); + let any: DynAnyNode<#input_type, _, _> = DynAnyNode::new(node); + Box::new(any) as TypeErasedBox<'_> }, { let node = #variant_struct_name::new(#(PanicNode::<#panic_node_types>::new(),)*); let params = vec![#(#temp_node_io,)*]; - let mut node_io = NodeIO::<'_, #input_type>::to_async_node_io(&node, params); - node_io - + NodeIO::<#input_type>::to_node_io(&node, params) } ) )); diff --git a/node-graph/node-macro/src/parsing.rs b/node-graph/node-macro/src/parsing.rs index 16da13e276..069a33641b 100644 --- a/node-graph/node-macro/src/parsing.rs +++ b/node-graph/node-macro/src/parsing.rs @@ -59,6 +59,10 @@ pub(crate) struct NodeFnAttributes { pub(crate) memoize: bool, /// Whether this node provides a scope pub(crate) inject_scope: bool, + /// Fn producing an placeholder value used while node evaluation is pending + pub(crate) placeholder: Option, + /// Whether the node refuses placeholder data + pub(crate) no_partial: bool, /// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source. pub(crate) destructure_extractor: bool, } @@ -69,6 +73,7 @@ pub enum ParsedValueSource { None, Default(TokenStream2), Scope(Box), + SourceId, } // #[widget(ParsedWidgetOverride::Hidden)] @@ -128,6 +133,40 @@ pub struct ParsedField { } impl ParsedField { + pub(crate) fn hidden(name: &str, ty: Type, value_source: ParsedValueSource) -> Self { + Self { + pat_ident: PatIdent { + attrs: Vec::new(), + by_ref: None, + mutability: None, + ident: Ident::new(name, proc_macro2::Span::call_site()), + subpat: None, + }, + name: None, + description: String::new(), + widget_override: ParsedWidgetOverride::None, + ty: ParsedFieldType::classify(RegularParsedField { + ty, + exposed: false, + value_source, + number_soft_min: None, + number_soft_max: None, + number_hard_min: None, + number_hard_max: None, + number_mode_range: false, + implementations: Default::default(), + gpu_image: false, + narrowed_body_ty: None, + }), + number_display_decimal_places: None, + number_step: None, + unit: None, + multiline: false, + progression: false, + is_data_field: false, + } + } + /// Whether the field is environment rather than an argument: `#[data]` state or a `#[scope]`-injected wire. /// Environment fields never classify the node, never supply the element-wise frame, and broadcast by clone. pub(crate) fn is_environment(&self) -> bool { @@ -135,7 +174,7 @@ impl ParsedField { || matches!( self.ty.regular(), Some(RegularParsedField { - value_source: ParsedValueSource::Scope(_), + value_source: ParsedValueSource::Scope(_) | ParsedValueSource::SourceId, .. }) ) @@ -417,6 +456,8 @@ impl Parse for NodeFnAttributes { let mut serialize = None; let mut memoize = false; let mut inject_scope = false; + let mut placeholder = None; + let mut no_partial = false; let content = input; // let content; @@ -571,13 +612,37 @@ impl Parse for NodeFnAttributes { } inject_scope = true; } + // The placeholder value used while a node's evaluation is pending. + // + // Example usage: + // #[node_macro::node(..., placeholder = get_placeholder, ...)] + "placeholder" => { + let meta = meta.require_name_value()?; + if placeholder.is_some() { + return Err(Error::new_spanned(meta, "Multiple 'placeholder' attributes are not allowed")); + } + let parsed_path: Path = + syn::parse2(meta.value.to_token_stream()).map_err(|_| Error::new_spanned(meta, "Expected a fn path for 'placeholder', e.g., placeholder = get_placeholder"))?; + placeholder = Some(parsed_path); + } + // Maps `Partial` inputs to `Pending`, for nodes where placeholder data makes no sense. + // + // Example usage: + // #[node_macro::node(..., no_partial, ...)] + "no_partial" => { + let path = meta.require_path_only()?; + if no_partial { + return Err(Error::new_spanned(path, "Multiple 'no_partial' attributes are not allowed")); + } + no_partial = true; + } _ => { return Err(Error::new_spanned( meta, indoc!( r#" Unsupported attribute in `node`. - Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'shader_node', 'serialize', 'memoize', and 'inject_scope'. + Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'shader_node', 'serialize', 'memoize', 'inject_scope', 'placeholder', and 'no_partial'. Example usage: #[node_macro::node(..., name("Test Node"), ...)] "# @@ -612,6 +677,8 @@ impl Parse for NodeFnAttributes { serialize, memoize, inject_scope, + placeholder, + no_partial, destructure_extractor: false, }) } @@ -633,7 +700,7 @@ pub(crate) fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Resu narrow_shader_fields(&mut fields)?; } let output_type = parse_output(&input_fn.sig.output)?; - let output_element = peel_item(&output_type); + let output_element = peel_item(&output_payload(&output_type)); let where_clause = input_fn.sig.generics.where_clause; let body = input_fn.block.to_token_stream(); let description = input_fn @@ -1165,7 +1232,7 @@ impl ParsedNodeFn { if let Type::ImplTrait(impl_trait) = self.input.ty.clone() { let ident = Ident::new("_Input", impl_trait.span()); let mut bounds = impl_trait.bounds; - bounds.push(parse_quote!('n)); + bounds.push(parse_quote!(Clone)); self.fn_generics.push(GenericParam::Type(TypeParam { attrs: Default::default(), ident: ident.clone(), @@ -1185,6 +1252,48 @@ impl ParsedNodeFn { } } +#[derive(Clone, Copy, PartialEq, Debug)] +pub(crate) enum NodeOutputTier { + /// `-> T` + Plain, + /// `-> Result` + Interrupt, + /// `-> Result` + Fallback, + /// `-> Poll` + Poll, +} + +pub(crate) fn output_tier(output_type: &Type) -> NodeOutputTier { + let Type::Path(type_path) = output_type else { return NodeOutputTier::Plain }; + let Some(segment) = type_path.path.segments.last() else { return NodeOutputTier::Plain }; + let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else { + return NodeOutputTier::Plain; + }; + match (segment.ident.to_string().as_str(), arguments.args.len()) { + ("Poll", 1) => NodeOutputTier::Poll, + ("Result", 2) => match arguments.args.last() { + Some(syn::GenericArgument::Type(Type::Tuple(_))) => NodeOutputTier::Fallback, + _ => NodeOutputTier::Interrupt, + }, + _ => NodeOutputTier::Plain, + } +} + +pub(crate) fn output_payload(output_type: &Type) -> Type { + if output_tier(output_type) == NodeOutputTier::Plain { + return output_type.clone(); + } + let Type::Path(type_path) = output_type else { unreachable!() }; + let syn::PathArguments::AngleBracketed(arguments) = &type_path.path.segments.last().unwrap().arguments else { + unreachable!() + }; + match arguments.args.first() { + Some(syn::GenericArgument::Type(payload)) => payload.clone(), + _ => output_type.clone(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -1308,6 +1417,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("add", Span::call_site()), @@ -1384,6 +1495,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("transform", Span::call_site()), @@ -1477,6 +1590,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("circle", Span::call_site()), @@ -1549,6 +1664,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("levels", Span::call_site()), @@ -1633,6 +1750,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("add", Span::call_site()), @@ -1720,6 +1839,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("load_image", Span::call_site()), @@ -1792,6 +1913,8 @@ mod tests { serialize: None, memoize: false, inject_scope: false, + placeholder: None, + no_partial: false, destructure_extractor: false, }, fn_name: Ident::new("custom_node", Span::call_site()), @@ -1969,4 +2092,19 @@ mod tests { ); assert!(parse_node_fn(attr, declared_list).is_err(), "a uniform cannot carry a List"); } + + #[test] + fn a_kernel_is_classified_by_its_declared_return_type() { + let payload: Type = parse_quote!(Item); + for (ty, tier) in [ + (parse_quote!(Item), NodeOutputTier::Plain), + (parse_quote!(Result, Interrupt>), NodeOutputTier::Interrupt), + (parse_quote!(Result, (Item, NodeError)>), NodeOutputTier::Fallback), + (parse_quote!(Poll>), NodeOutputTier::Poll), + ] { + let ty: Type = ty; + assert_eq!(output_tier(&ty), tier); + assert_eq!(output_payload(&ty), payload); + } + } } diff --git a/node-graph/node-macro/src/shader_nodes/per_pixel_adjust.rs b/node-graph/node-macro/src/shader_nodes/per_pixel_adjust.rs index 2805d76988..1d3372ad03 100644 --- a/node-graph/node-macro/src/shader_nodes/per_pixel_adjust.rs +++ b/node-graph/node-macro/src/shader_nodes/per_pixel_adjust.rs @@ -255,7 +255,7 @@ impl PerPixelAdjustCodegen<'_> { description: "".to_string(), widget_override: Default::default(), ty: ParsedFieldType::classify(RegularParsedField { - ty: parse_quote!(#gcore::list::Item<&'a WgpuExecutor>), + ty: parse_quote!(#gcore::list::Item), exposed: true, value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))), number_soft_min: None, @@ -325,7 +325,7 @@ impl PerPixelAdjustCodegen<'_> { wgsl_shader: crate::WGSL_SHADER, fragment_shader_name: super::#entry_point_name, has_uniform: #has_uniform, - }, #gpu_image, #uniform_buffer).await + }, #gpu_image, #uniform_buffer) } }; @@ -343,7 +343,7 @@ impl PerPixelAdjustCodegen<'_> { fn_name: self.shader_node_mod.clone(), struct_name: format_ident!("{}", self.shader_node_mod.to_string().to_case(Case::Pascal)), mod_name: self.shader_node_mod.clone(), - fn_generics: vec![parse_quote!('a: 'n)], + fn_generics: Vec::new(), where_clause: None, input: Input { pat_ident: self.parsed.input.pat_ident.clone(), @@ -353,7 +353,7 @@ impl PerPixelAdjustCodegen<'_> { }, output_type: raster_gpu, output_element: None, - is_async: true, + is_async: false, fields, body, description: self.parsed.description.clone(), diff --git a/node-graph/node-macro/src/validation.rs b/node-graph/node-macro/src/validation.rs index 4e6a91ab21..225fd73a28 100644 --- a/node-graph/node-macro/src/validation.rs +++ b/node-graph/node-macro/src/validation.rs @@ -1,4 +1,4 @@ -use crate::parsing::{Implementation, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField}; +use crate::parsing::{Implementation, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload}; use proc_macro_error2::emit_error; use quote::quote; use syn::spanned::Spanned; @@ -72,9 +72,16 @@ fn validate_no_item_parameters(parsed: &ParsedNodeFn) { } fn validate_element_wise(parsed: &ParsedNodeFn) { + if parsed.is_async && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) { + emit_error!(parsed.fn_name.span(), "An async node cannot take `impl Node` inputs"); + } + if parsed.attributes.placeholder.is_some() && !parsed.is_async { + emit_error!(parsed.fn_name.span(), "Only an async node can have a `placeholder`"); + } if parsed.attributes.skip_impl { return; } + let output = output_payload(&parsed.output_type); let Some((_, primary)) = parsed.primary_input_field() else { return }; let Some(RegularParsedField { ty, implementations, .. }) = primary.ty.regular() else { @@ -88,7 +95,7 @@ fn validate_element_wise(parsed: &ParsedNodeFn) { || primary.ty.list_element().is_some() || outer_wrapper_is(ty, "ListDyn") || implementations.iter().any(|ty| outer_wrapper_is(ty, "List") || outer_wrapper_is(ty, "ListDyn")); - if outer_wrapper_is(&parsed.output_type, "Item") && !primary_reduces_or_generates { + if outer_wrapper_is(&output, "Item") && !primary_reduces_or_generates { emit_error!( parsed.output_type.span(), "Returning `Item` requires the primary input to be `Item` (element-wise), `List`/`ListDyn` (aggregation), or `()` (generator)" @@ -108,7 +115,7 @@ fn validate_element_wise(parsed: &ParsedNodeFn) { ); } - let output_type = &parsed.output_type; + let output_type = &output; let ranked = outer_wrapper_is(output_type, "Item") || outer_wrapper_is(output_type, "List"); if !ranked && (outer_wrapper_is(output_type, "ListDyn") || is_unit_type(output_type) || contains_generic_param(output_type, &parsed.fn_generics)) { emit_error!( diff --git a/node-graph/nodes/brush/src/basic_brush/mod.rs b/node-graph/nodes/brush/src/basic_brush/mod.rs index 6686e9be36..0141996005 100644 --- a/node-graph/nodes/brush/src/basic_brush/mod.rs +++ b/node-graph/nodes/brush/src/basic_brush/mod.rs @@ -15,7 +15,7 @@ use raster_types::{GPU, Raster}; use wgpu_executor::{WgpuExecutor, WgpuPipelineCache}; #[node_macro::node(category("Raster: Brush"), icon("NodeBasicBrush"))] -pub async fn basic_brush<'a: 'n>( +fn basic_brush( ctx: impl Ctx + ExtractFootprint, strokes: List, #[widget(ParsedWidgetOverride::Hidden)] _cache: Item, @@ -57,7 +57,7 @@ pub async fn basic_brush<'a: 'n>( strokes: &strokes, cache: &cache, }; - let Some((texture, transform)) = pipeline.run::(&args).await else { + let Some((texture, transform)) = pipeline.run::(&args) else { return List::new(); }; let raster = Raster::::new_gpu(texture); @@ -65,9 +65,9 @@ pub async fn basic_brush<'a: 'n>( } #[node_macro::node(category(""), inject_scope)] -async fn basic_brush_pipeline<'a: 'n>( +fn basic_brush_pipeline( _ctx: impl Ctx, - #[scope(ProtoNodeIdentifier::new("graphene_std::platform_application_io::WgpuExecutorNode"))] executor: Item<&'a WgpuExecutor>, + #[scope(ProtoNodeIdentifier::new("graphene_std::platform_application_io::WgpuExecutorNode"))] executor: Item, #[data] pipeline: WgpuPipelineCache, ) -> Item { executor.into_element().pipeline_init::(pipeline); diff --git a/node-graph/nodes/brush/src/basic_brush/pipeline.rs b/node-graph/nodes/brush/src/basic_brush/pipeline.rs index b103f3fb61..01430293bb 100644 --- a/node-graph/nodes/brush/src/basic_brush/pipeline.rs +++ b/node-graph/nodes/brush/src/basic_brush/pipeline.rs @@ -9,7 +9,7 @@ use core_types::Color; use core_types::transform::Footprint; use glam::{DAffine2, UVec2}; use raster_types::Texture; -use wgpu_executor::{AsyncWgpuPipeline, Buffer, WgpuExecutor}; +use wgpu_executor::{Buffer, WgpuExecutor, WgpuPipeline}; pub(super) const DENSITY_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Float; pub(super) const COMPOSITE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; @@ -71,7 +71,7 @@ pub struct BasicBrushPipelineArgs<'a> { pub(super) cache: &'a BrushCache, } -impl AsyncWgpuPipeline for BasicBrushPipeline { +impl WgpuPipeline for BasicBrushPipeline { type Args<'a> = BasicBrushPipelineArgs<'a>; type Out = Option<(Texture, DAffine2)>; @@ -85,7 +85,7 @@ impl AsyncWgpuPipeline for BasicBrushPipeline { } } - async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out { + fn run(&self, executor: &WgpuExecutor, args: &Self::Args<'_>) -> Self::Out { let frame = super::render::Frame::new(args.strokes)?; let region = Region::new(&args.footprint)?; let state = args.cache.take(&args.footprint).unwrap_or_default(); diff --git a/node-graph/nodes/gcore/src/animation.rs b/node-graph/nodes/gcore/src/animation.rs index fbb7c30e14..d736f418c4 100644 --- a/node-graph/nodes/gcore/src/animation.rs +++ b/node-graph/nodes/gcore/src/animation.rs @@ -1,6 +1,6 @@ use core_types::list::{Item, List}; use core_types::transform::Footprint; -use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl}; +use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphene_animation::AnimationCurve; use graphic_types::vector_types::Gradient; @@ -73,7 +73,7 @@ fn animation_time( } #[node_macro::node(category("Debug"), icon("NodeQuantizeRealTime"))] -async fn quantize_real_time( +fn quantize_real_time( ctx: impl Ctx + ExtractAll + CloneVarArgs, #[implementations( Context -> Item, @@ -101,11 +101,11 @@ async fn quantize_real_time( Context -> List, Context -> List, )] - value: impl Node<'n, Context<'static>, Output = T>, + value: impl Node, Output = T>, #[default(1)] #[unit(" sec")] quantum: Item, -) -> T { +) -> Result { let time = ctx.try_real_time().unwrap_or_default(); let time = time / 1000.; let quantum = quantum.into_element(); @@ -115,11 +115,11 @@ async fn quantize_real_time( } let quantized_time = quantized_time * 1000.; let new_context = OwnedContextImpl::from(ctx).with_real_time(quantized_time); - value.eval(Some(new_context.into())).await + value.eval(Some(new_context.into())) } #[node_macro::node(category("Debug"), icon("NodeQuantizeAnimationTime"))] -async fn quantize_animation_time( +fn quantize_animation_time( ctx: impl Ctx + ExtractAll + CloneVarArgs, #[implementations( Context -> Item, @@ -147,11 +147,11 @@ async fn quantize_animation_time( Context -> List, Context -> List, )] - value: impl Node<'n, Context<'static>, Output = T>, + value: impl Node, Output = T>, #[default(1)] #[unit(" sec")] quantum: Item, -) -> T { +) -> Result { let time = ctx.try_animation_time().unwrap_or_default(); let quantum = quantum.into_element(); let mut quantized_time = (time * quantum.recip()).round() / quantum.recip(); @@ -159,7 +159,7 @@ async fn quantize_animation_time( quantized_time = time; } let new_context = OwnedContextImpl::from(ctx).with_animation_time(quantized_time); - value.eval(Some(new_context.into())).await + value.eval(Some(new_context.into())) } /// Produces the current position of the user's pointer within the document canvas. diff --git a/node-graph/nodes/gcore/src/context.rs b/node-graph/nodes/gcore/src/context.rs index eb28a53e9e..66576ad8d3 100644 --- a/node-graph/nodes/gcore/src/context.rs +++ b/node-graph/nodes/gcore/src/context.rs @@ -66,7 +66,7 @@ fn read_number(ctx: impl Ctx + ExtractVarArgs) -> Item { } #[node_macro::node(category("Context"), icon("NodeReadPosition"), path(core_types::vector))] -async fn read_position( +fn read_position( ctx: impl Ctx + ExtractPosition, _primary: (), /// The number of nested loops to traverse outwards (from the innermost loop) to get the position from. The most upstream loop is level 0, and downstream loops add levels. @@ -85,7 +85,7 @@ async fn read_position( /// /// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops. #[node_macro::node(category("Context"), icon("NodeReadIndex"), path(core_types::vector))] -async fn read_index( +fn read_index( ctx: impl Ctx + ExtractIndex, _primary: (), /// The number of nested loops to traverse outwards (from the innermost loop) to get the index from. The most upstream loop is level 0, and downstream loops add levels. diff --git a/node-graph/nodes/gcore/src/context_modification.rs b/node-graph/nodes/gcore/src/context_modification.rs index 8862bba393..d98e54646d 100644 --- a/node-graph/nodes/gcore/src/context_modification.rs +++ b/node-graph/nodes/gcore/src/context_modification.rs @@ -1,8 +1,8 @@ use core::f64; -use core_types::context::{CloneVarArgs, Context, ContextFeatures, Ctx, ExtractAll}; +use core_types::context::{CloneVarArgs, Context, ContextModification, Ctx, ExtractAll}; use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath}; use core_types::transform::Footprint; -use core_types::{Color, OwnedContextImpl}; +use core_types::{Color, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphene_animation::AnimationCurve; use graphic_types::vector_types::Gradient; @@ -12,7 +12,7 @@ use raster_types::{CPU, GPU, Raster}; /// Filters out what should be unused components of the context based on the specified requirements. /// This node is inserted by the compiler to "zero out" unused context components. #[node_macro::node(category("_Context Nullification"))] -async fn context_modification( +fn context_modification( ctx: impl Ctx + CloneVarArgs + ExtractAll, /// The data to pass through, evaluated with the stripped down context. #[implementations( @@ -48,16 +48,18 @@ async fn context_modification( )] value: impl Node, Output = T>, /// The parts of the context to keep when evaluating the input value. All other parts are nullified. - features_to_keep: Item, -) -> T { - let new_context = OwnedContextImpl::from_flags(ctx, features_to_keep.into_element()); + modification: Item, +) -> Result { + let new_context = OwnedContextImpl::from_modification(ctx, modification.element()); - value.eval(Some(new_context.into())).await + value.eval(Some(new_context.into())) } #[cfg(test)] mod tests { use super::*; + use core_types::SourceId; + use core_types::context::ContextFeatures; use core_types::graphene_hash::CacheHash; use core_types::transform::Footprint; use std::collections::hash_map::DefaultHasher; @@ -122,4 +124,41 @@ mod tests { "Hash should be stable when keeping only footprint and varargs and their values are the same" ); } + + fn hash_of(context: OwnedContextImpl) -> u64 { + let mut hasher = DefaultHasher::new(); + context.cache_hash(&mut hasher); + hasher.finish() + } + + fn with_generations(generations: &[(u64, u64)]) -> std::sync::Arc { + let generations = generations.iter().map(|&(source, generation)| (SourceId(source), generation)).collect(); + std::sync::Arc::new(OwnedContextImpl::empty().with_generations(generations)) + } + + #[test] + fn a_modification_keys_only_on_its_retained_sources() { + let modification = ContextModification { + features: ContextFeatures::all(), + sources: [SourceId(1)].into(), + }; + let key = |generations: &[(u64, u64)]| hash_of(OwnedContextImpl::from_modification(with_generations(generations), &modification)); + let initial = key(&[(0, 1), (1, 3)]); + assert_eq!(initial, key(&[(0, 2), (1, 3)]), "a bump of an unretained source keeps the key"); + assert_ne!(initial, key(&[(0, 1), (1, 4)]), "a bump of a retained source changes the key"); + } + + #[test] + fn a_source_key_ignores_its_own_bumps() { + let key = |generations: &[(u64, u64)]| hash_of(OwnedContextImpl::from(with_generations(generations)).without_source(SourceId(7))); + let initial = key(&[(7, 1), (9, 5)]); + assert_eq!(initial, key(&[(7, 2), (9, 5)]), "its own bump keeps the key"); + assert_ne!(initial, key(&[(7, 1), (9, 6)]), "another source's bump changes the key"); + } + + #[test] + fn an_unfiltered_context_sees_every_bump() { + let key = |generations: &[(u64, u64)]| hash_of(OwnedContextImpl::from(with_generations(generations))); + assert_ne!(key(&[(0, 1)]), key(&[(0, 2)])); + } } diff --git a/node-graph/nodes/gcore/src/memo.rs b/node-graph/nodes/gcore/src/memo.rs index a7756b37ec..ced5c70309 100644 --- a/node-graph/nodes/gcore/src/memo.rs +++ b/node-graph/nodes/gcore/src/memo.rs @@ -1,7 +1,7 @@ use core_types::graphene_hash::CacheHash; use core_types::memo::*; use core_types::registry::{DowncastBothNode, DynAnyNode, NODE_REGISTRY, NodeConstructor, PanicNode, TypeErasedBox}; -use core_types::{Context, NodeIO, NodeIOTypes, WasmNotSend, concrete, fn_type_fut, future}; +use core_types::{Context, Interrupt, NodeIO, NodeIOTypes, Poll, WasmNotSend, concrete, fn_type}; use dyn_any::StaticType; use std::hash::DefaultHasher; use std::hash::Hasher; @@ -12,7 +12,7 @@ use std::sync::Mutex; /// /// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed. #[node_macro::node(category("General"), icon("NodeMemoize"), path(graphene_core::memo), skip_impl)] -async fn memoize(input: I, content: impl Node, #[data] cache: Arc>>) -> T { +fn memoize(input: I, content: impl Node, #[data] cache: Arc)>>>) -> Poll { // Caches the output of a given node called with a specific input. // // A cache miss occurs when the Option is None. In this case, the node evaluates the inner node and memoizes (stores) the result. @@ -29,25 +29,27 @@ async fn memoize(input: I, con return data; } - let value = content.eval(input).await; - *cache.lock().unwrap() = Some((hash, value.clone())); - value + let state = content.eval(&input); + if !matches!(state, Poll::Pending | Poll::Error(_)) { + *cache.lock().unwrap() = Some((hash, state.clone())); + } + state } type MonitorValue = Arc>>>>; /// The Monitor node is used by the editor to access the data flowing through it. #[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), inspector("monitor_inspector"), skip_impl)] -async fn monitor( +fn monitor( input: I, content: impl Node, #[allow(clippy::type_complexity)] #[data] io: MonitorValue, -) -> T { - let output = content.eval(input.clone()).await; +) -> Result { + let output = content.eval(input.clone())?; *io.lock().unwrap() = Some(Arc::new(IORecord { input, output: output.clone() })); - output + Ok(output) } fn serialize_monitor(io: &MonitorValue) -> Option> { @@ -58,29 +60,25 @@ fn serialize_monitor + 'static>() { let memoize_constructor: NodeConstructor = |mut arguments| { - Box::pin(async move { - let node = MemoizeNode::new(DowncastBothNode::::new(arguments.pop().expect("Not enough arguments provided to construct node"))); - let any: DynAnyNode = DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = MemoizeNode::new(DowncastBothNode::::new(arguments.pop().expect("Not enough arguments provided to construct node"))); + let any: DynAnyNode = DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }; let monitor_constructor: NodeConstructor = |mut arguments| { - Box::pin(async move { - let node = MonitorNode::new(DowncastBothNode::::new(arguments.pop().expect("Not enough arguments provided to construct node"))); - let any: DynAnyNode = DynAnyNode::new(node); - Box::new(any) as TypeErasedBox - }) + let node = MonitorNode::new(DowncastBothNode::::new(arguments.pop().expect("Not enough arguments provided to construct node"))); + let any: DynAnyNode = DynAnyNode::new(node); + Box::new(any) as TypeErasedBox }; let memoize_types: NodeIOTypes = { - let node = MemoizeNode::new(PanicNode:: + Send>>>::new()); - let mut node_io = NodeIO::<'_, Context>::to_async_node_io(&node, vec![fn_type_fut!(Context, T)]); + let node = MemoizeNode::new(PanicNode::::new()); + let mut node_io = NodeIO::::to_node_io(&node, vec![fn_type!(Context, T)]); node_io.call_argument = concrete!(::Static); node_io }; let monitor_types: NodeIOTypes = { - let node = MonitorNode::new(PanicNode:: + Send>>>::new()); - let mut node_io = NodeIO::<'_, Context>::to_async_node_io(&node, vec![fn_type_fut!(Context, T)]); + let node = MonitorNode::new(PanicNode::::new()); + let mut node_io = NodeIO::::to_node_io(&node, vec![fn_type!(Context, T)]); node_io.call_argument = concrete!(::Static); node_io }; @@ -89,3 +87,46 @@ pub fn register_memoize_and_monitor for Fail { + type Output = u32; + fn eval(&self, _: &()) -> Poll { + Poll::error("error") + } + } + + #[test] + fn an_error_records_the_index_of_the_memoized_input() { + let Poll::Error(error) = MemoizeNode::new(Fail).eval(&()) else { unreachable!() }; + assert_eq!(error.trace(), [0]); + } + + struct StandIn(Arc); + + impl Node<()> for StandIn { + type Output = u32; + fn eval(&self, _: &()) -> Poll { + self.0.fetch_add(1, Ordering::Relaxed); + Poll::fallback(1, "stand-in") + } + } + + #[test] + fn a_fallback_is_memoized_with_its_error() { + let evaluations = Arc::new(AtomicU32::new(0)); + let memo = MemoizeNode::new(StandIn(evaluations.clone())); + + let first = memo.eval(&()); + assert!(matches!(first, Poll::Fallback(_))); + assert_eq!(memo.eval(&()), first); + assert_eq!(evaluations.load(Ordering::Relaxed), 1); + } +} diff --git a/node-graph/nodes/gcore/src/ops.rs b/node-graph/nodes/gcore/src/ops.rs index 1af9e0bdf4..e840aeb14b 100644 --- a/node-graph/nodes/gcore/src/ops.rs +++ b/node-graph/nodes/gcore/src/ops.rs @@ -92,22 +92,22 @@ fn embed_list<'i, T: 'i + Send, E: 'i + Send + From>>(_: impl Ctx, value /// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type. #[node_macro::node(category("_Adapters"), skip_impl)] -async fn convert_item<'i, T: 'i + Send + Convert, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item, _element_ty: PhantomData) -> Item { +fn convert_item<'i, T: 'i + Send + Convert, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item, _element_ty: PhantomData) -> Item { let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT); let (value, attributes) = value.into_parts(); - Item::from_parts(value.convert(footprint, ()).await, attributes) + Item::from_parts(value.convert(footprint, ()), attributes) } /// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type. #[node_macro::node(category("_Adapters"), skip_impl)] -async fn convert_list<'i, T: 'i + Send + Convert, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: List, _element_ty: PhantomData) -> List { +fn convert_list<'i, T: 'i + Send + Convert, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: List, _element_ty: PhantomData) -> List { let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT); let mut result = List::default(); for item in value.into_iter() { let (value, attributes) = item.into_parts(); - result.push(Item::from_parts(value.convert(footprint, ()).await, attributes)); + result.push(Item::from_parts(value.convert(footprint, ()), attributes)); } result diff --git a/node-graph/nodes/graphic/src/artboard.rs b/node-graph/nodes/graphic/src/artboard.rs index 4f20a023c3..9a4498a69f 100644 --- a/node-graph/nodes/graphic/src/artboard.rs +++ b/node-graph/nodes/graphic/src/artboard.rs @@ -1,6 +1,6 @@ use core_types::list::{Item, List}; use core_types::transform::TransformMut; -use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl}; +use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphic_types::graphic::{Graphic, IntoGraphicList}; use graphic_types::{Artboard, Vector}; @@ -9,7 +9,7 @@ use vector_types::Gradient; /// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes. #[node_macro::node(category(""))] -pub async fn create_artboard( +fn create_artboard( ctx: impl ExtractAll + CloneVarArgs + Ctx, /// Graphics to include within the artboard. #[implementations( @@ -34,7 +34,7 @@ pub async fn create_artboard( /// Whether to cut off the contained content that extends outside the artboard, or keep it visible. #[default(true)] clip: Item, -) -> Item { +) -> Result, Interrupt> { let (location, dimensions, clip) = (location.into_element(), dimensions.into_element(), clip.into_element()); let footprint = ctx.try_footprint().copied(); @@ -43,7 +43,7 @@ pub async fn create_artboard( footprint.translate(location); new_ctx = new_ctx.with_footprint(footprint); } - let content = content.eval(new_ctx.into_context()).await.into_graphic_list(); + let content = content.eval(new_ctx.into_context())?.into_graphic_list(); // Normalize so `location` is the top-left corner and `dimensions` are positive (allowing negative input // dimensions to represent dragging from the opposite corner). Compute the corner using the raw signed @@ -54,9 +54,9 @@ pub async fn create_artboard( let background = background.into_element(); // Name is not stored here, it's resolved live from the parent layer's display name - Item::new_from_element(Artboard::new(content)) + Ok(Item::new_from_element(Artboard::new(content)) .with_attribute(ATTR_LOCATION, normalized_location) .with_attribute(ATTR_DIMENSIONS, normalized_dimensions) .with_attribute(ATTR_BACKGROUND, background) - .with_attribute(ATTR_CLIP, clip) + .with_attribute(ATTR_CLIP, clip)) } diff --git a/node-graph/nodes/graphic/src/graphic.rs b/node-graph/nodes/graphic/src/graphic.rs index dbc95140e7..e030284685 100644 --- a/node-graph/nodes/graphic/src/graphic.rs +++ b/node-graph/nodes/graphic/src/graphic.rs @@ -1,7 +1,7 @@ use brush_types::Stroke; use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath}; -use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl}; +use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf}; use graphic_types::{Artboard, Vector}; @@ -15,7 +15,7 @@ use vector_types::{Gradient, ReferencePoint}; /// Returns the list with the item at the specified index removed. /// If no value exists at that index, the list is returned unchanged. #[node_macro::node(category("General"), icon("NodeRemoveAtIndex"), name("Remove at Index"))] -pub fn remove_at_index( +fn remove_at_index( _: impl Ctx, /// The list of data. #[implementations( @@ -49,7 +49,7 @@ pub fn remove_at_index( /// Returns the item at the specified index in a list, keeping its attributes. /// If no value exists at that index, the element type's default is returned. #[node_macro::node(category("General"), icon("NodeItemAtIndex"), name("Item at Index"))] -pub fn item_at_index( +fn item_at_index( _: impl Ctx, /// The list of data to take the item from. #[implementations( @@ -383,7 +383,7 @@ fn sort( +fn map( ctx: impl Ctx + CloneVarArgs + ExtractAll, #[implementations( List, @@ -417,22 +417,22 @@ async fn map( Context -> List, )] mapped: impl Node, Output = List>, -) -> List { +) -> Result, Interrupt> { let mut rows = List::new(); for (i, row) in content.into_iter().enumerate() { let owned_ctx = OwnedContextImpl::from(ctx.clone()); let owned_ctx = owned_ctx.with_vararg(Box::new(row)).with_index(i); - let list = mapped.eval(owned_ctx.into_context()).await; + let list = mapped.eval(owned_ctx.into_context())?; rows.extend(list); } - rows + Ok(rows) } #[node_macro::node(category("General"), icon("NodeMirror"))] -async fn mirror( +fn mirror( _: impl Ctx, #[implementations( Graphic, @@ -503,7 +503,7 @@ async fn mirror( /// editor tools (e.g. selection, click target routing) trace data back to its owning layer regardless of whether /// the layer is at the root document network or nested inside a custom subgraph. #[node_macro::node(name("Path of Subgraph"), category(""))] -pub fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item { +fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item { let node_path = node_path.into_element().0; let len = node_path.len(); Item::new_from_element(NodeIdPath(node_path.into_iter().take(len.saturating_sub(1)).collect())) @@ -516,7 +516,7 @@ pub fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item` by the auto-inserted input adapter, so this node only /// monomorphizes over `T` instead of the cartesian product `(T, U)`. #[node_macro::node(category("Attributes: Write"), icon("NodeWriteAttribute"))] -async fn write_attribute( +fn write_attribute( ctx: impl ExtractAll + CloneVarArgs + Ctx, /// The list to set the named attribute on (one value per item). #[implementations( @@ -541,18 +541,18 @@ async fn write_attribute( /// The attribute name (key) to write or replace. name: Item, /// The node that produces the attribute value for each item. Called once per item with the item's index in context. - value: impl Node<'n, Context<'static>, Output = Item>, -) -> List { + value: impl Node, Output = Item>, +) -> Result, Interrupt> { let name = name.into_element(); let mut content = content; for index in 0..content.len() { let row = content.clone_item(index).expect("index is within bounds"); let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_vararg(Box::new(row)).with_index(index); - let v = value.eval(owned_ctx.into_context()).await.into_element(); + let v = value.eval(owned_ctx.into_context())?.into_element(); content.set_attribute_value_dyn(&name, index, v); } - content + Ok(content) } /// Reads a named `Vector` attribute from the input list, outputting each value as an element of a new `Vector[]`. @@ -813,7 +813,7 @@ fn read_attribute_raster( /// Joins two lists of the same type, extending the base list with the items from the new list. #[node_macro::node(category("General"), icon("NodeExtend"))] -pub async fn extend( +fn extend( _: impl Ctx, /// The list whose items will appear at the start of the extended list. #[implementations( @@ -863,7 +863,7 @@ pub async fn extend( /// Performs an obsolete function as part of a migration from an older document format. /// Users are advised to delete this node and replace it with a new one. #[node_macro::node(category(""))] -pub async fn legacy_layer_extend( +fn legacy_layer_extend( _: impl Ctx, #[implementations(List, List, List, List, List>, List>, List, List)] base: List, #[expose] @@ -890,7 +890,7 @@ pub async fn legacy_layer_extend( /// Nests the input graphical content in a wrapper graphic, collecting it all into a single group. /// The inverse of this node is 'Flatten Graphic'. #[node_macro::node(category("General"), icon("NodeIntoGroup"))] -pub async fn into_group + 'n>( +fn into_group>( _: impl Ctx, #[implementations( List, @@ -912,13 +912,13 @@ pub async fn into_group + 'n>( /// Type-asserts a value to be graphical content, converting each item of other content types into its matching form. /// Use the 'Into Group' node instead to collect the content into a single group. #[node_macro::node(category("General"), icon("NodeAsGraphic"))] -pub async fn as_graphic(_: impl Ctx, value: Item) -> Item { +fn as_graphic(_: impl Ctx, value: Item) -> Item { value } /// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled. #[node_macro::node(category("General"), icon("NodeFlattenGraphic"))] -pub async fn flatten_graphic(_: impl Ctx, content: List, fully_flatten: Item) -> List { +fn flatten_graphic(_: impl Ctx, content: List, fully_flatten: Item) -> List { let fully_flatten = fully_flatten.into_element(); // TODO: Avoid mutable reference, instead return a new List? @@ -963,7 +963,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List, fully_flatten: /// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content. #[node_macro::node(category("Vector"), icon("NodeFlattenVector"))] -pub async fn flatten_vector(_: impl Ctx, content: List) -> List { +pub fn flatten_vector(_: impl Ctx, content: List) -> List { let mut output: List = content.clone().into_flattened_list(); // TODO: Replace this snapshot hack with per-layer metadata driven by each layer's Monitor node. @@ -995,19 +995,19 @@ pub async fn flatten_vector(_: impl Ctx, content: List) -> List /// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content. #[node_macro::node(category("Raster"), icon("NodeFlattenRaster"))] -pub async fn flatten_raster(_: impl Ctx, content: List) -> List> { +fn flatten_raster(_: impl Ctx, content: List) -> List> { content.into_flattened_list() } /// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content. #[node_macro::node(category("General"), icon("NodeFlattenColor"))] -pub async fn flatten_color(_: impl Ctx, content: List) -> List { +fn flatten_color(_: impl Ctx, content: List) -> List { content.into_flattened_list() } /// Converts a `Graphic[]` into a `Gradient[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content. #[node_macro::node(category("General"), icon("NodeFlattenGradient"))] -pub async fn flatten_gradient(_: impl Ctx, content: List) -> List { +fn flatten_gradient(_: impl Ctx, content: List) -> List { content.into_flattened_list() } diff --git a/node-graph/nodes/gstd/src/any.rs b/node-graph/nodes/gstd/src/any.rs index c8959d23e2..6aa4eced61 100644 --- a/node-graph/nodes/gstd/src/any.rs +++ b/node-graph/nodes/gstd/src/any.rs @@ -1,10 +1,8 @@ -use core_types::NodeIO; use core_types::WasmNotSend; -pub use core_types::registry::{DowncastBothNode, DynAnyNode, FutureWrapperNode, PanicNode}; +pub use core_types::registry::{DowncastBothNode, DynAnyNode, PanicNode}; pub use core_types::{Node, generic, ops}; -use dyn_any::StaticType; -pub use graph_craft::proto::{Any, NodeContainer, TypeErasedBox, TypeErasedNode}; -use graph_craft::proto::{FutureAny, SharedNodeContainer}; +use graph_craft::proto::SharedNodeContainer; +pub use graph_craft::proto::{Any, AnyInput, NodeContainer, TypeErasedBox, TypeErasedNode}; pub trait IntoTypeErasedNode<'n> { fn into_type_erased(self) -> TypeErasedBox<'n>; @@ -12,16 +10,16 @@ pub trait IntoTypeErasedNode<'n> { impl<'n, N: 'n> IntoTypeErasedNode<'n> for N where - N: for<'i> NodeIO<'i, Any<'i>, Output = FutureAny<'i>> + Sync + WasmNotSend, + N: Node + Sync + WasmNotSend, { fn into_type_erased(self) -> TypeErasedBox<'n> { Box::new(self) } } -pub fn input_node(n: SharedNodeContainer) -> DowncastBothNode<(), O> { +pub fn input_node(n: SharedNodeContainer) -> DowncastBothNode<(), O> { downcast_node(n) } -pub fn downcast_node(n: SharedNodeContainer) -> DowncastBothNode { +pub fn downcast_node(n: SharedNodeContainer) -> DowncastBothNode { DowncastBothNode::new(n) } diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index e75853f9a6..9070541167 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -1,5 +1,6 @@ pub mod any; pub mod platform_application_io; +pub mod poll_debug; pub mod render_background; pub mod render_cache; pub mod render_node; diff --git a/node-graph/nodes/gstd/src/platform_application_io.rs b/node-graph/nodes/gstd/src/platform_application_io.rs index 13f81dbcff..9009d93928 100644 --- a/node-graph/nodes/gstd/src/platform_application_io.rs +++ b/node-graph/nodes/gstd/src/platform_application_io.rs @@ -24,6 +24,7 @@ use graphic_types::raster_types::Image; use graphic_types::raster_types::{CPU, GPU, Raster}; #[cfg(target_family = "wasm")] use rendering::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; +use std::sync::Arc; fn parse_headers(headers: &str) -> reqwest::header::HeaderMap { use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; @@ -40,7 +41,7 @@ fn parse_headers(headers: &str) -> reqwest::header::HeaderMap { } /// Sends an HTTP GET request to a specified URL and optionally waits for the response (unless discarded) which is output as a string. -#[node_macro::node(category("Web Request"), icon("NodeGetRequest"))] +#[node_macro::node(category("Web Request"), icon("NodeGetRequest"), placeholder = pending_text)] async fn get_request( _: impl Ctx, _primary: (), @@ -58,14 +59,7 @@ async fn get_request( let request = reqwest::Client::new().get(url).headers(header_map); if discard_result { - #[cfg(target_family = "wasm")] - wasm_bindgen_futures::spawn_local(async move { - let _ = request.send().await; - }); - #[cfg(all(not(target_family = "wasm"), feature = "tokio"))] - tokio::spawn(async move { - let _ = request.send().await; - }); + let _ = request.send().await; return Item::default(); } @@ -75,8 +69,12 @@ async fn get_request( Item::new_from_element(response.text().await.ok().unwrap_or_default()) } +fn pending_text(_primary: &(), _url: &Item, _discard_result: &Item, _headers: &Item) -> Item { + Item::default() +} + /// Sends an HTTP POST request to a specified URL with the provided binary data and optionally waits for the response (unless discarded) which is output as a string. -#[node_macro::node(category("Web Request"), icon("NodePostRequest"))] +#[node_macro::node(category("Web Request"), icon("NodePostRequest"), placeholder = pending_post_text)] async fn post_request( _: impl Ctx, _primary: (), @@ -98,14 +96,7 @@ async fn post_request( let request = reqwest::Client::new().post(url).body(body_bytes).headers(header_map); if discard_result { - #[cfg(target_family = "wasm")] - wasm_bindgen_futures::spawn_local(async move { - let _ = request.send().await; - }); - #[cfg(all(not(target_family = "wasm"), feature = "tokio"))] - tokio::spawn(async move { - let _ = request.send().await; - }); + let _ = request.send().await; return Item::default(); } @@ -115,6 +106,10 @@ async fn post_request( Item::new_from_element(response.text().await.ok().unwrap_or_default()) } +fn pending_post_text(_primary: &(), _url: &Item, _body: &Item, _discard_result: &Item, _headers: &Item) -> Item { + Item::default() +} + /// Converts a text string to raw binary data. Useful for transmission over HTTP or writing to files. #[node_macro::node(category("Web Request"), icon("NodeStringToBytes"), name("String to Bytes"))] fn string_to_bytes(_: impl Ctx, string: Item) -> Item { @@ -138,8 +133,8 @@ fn image_to_bytes(_: impl Ctx, image: Item>) -> Item { } /// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue. -#[node_macro::node(category("Web Request"), icon("NodeLoadResource"))] -async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: Item) -> Item { +#[node_macro::node(category("Web Request"), icon("NodeLoadResource"), placeholder = pending_resource)] +async fn load_resource(_: impl Ctx, _primary: (), #[name("URL")] url: Item) -> Item { let url = url.into_element(); let placeholder = || -> Item { Item::new_from_element(Resource::empty()) }; @@ -160,6 +155,10 @@ async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: It } } +fn pending_resource(_primary: &(), _url: &Item) -> Item { + Item::new_from_element(Resource::empty()) +} + /// Converts the raw byte data of an image file to a raster image. /// /// Supports the formats: PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, EXR. @@ -173,13 +172,13 @@ fn decode_image(_: impl Ctx, data: Item) -> Item> { #[cfg(target_family = "wasm")] #[node_macro::node(category(""))] -async fn create_canvas(_: impl Ctx) -> Item { +fn create_canvas(_: impl Ctx) -> Item { Item::new_from_element(CanvasHandle::new()) } /// Renders a view of the input graphic within an area defined by the *Footprint*. #[cfg(target_family = "wasm")] -#[node_macro::node(category(""))] +#[node_macro::node(category(""), placeholder = pending_raster)] async fn rasterize(_: impl Ctx, data: List, footprint: Item, canvas: Item) -> List> { let mut data = data; let mut canvas = canvas.into_element(); @@ -238,24 +237,30 @@ async fn rasterize(_: impl Ctx, data: List, footprint: Item, ) } +#[cfg(target_family = "wasm")] +fn pending_raster(_data: &List, _footprint: &Item, _canvas: &Item) -> List> { + List::new() +} + #[node_macro::node(category(""), inject_scope)] -pub async fn editor_api<'a: 'n>(_: impl Ctx, #[scope("editor-api")] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a PlatformEditorApi> { +fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item>) -> Item> { editor_api } -#[node_macro::node(category(""))] -pub async fn resource<'a: 'n>( +#[node_macro::node(category(""), placeholder = pending_stored_resource)] +async fn resource( _: impl Ctx, /// The scope-provided editor API giving access to the platform's resource storage. #[scope(editor_api::IDENTIFIER)] - editor_api: Item<&'a PlatformEditorApi>, + editor_api: Item>, /// The content hash identifying which stored resource to load. hash: Item, ) -> Item { let hash = hash.into_element(); let placeholder = || -> Item { Item::new_from_element(Resource::empty()) }; - let Some(application_io) = editor_api.into_element().application_io.as_ref() else { + let editor_api = editor_api.into_element(); + let Some(application_io) = editor_api.application_io.as_ref() else { log::error!("Resource {hash} is unavailable because the platform's application IO is missing"); return placeholder(); }; @@ -268,29 +273,34 @@ pub async fn resource<'a: 'n>( Item::new_from_element(resource) } +fn pending_stored_resource(_editor_api: &Item>, _hash: &Item) -> Item { + Item::new_from_element(Resource::empty()) +} + #[node_macro::node(category(""), inject_scope)] -pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item<&'a ::wgpu_executor::WgpuExecutor> { +fn wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item>) -> Item<::wgpu_executor::WgpuExecutor> { let executor = editor_api .into_element() .application_io .as_ref() .expect("ApplicationIo not available") .gpu_executor() - .expect("GPU executor not available"); + .expect("GPU executor not available") + .clone(); Item::new_from_element(executor) } #[node_macro::node(category(""), inject_scope)] -pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>) -> Item> { - let executor = editor_api.into_element().application_io.as_ref().and_then(|application_io| application_io.gpu_executor()); +fn try_wgpu_executor(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item>) -> Item> { + let executor = editor_api.into_element().application_io.as_ref().and_then(|application_io| application_io.gpu_executor()).cloned(); Item::new_from_element(executor) } /// Uploads image data from CPU memory into a GPU texture so that GPU-based nodes can process it. #[node_macro::node(category("Debug"), icon("NodeUploadTexture"), memoize)] -pub async fn upload_texture<'a: 'n>(_: impl Ctx, content: Item>, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<&'a ::wgpu_executor::WgpuExecutor>) -> Item> { +fn upload_texture(_: impl Ctx, content: Item>, #[scope(wgpu_executor::IDENTIFIER)] executor: Item<::wgpu_executor::WgpuExecutor>) -> Item> { let executor = executor.into_element(); let (raster, attributes) = content.into_parts(); - Item::from_parts(raster.convert(Footprint::DEFAULT, executor).await, attributes) + Item::from_parts(raster.convert(Footprint::DEFAULT, executor), attributes) } diff --git a/node-graph/nodes/gstd/src/poll_debug.rs b/node-graph/nodes/gstd/src/poll_debug.rs new file mode 100644 index 0000000000..cd40cb3c3d --- /dev/null +++ b/node-graph/nodes/gstd/src/poll_debug.rs @@ -0,0 +1,131 @@ +use core_types::list::Item; +use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractGenerations, Interrupt, NodeError, OwnedContextImpl, Poll}; +use graphic_types::{Graphic, Vector}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +#[node_macro::node(category("Debug"), placeholder = pending_delay)] +async fn delay( + _: impl Ctx, + #[implementations(f64, String, Vector, Graphic)] value: Item, + #[default(1.)] + #[unit(" sec")] + seconds: Item, +) -> Item { + sleep(*seconds.element()).await; + value +} + +fn pending_delay(_value: &Item, _seconds: &Item) -> Item { + Item::default() +} + +#[node_macro::node(category("Debug"))] +async fn hold( + _: impl Ctx, + #[implementations(f64, String, Vector, Graphic)] value: Item, + #[default(1.)] + #[unit(" sec")] + seconds: Item, +) -> Item { + sleep(*seconds.element()).await; + value +} + +#[node_macro::node(category("Debug"))] +fn error(_: impl Ctx, #[implementations(f64, String, Vector, Graphic)] value: Item, #[default(true)] fail: Item) -> Result, Interrupt> { + match *fail.element() { + true => Err(NodeError::new("debug error").into()), + false => Ok(value), + } +} + +#[node_macro::node(category("Debug"))] +fn fallback(_: impl Ctx, #[implementations(f64, String, Vector, Graphic)] value: Item, #[default(true)] fail: Item) -> Result, (Item, NodeError)> { + match *fail.element() { + true => Err((Item::default(), NodeError::new("debug fallback"))), + false => Ok(value), + } +} + +#[node_macro::node(category("Debug"), name("Panic"))] +fn unwind(_: impl Ctx, #[implementations(f64, String, Vector, Graphic)] value: Item, fail: Item) -> Item { + if *fail.element() { + panic!("debug panic"); + } + value +} + +#[node_macro::node(category("Debug"))] +fn evaluation_count(_: impl Ctx, #[implementations(f64, String, Vector, Graphic)] value: Item, #[data] count: Arc) -> Item { + let count = count.fetch_add(1, Ordering::Relaxed) + 1; + log::info!("Debug evaluation count: {count}"); + value +} + +#[node_macro::node(category("Debug"))] +fn generations(ctx: impl Ctx + ExtractGenerations, value: Item) -> Item { + let generations = ctx + .try_generations() + .map(|generations| generations.iter().map(|(source, generation)| format!("{:x}={generation}", source.0)).collect::>().join(", ")) + .unwrap_or_default(); + Item::new_from_element(format!("{} [{generations}]", value.element())) +} + +#[node_macro::node(category("Debug"), name("Stand-In"))] +fn stand_in( + ctx: impl Ctx + ExtractAll + CloneVarArgs, + #[expose] + #[implementations(Context -> Item, Context -> Item, Context -> Item, Context -> Item)] + content: impl Node, Output = T>, + #[implementations(Item, Item, Item, Item)] placeholder: T, +) -> Poll { + match content.eval(&OwnedContextImpl::from(ctx).into_context()) { + Poll::Pending | Poll::Partial(_) => Poll::Partial(placeholder), + finished => finished, + } +} + +#[cfg(not(target_family = "wasm"))] +async fn sleep(seconds: f64) { + use std::sync::Mutex; + use std::task::{Poll, Waker}; + + #[derive(Default)] + struct Timer(Arc)>>); + + impl Future for Timer { + type Output = (); + fn poll(self: std::pin::Pin<&mut Self>, context: &mut std::task::Context<'_>) -> Poll<()> { + let mut state = self.0.lock().unwrap(); + if state.0 { + return Poll::Ready(()); + } + state.1 = Some(context.waker().clone()); + Poll::Pending + } + } + + let timer = Timer::default(); + let state = Arc::clone(&timer.0); + std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_secs_f64(seconds.max(0.))); + let mut state = state.lock().unwrap(); + state.0 = true; + if let Some(waker) = state.1.take() { + waker.wake(); + } + }); + timer.await +} + +#[cfg(target_family = "wasm")] +async fn sleep(seconds: f64) { + let promise = web_sys::js_sys::Promise::new(&mut |resolve, _| { + let window = web_sys::window().expect("a window exists on the web"); + window + .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, (seconds.max(0.) * 1000.) as i32) + .expect("setTimeout accepts a function"); + }); + let _ = wasm_bindgen_futures::JsFuture::from(promise).await; +} diff --git a/node-graph/nodes/gstd/src/render_background.rs b/node-graph/nodes/gstd/src/render_background.rs index ae60d18974..c4d2f493f6 100644 --- a/node-graph/nodes/gstd/src/render_background.rs +++ b/node-graph/nodes/gstd/src/render_background.rs @@ -9,10 +9,10 @@ use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graphic_types::raster_types::Texture; use rendering::{RenderParams, SvgRender, SvgRenderOutput}; use std::fmt::Write; -use wgpu_executor::{AsyncWgpuPipeline, Buffer, WgpuExecutor, WgpuPipelineCache}; +use wgpu_executor::{Buffer, WgpuExecutor, WgpuPipeline, WgpuPipelineCache}; #[node_macro::node(category(""))] -async fn render_background<'a: 'n>( +fn render_background( ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: Item, data: Item, @@ -35,15 +35,12 @@ async fn render_background<'a: 'n>( let data = match foreground_data { RenderOutputType::Texture(foreground_texture) => { let doc_to_screen = render_params.footprint.transform.as_affine2(); - let blended = pipeline - .into_element() - .run::(&CompositeBackgroundArgs { - foreground: foreground_texture.as_ref(), - backgrounds: &metadata.backgrounds, - document_to_screen: doc_to_screen, - zoom: render_params.viewport_zoom.unwrap_or(1.).to_f32(), - }) - .await; + let blended = pipeline.into_element().run::(&CompositeBackgroundArgs { + foreground: foreground_texture.as_ref(), + backgrounds: &metadata.backgrounds, + document_to_screen: doc_to_screen, + zoom: render_params.viewport_zoom.unwrap_or(1.).to_f32(), + }); RenderOutputType::Texture(blended) } @@ -122,9 +119,9 @@ async fn render_background<'a: 'n>( } #[node_macro::node(category(""), inject_scope)] -async fn composite_background_pipeline<'a: 'n>( +fn composite_background_pipeline( _ctx: impl Ctx, - #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, + #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, #[data] pipeline: WgpuPipelineCache, ) -> Item { if let Some(executor) = executor.into_element() { @@ -149,7 +146,7 @@ pub struct CompositeBackgroundArgs<'a> { zoom: f32, } -impl AsyncWgpuPipeline for CompositeBackground { +impl WgpuPipeline for CompositeBackground { type Args<'a> = CompositeBackgroundArgs<'a>; type Out = Texture; @@ -332,7 +329,7 @@ impl AsyncWgpuPipeline for CompositeBackground { } } - async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out { + fn run(&self, executor: &WgpuExecutor, args: &Self::Args<'_>) -> Self::Out { let &CompositeBackgroundArgs { foreground, backgrounds, diff --git a/node-graph/nodes/gstd/src/render_cache.rs b/node-graph/nodes/gstd/src/render_cache.rs index a87c5689d2..6e52056504 100644 --- a/node-graph/nodes/gstd/src/render_cache.rs +++ b/node-graph/nodes/gstd/src/render_cache.rs @@ -3,11 +3,10 @@ use core_types::list::Item; use core_types::math::bbox::AxisAlignedBbox; use core_types::transform::{Footprint, RenderQuality, Transform}; -use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, OwnedContextImpl}; +use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, Generations, OwnedContextImpl, Poll}; use glam::{DAffine2, DVec2, IVec2, UVec2}; use graph_craft::application_io::PlatformEditorApi; use graph_craft::document::value::{RenderOutput, RenderOutputType}; -use graphene_application_io::Texture; use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams}; use std::collections::HashSet; use std::hash::Hash; @@ -27,10 +26,9 @@ pub struct TileCoord { #[derive(Debug, Clone)] pub struct CachedRegion { - pub texture: Texture, - pub texture_size: UVec2, + pub output: Poll, + pub size: UVec2, pub tiles: Vec, - pub metadata: rendering::RenderMetadata, last_access: u64, memory_size: usize, } @@ -49,6 +47,7 @@ pub struct CacheKey { pub animation_time_ms: i64, pub real_time_ms: i64, pub pointer: [u8; 16], + pub generations: Generations, } impl CacheKey { @@ -66,6 +65,7 @@ impl CacheKey { animation_time: f64, real_time: f64, pointer: Option, + generations: Generations, ) -> Self { let pointer_bytes = pointer .map(|p| { @@ -91,6 +91,7 @@ impl CacheKey { animation_time_ms: (animation_time * 1000.).round() as i64, real_time_ms: (real_time * 1000.).round() as i64, pointer: pointer_bytes, + generations, } } } @@ -323,18 +324,18 @@ fn flood_fill(start: &TileCoord, tile_set: &HashSet, visited: &mut Ha } #[node_macro::node(category(""))] -pub async fn render_output_cache<'a: 'n>( +fn render_output_cache( ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync, - #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, - #[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item<&'a PlatformEditorApi>, + #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, + #[scope(crate::platform_application_io::editor_api::IDENTIFIER)] editor_api: Item>, data: impl Node, Output = Item> + Send + Sync, #[data] tile_cache: TileCache, -) -> Item { +) -> Poll> { let footprint = ctx.footprint(); let Some(mut render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::().cloned()) else { log::warn!("render_output_cache: missing or invalid render params, falling back to direct render"); let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint); - return data.eval(context.into_context()).await; + return data.eval(&context.into_context()); }; render_params.viewport_zoom = if let RenderMode::Outline = render_params.render_mode { render_params.viewport_zoom } else { None }; @@ -343,7 +344,7 @@ pub async fn render_output_cache<'a: 'n>( let physical_resolution = footprint.resolution; if !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || physical_resolution.x == 0 || physical_resolution.y == 0 { let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone())); - return data.eval(context.into_context()).await; + return data.eval(&context.into_context()); } let zoom = footprint.scale_magnitudes().x; @@ -370,41 +371,53 @@ pub async fn render_output_cache<'a: 'n>( ctx.try_animation_time().unwrap_or(0.), ctx.try_real_time().unwrap_or(0.), ctx.try_pointer_position(), + ctx.try_generations().cloned().unwrap_or_default(), ); let cache_query = tile_cache.query(&viewport_bounds_device, &cache_key, max_region_area); + // If no regions, fall back to direct render + if cache_query.cached_regions.is_empty() && cache_query.missing_regions.iter().all(|region| region.tiles.is_empty()) { + let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone())); + return data.eval(&context.into_context()); + } + let mut new_regions = Vec::new(); - for missing_region in &cache_query.missing_regions { - if missing_region.tiles.is_empty() { - continue; + for missing_region in cache_query.missing_regions.iter().filter(|region| !region.tiles.is_empty()) { + let region = render_missing_region(missing_region, |ctx| data.eval(&ctx), ctx.clone(), &render_params, &footprint.transform, &device_origin_offset); + match ®ion.output { + Poll::Pending => return Poll::Pending, + Poll::Error(error) => return Poll::Error(error.clone()), + Poll::Final(_) | Poll::Partial(_) | Poll::Fallback(_) => new_regions.push(region), } - let region = render_missing_region(missing_region, |ctx| data.eval(ctx), ctx.clone(), &render_params, &footprint.transform, &device_origin_offset).await; - new_regions.push(region); } tile_cache.store_regions(new_regions.clone()); let all_regions: Vec<_> = cache_query.cached_regions.into_iter().chain(new_regions).collect(); - - // If no regions, fall back to direct render - if all_regions.is_empty() { - let context = OwnedContextImpl::from(ctx.clone()).with_footprint(*footprint).with_vararg(Box::new(render_params.clone())); - return data.eval(context.into_context()).await; - } + let partial = all_regions.iter().any(|region| matches!(region.output, Poll::Partial(_))); + let error = all_regions.iter().find_map(|region| match ®ion.output { + Poll::Fallback(boxed) => Some(boxed.1.clone()), + Poll::Final(_) | Poll::Partial(_) | Poll::Pending | Poll::Error(_) => None, + }); let executor = executor.into_element().expect("GPU executor not available"); let output_texture = executor.request_texture(physical_resolution); - let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, executor); + let combined_metadata = composite_cached_regions(&all_regions, &output_texture, &device_origin_offset, &footprint.transform, &executor); - Item::new_from_element(RenderOutput { + let output = Item::new_from_element(RenderOutput { data: RenderOutputType::Texture(output_texture), metadata: combined_metadata, - }) + }); + match (partial, error) { + (true, _) => Poll::Partial(output), + (false, Some(error)) => Poll::Fallback(Box::new((output, error))), + (false, None) => Poll::Final(output), + } } -async fn render_missing_region( +fn render_missing_region( region: &RenderRegion, render_fn: F, ctx: impl Ctx + ExtractAll + CloneVarArgs, @@ -413,8 +426,7 @@ async fn render_missing_region( viewport_origin_offset: &DVec2, ) -> CachedRegion where - F: Fn(Context<'static>) -> Fut, - Fut: std::future::Future>, + F: Fn(Context<'static>) -> Poll>, { let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y))); let max_tile = region.tiles.iter().fold(IVec2::new(i32::MIN, i32::MIN), |acc, t| acc.max(IVec2::new(t.x, t.y))); @@ -432,24 +444,18 @@ where let region_params = render_params.clone(); let region_ctx = OwnedContextImpl::from(ctx).with_footprint(region_footprint).with_vararg(Box::new(region_params)).into_context(); - let mut result = render_fn(region_ctx).await.into_element(); - - let RenderOutputType::Texture(texture) = result.data else { - unreachable!("render_missing_region: expected texture output from Vello render"); - }; - - let pixel_to_document = region_transform.inverse(); - result.metadata.apply_transform(pixel_to_document); - - let memory_size = (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL; + let output = render_fn(region_ctx).map(|output| { + let mut output = output.into_element(); + output.metadata.apply_transform(region_transform.inverse()); + output + }); CachedRegion { - texture, - texture_size: region_pixel_size, + output, + size: region_pixel_size, tiles: region.tiles.clone(), - metadata: result.metadata, last_access: 0, - memory_size, + memory_size: (region_pixel_size.x * region_pixel_size.y) as usize * BYTES_PER_PIXEL, } } @@ -468,29 +474,38 @@ fn composite_cached_regions( let mut combined_metadata = rendering::RenderMetadata::default(); for region in regions { + let output = match ®ion.output { + Poll::Final(output) | Poll::Partial(output) => output, + Poll::Fallback(boxed) => &boxed.0, + Poll::Pending | Poll::Error(_) => unreachable!("Only rendered regions are composited"), + }; + let RenderOutputType::Texture(texture) = &output.data else { + unreachable!("composite_cached_regions: expected texture output from Vello render"); + }; + let min_tile = region.tiles.iter().fold(IVec2::new(i32::MAX, i32::MAX), |acc, t| acc.min(IVec2::new(t.x, t.y))); // Convert global tile position to physical pixel offset in the output texture let offset_pixels = min_tile * TILE_SIZE as i32 + device_origin_offset.round().as_ivec2(); let (src_x, dst_x, width) = if offset_pixels.x >= 0 { - (0, offset_pixels.x as u32, region.texture_size.x.min(output_resolution.x.saturating_sub(offset_pixels.x as u32))) + (0, offset_pixels.x as u32, region.size.x.min(output_resolution.x.saturating_sub(offset_pixels.x as u32))) } else { let skip = (-offset_pixels.x) as u32; - (skip, 0, region.texture_size.x.saturating_sub(skip).min(output_resolution.x)) + (skip, 0, region.size.x.saturating_sub(skip).min(output_resolution.x)) }; let (src_y, dst_y, height) = if offset_pixels.y >= 0 { - (0, offset_pixels.y as u32, region.texture_size.y.min(output_resolution.y.saturating_sub(offset_pixels.y as u32))) + (0, offset_pixels.y as u32, region.size.y.min(output_resolution.y.saturating_sub(offset_pixels.y as u32))) } else { let skip = (-offset_pixels.y) as u32; - (skip, 0, region.texture_size.y.saturating_sub(skip).min(output_resolution.y)) + (skip, 0, region.size.y.saturating_sub(skip).min(output_resolution.y)) }; if width > 0 && height > 0 { encoder.copy_texture_to_texture( wgpu::TexelCopyTextureInfo { - texture: region.texture.as_ref(), + texture: texture.as_ref(), mip_level: 0, origin: wgpu::Origin3d { x: src_x, y: src_y, z: 0 }, aspect: wgpu::TextureAspect::All, @@ -509,7 +524,7 @@ fn composite_cached_regions( ); } - let mut region_metadata = region.metadata.clone(); + let mut region_metadata = output.metadata.clone(); region_metadata.apply_transform(*viewport_transform); combined_metadata.merge(®ion_metadata); } diff --git a/node-graph/nodes/gstd/src/render_node.rs b/node-graph/nodes/gstd/src/render_node.rs index 094041fb41..b84476e942 100644 --- a/node-graph/nodes/gstd/src/render_node.rs +++ b/node-graph/nodes/gstd/src/render_node.rs @@ -1,7 +1,7 @@ use core_types::list::{Item, List}; use core_types::transform::{Footprint, Transform}; use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs}; -use core_types::{Color, Context, Ctx, ExtractFootprint, OwnedContextImpl, WasmNotSend}; +use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, OwnedContextImpl, WasmNotSend}; use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graphene_application_io::{ExportFormat, RenderConfig}; use graphic_types::raster_types::{CPU, Raster}; @@ -23,7 +23,7 @@ pub struct RenderIntermediate { } #[node_macro::node(category(""))] -async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + Sync>( +fn render_intermediate( ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs, #[implementations( Context -> List, @@ -35,7 +35,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + Context -> List, )] data: impl Node, Output = T>, -) -> Item { +) -> Result, Interrupt> { let render_params = ctx .vararg(0) .expect("Did not find var args") @@ -43,7 +43,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + .expect("Downcasting render params yielded invalid type"); let ctx = OwnedContextImpl::from(ctx.clone()).into_context(); - let data = data.eval(ctx).await; + let data = data.eval(ctx)?; let footprint = Footprint::default(); let mut metadata = RenderMetadata::default(); @@ -72,13 +72,13 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send + } }; - Item::new_from_element(intermediate) + Ok(Item::new_from_element(intermediate)) } #[node_macro::node(category(""))] -async fn render<'a: 'n>( +fn render( ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, - #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, + #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, data: Item, ) -> Item { let footprint = ctx.footprint(); @@ -136,7 +136,6 @@ async fn render<'a: 'n>( .into_element() .expect("GPU executor not available") .render_vello_scene(&transformed_scene, footprint.resolution, context, None) - .await .expect("Failed to render Vello scene"); RenderOutputType::Texture(texture) } @@ -147,11 +146,11 @@ async fn render<'a: 'n>( } #[node_macro::node(category(""))] -async fn create_context<'a: 'n>( +fn create_context( // The executor boundary supplies the render config as the sole vararg (see `wrap_network_in_scope()`) ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync, data: impl Node, Output = Item>, -) -> Item { +) -> Result, Interrupt> { let render_config = ctx.vararg(0).ok().and_then(|config| config.downcast_ref::()).copied().unwrap_or_else(|| { log::error!("The boundary context is missing its render config vararg"); RenderConfig::default() @@ -183,10 +182,11 @@ async fn create_context<'a: 'n>( .with_animation_time(render_config.time.animation_time.as_secs_f64()) .with_pointer_position(render_config.pointer) .with_vararg(Box::new(render_params)) + .with_generations(ctx.try_generations().cloned().unwrap_or_default()) .into_context(); - let mut result = data.eval(ctx).await; + let mut result = data.eval(ctx)?; result.element_mut().metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale))); - result + Ok(result) } diff --git a/node-graph/nodes/gstd/src/render_pixel_preview.rs b/node-graph/nodes/gstd/src/render_pixel_preview.rs index eb1546b022..7f4bc7cc0a 100644 --- a/node-graph/nodes/gstd/src/render_pixel_preview.rs +++ b/node-graph/nodes/gstd/src/render_pixel_preview.rs @@ -1,23 +1,23 @@ use core_types::list::Item; use core_types::transform::{Footprint, Transform}; -use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, OwnedContextImpl}; +use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2, UVec2, Vec2}; use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graphic_types::raster_types::Texture; use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams}; use vector_types::vector::style::RenderMode; -use wgpu_executor::{AsyncWgpuPipeline, WgpuExecutor, WgpuPipelineCache}; +use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache}; #[node_macro::node(category(""))] -pub async fn render_pixel_preview<'a: 'n>( +fn render_pixel_preview( ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync, #[scope(pixel_preview_pipeline::IDENTIFIER)] pipeline: Item, data: impl Node, Output = Item> + Send + Sync, -) -> Item { +) -> Result, Interrupt> { let Some(render_params) = ctx.vararg(0).ok().and_then(|v| v.downcast_ref::()).cloned() else { log::error!("invalid render params for pixel preview"); let context = OwnedContextImpl::from(ctx).into_context(); - return data.eval(context).await; + return data.eval(context); }; let physical_scale = render_params.scale; @@ -26,7 +26,7 @@ pub async fn render_pixel_preview<'a: 'n>( if render_params.render_mode != RenderMode::PixelPreview || !matches!(render_params.render_output_type, RenderOutputTypeRequest::Vello) || viewport_zoom <= 1. { let context = OwnedContextImpl::from(ctx).into_context(); - return data.eval(context).await; + return data.eval(context); } let physical_resolution = footprint.resolution; @@ -53,35 +53,32 @@ pub async fn render_pixel_preview<'a: 'n>( }; let new_ctx = OwnedContextImpl::from(ctx).with_footprint(upstream_footprint).with_vararg(Box::new(render_params)).into_context(); - let mut result = data.eval(new_ctx).await.into_element(); + let mut result = data.eval(new_ctx)?.into_element(); let RenderOutputType::Texture(ref source_texture) = result.data else { - return Item::new_from_element(result); + return Ok(Item::new_from_element(result)); }; let logical_transform = DAffine2::from_scale(DVec2::splat(1. / physical_scale)) * footprint.transform; let transform = DAffine2::from_translation(-upstream_min) * logical_transform.inverse() * DAffine2::from_scale(logical_resolution); - let resampled = pipeline - .into_element() - .run::(&PixelPreviewArgs { - source: source_texture.as_ref(), - transform: &transform, - size: physical_resolution, - }) - .await; + let resampled = pipeline.into_element().run::(&PixelPreviewArgs { + source: source_texture.as_ref(), + transform: &transform, + size: physical_resolution, + }); result.data = RenderOutputType::Texture(resampled); result.metadata.apply_transform(footprint.transform * DAffine2::from_translation(upstream_min)); - Item::new_from_element(result) + Ok(Item::new_from_element(result)) } #[node_macro::node(category(""), inject_scope)] -async fn pixel_preview_pipeline<'a: 'n>( +fn pixel_preview_pipeline( _ctx: impl Ctx, - #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, + #[scope(crate::platform_application_io::try_wgpu_executor::IDENTIFIER)] executor: Item>, #[data] pipeline: WgpuPipelineCache, ) -> Item { if let Some(executor) = executor.into_element() { @@ -101,7 +98,7 @@ pub struct PixelPreviewArgs<'a> { size: UVec2, } -impl AsyncWgpuPipeline for PixelPreview { +impl WgpuPipeline for PixelPreview { type Args<'a> = PixelPreviewArgs<'a>; type Out = Texture; @@ -173,7 +170,7 @@ impl AsyncWgpuPipeline for PixelPreview { PixelPreview { pipeline, bind_group_layout } } - async fn run<'a>(&'a self, executor: &'a WgpuExecutor, args: &'a Self::Args<'_>) -> Self::Out { + fn run(&self, executor: &WgpuExecutor, args: &Self::Args<'_>) -> Self::Out { let context = &executor.context(); let &PixelPreviewArgs { source, transform, size } = args; diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index dcea6069b7..410937fda9 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -1,9 +1,9 @@ -use core_types::Context; use core_types::FallibleVec2Operations; use core_types::context::{CloneVarArgs, ExtractAll}; use core_types::list::{Bundle, Item, List}; use core_types::transform::Footprint; use core_types::{Color, Ctx, OwnedContextImpl, num_traits}; +use core_types::{Context, Interrupt}; use glam::{DAffine2, DMat2, DVec2}; use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::{Artboard, Graphic, Vector}; @@ -1377,7 +1377,7 @@ fn logical_not( /// Evaluates either the "If True" or "If False" input branch based on whether the input condition is true or false. #[node_macro::node(category("Math: Logic"), icon("NodeSwitch"))] -async fn switch( +fn switch( ctx: impl Ctx + CloneVarArgs + ExtractAll, condition: Item, #[expose] @@ -1440,10 +1440,10 @@ async fn switch( Context -> Item>, )] if_false: impl Node, Output = Item>, -) -> Item { +) -> Result, Interrupt> { let ctx = OwnedContextImpl::from(ctx).into_context(); - if *condition.element() { if_true.eval(ctx).await } else { if_false.eval(ctx).await } + if *condition.element() { if_true.eval(ctx) } else { if_false.eval(ctx) } } /// Constructs a `Bool` value which may be set to true or false. @@ -2327,8 +2327,8 @@ mod test { #[test] pub fn foo() { - let fnn = FnNode::new(|(a, b)| (b, a)); - assert_eq!(fnn.eval((1u32, 2u32)), (2, 1)); + let fnn = FnNode::new(|&(a, b): &(u32, u32)| (b, a)); + assert_eq!(fnn.eval(&(1u32, 2u32)).value(), Some((2, 1))); } #[test] diff --git a/node-graph/nodes/path-bool/src/lib.rs b/node-graph/nodes/path-bool/src/lib.rs index 3af6a11db5..5ec2555862 100644 --- a/node-graph/nodes/path-bool/src/lib.rs +++ b/node-graph/nodes/path-bool/src/lib.rs @@ -19,7 +19,7 @@ pub use vector_types::vector::misc::BooleanOperation; /// Combines the geometric forms of one or more closed paths into a new vector path that results from cutting or joining the paths by the chosen method. #[node_macro::node(category("Vector: Modifier"), icon("NodeBooleanOperation"), memoize)] -async fn boolean_operation( +fn boolean_operation( _: impl Ctx, /// The `List` of vector paths to perform the boolean operation on. Nested `List`s are automatically flattened. content: List, diff --git a/node-graph/nodes/raster/src/adjustments.rs b/node-graph/nodes/raster/src/adjustments.rs index 849492427f..6b06a5838a 100644 --- a/node-graph/nodes/raster/src/adjustments.rs +++ b/node-graph/nodes/raster/src/adjustments.rs @@ -679,7 +679,7 @@ fn levels>( // Needs the heap for its curves, so it stays off the shader build for now. #[cfg(feature = "std")] #[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))] -async fn curves + Send>( +fn curves + Send>( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, curve: Item, @@ -1466,7 +1466,7 @@ fn threshold>( // TODO: - The ramp is `(1 - s) * linear + s * smooth` for smoothness s, clamped per interval to its two stop colors. #[cfg(feature = "std")] #[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))] -async fn gradient_map + Send>( +fn gradient_map + Send>( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[default(Color::BLACK, Color::WHITE)] gradient: Item, @@ -2537,7 +2537,7 @@ fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { // TODO: Verify the tetrahedral interpolation, which is unconfirmed against other implementations. #[cfg(feature = "std")] #[node_macro::node(category("Raster: Adjustment"), icon("NodeColorLookup"))] -async fn color_lookup + Send>( +fn color_lookup + Send>( _: impl Ctx, /// The image whose colors are remapped by the LUT (lookup table). #[implementations(Raster, Color, Gradient)] diff --git a/node-graph/nodes/raster/src/blending_nodes.rs b/node-graph/nodes/raster/src/blending_nodes.rs index 81c4809566..6562d33aaa 100644 --- a/node-graph/nodes/raster/src/blending_nodes.rs +++ b/node-graph/nodes/raster/src/blending_nodes.rs @@ -137,8 +137,8 @@ mod test { use raster_types::Image; use raster_types::Raster; - #[tokio::test] - async fn color_overlay_multiply() { + #[test] + fn color_overlay_multiply() { let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4); let image = Image::new(1, 1, image_color); diff --git a/node-graph/nodes/raster/src/dehaze.rs b/node-graph/nodes/raster/src/dehaze.rs index 604fd70d25..7b79b09689 100644 --- a/node-graph/nodes/raster/src/dehaze.rs +++ b/node-graph/nodes/raster/src/dehaze.rs @@ -7,7 +7,7 @@ use raster_types::{CPU, Raster}; use std::cmp::{max, min}; #[node_macro::node(category("Raster: Filter"), icon("NodeDehaze"))] -async fn dehaze( +fn dehaze( _: impl Ctx, image_frame: Item>, #[unit("%")] diff --git a/node-graph/nodes/raster/src/filter.rs b/node-graph/nodes/raster/src/filter.rs index 44cf030d9d..91d0cafe04 100644 --- a/node-graph/nodes/raster/src/filter.rs +++ b/node-graph/nodes/raster/src/filter.rs @@ -86,7 +86,7 @@ fn unpremultiply_gamma_to_linear(buffer: Image) -> Imag /// Blurs the image with a Gaussian or box blur kernel filter. #[node_macro::node(category("Raster: Filter"), icon("NodeBlur"))] -async fn blur( +fn blur( _: impl Ctx, /// The image to be blurred. image_frame: Item>, @@ -121,7 +121,7 @@ async fn blur( /// Applies a median filter to reduce noise while preserving edges. #[node_macro::node(category("Raster: Filter"), icon("NodeMedianFilter"))] -async fn median_filter( +fn median_filter( _: impl Ctx, /// The image to be filtered. image_frame: Item>, diff --git a/node-graph/nodes/raster/src/image_color_palette.rs b/node-graph/nodes/raster/src/image_color_palette.rs index f7d3e9989e..f569a7cff6 100644 --- a/node-graph/nodes/raster/src/image_color_palette.rs +++ b/node-graph/nodes/raster/src/image_color_palette.rs @@ -15,7 +15,7 @@ const OKLAB_GAMUT_RANGES: [(f32, f32); 3] = [(0., 1.), (-0.24, 0.28), (-0.32, 0. /// Finds the colors that best represent the distinct color ranges in an image, ignoring transparent areas. #[node_macro::node(category("Color"), icon("NodeImageColorPalette"))] -async fn image_color_palette( +fn image_color_palette( _: impl Ctx, /// The image to find colors in. image: Item>, @@ -236,7 +236,7 @@ mod test { base64_string: None, }); - let palette = futures::executor::block_on(image_color_palette((), Item::new_from_element(image), Item::new_from_element(count))); + let palette = image_color_palette((), Item::new_from_element(image), Item::new_from_element(count)); palette.iter_element_values().copied().collect() } diff --git a/node-graph/nodes/raster/src/std_nodes.rs b/node-graph/nodes/raster/src/std_nodes.rs index 83040a76f2..2dfdeff73a 100644 --- a/node-graph/nodes/raster/src/std_nodes.rs +++ b/node-graph/nodes/raster/src/std_nodes.rs @@ -31,7 +31,7 @@ impl From for Error { } #[node_macro::node(category("Debug"), icon("NodeSampleImage"))] -pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Item>) -> Item> { +fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Item>) -> Item> { let image_frame_transform: DAffine2 = image_frame.attribute_cloned_or_default(ATTR_TRANSFORM); let footprint = ctx.footprint(); @@ -95,7 +95,7 @@ pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Item } #[node_macro::node(category("Raster: Channels"), icon("NodeChannelsToImage"), name("Channels to Image"))] -pub fn channels_to_image( +fn channels_to_image( _: impl Ctx, _primary: (), #[expose] red: Item>, @@ -150,7 +150,7 @@ pub fn channels_to_image( } #[node_macro::node(category("Raster"), icon("NodeMask"))] -pub fn mask( +fn mask( _: impl Ctx, /// The image to be masked. image: Item>, @@ -196,7 +196,7 @@ pub fn mask( } #[node_macro::node(category(""))] -pub fn extend_image_to_bounds(_: impl Ctx, image: Item>, bounds: Item) -> Item> { +fn extend_image_to_bounds(_: impl Ctx, image: Item>, bounds: Item) -> Item> { let bounds = *bounds.element(); let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); @@ -240,7 +240,7 @@ pub fn extend_image_to_bounds(_: impl Ctx, image: Item>, bounds: Ite } #[node_macro::node(category("Debug"), icon("NodeEmptyImage"))] -pub fn empty_image(_: impl Ctx, transform: Item, color: Item) -> Item> { +fn empty_image(_: impl Ctx, transform: Item, color: Item) -> Item> { let transform = transform.into_element(); let width = transform.transform_vector2(DVec2::new(1., 0.)).length() as u32; let height = transform.transform_vector2(DVec2::new(0., 1.)).length() as u32; @@ -254,7 +254,7 @@ pub fn empty_image(_: impl Ctx, transform: Item, color: Item) - /// /// Reads PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, and EXR files. Light brighter than white, as HDR and EXR files can hold, is clipped to white. #[node_macro::node(category("Raster"), icon("NodeImage"))] -pub fn image<'a: 'n>( +fn image( _: impl Ctx, _primary: (), /// The image file to display. @@ -270,7 +270,7 @@ pub fn image<'a: 'n>( /// Generates customizable procedural noise patterns. #[node_macro::node(category("Raster: Pattern"), icon("NodeNoisePattern"))] #[allow(clippy::too_many_arguments)] -pub fn noise_pattern( +fn noise_pattern( ctx: impl ExtractFootprint + Ctx, _primary: (), #[default(true)] clip: Item, @@ -435,7 +435,7 @@ pub fn noise_pattern( } #[node_macro::node(category("Raster: Pattern"), icon("NodeMandelbrot"))] -pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item> { +fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item> { let footprint = ctx.footprint(); let viewport_bounds = footprint.viewport_bounds_in_local_space(); diff --git a/node-graph/nodes/repeat/src/repeat_nodes.rs b/node-graph/nodes/repeat/src/repeat_nodes.rs index 29bec64cee..f6e6112134 100644 --- a/node-graph/nodes/repeat/src/repeat_nodes.rs +++ b/node-graph/nodes/repeat/src/repeat_nodes.rs @@ -1,7 +1,7 @@ use crate::gcore::Context; use core::f64::consts::TAU; use core_types::list::{Item, List}; -use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl}; +use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, OwnedContextImpl}; use glam::{DAffine2, DVec2}; use graphic_types::{Artboard, Graphic, Vector}; use raster_types::{CPU, GPU, Raster}; @@ -9,7 +9,7 @@ use vector_types::Gradient; use vector_types::vector::{no_paths, paths_from_list_row_attributes}; #[node_macro::node(category("Repeat"), icon("NodeRepeat"))] -async fn repeat( +fn repeat( ctx: impl ExtractAll + CloneVarArgs + Ctx, #[implementations( Context -> List, @@ -26,12 +26,12 @@ async fn repeat( Context -> List, Context -> List, )] - content: impl Node<'n, Context<'static>, Output = List>, + content: impl Node, Output = List>, #[default(1)] #[hard(1..)] count: Item, reverse: Item, -) -> List { +) -> Result, Interrupt> { // Someday this node can have the option to generate infinitely instead of a fixed count (basically `std::iter::repeat`). let (count, reverse) = (count.into_element(), reverse.into_element()); @@ -43,18 +43,18 @@ async fn repeat( let index = if reverse { count - index - 1 } else { index }; let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index); - let generated_content = content.eval(new_ctx.into_context()).await; + let generated_content = content.eval(new_ctx.into_context())?; for generated_row in generated_content.into_iter() { result_list.push(generated_row); } } - result_list + Ok(result_list) } #[node_macro::node(category("Repeat"), icon("NodeRepeatArray"))] -pub async fn repeat_array( +fn repeat_array( ctx: impl ExtractAll + CloneVarArgs + Ctx, #[implementations( Context -> List, @@ -71,7 +71,7 @@ pub async fn repeat_array( Context -> List, Context -> List, )] - content: impl Node<'n, Context<'static>, Output = List>, + content: impl Node, Output = List>, #[unit(" px")] #[default(100., 100.)] // TODO: When using a custom Inspector layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Inspector. Investigation is needed. @@ -83,7 +83,7 @@ pub async fn repeat_array( #[default(5)] #[hard(1..)] count: Item, -) -> List { +) -> Result, Interrupt> { let (direction, angle, count) = (direction.into_element(), angle.into_element(), count.into_element()); let angle = angle.to_radians(); // A single copy has no steps between copies, so the denominator is kept at 1 to avoid `0. / 0.` producing a NaN transform @@ -97,7 +97,7 @@ pub async fn repeat_array( let transform = DAffine2::from_angle(angle) * DAffine2::from_translation(translation); let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize); - let generated_content = content.eval(new_ctx.into_context()).await; + let generated_content = content.eval(new_ctx.into_context())?; for row_index in 0..generated_content.len() { let Some(mut row) = generated_content.clone_item(row_index) else { continue }; @@ -111,11 +111,11 @@ pub async fn repeat_array( } } - result_list + Ok(result_list) } #[node_macro::node(category("Repeat"), icon("NodeRepeatRadial"))] -async fn repeat_radial( +fn repeat_radial( ctx: impl ExtractAll + CloneVarArgs + Ctx, #[implementations( Context -> List, @@ -132,7 +132,7 @@ async fn repeat_radial( Context -> List, Context -> List, )] - content: impl Node<'n, Context<'static>, Output = List>, + content: impl Node, Output = List>, #[unit("°")] #[range] #[soft(-180..180)] @@ -143,7 +143,7 @@ async fn repeat_radial( #[default(5)] #[hard(1..)] count: Item, -) -> List { +) -> Result, Interrupt> { let (start_angle, radius, count) = (start_angle.into_element(), radius.into_element(), count.into_element()); let mut result_list = List::new(); @@ -154,7 +154,7 @@ async fn repeat_radial( let transform = angle * translation; let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index as usize); - let generated_content = content.eval(new_ctx.into_context()).await; + let generated_content = content.eval(new_ctx.into_context())?; for row_index in 0..generated_content.len() { let Some(mut row) = generated_content.clone_item(row_index) else { continue }; @@ -168,11 +168,11 @@ async fn repeat_radial( } } - result_list + Ok(result_list) } #[node_macro::node(category("Repeat"), icon("NodeRepeatOnPoints"), name("Repeat on Points"))] -async fn repeat_on_points( +fn repeat_on_points( ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs, points: List, #[implementations( @@ -190,9 +190,9 @@ async fn repeat_on_points( Context -> List, Context -> List, )] - content: impl Node<'n, Context<'static>, Output = List>, + content: impl Node, Output = List>, reverse: Item, -) -> List { +) -> Result, Interrupt> { let reverse = reverse.into_element(); let mut result_list = List::new(); @@ -201,16 +201,17 @@ async fn repeat_on_points( let Some(points_element) = points.element(points_index) else { continue }; let transform: DAffine2 = points.attribute_cloned_or_default(ATTR_TRANSFORM, points_index); - let mut iteration = async |index, point| { + let mut iteration = |index, point| -> Result<(), Interrupt> { let transformed_point = transform.transform_point2(point); let new_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(transformed_point); - let generated_content = content.eval(new_ctx.into_context()).await; + let generated_content = content.eval(new_ctx.into_context())?; for mut generated_row in generated_content.into_iter() { generated_row.attribute_mut_or_insert_default::(ATTR_TRANSFORM).translation = transformed_point; result_list.push(generated_row); } + Ok(()) }; let paths = paths_from_list_row_attributes(&points, points_index).unwrap_or_else(|| no_paths()); @@ -218,32 +219,29 @@ async fn repeat_on_points( let range = positions.iter().enumerate(); if reverse { for (index, &point) in range.rev() { - iteration(index, point).await; + iteration(index, point)?; } } else { for (index, &point) in range { - iteration(index, point).await; + iteration(index, point)?; } } } - result_list + Ok(result_list) } #[cfg(test)] mod test { use super::*; - use core_types::Ctx; - use core_types::Node; use core_types::list::Item; use core_types::transform::Footprint; + use core_types::{LazyInput, Node, Poll, Status}; use glam::DVec2; use graphene_core::ReadPositionNode; use graphic_types::Vector; use kurbo::Shape; use kurbo::{BezPath, DEFAULT_ACCURACY, Rect}; - use std::future::Future; - use std::pin::Pin; use vector_nodes::generator_nodes::RectangleNode; use vector_types::vector::Path; use vector_types::vector::misc::BoxCorners; @@ -258,13 +256,12 @@ mod test { } #[derive(Clone)] - pub struct FutureWrapperNode(T); + pub struct ValueNode(T); - impl<'i, I: Ctx, T: 'i + Clone + Send> Node<'i, I> for FutureWrapperNode { - type Output = Pin + 'i + Send>>; - fn eval(&'i self, _input: I) -> Self::Output { - let value = self.0.clone(); - Box::pin(async move { value }) + impl Node for ValueNode { + type Output = T; + fn eval(&self, _input: &I) -> Poll { + Poll::Final(self.0.clone()) } } @@ -272,14 +269,10 @@ mod test { #[derive(Clone)] pub struct RaiseToListNode(N); - impl<'i, I: 'i, N> Node<'i, I> for RaiseToListNode - where - N: Node<'i, I, Output = Pin> + 'i + Send>>>, - { - type Output = Pin> + 'i + Send>>; - fn eval(&'i self, input: I) -> Self::Output { - let future = self.0.eval(input); - Box::pin(async move { future.await.into() }) + impl>> Node for RaiseToListNode { + type Output = List; + fn eval(&self, input: &I) -> Poll> { + self.0.eval(input).map(Into::into) } } @@ -287,27 +280,26 @@ mod test { #[derive(Clone)] struct ExtractYNode(Position); - impl<'i, I: Ctx, Position> Node<'i, I> for ExtractYNode + impl Node for ExtractYNode where - Position: Node<'i, I, Output = Pin> + 'i + Send>>>, + Position: Node>, { - type Output = Pin> + 'i + Send>>; - fn eval(&'i self, input: I) -> Self::Output { - let position = self.0.eval(input); - Box::pin(async move { Item::new_from_element(position.await.element().y) }) + type Output = Item; + fn eval(&self, input: &I) -> Poll> { + self.0.eval(input).map(|position| Item::new_from_element(position.element().y)) } } - #[tokio::test] - async fn repeat_on_points_test() { + #[test] + fn repeat_on_points_test() { let context = OwnedContextImpl::default().into_context(); let rect = RectangleNode::new( - FutureWrapperNode(()), - ExtractYNode(ReadPositionNode::new(FutureWrapperNode(()), FutureWrapperNode(Item::new_from_element(0_i64)))), - FutureWrapperNode(Item::new_from_element(2_f64)), - FutureWrapperNode(Item::new_from_element(BoxCorners::default())), - FutureWrapperNode(Item::new_from_element(false)), - FutureWrapperNode(Item::new_from_element(false)), + ValueNode(()), + ExtractYNode(ReadPositionNode::new(ValueNode(()), ValueNode(Item::new_from_element(0_i64)))), + ValueNode(Item::new_from_element(2_f64)), + ValueNode(Item::new_from_element(BoxCorners::default())), + ValueNode(Item::new_from_element(false)), + ValueNode(Item::new_from_element(false)), ); let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)]; @@ -317,7 +309,8 @@ mod test { polyline.line_to((position.x, position.y)); } let points = vector_node_from_bezpath(polyline); - let generated = super::repeat_on_points(context, points, &RaiseToListNode(rect), Item::new_from_element(false)).await; + let status = Status::new(); + let generated = super::repeat_on_points(context, points, LazyInput::new(&RaiseToListNode(rect), &status, 1), Item::new_from_element(false)).unwrap(); assert_eq!(generated.len(), positions.len()); for (position, index) in positions.into_iter().zip(0..generated.len()) { let bounds = generated @@ -330,20 +323,21 @@ mod test { } } - #[tokio::test] - async fn repeat() { + #[test] + fn repeat() { let direction = DVec2::X * 1.5; let count = 3; let context = OwnedContextImpl::default().into_context(); + let status = Status::new(); let repeated = super::repeat_array( context, - &FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))), + LazyInput::new(&ValueNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))), &status, 0), Item::new_from_element(direction), Item::new_from_element(0.), Item::new_from_element(count), ) - .await; - let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); + .unwrap(); + let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated)))); let vector = vector_list.element(0).unwrap(); let paths = row_paths(&vector_list, 0); assert_eq!(vector.stroke_manipulator_groups(paths).count(), 3); @@ -352,18 +346,19 @@ mod test { } } - #[tokio::test] - async fn repeat_single_copy() { + #[test] + fn repeat_single_copy() { let context = OwnedContextImpl::default().into_context(); + let status = Status::new(); let repeated = super::repeat_array( context, - &FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))), + LazyInput::new(&ValueNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))), &status, 0), Item::new_from_element(DVec2::new(12., 10.)), Item::new_from_element(45.), Item::new_from_element(1), ) - .await; - let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); + .unwrap(); + let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated)))); let vector = vector_list.element(0).unwrap(); let paths = row_paths(&vector_list, 0); assert_eq!(vector.stroke_manipulator_groups(paths).count(), 1); @@ -373,20 +368,21 @@ mod test { assert!(anchor.length() < 1e-5, "Expected the single copy to be untransformed, found anchor {anchor}"); } - #[tokio::test] - async fn repeat_transform_position() { + #[test] + fn repeat_transform_position() { let direction = DVec2::new(12., 10.); let count = 8; let context = OwnedContextImpl::default().into_context(); + let status = Status::new(); let repeated = super::repeat_array( context, - &FutureWrapperNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))), + LazyInput::new(&ValueNode(vector_node_from_bezpath(Rect::new(0., 0., 1., 1.).to_path(DEFAULT_ACCURACY))), &status, 0), Item::new_from_element(direction), Item::new_from_element(0.), Item::new_from_element(count), ) - .await; - let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); + .unwrap(); + let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated)))); let vector = vector_list.element(0).unwrap(); let paths = row_paths(&vector_list, 0); assert_eq!(vector.stroke_manipulator_groups(paths).count(), 8); @@ -395,18 +391,19 @@ mod test { } } - #[tokio::test] - async fn repeat_radial() { + #[test] + fn repeat_radial() { let context = OwnedContextImpl::default().into_context(); + let status = Status::new(); let repeated = super::repeat_radial( context, - &FutureWrapperNode(vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))), + LazyInput::new(&ValueNode(vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))), &status, 0), Item::new_from_element(45.), Item::new_from_element(4.), Item::new_from_element(8), ) - .await; - let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated))).await); + .unwrap(); + let vector_list = List::new_from_item(vector_nodes::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(repeated)))); let vector = vector_list.element(0).unwrap(); let paths = row_paths(&vector_list, 0); assert_eq!(vector.stroke_manipulator_groups(paths).count(), 8); diff --git a/node-graph/nodes/text/src/lib.rs b/node-graph/nodes/text/src/lib.rs index ddf6fcd4e0..a9b4c9d05f 100644 --- a/node-graph/nodes/text/src/lib.rs +++ b/node-graph/nodes/text/src/lib.rs @@ -7,6 +7,7 @@ mod text_context; mod to_path; use convert_case::{Boundary, Converter, Pattern}; +use core_types::Interrupt; use core_types::graphene_hash::CacheHash; use core_types::list::{Item, List}; use core_types::math::float_noise::round_away_float_noise; @@ -948,24 +949,24 @@ fn string_join( /// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop. #[node_macro::node(category("Text"), icon("NodeMapString"))] -async fn map_string( +fn map_string( ctx: impl Ctx + CloneVarArgs + ExtractAll, strings: List, #[expose] #[implementations(Context -> Item)] mapped: impl Node, Output = Item>, -) -> List { +) -> Result, Interrupt> { let mut result = List::new(); for (i, row) in strings.into_iter().enumerate() { let owned_ctx = OwnedContextImpl::from(ctx.clone()); let owned_ctx = owned_ctx.with_vararg(Box::new(row)).with_index(i); - let mapped_string = mapped.eval(owned_ctx.into_context()).await; + let mapped_string = mapped.eval(owned_ctx.into_context())?; result.push(mapped_string); } - result + Ok(result) } /// Reads the current string from within a **Map String** node's loop. diff --git a/node-graph/nodes/transform/src/transform_nodes.rs b/node-graph/nodes/transform/src/transform_nodes.rs index 6200825002..40b05a4006 100644 --- a/node-graph/nodes/transform/src/transform_nodes.rs +++ b/node-graph/nodes/transform/src/transform_nodes.rs @@ -2,7 +2,7 @@ use core::f64; use core_types::color::Color; use core_types::list::{Item, List}; use core_types::transform::{ApplyTransform, ScaleType, Transform}; -use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl}; +use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, Interrupt, ModifyFootprint, OwnedContextImpl}; use glam::{DAffine2, DMat2, DVec2}; use graphic_types::raster_types::{CPU, GPU, Raster}; use graphic_types::{Artboard, Graphic, Vector}; @@ -10,7 +10,7 @@ use vector_types::Gradient; /// Applies the specified transform to the input content. #[node_macro::node(category("Math: Transform"), icon("NodeTransform"))] -async fn transform( +fn transform( ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint, #[implementations( Context -> Item, @@ -33,7 +33,7 @@ async fn transform( #[widget(ParsedWidgetOverride::Custom = "transform_skew")] #[hard(-89.9..89.9)] skew: Item, -) -> Item { +) -> Result, Interrupt> { let (translation, rotation, scale, skew) = (*translation.element(), *rotation.element(), *scale.element(), *skew.element()); let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation); @@ -48,24 +48,24 @@ async fn transform( ctx = ctx.with_footprint(footprint); } - let mut item = content.eval(ctx.into_context()).await; + let mut item = content.eval(ctx.into_context())?; item.left_apply_transform(&matrix); - item + Ok(item) } /// The whole-`List` counterpart of `transform`, composing the matrix onto every item of a rank-1 content wire. /// Registered under the `TransformNode` identifier by manual registry rows, since the macro's element-wise variants require an `Item`-peeling primary. #[node_macro::node(category(""), skip_impl)] -async fn transform_list( +fn transform_list( ctx: impl Ctx + CloneVarArgs + ExtractAll + ModifyFootprint, content: impl Node, Output = List>, translation: Item, rotation: Item, scale: Item, #[hard(-89.9..89.9)] skew: Item, -) -> List { +) -> Result, Interrupt> { let (translation, rotation, scale, skew) = (*translation.element(), *rotation.element(), *scale.element(), *skew.element()); let trs = DAffine2::from_scale_angle_translation(scale, rotation.to_radians(), translation); @@ -80,11 +80,11 @@ async fn transform_list( ctx = ctx.with_footprint(footprint); } - let mut list = content.eval(ctx.into_context()).await; + let mut list = content.eval(ctx.into_context())?; list.left_apply_transform(&matrix); - list + Ok(list) } /// Resets the desired components of the input transform to their default values. If all components are reset, the output will be set to the identity transform. @@ -156,7 +156,7 @@ fn replace_transform( /// Obtains the transform of the input content. #[node_macro::node(category("Math: Transform"), icon("NodeExtractTransform"), path(core_types::vector))] -fn extract_transform(_: impl Ctx, #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Artboard)] content: Item) -> Item { +fn extract_transform(_: impl Ctx, #[implementations(Graphic, Vector, Raster, Raster, Color, Gradient, String, Artboard)] content: Item) -> Item { Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM)) } diff --git a/node-graph/nodes/vector/src/vector_modification_nodes.rs b/node-graph/nodes/vector/src/vector_modification_nodes.rs index c25257d99f..514e364d66 100644 --- a/node-graph/nodes/vector/src/vector_modification_nodes.rs +++ b/node-graph/nodes/vector/src/vector_modification_nodes.rs @@ -9,7 +9,7 @@ use vector_types::vector::{VectorModification, edit_item_geometry, ensure_paths_ /// Applies a differential modification to a vector path, associating changes made by the Pen and Path tools to indices of edited points and segments. #[node_macro::node(category(""))] -async fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item>, node_path: Item) -> Item { +fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item>, node_path: Item) -> Item { let mut vector = vector; let modification = modification.into_element(); @@ -54,7 +54,7 @@ async fn path_modify(_ctx: impl Ctx, vector: Item, modification: Item(_ctx: impl Ctx, #[implementations(Vector, DAffine2, DVec2)] content: Item) -> Item { +fn bake_transform(_ctx: impl Ctx, #[implementations(Vector, DAffine2, DVec2)] content: Item) -> Item { let mut content = content; if let Some(transform) = content.remove_attribute::(ATTR_TRANSFORM) { content.element_mut().bake_transform(&transform); @@ -70,8 +70,8 @@ mod tests { use vector_types::vector::{CurveType, PointId, SegmentId, VectorModificationType, paths_from_item_attributes, push_path}; // A lone loop fills by its contour alone, so it keeps the direction it was drawn in even when that winds backwards - #[tokio::test] - async fn a_drawn_loop_keeps_its_direction() { + #[test] + fn a_drawn_loop_keeps_its_direction() { let mut bezpath = BezPath::new(); bezpath.move_to((0., 0.)); bezpath.line_to((0., 10.)); @@ -80,14 +80,14 @@ mod tests { bezpath.close_path(); let drawn = Vector::item_from_bezpath(&bezpath); - let modified = path_modify((), drawn.clone(), Item::default(), Item::default()).await; + let modified = path_modify((), drawn.clone(), Item::default(), Item::default()); assert_eq!(paths_from_item_attributes(&modified), paths_from_item_attributes(&drawn)); } // Moving a point of a mesh leaves its paths in place to begin with, and its loops still get their winding set for the face fill - #[tokio::test] - async fn a_mesh_moved_in_place_still_has_its_winding_set() { + #[test] + fn a_mesh_moved_in_place_still_has_its_winding_set() { // A reverse-wound square beside three spokes meeting at a hub, which makes the geometry branch let positions = [(0., 0.), (0., 10.), (10., 10.), (10., 0.), (30., 0.), (40., 0.), (30., 10.), (20., 10.)]; let (mut vector, mut paths) = (Vector::default(), List::new()); @@ -105,7 +105,7 @@ mod tests { let mut modification = VectorModification::default(); modification.modify(&VectorModificationType::ApplyPointDelta { point: hub, delta: DVec2::X }); - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()).await; + let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); let first_path = |item: &Item| paths_from_item_attributes(item).unwrap().element(0).unwrap().0.iter_element_values().copied().collect::>(); assert_eq!(first_path(&drawn), [0, 1, 2, 3, 0]); @@ -113,8 +113,8 @@ mod tests { } // Moving points leaves the paths shared with the incoming geometry, and where they sat among its attributes - #[tokio::test] - async fn moving_points_leaves_the_paths_shared_and_in_place() { + #[test] + fn moving_points_leaves_the_paths_shared_and_in_place() { let mut bezpath = BezPath::new(); bezpath.move_to((0., 0.)); bezpath.line_to((10., 0.)); @@ -124,7 +124,7 @@ mod tests { let mut modification = VectorModification::default(); modification.modify(&VectorModificationType::ApplyPointDelta { point: corner, delta: DVec2::X }); - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()).await; + let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); assert_eq!(modified.element().0.element(1), Some(&DVec2::new(11., 0.))); assert!(std::ptr::eq(paths_from_item_attributes(&drawn).unwrap(), paths_from_item_attributes(&modified).unwrap())); @@ -132,8 +132,8 @@ mod tests { } // A point cloud comes out with an empty paths attribute placed last, whether the edit is made in place or by reweaving - #[tokio::test] - async fn a_point_cloud_gains_an_empty_paths_attribute() { + #[test] + fn a_point_cloud_gains_an_empty_paths_attribute() { let mut cloud = Vector::default(); cloud.0.push(Item::new_from_element(DVec2::ZERO).with_attribute(ATTR_ID, PointId::ZERO)); let drawn = Item::new_from_element(cloud).with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY); @@ -145,7 +145,7 @@ mod tests { }); for modification in [VectorModification::default(), adds_a_point] { - let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()).await; + let modified = path_modify((), drawn.clone(), Item::new_from_element(Box::new(modification)), Item::default()); assert_eq!(paths_from_item_attributes(&modified).map(List::len), Some(0)); assert_eq!(modified.attributes().keys().collect::>(), [ATTR_TRANSFORM, ATTR_PATHS, ATTR_EDITOR_LAYER_PATH]); diff --git a/node-graph/nodes/vector/src/vector_nodes.rs b/node-graph/nodes/vector/src/vector_nodes.rs index 4c50ed81a1..016116766e 100644 --- a/node-graph/nodes/vector/src/vector_nodes.rs +++ b/node-graph/nodes/vector/src/vector_nodes.rs @@ -1,6 +1,7 @@ use core::cmp::Ordering; use core::f64::consts::{PI, TAU}; use core::hash::{Hash, Hasher}; +use core_types::Interrupt; use core_types::blending::BlendMode; use core_types::bounds::{BoundingBox, RenderBoundingBox}; use core_types::list::{ATTR_APPEARANCE, ATTR_ID, ATTR_PATHS, Item, ItemAttributeValues, List, ListDyn, NodeIdPath}; @@ -263,7 +264,7 @@ impl ExpandVectorItems for Graphic { /// Uniquely sets the fill and/or stroke style of every vector element to individual colors sampled along a chosen gradient. #[node_macro::node(category("Vector: Style"), icon("NodeAssignColors"), path(graphene_core::vector))] -async fn assign_colors( +fn assign_colors( _: impl Ctx, /// The content with vector paths to apply the fill and/or stroke style to. #[implementations(List, List)] @@ -292,7 +293,7 @@ async fn assign_colors( repeat_every: Item, ) -> T where - T: VectorListIterMut + 'n + Send, + T: VectorListIterMut + Send, { let (fill, stroke, reverse, randomize) = (fill.into_element(), stroke.into_element(), reverse.into_element(), randomize.into_element()); let (seed, repeat_every) = (seed.into_element(), repeat_every.into_element()); @@ -352,7 +353,7 @@ where /// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry. #[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"))] -async fn fill( +fn fill( _: impl Ctx, /// The content with vector paths to apply the fill style to. #[implementations(Vector, Graphic)] @@ -365,7 +366,7 @@ async fn fill( _transform: Item, ) -> Item where - Item: VectorItemMut + 'n + Send, + Item: VectorItemMut + Send, { let _gradient_form = _gradient_form.into_element(); let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element()); @@ -442,7 +443,7 @@ where /// Applies a stroke style to the vector content, giving an appearance to the area within the outline of the geometry. #[node_macro::node(category("Vector: Style"), icon("NodeStroke"), path(graphene_core::vector), inspector("stroke_inspector"))] -async fn stroke( +fn stroke( _: impl Ctx, /// The content with vector paths to apply the stroke style to. #[implementations(Vector, Graphic)] @@ -472,7 +473,7 @@ async fn stroke( dash_offset: Item, ) -> Item where - Item: VectorItemMut + 'n + Send, + Item: VectorItemMut + Send, { let mut content = content; let (weight, align, cap, join, miter_limit, dash_offset) = ( @@ -521,7 +522,7 @@ fn dash_pattern( } #[node_macro::node(category("Repeat"), icon("NodeRepeatOnPoints"), name("Copy to Points"), path(core_types::vector))] -async fn copy_to_points( +fn copy_to_points( _: impl Ctx, points: List, /// Artwork to be copied and placed at each point. @@ -612,7 +613,7 @@ async fn copy_to_points( } #[node_macro::node(category("Vector: Modifier"), icon("NodeRoundCorners"), path(core_types::vector))] -async fn round_corners( +fn round_corners( _: impl Ctx, #[implementations(Graphic, Vector)] source: Item, #[unit(" px")] @@ -1022,7 +1023,7 @@ pub mod extrude_algorithms { } #[node_macro::node(category("Vector: Modifier"), icon("NodeExtrude"), path(core_types::vector))] -async fn extrude(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item, direction: Item, joining_algorithm: Item) -> Item { +fn extrude(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item, direction: Item, joining_algorithm: Item) -> Item { V::map_vector_items(source, |source| { let mut source = source; let (direction, joining_algorithm) = (*direction.element(), *joining_algorithm.element()); @@ -1033,7 +1034,7 @@ async fn extrude(_: impl Ctx, #[implementations(G } #[node_macro::node(category("Vector: Modifier"), icon("NodeBoxWarp"), path(core_types::vector))] -async fn box_warp(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item, #[expose] rectangle: Item) -> Item { +fn box_warp(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item, #[expose] rectangle: Item) -> Item { let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM); let target_paths = shared_paths_from_item_attributes(&rectangle); let target = rectangle.into_element(); @@ -1104,7 +1105,7 @@ fn bilinear_interpolate(t: DVec2, quad: &[DVec2; 4]) -> DVec2 { } #[node_macro::node(category("Vector"), icon("NodePackStrips"), path(graphene_core::vector))] -async fn pack_strips( +fn pack_strips( _: impl Ctx, #[implementations( List, @@ -1227,7 +1228,7 @@ where /// Automatically constructs tangents (Bézier handles) for anchor points in a vector path. #[node_macro::node(category("Vector: Modifier"), icon("NodeAutoTangents"), name("Auto-Tangents"), path(core_types::vector))] -async fn auto_tangents( +fn auto_tangents( _: impl Ctx, #[implementations(Graphic, Vector)] source: Item, /// The amount of spread for the auto-tangents, from 0 (sharp corner) to 1 (full spread). @@ -1398,7 +1399,7 @@ async fn auto_tangents( } #[node_macro::node(category("Vector: Modifier"), icon("NodeBoundingBox"), path(core_types::vector))] -async fn bounding_box(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { +fn bounding_box(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { V::map_vector_items(content, |content| { let mut content = content; let paths = shared_paths_from_item_attributes(&content); @@ -1415,7 +1416,7 @@ async fn bounding_box(_: impl Ctx, #[implementati } #[node_macro::node(category("Vector: Measure"), icon("NodeDimensions"), path(core_types::vector))] -async fn dimensions(_: impl Ctx, content: Item) -> Item { +fn dimensions(_: impl Ctx, content: Item) -> Item { let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let dimensions = content .element() @@ -1450,7 +1451,7 @@ fn points_to_vector( /// Creates a polyline from a series of vector points, replacing any existing segments that may already exist. #[node_macro::node(category("Vector"), icon("NodePointsToPolyline"), name("Points to Polyline"), path(core_types::vector))] -async fn points_to_polyline(_: impl Ctx, #[implementations(Graphic, Vector)] points: Item, #[default(true)] closed: Item) -> Item { +fn points_to_polyline(_: impl Ctx, #[implementations(Graphic, Vector)] points: Item, #[default(true)] closed: Item) -> Item { let closed = *closed.element(); V::map_vector_items(points, |points| { @@ -1482,7 +1483,7 @@ async fn points_to_polyline(_: impl Ctx, #[implem /// Evens out the distances between points by applying Lloyd's relaxation, moving every interior point toward the center of its Voronoi cell. #[node_macro::node(category("Vector: Modifier"), icon("NodeRelaxPoints"), path(core_types::vector))] -async fn relax_points( +fn relax_points( _: impl Ctx, /// A vector path or point cloud to relax. #[implementations(Graphic, Vector)] @@ -1515,7 +1516,7 @@ async fn relax_points( /// /// When Connect Cells is off, every cell becomes its own closed, fillable subpath. When on, the cells share their common points and segments, forming a single connected mesh. #[node_macro::node(category("Vector"), icon("NodeVoronoiCells"), path(core_types::vector))] -async fn voronoi_cells(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item, connect_cells: Item) -> Item { +fn voronoi_cells(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item, connect_cells: Item) -> Item { V::map_vector_items(source, |source| { let mut source = source; let connect_cells = *connect_cells.element(); @@ -1536,7 +1537,7 @@ async fn voronoi_cells(_: impl Ctx, #[implementat /// /// When Connect Cells is off, every triangle becomes its own closed, fillable subpath. When on, the triangles share their common points and segments, forming a single connected mesh. #[node_macro::node(category("Vector"), icon("NodeTriangulate"), path(core_types::vector))] -async fn triangulate(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item, connect_cells: Item) -> Item { +fn triangulate(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item, connect_cells: Item) -> Item { V::map_vector_items(source, |source| { let mut source = source; let connect_cells = *connect_cells.element(); @@ -1646,7 +1647,7 @@ fn mesh_weld_tolerance(polygons: &[Vec]) -> f64 { } #[node_macro::node(category("Vector: Modifier"), icon("NodeOffsetPath"), path(core_types::vector), inspector("offset_path_inspector"))] -async fn offset_path( +fn offset_path( _: impl Ctx, #[implementations(Graphic, Vector)] content: Item, distance: Item, @@ -1857,14 +1858,14 @@ fn solidify_stroke_list(content: List) -> List { } #[node_macro::node(category("Vector: Modifier"), icon("NodeSolidifyStroke"), path(core_types::vector))] -async fn solidify_stroke(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> List { +fn solidify_stroke(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> List { // TODO: Make this node support stroke align, which it currently ignores V::solidify_strokes(content) } #[node_macro::node(category("Vector: Modifier"), icon("NodeSeparateSubpaths"), path(core_types::vector))] -async fn separate_subpaths(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> List { +fn separate_subpaths(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> List { V::expand_vector_items(content, |content| { let content_paths = shared_paths_from_item_attributes(&content); let bezpaths = content.element().stroke_bezpath_iter(&content_paths).collect::>(); @@ -1892,7 +1893,7 @@ async fn separate_subpaths(_: impl Ctx, #[impl /// Determines if the subpath at the given index is closed, meaning its ends are connected together forming a loop. #[node_macro::node(name("Path is Closed"), category("Vector: Measure"), icon("NodePathIsClosed"), path(core_types::vector))] -async fn path_is_closed( +fn path_is_closed( _: impl Ctx, /// The vector content whose subpaths are inspected. content: Item, @@ -1908,11 +1909,11 @@ async fn path_is_closed( } #[node_macro::node(category("Vector"), icon("NodeMapPoints"), path(graphene_core::vector))] -async fn map_points( +fn map_points( ctx: impl Ctx + CloneVarArgs + ExtractAll, #[implementations(Graphic, Vector)] content: Item, mapped: impl Node, Output = Item>, -) -> Item { +) -> Result, Interrupt> { let mut content = content; // Handles keep their own positions, so the mapping walks anchors alone, indexed in anchor order @@ -1921,19 +1922,19 @@ async fn map_points( let Some(position) = vector.position(pool_index) else { continue }; let owned_ctx = OwnedContextImpl::from(ctx.clone()).with_index(index).with_position(position); - let mapped_position = mapped.eval(owned_ctx.into_context()).await.into_element(); + let mapped_position = mapped.eval(owned_ctx.into_context())?.into_element(); if let Some(slot) = vector.0.element_mut(pool_index) { *slot = mapped_position; } } } - content + Ok(content) } /// Combines every vector path across the input into a single compound path. #[node_macro::node(category("Vector"), icon("NodeCombinePaths"), path(graphene_core::vector))] -pub async fn combine_paths(_: impl Ctx, content: List) -> Item { +pub fn combine_paths(_: impl Ctx, content: List) -> Item { let graphic_list = content.clone(); let flattened = content.into_flattened_list::(); @@ -1979,7 +1980,7 @@ pub async fn combine_paths(_: impl Ctx, content: List) -> Item /// Convert vector geometry into a polyline composed of evenly spaced points. #[node_macro::node(category("Vector: Modifier"), icon("NodeSamplePolyline"), path(core_types::vector), inspector("sample_polyline_inspector"), memoize)] -async fn sample_polyline( +fn sample_polyline( _: impl Ctx, #[implementations(Graphic, Vector)] content: Item, spacing: Item, @@ -2063,7 +2064,7 @@ async fn sample_polyline( /// Simplifies vector paths by reducing the number of curve segments while preserving the overall shape within the given tolerance. #[node_macro::node(category("Vector: Modifier"), icon("NodeSimplify"), path(core_types::vector))] -async fn simplify( +fn simplify( _: impl Ctx, /// The vector paths to simplify. #[implementations(Graphic, Vector)] @@ -2108,7 +2109,7 @@ async fn simplify( /// Decimates vector paths into polylines by sampling any curves into line segments, then removing points that don't significantly contribute to the shape using the Ramer-Douglas-Peucker algorithm. #[node_macro::node(category("Vector: Modifier"), icon("NodeDecimate"), path(core_types::vector))] -async fn decimate( +fn decimate( _: impl Ctx, /// The vector paths to decimate. #[implementations(Graphic, Vector)] @@ -2240,7 +2241,7 @@ async fn decimate( /// /// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it. #[node_macro::node(category("Vector: Modifier"), icon("NodeCutPath"), path(graphene_core::vector))] -async fn cut_path( +fn cut_path( _: impl Ctx, /// The path to insert a cut into. #[implementations(Graphic, Vector)] @@ -2292,7 +2293,7 @@ async fn cut_path( /// Cuts path segments into separate disconnected pieces where each is a distinct subpath. #[node_macro::node(category("Vector: Modifier"), icon("NodeCutSegments"), path(core_types::vector))] -async fn cut_segments(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { +fn cut_segments(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { V::map_vector_items(content, |content| { let mut content = content; // Iterate through every segment and make a copy of each of its endpoints, then reassign each segment's endpoints to its own unique point copy @@ -2374,7 +2375,7 @@ pub struct PathEvaluation { /// /// If multiple subpaths make up the path, the whole number part of the progression value selects the subpath and the decimal part determines the position along it. #[node_macro::node(category("Vector: Measure"), icon("NodeEvaluatePath"), path(graphene_core::vector))] -async fn evaluate_path( +fn evaluate_path( _: impl Ctx, /// The path to traverse. content: Item, @@ -2431,7 +2432,7 @@ async fn evaluate_path( } #[node_macro::node(category("Vector: Modifier"), icon("NodeScatterPoints"), path(core_types::vector), memoize)] -async fn scatter_points( +fn scatter_points( _: impl Ctx, #[implementations(Graphic, Vector)] content: Item, #[unit(" px")] @@ -2484,7 +2485,7 @@ async fn scatter_points( } #[node_macro::node(name("Spline"), category("Vector: Modifier"), icon("NodeSpline"), path(core_types::vector))] -async fn spline(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { +fn spline(_: impl Ctx, #[implementations(Graphic, Vector)] content: Item) -> Item { V::map_vector_items(content, |content| { let mut content = content; // Exit early if there are no points to generate splines from. @@ -2620,7 +2621,7 @@ fn apply_point_deltas(vector: &mut Vector, paths: &List, anchors: &[usize] /// Perturbs the positions of anchor points in vector geometry by random amounts and directions. #[node_macro::node(category("Vector: Modifier"), icon("NodeJitterPoints"), path(core_types::vector))] -async fn jitter_points( +fn jitter_points( _: impl Ctx, /// The vector geometry with points to be jittered. #[implementations(Graphic, Vector)] @@ -2672,7 +2673,7 @@ async fn jitter_points( /// Displaces anchor points along their normal direction (perpendicular to the path) by a set distance. /// Points with 0 or 3+ segment connections have no well-defined normal and are left in place. #[node_macro::node(category("Vector: Modifier"), icon("NodeOffsetPoints"), path(core_types::vector))] -async fn offset_points( +fn offset_points( _: impl Ctx, /// The vector geometry with points to be offset. #[implementations(Graphic, Vector)] @@ -2713,7 +2714,7 @@ async fn offset_points( /// /// *Progression* morphs through all objects. Interpolation is linear unless *Path* geometry is provided to control the trajectory between key objects. The **Origins to Polyline** node may be used to create a path with anchor points corresponding to each object. Other nodes can modify its path segments. #[node_macro::node(category("Vector: Modifier"), icon("NodeMorph"), path(core_types::vector))] -async fn morph( +fn morph( _: impl Ctx, /// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements. content: List, @@ -3711,12 +3712,12 @@ fn point_inside(_: impl Ctx, source: Item, point: Item) -> Item Item { +fn list_length(_: impl Ctx, content: ListDyn) -> Item { Item::new_from_element(content.len() as f64) } #[node_macro::node(category("Vector: Measure"), icon("NodeCountPoints"), path(graphene_core::vector))] -async fn count_points(_: impl Ctx, content: Item) -> Item { +fn count_points(_: impl Ctx, content: Item) -> Item { let paths = paths_from_item_attributes(&content).unwrap_or_else(|| no_paths()); let count = content.element().anchor_indices(paths).len() as f64; @@ -3726,7 +3727,7 @@ async fn count_points(_: impl Ctx, content: Item) -> Item { /// Retrieves the vec2 position (in local space) of the anchor point at the specified index within a vector element. /// If no value exists at that index, the position (0, 0) is returned. #[node_macro::node(category("Vector: Measure"), icon("NodeIndexPoints"), path(graphene_core::vector))] -async fn index_points( +fn index_points( _: impl Ctx, /// The vector element containing the anchor points to be retrieved. content: Item, @@ -3752,7 +3753,7 @@ async fn index_points( } #[node_macro::node(category("Vector: Measure"), icon("NodePathLength"), path(core_types::vector))] -async fn path_length(_: impl Ctx, source: Item) -> Item { +fn path_length(_: impl Ctx, source: Item) -> Item { let paths = paths_from_item_attributes(&source).unwrap_or_else(|| no_paths()); let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM); let length = source @@ -3768,29 +3769,29 @@ async fn path_length(_: impl Ctx, source: Item) -> Item { } #[node_macro::node(category("Vector: Measure"), icon("NodeArea"), path(core_types::vector))] -async fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node, Output = Item>) -> Item { +fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node, Output = Item>) -> Result, Interrupt> { let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); - let vector = content.eval(new_ctx).await; + let vector = content.eval(new_ctx)?; let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM); let area_scale = transform.matrix2.determinant().abs(); let paths = paths_from_item_attributes(&vector).unwrap_or_else(|| no_paths()); let area = vector.element().stroke_bezpath_iter(paths).map(|subpath| subpath.area() * area_scale).sum::(); - Item::new_from_element(area) + Ok(Item::new_from_element(area)) } #[node_macro::node(category("Vector: Measure"), icon("NodeCentroid"), path(core_types::vector))] -async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node, Output = Item>, centroid_type: Item) -> Item { +fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node, Output = Item>, centroid_type: Item) -> Result, Interrupt> { let centroid_type = centroid_type.into_element(); let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context(); - let vector = content.eval(new_ctx).await; + let vector = content.eval(new_ctx)?; let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM); let paths = paths_from_item_attributes(&vector).unwrap_or_else(|| no_paths()); let position = element_centroid(vector.element(), paths, transform, centroid_type); - Item::new_from_element(position) + Ok(Item::new_from_element(position)) } /// The area- or length-weighted centroid of one vector element's subpaths, averaging anchor positions when the weights all vanish. @@ -3825,22 +3826,19 @@ fn element_centroid(element: &Vector, paths: &List, transform: DAffine2, c #[cfg(test)] mod test { use super::*; - use core_types::Node; + use core_types::{Node, Poll}; use kurbo::{CubicBez, ParamCurveNearest, Point, Rect}; - use std::future::Future; - use std::pin::Pin; use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg}; use vector_types::vector::algorithms::shapes::ellipse_bezpath; use vector_types::vector::misc::pathseg_abs_diff_eq; #[derive(Clone)] - pub struct FutureWrapperNode(T); + pub struct ValueNode(T); - impl<'i, T: 'i + Clone + Send> Node<'i, Footprint> for FutureWrapperNode { - type Output = Pin + 'i + Send>>; - fn eval(&'i self, _input: Footprint) -> Self::Output { - let value = self.0.clone(); - Box::pin(async move { value }) + impl Node for ValueNode { + type Output = T; + fn eval(&self, _input: &Footprint) -> Poll { + Poll::Final(self.0.clone()) } } @@ -3940,12 +3938,12 @@ mod test { assert_eq!(vector.position(5), Some(DVec2::new(53., 0.))); } - #[tokio::test] - async fn offset_path_does_not_duplicate_closing_anchors() { + #[test] + fn offset_path_does_not_duplicate_closing_anchors() { // Offsetting closed triangles must not leave each subpath with a redundant start/end anchor (a Kurbo offset // contour returns to approximately, not exactly, its start; that near-coincident point must close, not duplicate). - let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; - let offset = super::offset_path((), delaunay, item(0.5), item(StrokeJoin::Miter), item(4.)).await; + let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)); + let offset = super::offset_path((), delaunay, item(0.5), item(StrokeJoin::Miter), item(4.)); let paths = item_paths(&offset); let result = offset.element(); @@ -3960,9 +3958,9 @@ mod test { assert!(subpaths > 0); } - #[tokio::test] - async fn delaunay_disconnected_cells_make_one_subpath_per_triangle() { - let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; + #[test] + fn delaunay_disconnected_cells_make_one_subpath_per_triangle() { + let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)); let paths = item_paths(&result); let vector = result.element(); // The square plus its center tessellates into four triangles, each its own closed subpath. @@ -3972,8 +3970,8 @@ mod test { assert!(!vector.use_face_fill(paths)); } - #[tokio::test] - async fn delaunay_and_voronoi_cells_share_winding() { + #[test] + fn delaunay_and_voronoi_cells_share_winding() { fn signed_area(anchors: &[DVec2]) -> f64 { (0..anchors.len()).map(|i| anchors[i].perp_dot(anchors[(i + 1) % anchors.len()])).sum::() / 2. } @@ -3993,8 +3991,8 @@ mod test { assert_eq!(subpath_winding_signs(&ellipse, &ellipse_paths)[0], expected, "Rectangle and Ellipse should agree on winding"); // Delaunay and Voronoi must emit subpaths that wind the same way as those generators. - let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; - let voronoi = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; + let delaunay = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)); + let voronoi = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)); for sign in subpath_winding_signs(delaunay.element(), item_paths(&delaunay)) { assert_eq!(sign, expected, "Delaunay subpath winding should match the Rectangle/Ellipse generators"); } @@ -4003,9 +4001,9 @@ mod test { } } - #[tokio::test] - async fn delaunay_shared_mesh_welds_points_and_shares_edges() { - let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await; + #[test] + fn delaunay_shared_mesh_welds_points_and_shares_edges() { + let result = super::triangulate((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)); let paths = item_paths(&result); let vector = result.element(); // The connected mesh reuses the five input points and shares edges, so it fills face by face. @@ -4015,9 +4013,9 @@ mod test { assert_eq!(vector.segment_ids(paths).len(), 8); } - #[tokio::test] - async fn voronoi_disconnected_cells_make_a_subpath_per_cell() { - let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)).await; + #[test] + fn voronoi_disconnected_cells_make_a_subpath_per_cell() { + let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(false)); let paths = item_paths(&result); let vector = result.element(); let cells = vector.stroke_manipulator_groups(paths).filter(|(_, closed)| *closed).count(); @@ -4032,28 +4030,28 @@ mod test { } } - #[tokio::test] - async fn voronoi_shared_mesh_uses_face_fill() { - let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)).await; + #[test] + fn voronoi_shared_mesh_uses_face_fill() { + let result = super::voronoi_cells((), vector_item_from_points(&SQUARE_WITH_CENTER), item(true)); let paths = item_paths(&result); let vector = result.element(); assert!(vector.use_face_fill(paths)); assert!(!vector.segment_ids(paths).is_empty()); } - #[tokio::test] - async fn voronoi_leaves_degenerate_input_untouched() { + #[test] + fn voronoi_leaves_degenerate_input_untouched() { // Two points cannot form a diagram, so the element passes through unchanged. let points = [DVec2::new(0., 0.), DVec2::new(1., 1.)]; - let result = super::voronoi_cells((), vector_item_from_points(&points), item(false)).await; + let result = super::voronoi_cells((), vector_item_from_points(&points), item(false)); let paths = item_paths(&result); let vector = result.element(); assert_eq!(vector.anchor_indices(paths).len(), 2); assert_eq!(vector.segment_ids(paths).len(), 0); } - #[tokio::test] - async fn relax_points_redistributes_anchors() { + #[test] + fn relax_points_redistributes_anchors() { // Four hull corners plus two off-center interior points. let points = [ DVec2::new(0., 0.), @@ -4063,7 +4061,7 @@ mod test { DVec2::new(3., 4.), DVec2::new(7., 5.), ]; - let result = super::relax_points((), vector_item_from_points(&points), item(2.)).await; + let result = super::relax_points((), vector_item_from_points(&points), item(2.)); let positions = result.element().anchor_positions(item_paths(&result)); // Relaxation preserves the point count but repositions the interior anchors within the hull. @@ -4081,9 +4079,9 @@ mod test { } } - #[tokio::test] - async fn bounding_box() { - let bounding_box = super::bounding_box((), Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))).await; + #[test] + fn bounding_box() { + let bounding_box = super::bounding_box((), Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))); let paths = item_paths(&bounding_box); let bounding_box = bounding_box.element(); assert_eq!(bounding_box.stroke_manipulator_groups(paths).count(), 1); @@ -4102,7 +4100,7 @@ mod test { let square = Vector::item_from_bezpath(&Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)); let mut square = List::new_from_item(square); square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4)); - let bounding_box = BoundingBoxNodeMapped { content: FutureWrapperNode(square) }.eval(Footprint::default()).await; + let bounding_box = BoundingBoxNodeMapped { content: ValueNode(square) }.eval(&Footprint::default()).value().unwrap(); let paths = row_paths(&bounding_box, 0); let bounding_box = bounding_box.element(0).unwrap(); assert_eq!(bounding_box.stroke_manipulator_groups(paths).count(), 1); @@ -4120,8 +4118,8 @@ mod test { assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]); } } - #[tokio::test] - async fn copy_to_points() { + #[test] + fn copy_to_points() { let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY); let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY); @@ -4140,9 +4138,8 @@ mod test { Item::new_from_element(0), Item::new_from_element(0.), Item::new_from_element(0), - ) - .await; - let combined = List::new_from_item(super::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(copy_to_points))).await); + ); + let combined = List::new_from_item(super::combine_paths(Footprint::default(), List::new_from_element(Graphic::VectorList(copy_to_points)))); let combined_paths = row_paths(&combined, 0); let combined_copy_to_points = combined.element(0).unwrap(); @@ -4158,8 +4155,8 @@ mod test { } } - #[tokio::test] - async fn sample_polyline() { + #[test] + fn sample_polyline() { let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]); let sample_polyline = super::sample_polyline( Footprint::default(), @@ -4170,16 +4167,15 @@ mod test { Item::new_from_element(0.), Item::new_from_element(0.), Item::new_from_element(false), - ) - .await; + ); let positions = sample_polyline.element().anchor_positions(item_paths(&sample_polyline)); assert_eq!(positions.len(), 4); for (pos, expected) in positions.iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) { assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}"); } } - #[tokio::test] - async fn sample_polyline_adaptive_spacing() { + #[test] + fn sample_polyline_adaptive_spacing() { let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]); let sample_polyline = super::sample_polyline( Footprint::default(), @@ -4190,43 +4186,41 @@ mod test { Item::new_from_element(45.), Item::new_from_element(10.), Item::new_from_element(true), - ) - .await; + ); let positions = sample_polyline.element().anchor_positions(item_paths(&sample_polyline)); assert_eq!(positions.len(), 4); for (pos, expected) in positions.iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) { assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}"); } } - #[tokio::test] - async fn poisson() { + #[test] + fn poisson() { let poisson_points = super::scatter_points( Footprint::default(), vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))), Item::new_from_element(10. * std::f64::consts::SQRT_2), Item::new_from_element(0), - ) - .await; + ); let positions = poisson_points.element().anchor_positions(item_paths(&poisson_points)); assert!((20..=40).contains(&positions.len()), "actual len {}", positions.len()); for point in positions { assert!(point.length() < 50. + 1., "Expected point in circle {point}") } } - #[tokio::test] - async fn path_length() { + #[test] + fn path_length() { let bezpath = Rect::new(100., 100., 201., 201.).to_path(DEFAULT_ACCURACY); let transform = DAffine2::from_scale(DVec2::new(2., 2.)); let item = create_vector_item(bezpath, transform); - let length = super::path_length(Footprint::default(), item).await; + let length = super::path_length(Footprint::default(), item); // 101 (each rectangle edge length) * 4 (rectangle perimeter) * 2 (scale) assert_eq!(length.into_element(), 101. * 4. * 2.); } - #[tokio::test] - async fn spline() { - let spline = super::spline(Footprint::default(), vector_item_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))).await; + #[test] + fn spline() { + let spline = super::spline(Footprint::default(), vector_item_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))); let paths = item_paths(&spline); let spline = spline.element(); assert_eq!(spline.stroke_bezpath_iter(paths).count(), 1); @@ -4239,18 +4233,18 @@ mod test { open.line_to((10., 10.)); open.line_to((20., 0.)); open.line_to((30., 10.)); - let spline = super::spline(Footprint::default(), vector_item_from_bezpath(open)).await; + let spline = super::spline(Footprint::default(), vector_item_from_bezpath(open)); assert_eq!(smooth_anchors_by_contour(&spline), [[false, true, true, false]]); } // A curved source's handles are replaced by the spline's own rather than kept alongside them - #[tokio::test] - async fn spline_replaces_the_handles_of_a_curved_source() { + #[test] + fn spline_replaces_the_handles_of_a_curved_source() { let ellipse = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))); let anchors = ellipse.element().anchor_positions(item_paths(&ellipse)); assert_eq!(anchors.len(), 4); - let spline = super::spline(Footprint::default(), ellipse).await; + let spline = super::spline(Footprint::default(), ellipse); let paths = item_paths(&spline); let spline = spline.element(); @@ -4260,12 +4254,12 @@ mod test { } // Only the source's anchors become corners, joined by lines in their stored order - #[tokio::test] - async fn points_to_polyline_joins_the_anchors_with_lines() { + #[test] + fn points_to_polyline_joins_the_anchors_with_lines() { let ellipse = vector_item_from_bezpath(ellipse_bezpath(DVec2::splat(-50.), DVec2::splat(50.))); let anchors = ellipse.element().anchor_positions(item_paths(&ellipse)); - let closed = super::points_to_polyline(Footprint::default(), ellipse.clone(), item(true)).await; + let closed = super::points_to_polyline(Footprint::default(), ellipse.clone(), item(true)); let paths = item_paths(&closed); let segments: Vec = closed.element().segment_iter(paths).map(|(_, segment, ..)| segment).collect(); assert_eq!(closed.element().point_count(), anchors.len(), "the source's handles should be dropped"); @@ -4274,11 +4268,11 @@ mod test { assert!(segments.iter().all(|segment| matches!(segment, PathSeg::Line(_)))); assert!(closed.element().stroke_bezpath_iter(paths).all(|bezpath| bezpath.elements().last() == Some(&PathEl::ClosePath))); - let open = super::points_to_polyline(Footprint::default(), ellipse, item(false)).await; + let open = super::points_to_polyline(Footprint::default(), ellipse, item(false)); assert_eq!(open.element().segment_iter(item_paths(&open)).count(), 3); // Two points have nowhere to close back to, so they draw one segment either way - let pair = super::points_to_polyline(Footprint::default(), vector_item_from_points(&[DVec2::ZERO, DVec2::X]), item(true)).await; + let pair = super::points_to_polyline(Footprint::default(), vector_item_from_points(&[DVec2::ZERO, DVec2::X]), item(true)); assert_eq!(pair.element().segment_iter(item_paths(&pair)).count(), 1); } @@ -4294,8 +4288,8 @@ mod test { } // Existing handles are kept, so only the anchors without them are tangented and smooth - #[tokio::test] - async fn auto_tangents_marks_the_tangented_anchors_smooth() { + #[test] + fn auto_tangents_marks_the_tangented_anchors_smooth() { let mut bezpath = BezPath::new(); bezpath.move_to((0., 0.)); bezpath.line_to((10., 10.)); @@ -4311,7 +4305,7 @@ mod test { bezpath.line_to((200., 50.)); bezpath.close_path(); - let output = super::auto_tangents((), vector_item_from_bezpath(bezpath), item(0.5), item(true)).await; + let output = super::auto_tangents((), vector_item_from_bezpath(bezpath), item(0.5), item(true)); assert_eq!( smooth_anchors_by_contour(&output), @@ -4320,8 +4314,8 @@ mod test { } // A loop of one segment has no neighbor to share a tangent with, so it passes through unchanged - #[tokio::test] - async fn auto_tangents_keeps_a_single_segment_loop() { + #[test] + fn auto_tangents_keeps_a_single_segment_loop() { let teardrop = CubicBez::new((0., 0.), (50., -50.), (100., 50.), (0., 0.)); let mut bezpath = BezPath::new(); bezpath.move_to(teardrop.p0); @@ -4332,7 +4326,7 @@ mod test { bezpath.line_to((225., 40.)); bezpath.close_path(); - let output = super::auto_tangents((), vector_item_from_bezpath(bezpath), item(0.5), item(true)).await; + let output = super::auto_tangents((), vector_item_from_bezpath(bezpath), item(0.5), item(true)); let paths = item_paths(&output); let segments: Vec = output.element().segment_iter(paths).map(|(_, segment, ..)| segment).collect(); @@ -4340,8 +4334,8 @@ mod test { assert!(segments.contains(&PathSeg::Cubic(teardrop)), "the loop should keep its curve, not among {segments:?}"); assert_eq!(smooth_anchors_by_contour(&output), [vec![false], vec![true, true, true]]); } - #[tokio::test] - async fn morph() { + #[test] + fn morph() { let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); let mut second_rectangle = rectangles.clone_item(0).unwrap(); *second_rectangle.attribute_mut_or_insert_default::(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into()); @@ -4354,8 +4348,7 @@ mod test { Item::new_from_element(false), Item::new_from_element(InterpolationDistribution::default()), Item::default(), - ) - .await; + ); let morphed = List::new_from_item(morphed); let morphed_positions = morphed.element(0).unwrap().anchor_positions(row_paths(&morphed, 0)); // Geometry stays in local space (original rectangle coordinates) @@ -4364,8 +4357,8 @@ mod test { assert!((morphed.attribute_cloned_or_default::(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3); } - #[tokio::test] - async fn morph_interpolates_fill() { + #[test] + fn morph_interpolates_fill() { let rect = || Vector::item_from_bezpath(&Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); let solid_fill = |color: Color| Appearance::new_single(Coverage::new_fill(), Graphic::from(List::new_from_element(color))); @@ -4384,8 +4377,7 @@ mod test { Item::new_from_element(false), Item::new_from_element(InterpolationDistribution::default()), Item::default(), - ) - .await; + ); let morphed = List::new_from_item(morphed); let appearance = morphed.attribute::(ATTR_APPEARANCE, 0).expect("Morph should keep the appearance at the midpoint"); @@ -4399,8 +4391,8 @@ mod test { assert!(color.r() > 0. && color.b() > 0., "Fill should be a red-to-blue blend, got {color:?}"); } - #[tokio::test] - async fn morph_pairs_appearance_coverages_by_cover() { + #[test] + fn morph_pairs_appearance_coverages_by_cover() { let rect = || Vector::item_from_bezpath(&Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)); let paint_color = |appearance: &Appearance, cover| { @@ -4436,8 +4428,7 @@ mod test { Item::new_from_element(false), Item::new_from_element(InterpolationDistribution::default()), Item::default(), - ) - .await; + ); let morphed = List::new_from_item(morphed); let appearance = morphed.attribute::(ATTR_APPEARANCE, 0).expect("Morph should keep the appearance at the midpoint"); @@ -4468,8 +4459,8 @@ mod test { ); } - #[tokio::test] - async fn bevel_rect() { + #[test] + fn bevel_rect() { let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY); let beveled = super::bevel(Footprint::default(), vector_item_from_bezpath(source), Item::new_from_element(2_f64.sqrt() * 10.)); let paths = item_paths(&beveled); @@ -4491,8 +4482,8 @@ mod test { contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.)))); } - #[tokio::test] - async fn bevel_open_curve() { + #[test] + fn bevel_open_curve() { let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.))); let mut source = BezPath::new(); @@ -4516,8 +4507,8 @@ mod test { contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start()))); } - #[tokio::test] - async fn bevel_with_transform() { + #[test] + fn bevel_with_transform() { let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.))); let mut source = BezPath::new(); @@ -4544,8 +4535,8 @@ mod test { contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start()))); } - #[tokio::test] - async fn bevel_too_high() { + #[test] + fn bevel_too_high() { let mut source = BezPath::new(); source.move_to(Point::ZERO); source.line_to(Point::new(100., 0.)); @@ -4569,8 +4560,8 @@ mod test { contains_segment(beveled, paths, PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.)))); } - #[tokio::test] - async fn bevel_repeated_point() { + #[test] + fn bevel_repeated_point() { let line = PathSeg::Line(Line::new(Point::ZERO, Point::new(100., 0.))); let point = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::ZERO, Point::ZERO, Point::new(100., 0.))); let curve = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::new(110., 0.), Point::new(110., 200.), Point::new(200., 0.))); @@ -4586,8 +4577,8 @@ mod test { } // A rank-0 vector reaches the same per-list styling path as a vector list, rather than being skipped - #[tokio::test] - async fn assign_colors_reaches_rank_0_vector_graphics() { + #[test] + fn assign_colors_reaches_rank_0_vector_graphics() { let leaf = Graphic::Vector(Box::new(vector_item_from_bezpath(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY)))); let content = List::new_from_element(leaf); @@ -4601,8 +4592,7 @@ mod test { Item::new_from_element(false), Item::new_from_element(0), Item::new_from_element(0_i64), - ) - .await; + ); let Some(Graphic::Vector(item)) = styled.element(0) else { panic!("the leaf should stay a rank-0 vector") @@ -4626,8 +4616,8 @@ mod test { assert!(visited[0].0.is_some(), "its geometry should be measurable for the automatic gradient bounds"); } - async fn round_corners_of(bezpath: BezPath, transform: DAffine2) -> Vec { - let rounded = super::round_corners((), create_vector_item(bezpath, transform), item(10.), item(0.5), item(100.), item(5.)).await; + fn round_corners_of(bezpath: BezPath, transform: DAffine2) -> Vec { + let rounded = super::round_corners((), create_vector_item(bezpath, transform), item(10.), item(0.5), item(100.), item(5.)); rounded.element().stroke_bezpath_iter(item_paths(&rounded)).collect() } @@ -4638,12 +4628,12 @@ mod test { .fold(f64::INFINITY, f64::min) } - #[tokio::test] - async fn round_corners_leaves_a_circle_unchanged() { + #[test] + fn round_corners_leaves_a_circle_unchanged() { let circle = ellipse_bezpath(DVec2::ZERO, DVec2::splat(200.)); let transform = DAffine2::from_scale_angle_translation(DVec2::splat(1.5), 0.4, DVec2::new(30., -20.)); - let rounded = round_corners_of(circle.clone(), transform).await; + let rounded = round_corners_of(circle.clone(), transform); assert_eq!(rounded.len(), 1); assert_eq!(rounded[0].segments().count(), circle.segments().count(), "a circle has no corners to round"); for (rounded, original) in rounded[0].segments().zip(circle.segments()) { @@ -4651,9 +4641,9 @@ mod test { } } - #[tokio::test] - async fn round_corners_rounds_a_rectangles_corners() { - let rounded = round_corners_of(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY).await; + #[test] + fn round_corners_rounds_a_rectangles_corners() { + let rounded = round_corners_of(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY); let segments: Vec = rounded[0].segments().collect(); assert_eq!(segments.len(), 8, "each of the four corners becomes a curve between two edges"); @@ -4668,8 +4658,8 @@ mod test { } } - #[tokio::test] - async fn round_corners_keeps_curves_beside_a_corner() { + #[test] + fn round_corners_keeps_curves_beside_a_corner() { // A half-disc, whose two corners join its arc to its flat side, and whose arc is smooth where its two curves meet let handle = 50. * 0.552_284_749_8; let mut half_disc = BezPath::new(); @@ -4679,7 +4669,7 @@ mod test { half_disc.line_to((-50., 0.)); half_disc.close_path(); - let rounded = round_corners_of(half_disc.clone(), DAffine2::IDENTITY).await; + let rounded = round_corners_of(half_disc.clone(), DAffine2::IDENTITY); assert_eq!(rounded[0].segments().count(), 5, "only the two corners are rounded"); // The arc away from the corners, up to and past the smooth join at its top @@ -4691,14 +4681,14 @@ mod test { assert!(distance_to_path(DVec2::new(-50., 0.), &rounded[0]) > 1., "the corner should be rounded off"); } - #[tokio::test] - async fn round_corners_leaves_short_subpaths_in_place() { + #[test] + fn round_corners_leaves_short_subpaths_in_place() { let mut line = BezPath::new(); line.move_to((0., 0.)); line.line_to((40., 10.)); let transform = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.3, DVec2::new(100., 50.)); - let rounded = round_corners_of(line.clone(), transform).await; + let rounded = round_corners_of(line.clone(), transform); assert_eq!(rounded.len(), 1); assert!( pathseg_abs_diff_eq(rounded[0].segments().next().unwrap(), line.segments().next().unwrap(), 1e-9), diff --git a/node-graph/preprocessor/src/lib.rs b/node-graph/preprocessor/src/lib.rs index 37b2d71676..7ff3adbfda 100644 --- a/node-graph/preprocessor/src/lib.rs +++ b/node-graph/preprocessor/src/lib.rs @@ -13,10 +13,17 @@ use graphene_std::*; use std::collections::{HashMap, HashSet}; use std::hash::{DefaultHasher, Hash, Hasher}; +#[derive(Debug, Clone)] +struct Substitution { + node: DocumentNode, + wrapped_node_id: NodeId, +} + #[derive(Debug, Default, Clone)] pub struct Preprocessor { - substitutions: HashMap, + substitutions: HashMap, inject_scopes: HashMap, + context_dependencies: HashMap, } impl Preprocessor { @@ -81,10 +88,6 @@ impl Preprocessor { let curve_node = DocumentNode { inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::AnimationCurve(curve.clone()), false)], implementation: DocumentNodeImplementation::ProtoNode(graphene_core::animation::evaluate_curve::IDENTIFIER), - context_features: ContextDependencies { - extract: ContextFeatures::ANIMATION_TIME, - inject: ContextFeatures::empty(), - }, ..Default::default() }; new_nodes.push((id, curve_node)); @@ -109,7 +112,9 @@ impl Preprocessor { match &mut node.implementation { DocumentNodeImplementation::Network(node_network) => self.expand_network(node_network), DocumentNodeImplementation::ProtoNode(proto_node_identifier) => { - if let Some(new_node) = self.substitutions.get(proto_node_identifier) { + let context_dependencies = node.context_dependencies.take().or_else(|| self.context_dependencies.get(proto_node_identifier).copied()); + + if let Some(Substitution { node: new_node, wrapped_node_id }) = self.substitutions.get(proto_node_identifier) { // Reconcile the document node's inputs with what the current node definition expects, // since the saved document may have fewer or more inputs than the current version while node.inputs.len() < new_node.inputs.len() { @@ -118,6 +123,15 @@ impl Preprocessor { node.inputs.truncate(new_node.inputs.len()); node.implementation = new_node.implementation.clone(); + + // Move context dependencies to the wrapped node because networks are not allowed to have context dependencies so we need to + if let DocumentNodeImplementation::Network(network) = &mut node.implementation + && let Some(wrapped_node) = network.nodes.get_mut(wrapped_node_id) + { + wrapped_node.context_dependencies = context_dependencies; + } + } else { + node.context_dependencies = context_dependencies; } } DocumentNodeImplementation::Extract => (), @@ -127,6 +141,7 @@ impl Preprocessor { pub fn new() -> Self { let mut substitutions = HashMap::new(); + let mut context_dependencies = HashMap::new(); let mut inject_scopes = HashMap::new(); // We pre initialize the node registry here to avoid a deadlock let into_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY; @@ -138,9 +153,12 @@ impl Preprocessor { fields, memoize, inject_scope, + asynchronous, output_fields, .. } = metadata; + context_dependencies.insert(id.clone(), ContextDependencies::from(metadata.context_features.as_slice())); + let Some(implementations) = node_registry.get(&id) else { continue }; let valid_call_args: HashSet<_> = implementations.iter().map(|(_, node_io)| node_io.call_argument.clone()).collect(); let first_node_io = implementations.first().map(|(_, node_io)| node_io).unwrap_or(const { &NodeIOTypes::empty() }); @@ -269,7 +287,7 @@ impl Preprocessor { id.as_str() ); - if generated_nodes == 0 && !memoize && !inject_scope && output_fields.is_none() { + if generated_nodes == 0 && !memoize && !inject_scope && output_fields.is_none() && !asynchronous { continue; } @@ -279,17 +297,17 @@ impl Preprocessor { implementation: DocumentNodeImplementation::ProtoNode(id.clone()), visible: true, skip_deduplication: false, - context_features: ContextDependencies::from(metadata.context_features.as_slice()), ..Default::default() }; - nodes.insert(NodeId(input_count as u64), document_node); + let wrapped_node_id = NodeId(input_count as u64); + nodes.insert(wrapped_node_id, document_node); // If memoize is requested, append a Memoize node after the main node and redirect the export through it let export_node_id = if memoize { let memoize_node_id = NodeId(input_count as u64 + 1); let memoize_node = DocumentNode { - inputs: vec![NodeInput::node(NodeId(input_count as u64), 0)], + inputs: vec![NodeInput::node(wrapped_node_id, 0)], implementation: DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER.clone()), visible: true, ..Default::default() @@ -297,7 +315,7 @@ impl Preprocessor { nodes.insert(memoize_node_id, memoize_node); memoize_node_id } else { - NodeId(input_count as u64) + wrapped_node_id }; // A multi-output node exports each field through its generated extractor node, after the hidden primary output if it has one @@ -336,7 +354,7 @@ impl Preprocessor { ..Default::default() }; - substitutions.insert(id.clone(), node); + substitutions.insert(id.clone(), Substitution { node, wrapped_node_id }); // If `inject_scope` is requested, prepare the proto node template and type info needed if *inject_scope @@ -348,14 +366,17 @@ impl Preprocessor { call_argument: node_io.call_argument.clone(), implementation: DocumentNodeImplementation::ProtoNode(id.clone()), visible: true, - context_features: ContextDependencies::from(metadata.context_features.as_slice()), ..Default::default() }; inject_scopes.insert(id.clone(), (template, node_io.return_value.clone())); } } - Self { substitutions, inject_scopes } + Self { + substitutions, + context_dependencies, + inject_scopes, + } } } @@ -370,7 +391,7 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp return NodeInput::value(TaggedValue::None, true); }; let ty = ty.clone().normalize_rank(); - let exposed = if index == 0 { ty != fn_type_fut!(Context, ()) } else { field.exposed }; + let exposed = if index == 0 { ty != fn_type!(Context, ()) } else { field.exposed }; match &field.value_source { RegistryValueSource::None => {} @@ -383,6 +404,7 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp } } RegistryValueSource::Scope(data) => return NodeInput::scope(*data), + RegistryValueSource::SourceId => return NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId), }; // A ranked `Item` type prefers a bare `T` value (promoted at resolution), since bare values drive the Inspector widgets @@ -503,11 +525,11 @@ mod destructure_tests { fn assert_execution_result(network: NodeNetwork, expected: TaggedValue) { let proto_network = Compiler {}.compile_single(network).expect("Compilation should succeed"); - let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).expect("The executor should type check and build"); + let executor = DynamicExecutor::new(proto_network).expect("The executor should type check and build"); let context: core_types::Context = None; - let result = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context)).expect("Execution should succeed"); - assert_eq!(result, expected); + let result = executor.tree().eval_tagged_value(executor.output(), &context).expect("Execution should succeed"); + assert_eq!(result, core_types::Poll::Final(expected)); } #[test] @@ -727,4 +749,51 @@ mod tests { "The paint input's `Color::BLACK` default should parse against its `Item` wire type" ); } + + #[test] + fn substitution_moves_context_dependencies_onto_the_wrapped_node() { + let identifier = graphene_std::path_bool_nodes::boolean_operation::IDENTIFIER; + let context_dependencies = ContextDependencies { + extract: ContextFeatures::FOOTPRINT, + inject: ContextFeatures::INDEX, + }; + let mut network = NodeNetwork { + nodes: [( + NodeId(0), + DocumentNode { + implementation: DocumentNodeImplementation::ProtoNode(identifier.clone()), + context_dependencies: Some(context_dependencies), + ..Default::default() + }, + )] + .into_iter() + .collect(), + ..Default::default() + }; + + Preprocessor::new().expand_network(&mut network); + + let node = &network.nodes[&NodeId(0)]; + assert_eq!( + node.context_dependencies, None, + "The network node replacing the substituted node should not keep its context dependencies" + ); + let DocumentNodeImplementation::Network(substitution) = &node.implementation else { + panic!("Boolean Operation is memoized, so it should be substituted with a network"); + }; + + let wrapped_node = substitution + .nodes + .values() + .find(|inner| inner.implementation == DocumentNodeImplementation::ProtoNode(identifier.clone())) + .expect("The substitution network should contain the wrapped proto node"); + assert_eq!(wrapped_node.context_dependencies, Some(context_dependencies), "The wrapped proto node should carry the override"); + + let NodeInput::Node { node_id: export_id, .. } = substitution.exports[0] else { + panic!("The substitution network should export a node"); + }; + let export = &substitution.nodes[&export_id]; + assert_eq!(export.implementation, DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER)); + assert_eq!(export.context_dependencies, None, "The memoize node should not take over the wrapped node's context dependencies"); + } } From b837b399442f5cd355e5da3ea778b97ddc1de90d Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 18 Oct 2026 18:36:28 +0000 Subject: [PATCH 37/47] Give hot ops shared attributes, and close an interaction with a flagged Meta op (#4753) * Give hot ops shared attributes, and close an interaction with a flagged Meta op * Review fixes * Cleanup --- document/format/tests/open_create.rs | 5 + document/format/tests/staging_and_reopen.rs | 1 + document/graph-storage/src/attributes/attr.rs | 3 +- document/graph-storage/src/crdt.rs | 1 + document/graph-storage/src/document.rs | 2 +- document/graph-storage/src/prior.rs | 2 +- document/graph-storage/src/session.rs | 93 +++++++++++++++++-- .../graph-storage/src/tests/bookkeeping.rs | 88 ++++++++++++++++++ document/graph-storage/src/tests/crdt.rs | 2 + node-graph/rfcs/document-format.md | 3 + 10 files changed, 191 insertions(+), 9 deletions(-) diff --git a/document/format/tests/open_create.rs b/document/format/tests/open_create.rs index d58732614d..ae2b8a7ddf 100644 --- a/document/format/tests/open_create.rs +++ b/document/format/tests/open_create.rs @@ -123,6 +123,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() { }, timestamp: TimeStamp { counter: 1, peer: PeerId(5) }, sequence: HotSequence(1), + attributes: Default::default(), }; gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}")); @@ -148,6 +149,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() { }, timestamp: TimeStamp { counter: 1, peer: PeerId(5) }, sequence: HotSequence(1), + attributes: Default::default(), }; let late = HotOp { op: RegistryDelta::AddNetwork { @@ -156,6 +158,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() { }, timestamp: TimeStamp { counter: 10, peer: PeerId(5) }, sequence: HotSequence(2), + attributes: Default::default(), }; gdd.apply_hot_op(early).unwrap(); gdd.apply_hot_op(late).unwrap(); @@ -194,6 +197,7 @@ fn last_broadcast_rev_persists_across_reopen() { }, timestamp: TimeStamp { counter: 1, peer: PeerId(5) }, sequence: HotSequence(1), + attributes: Default::default(), }; gdd.apply_hot_op(op).unwrap(); let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}")); @@ -632,6 +636,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() { }, timestamp: TimeStamp { counter: 1, peer: PeerId(5) }, sequence: HotSequence(1), + attributes: Default::default(), }; gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}")); diff --git a/document/format/tests/staging_and_reopen.rs b/document/format/tests/staging_and_reopen.rs index ab6eb51399..87dce9bcae 100644 --- a/document/format/tests/staging_and_reopen.rs +++ b/document/format/tests/staging_and_reopen.rs @@ -54,6 +54,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() { }, timestamp: TimeStamp { counter, peer: PeerId(22) }, sequence: HotSequence(counter), + attributes: Default::default(), }; futures::executor::block_on(async { let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap(); diff --git a/document/graph-storage/src/attributes/attr.rs b/document/graph-storage/src/attributes/attr.rs index edf58496dd..1fa119cf4d 100644 --- a/document/graph-storage/src/attributes/attr.rs +++ b/document/graph-storage/src/attributes/attr.rs @@ -67,6 +67,7 @@ pub mod network { } pub mod delta { - /// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. + /// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. Also set on + /// the last hot op of an interaction. pub const INTERACTION_END: &str = "interaction_end"; } diff --git a/document/graph-storage/src/crdt.rs b/document/graph-storage/src/crdt.rs index 4eb23f3c05..1e18426dea 100644 --- a/document/graph-storage/src/crdt.rs +++ b/document/graph-storage/src/crdt.rs @@ -211,6 +211,7 @@ pub enum RegistryDelta { Merge { extra_parents: Vec, }, + Meta, // Allow for future delta types without a model change Other(Value), } diff --git a/document/graph-storage/src/document.rs b/document/graph-storage/src/document.rs index 0e3ca48836..7da8ced710 100644 --- a/document/graph-storage/src/document.rs +++ b/document/graph-storage/src/document.rs @@ -350,7 +350,7 @@ impl Document { registry.attributes.apply_delta(delta, timestamp); } // Merge is a structural sync point only; it mutates no registry state. - RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {} + RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {} } Ok(()) } diff --git a/document/graph-storage/src/prior.rs b/document/graph-storage/src/prior.rs index d66bfad852..1d7b59e6be 100644 --- a/document/graph-storage/src/prior.rs +++ b/document/graph-storage/src/prior.rs @@ -184,7 +184,7 @@ pub(crate) fn capture(registry: &Registry, op: &RegistryDelta) -> Vec { key: delta.key.clone(), previous: registry.attributes.get(&delta.key).cloned(), }), - RegistryDelta::Merge { .. } | RegistryDelta::Other(_) => {} + RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {} } priors } diff --git a/document/graph-storage/src/session.rs b/document/graph-storage/src/session.rs index 4cb6c33be7..b387e74c1a 100644 --- a/document/graph-storage/src/session.rs +++ b/document/graph-storage/src/session.rs @@ -3,7 +3,8 @@ use crate::NodeMetadataSource; #[cfg(any(feature = "conversion", test))] use crate::from_runtime; use crate::{ - ApplyMode, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, to_value, + ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value, + to_value, }; use graphene_resource::{ResourceHash, ResourceId}; use serde::{Deserialize, Serialize}; @@ -146,15 +147,19 @@ impl Session { /// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers) /// before any of its edits. A no-op batch doesn't register, since registration rides a real edit. pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator) -> Result, CrdtError> { + self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new()))) + } + + fn stage_ops_with(&mut self, ops: impl IntoIterator) -> Result, CrdtError> { // A batch is staged whole or not at all. - let mut pending: Vec = ops.into_iter().collect(); + let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect(); if pending.is_empty() { return Ok(Vec::new()); } let (peer, user) = (self.document.peer, self.document.user); if self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user) != Some(user) { - pending.insert(0, RegistryDelta::RegisterPeer { peer, user }); + pending.insert(0, (RegistryDelta::RegisterPeer { peer, user }, Attributes::new())); } // A reused sequence would fall under the retired marks, so a batch running past the end is refused. @@ -164,12 +169,13 @@ impl Session { let sequence_before = self.document.last_hot_sequence; let mut staged = Vec::with_capacity(pending.len()); - for op in pending { + for (op, attributes) in pending { let sequence = HotSequence(self.document.last_hot_sequence.0 + 1); let hot_op = HotOp { op, timestamp: self.document.clock.tick(), sequence, + attributes, }; if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) { // The run continues where it was, so no sequence goes unused. @@ -344,6 +350,60 @@ impl Session { self.document.history.len() } + /// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a + /// re-registration possibly before the marker; empty when nothing is open. + pub fn end_interaction(&mut self) -> Result, CrdtError> { + let peer = self.document.peer; + let open = self + .document + .hot_log + .iter() + .rev() + .find(|hot_op| hot_op.timestamp.peer == peer) + .is_some_and(|hot_op| !hot_op.ends_interaction()); + if !open { + return Ok(Vec::new()); + } + let mut closing = Attributes::new(); + closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN); + self.stage_ops_with([(RegistryDelta::Meta, closing)]) + } + + /// Every author's closed interactions in the hot log, the earliest closed first. + pub fn closed_interactions(&self) -> Vec { + let mut by_author: HashMap> = HashMap::new(); + for hot_op in &self.document.hot_log { + by_author.entry(hot_op.timestamp.peer).or_default().push(hot_op); + } + + let mut closed = Vec::new(); + for (author, mut ops) in by_author { + ops.sort_by_key(|hot_op| hot_op.sequence); + let mut expected = self.document.retired.retired_up_to.get(&author).copied().unwrap_or(HotSequence::NONE).next(); + let mut current = Vec::new(); + let mut contiguous = true; + for hot_op in ops { + // Retired past a gap: not in the log, but not missing either. + while expected < hot_op.sequence && self.document.retired.covers(HotOpId { peer: author, sequence: expected }) { + expected = expected.next(); + } + contiguous &= hot_op.sequence == expected; + expected = hot_op.sequence.next(); + current.push(hot_op.id()); + if hot_op.ends_interaction() { + closed.push(ClosedInteraction { + author, + ops: std::mem::take(&mut current), + closed_at: hot_op.timestamp, + contiguous, + }); + } + } + } + closed.sort_by_key(|interaction| interaction.closed_at); + closed + } + /// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains. pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec { self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect() @@ -351,7 +411,7 @@ impl Session { /// Promote the given hot ops into retired deltas in hot-log order, each keeping its authored stamp. /// - /// One retired delta per hot op. + /// One retired delta per hot op, except a `Meta` op, which commits nothing. pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result, CrdtError> { let wanted: HashSet = ids.iter().copied().collect(); let (drained, kept): (Vec, Vec) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id())); @@ -359,7 +419,10 @@ impl Session { self.document.resync_hot_timestamps(); self.document.retired.extend(drained.iter().map(HotOp::id)); - let ops = drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))); + let ops = drained + .into_iter() + .filter(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) + .map(|hot_op| (hot_op.op, Some(hot_op.timestamp))); self.commit_ops_authored_at(ops, true) } @@ -627,9 +690,16 @@ pub struct HotOp { pub timestamp: TimeStamp, /// Position in its author's run. See [`HotSequence`]. pub sequence: HotSequence, + /// Shared with every peer, unlike `Delta::attributes`. Dropped at retirement. + #[serde(default)] + pub attributes: Attributes, } impl HotOp { + pub fn ends_interaction(&self) -> bool { + self.attributes.get_or(crate::attr::delta::INTERACTION_END, false) + } + /// Identifies the op in the retired marks, which track a contiguous prefix per author. pub fn id(&self) -> HotOpId { HotOpId { @@ -639,6 +709,17 @@ impl HotOp { } } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ClosedInteraction { + pub author: PeerId, + /// In the author's order, the marker last. + pub ops: Vec, + /// The marker's stamp. + pub closed_at: TimeStamp, + /// No gap in the author's sequence since its retired frontier. + pub contiguous: bool, +} + /// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport /// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)] diff --git a/document/graph-storage/src/tests/bookkeeping.rs b/document/graph-storage/src/tests/bookkeeping.rs index f8a86dc7bf..176223a965 100644 --- a/document/graph-storage/src/tests/bookkeeping.rs +++ b/document/graph-storage/src/tests/bookkeeping.rs @@ -25,6 +25,7 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() { op, timestamp: crate::TimeStamp { counter, peer: PeerId(peer) }, sequence: crate::HotSequence(1), + attributes: Default::default(), }; let (late, own) = (hot(add_network(9), 50, 2), hot(set_attribute("x", 1), 20, 3)); host.replay_hot_op(late.clone()).expect("the late-stamped op lands first"); @@ -83,6 +84,7 @@ fn a_reopened_session_drops_a_late_copy_of_a_retired_op() { op: set_attribute("k", 1), timestamp: crate::TimeStamp { counter: 3, peer: PeerId(2) }, sequence: crate::HotSequence(1), + attributes: Default::default(), }; let mut host = Session::with_peer(PeerId(1)); host.replay_hot_op(op.clone()).unwrap(); @@ -165,6 +167,7 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() { op: set_attribute("k", 1), timestamp: crate::TimeStamp { counter: 50, peer: PeerId(1) }, sequence: crate::HotSequence(7), + attributes: Default::default(), }; let mut marks = crate::RetiredMarks::default(); marks.extend([own.id()]); @@ -176,3 +179,88 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() { assert!(next.sequence > own.sequence, "a fresh sequence"); assert!(next.timestamp > own.timestamp, "a later stamp"); } + +#[test] +fn only_closed_interactions_are_listed_and_the_marker_commits_nothing() { + let mut host = Session::with_peer(PeerId(1)); + let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp { + op, + timestamp: crate::TimeStamp { counter, peer: PeerId(2) }, + sequence: crate::HotSequence(sequence), + attributes: Default::default(), + }; + + assert!(host.end_interaction().expect("nothing to close").is_empty(), "no op of this peer is open"); + + // The guest's open interaction is stamped before everything the host does. + host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op"); + host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op"); + + host.stage_ops([set_attribute("host", 1)]).expect("host op"); + let marker = host.end_interaction().expect("close").pop().expect("the host's interaction was open"); + assert!(matches!(marker.op, RegistryDelta::Meta) && marker.ends_interaction()); + assert!(host.end_interaction().expect("nothing more to close").is_empty(), "closing twice stages nothing"); + + let closed = host.closed_interactions(); + assert_eq!(closed.len(), 1, "the guest's open interaction is not listed: {closed:?}"); + assert_eq!(closed[0].author, PeerId(1)); + assert!(closed[0].contiguous); + assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker"); + + let revs = host.retire_hot_ops(&closed[0].ops).expect("retire"); + assert_eq!(revs.len(), 2, "the marker commits no delta"); + assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot"); + + host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker"); + let closed = host.closed_interactions(); + assert_eq!(closed.len(), 1); + assert_eq!(closed[0].author, PeerId(2)); + assert_eq!(closed[0].ops.len(), 3); +} + +#[test] +fn an_interaction_with_a_gap_is_not_contiguous_until_the_gap_fills() { + let mut host = Session::with_peer(PeerId(1)); + let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp { + op, + timestamp: crate::TimeStamp { counter, peer: PeerId(2) }, + sequence: crate::HotSequence(sequence), + attributes: Default::default(), + }; + host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op"); + host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker, op 2 still in flight"); + host.replay_hot_op(closing(guest_op(13, 4, set_attribute("guest", 2)))).expect("a later interaction"); + + let closed = host.closed_interactions(); + assert_eq!(closed.len(), 2); + assert!(!closed[0].contiguous); + assert!(!closed[1].contiguous, "the gap is behind the later interaction too"); + + host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op"); + let closed = host.closed_interactions(); + assert!(closed.iter().all(|interaction| interaction.contiguous)); + assert_eq!(closed[0].ops.len(), 3); +} + +#[test] +fn a_flagged_write_closes_its_interaction() { + let mut host = Session::with_peer(PeerId(1)); + let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp { + op, + timestamp: crate::TimeStamp { counter, peer: PeerId(2) }, + sequence: crate::HotSequence(sequence), + attributes: Default::default(), + }; + host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op"); + assert!(host.closed_interactions().is_empty(), "the interaction is open"); + + host.replay_hot_op(closing(guest_op(11, 2, set_attribute("guest", 1)))).expect("flagged write"); + let closed = host.closed_interactions(); + assert_eq!(closed.len(), 1); + assert_eq!(closed[0].ops.len(), 2, "both writes, and no marker of its own"); +} + +fn closing(mut hot_op: crate::HotOp) -> crate::HotOp { + hot_op.attributes.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), crate::TimeStamp::ORIGIN); + hot_op +} diff --git a/document/graph-storage/src/tests/crdt.rs b/document/graph-storage/src/tests/crdt.rs index b56aa8b7ad..4121e3c515 100644 --- a/document/graph-storage/src/tests/crdt.rs +++ b/document/graph-storage/src/tests/crdt.rs @@ -41,6 +41,7 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() { op: remove_node_op(NodeId(99)), timestamp: observed, sequence: crate::HotSequence(1), + attributes: Default::default(), }; document @@ -978,6 +979,7 @@ fn hot_op(op: RegistryDelta, counter: u64, peer: u64, sequence: u64) -> HotOp { op, timestamp: ts(counter, peer), sequence, + attributes: Default::default(), } } diff --git a/node-graph/rfcs/document-format.md b/node-graph/rfcs/document-format.md index fff4b46ec5..a11ad767cb 100644 --- a/node-graph/rfcs/document-format.md +++ b/node-graph/rfcs/document-format.md @@ -123,6 +123,7 @@ pub enum RegistryDelta { AddResource { id: ResourceId, entry: ResourceEntry }, // whole-entry; reverse of RemoveResource RemoveResource { id: ResourceId, snapshot: ResourceEntry }, // snapshot for O(1) reverse Merge { extra_parents: Vec }, // joins divergent tips; registry no-op + Meta, Other(Value), // forward-compatible escape hatch } @@ -157,6 +158,8 @@ One timestamp per `Delta` applies to every LWW-eligible write inside its `kind`. `Delta.attributes` is a type-erased annotation bucket (the same shape as the registry's attribute buckets) for mutable, local-only labels: the `interaction_end` marker that bounds undo units, and later commit messages. It is **excluded from `id`** so that annotating a delta never changes its content-addressed identity. An inline write sets it before the delta's history frame is persisted, while a later relabel rewrites that frame. +`HotOp.attributes` is the same bucket on a hot op, but shared: it travels with the op to every peer and is left behind at retirement. The same `interaction_end` key marks the last op of its author's interaction, so the retirer takes the author's ops through it as one unit. When the boundary comes after the last write was sent, a data-less `RegistryDelta::Meta` op carries the flag; retirement drops `Meta` ops. The retirer marks the unit's last retired delta with `Delta.attributes`' own `interaction_end`, so the boundary survives without the hot op. + ## History as a tree History is a multi-parent DAG. Branching is implicit: every concurrent or out-of-sync edit creates a branch by virtue of sharing a parent with another delta. Divergent tips are rejoined by an explicit `Merge` delta listing the joined tips, which is a registry no-op (it only collapses the tips so `head` stays a single `Rev`). From 49711cd37591bbdccce9ecaac6eae98de65893bf Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Mon, 19 Oct 2026 23:39:53 -0700 Subject: [PATCH 38/47] Restyle Inspector panel sections and add in links between the selected layer's neighbors (#4757) Restyle Inspector sections and link the selected layer's neighbors --- .../layout/utility_types/layout_widget.rs | 20 +- .../data_panel/data_panel_message_handler.rs | 5 +- .../node_graph/node_graph_message_handler.rs | 68 ++++- .../document/node_graph/node_inspector.rs | 56 ++-- .../src/components/panels/Inspector.svelte | 39 ++- frontend/src/components/panels/Layers.svelte | 13 +- .../src/components/widgets/NodeSection.svelte | 257 +++++++++++++----- 7 files changed, 349 insertions(+), 109 deletions(-) diff --git a/editor/src/messages/layout/utility_types/layout_widget.rs b/editor/src/messages/layout/utility_types/layout_widget.rs index 0dc7a14c07..c964448106 100644 --- a/editor/src/messages/layout/utility_types/layout_widget.rs +++ b/editor/src/messages/layout/utility_types/layout_widget.rs @@ -423,9 +423,15 @@ pub struct NodeSection { /// For a section in the chain feeding another section's input, the wire drawn up to the section above, which its node's output feeds. #[serde(rename = "outputWire")] pub output_wire: Option, - /// Whether this section only refers to its node with a row like the Data panel's, in place of its header and parameters (for the layer whose stack feeds the bottom of a chain). + /// Whether this section only refers to its node with a row like the Data panel's, in place of its header and parameters (for a layer feeding a chain, or feeding or fed by the selected layer). #[serde(rename = "nodeReference")] pub node_reference: bool, + /// For a section referring to layers that take the wire from the section below into their content, rather than from their bottom, that wire turning in from the left past its indent. + #[serde(rename = "contentWire")] + pub content_wire: Option, + /// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom. + #[serde(rename = "contentWireContinues")] + pub content_wire_continues: bool, /// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header. pub expanded: bool, /// The ID of the node whose Inspector section this is. @@ -477,6 +483,8 @@ impl LayoutGroup { chain_wire: None, output_wire: None, node_reference: false, + content_wire: None, + content_wire_continues: false, expanded, id, layout, @@ -582,6 +590,8 @@ impl Diffable for LayoutGroup { chain_wire: current_chain_wire, output_wire: current_output_wire, node_reference: current_node_reference, + content_wire: current_content_wire, + content_wire_continues: current_content_wire_continues, expanded: current_expanded, id: current_id, layout: current_layout, @@ -596,6 +606,8 @@ impl Diffable for LayoutGroup { chain_wire: new_chain_wire, output_wire: new_output_wire, node_reference: new_node_reference, + content_wire: new_content_wire, + content_wire_continues: new_content_wire_continues, expanded: new_expanded, id: new_id, layout: new_layout, @@ -613,6 +625,8 @@ impl Diffable for LayoutGroup { || *current_chain_wire != new_chain_wire || *current_output_wire != new_output_wire || *current_node_reference != new_node_reference + || *current_content_wire != new_content_wire + || *current_content_wire_continues != new_content_wire_continues || *current_expanded != new_expanded || *current_id != new_id { @@ -626,6 +640,8 @@ impl Diffable for LayoutGroup { *current_chain_wire = new_chain_wire; *current_output_wire = new_output_wire; *current_node_reference = new_node_reference; + *current_content_wire = new_content_wire; + *current_content_wire_continues = new_content_wire_continues; *current_expanded = new_expanded; *current_id = new_id; current_layout.clone_from(&new_layout); @@ -641,6 +657,8 @@ impl Diffable for LayoutGroup { chain_wire: new_chain_wire, output_wire: new_output_wire, node_reference: new_node_reference, + content_wire: new_content_wire, + content_wire_continues: new_content_wire_continues, expanded: new_expanded, id: new_id, layout: new_layout, diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index 0eb405616e..cdd0469356 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -1044,7 +1044,7 @@ pub fn node_reference_button( network_path: &[NodeId], selection_network_path: &[NodeId], select: impl Fn() -> Message + Send + Sync + 'static, -) -> WidgetInstance { +) -> TextButton { let is_layer = network_interface.is_layer(&node_id, network_path); let icon = network_interface.node_icon(&node_id, network_path); let name = network_interface.display_name(&node_id, network_path); @@ -1063,7 +1063,6 @@ pub fn node_reference_button( (true, false, _) => "", }) .on_update(move |_| select()) - .widget_instance() } impl TableItemLayout for NodeId { @@ -1097,7 +1096,7 @@ impl TableItemLayout for NodeId { NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] }.into(), ]), }; - vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select)] + vec![node_reference_button(node_id, network_interface, &network_path, data.selection_network_path, select).widget_instance()] } fn value_page(&self, data: &mut LayoutData) -> Vec { vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), data))] diff --git a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs index c4228ccc68..8c045b4dff 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_graph_message_handler.rs @@ -3076,7 +3076,73 @@ impl NodeGraphMessageHandler { } } - vec![layer_section] + // The layers this one's output feeds, which a stack used in several places can be many of, and the graph's output none of. + // Followed through any nodes between, each layer takes it either from its bottom (as the sibling above in its stack) or into its content (as its parent). + let network_path = context.selection_network_path; + let outward_connectors = |node_id: NodeId| { + context + .network_interface + .with_outward_wires(network_path, |outward_wires| outward_wires.get(&OutputConnector::primary_output(node_id)).cloned()) + .flatten() + .unwrap_or_default() + }; + let (mut siblings, mut parents) = (Vec::new(), Vec::new()); + let mut pending_connectors = outward_connectors(layer); + let mut visited_nodes = HashSet::new(); + while let Some(connector) = pending_connectors.pop() { + let Some(node_id) = connector.node_id() else { continue }; + + if context.network_interface.is_layer(&node_id, network_path) { + let receivers = if connector.input_index() == 0 { &mut siblings } else { &mut parents }; + receivers.push(node_id); + continue; + } + + // A node passes it on only when taking it as its primary input, rather than as a parameter + if connector.input_index() == 0 && visited_nodes.insert(node_id) { + pending_connectors.extend(outward_connectors(node_id)); + } + } + + // Sorted for a stable button order, since outward wires are unordered + siblings.sort_unstable(); + siblings.dedup(); + parents.sort_unstable(); + parents.dedup(); + + // The layer feeding this one from below in its stack, unless this is the bottom + let layer_below = node_inspector::input_chain(layer, 0, context.network_interface, network_path).and_then(|(_, stack_layer)| stack_layer); + + // Each is only referred to by a button, wired to the layer's section. Parents sit just above, the wire turning into their content, + // and siblings above them, the wire continuing up past that turn into their bottom. + let mut sections = Vec::new(); + + if let Some(siblings_section) = node_inspector::layer_references_section(&siblings, "Select Sibling Layer", context) { + sections.push(siblings_section); + } + if let Some(mut parents_section) = node_inspector::layer_references_section(&parents, "Select Parent Layer", context) { + if let LayoutGroup::NodeSection(section) = &mut parents_section { + section.content_wire = Some(node_inspector::output_section_wire(layer, context)); + section.content_wire_continues = !siblings.is_empty(); + } + sections.push(parents_section); + } + if !sections.is_empty() + && let LayoutGroup::NodeSection(section) = &mut layer_section + { + section.output_wire = Some(node_inspector::output_section_wire(layer, context)); + } + sections.push(layer_section); + if let Some(layer_below) = layer_below + && let Some(mut below_section) = node_inspector::layer_references_section(&[layer_below], "Select Sibling Layer", context) + { + if let LayoutGroup::NodeSection(section) = &mut below_section { + section.output_wire = Some(node_inspector::output_section_wire(layer_below, context)); + } + sections.push(below_section); + } + + sections } // If multiple layers and/or nodes are selected, show nothing _ => Vec::new(), diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index bca938a149..8468c351d3 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -3086,15 +3086,6 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo ] } -pub(crate) fn node_no_inspector_content(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec { - let text = if context.network_interface.is_layer(&node_id, context.selection_network_path) { - "Layer has no parameters" - } else { - "Node has no parameters" - }; - string_inspector(text) -} - pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> LayoutGroup { let mut layout = Vec::new(); @@ -3183,10 +3174,6 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect } } - if layout.is_empty() { - layout = node_no_inspector_content(node_id, context); - } - let display_name = context .network_interface .node_metadata(&node_id, context.selection_network_path) @@ -3237,16 +3224,12 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect } // That layer is only referred to, as in the Data panel, rather than shown with its own parameters and chain - if let Some(layer) = stack_layer { - let button = node_reference_button(layer, context.network_interface, network_path, network_path, move || { - NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }.into() - }); - let name = context.network_interface.display_name(&layer, network_path); - let visible = context.network_interface.is_visible(&layer, network_path); - - let mut reference_section = LayoutGroup::section(name, None, "", visible, false, true, layer.0, Layout(vec![LayoutGroup::row(vec![button])])); + let feeds_content = input_index == LAYER_SECONDARY_INPUT_INDEX && context.network_interface.is_layer(&node_id, network_path); + let tooltip_label = if feeds_content { "Select Child Layer" } else { "Select Layer" }; + if let Some(layer) = stack_layer + && let Some(mut reference_section) = layer_references_section(&[layer], tooltip_label, context) + { if let LayoutGroup::NodeSection(section) = &mut reference_section { - section.node_reference = true; section.output_wire = Some(output_section_wire(layer, context)); } @@ -3261,8 +3244,35 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect section } +/// A section only referring to layers, as the Data panel does, with a row of buttons that each select one rather than showing its parameters and chain. +/// Their tooltip label names how the layers relate to the section they're shown beside. +pub(crate) fn layer_references_section(layers: &[NodeId], tooltip_label: &str, context: &NodeInspectorContext) -> Option { + let network_path = context.selection_network_path; + let &first_layer = layers.first()?; + + let mut buttons = Vec::with_capacity(layers.len() * 2); + for &layer in layers { + if !buttons.is_empty() { + buttons.push(Separator::new(SeparatorStyle::Related).widget_instance()); + } + let button = node_reference_button(layer, context.network_interface, network_path, network_path, move || { + NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }.into() + }); + buttons.push(button.tooltip_label(tooltip_label).widget_instance()); + } + + let name = context.network_interface.display_name(&first_layer, network_path); + let visible = context.network_interface.is_visible(&first_layer, network_path); + + let mut section = LayoutGroup::section(name, None, "", visible, false, true, first_layer.0, Layout(vec![LayoutGroup::row(buttons)])); + if let LayoutGroup::NodeSection(node_section) = &mut section { + node_section.node_reference = true; + } + Some(section) +} + /// The wire drawn up from a node's section in a chain to the section above, which its output feeds. -fn output_section_wire(node_id: NodeId, context: &NodeInspectorContext) -> SectionWire { +pub(crate) fn output_section_wire(node_id: NodeId, context: &NodeInspectorContext) -> SectionWire { let output_type = context.network_interface.output_type(&OutputConnector::node(node_id, 0), context.selection_network_path); SectionWire { diff --git a/frontend/src/components/panels/Inspector.svelte b/frontend/src/components/panels/Inspector.svelte index 15bd9b6c9d..fdef1eece5 100644 --- a/frontend/src/components/panels/Inspector.svelte +++ b/frontend/src/components/panels/Inspector.svelte @@ -15,7 +15,7 @@ let dragging = false; let fromIndex: number | undefined = undefined; let insertIndex: number | undefined = undefined; - let insertMarkerTop: number | undefined = undefined; + let insertMarker: { top: number; left: number; width: number } | undefined = undefined; let justFinishedDrag = false; // Used to suppress the click event that follows a drag release (which would otherwise toggle a section) onMount(() => { @@ -91,7 +91,7 @@ const sections = reorderableSections(); if (!container || sections.length === 0) { insertIndex = undefined; - insertMarkerTop = undefined; + insertMarker = undefined; return; } @@ -111,17 +111,38 @@ // Position the marker purely from the gap index so it has one fixed spot per gap, rather than snapping between adjacent // sections' edges as the cursor crosses their shared boundary. + // Above the first, it's centered in the room left below what comes before, and below the last, in a gap as wide as the sections leave between each other + const halfGap = (parseFloat(getComputedStyle(sections[0]).getPropertyValue("--section-gap")) || 0) / 2; let markerViewportY; if (index <= 0) { - markerViewportY = sections[0].getBoundingClientRect().top - 2; + markerViewportY = (bottomOfContentAbove(sections[0], container) + sections[0].getBoundingClientRect().top) / 2; } else if (index >= sections.length) { - markerViewportY = sections[sections.length - 1].getBoundingClientRect().bottom + 2; + markerViewportY = sections[sections.length - 1].getBoundingClientRect().bottom + halfGap; } else { markerViewportY = (sections[index - 1].getBoundingClientRect().bottom + sections[index].getBoundingClientRect().top) / 2; } + // Spanning the sections, which a layer's frame around them indents + const firstRect = sections[0].getBoundingClientRect(); + insertIndex = index; - insertMarkerTop = toContentOffset(markerViewportY); + insertMarker = { top: toContentOffset(markerViewportY), left: firstRect.left - containerRect.left, width: firstRect.width }; + } + + // The bottom of what's shown right above a section, which is the last row or section before it (even outside the frame it's in), or else the top of the panel + function bottomOfContentAbove(section: Element, container: HTMLElement): number { + let current = section; + while (current !== container && current.parentElement) { + let previous = current.previousElementSibling; + if (previous) { + // Down through the frames and section bodies to the last row or section within + while (previous.lastElementChild && previous.hasAttribute("data-section-contents")) previous = previous.lastElementChild; + return previous.getBoundingClientRect().bottom; + } + + current = current.parentElement; + } + return container.getBoundingClientRect().top; } function draggingPointerUp(e: PointerEvent) { @@ -160,15 +181,15 @@ dragging = false; fromIndex = undefined; insertIndex = undefined; - insertMarkerTop = undefined; + insertMarker = undefined; } - {#if dragging && insertMarkerTop !== undefined} -

+ {#if dragging && insertMarker} +
{/if} @@ -201,8 +222,6 @@ .insert-mark { position: absolute; - left: 4px; - right: 4px; background: var(--color-e-nearwhite); height: 5px; // The marker's `top` is the center of the gap, so shift up by half its height to straddle that line diff --git a/frontend/src/components/panels/Layers.svelte b/frontend/src/components/panels/Layers.svelte index 3cd6945754..43b60da6f6 100644 --- a/frontend/src/components/panels/Layers.svelte +++ b/frontend/src/components/panels/Layers.svelte @@ -1329,11 +1329,15 @@ background: rgb(from var(--color-4-dimgray) r g b / 0.5); } + // Spanning the insertion line beside the layer (past the visibility column and the indent), plus its own thickness outward so it clears the icons at both ends &.insert-folder::after { + --outline-thickness: 3px; content: ""; position: absolute; inset: 0; - border: 3px solid var(--color-e-nearwhite); + left: calc(24px + var(--layer-indent-levels) * 16px - var(--outline-thickness)); + right: calc(-1 * var(--outline-thickness)); + border: var(--outline-thickness) solid var(--color-e-nearwhite); border-radius: 2px; pointer-events: none; } @@ -1412,7 +1416,7 @@ } // The name (and lock) and the chain split the rest of the row evenly, except that either gives the other whatever share it doesn't need. - // Between them, the spacer keeps an unrelated-width gap. The right margin keeps the layer icon 4px from the row's end like the visibility icon at its start. + // Between them, the spacer keeps an unrelated-width gap. .layer-name-and-chain { flex: 1 1 0; min-width: 0; @@ -1420,7 +1424,6 @@ display: grid; grid-template-columns: minmax(0, max-content) auto minmax(4px, 1fr) minmax(0, var(--chain-width)); align-items: center; - margin-right: 2px; // While renaming, the name takes all the room its text needs, which the chain gives up until it disappears &.editing { @@ -1692,10 +1695,10 @@ margin: 0 8px; } - // At the row's end, past the layer icon's margin and the row's margin + // At the row's end, past a margin like the layer icon's .chain-node-icon { margin-left: auto; - margin-right: calc(2px + 2px); + margin-right: 2px; // Outlined like the layer icon when the active tool edits it &.tool-target, diff --git a/frontend/src/components/widgets/NodeSection.svelte b/frontend/src/components/widgets/NodeSection.svelte index 8dcefc8f5f..ea9442f641 100644 --- a/frontend/src/components/widgets/NodeSection.svelte +++ b/frontend/src/components/widgets/NodeSection.svelte @@ -16,8 +16,11 @@ export { className as class }; export let classes: Record = {}; + // A node without parameters has nothing to show, so its section stays collapsed with its arrow grayed out, like the Layers panel's + $: expandable = widgetData.layout.length > 0; + // Whether the section is expanded is owned by the backend (persisted per node), so just reflect it here - $: expanded = widgetData.expanded; + $: expanded = widgetData.expanded && expandable; // The sections of the chain feeding one of this node's inputs, which follow its own rows and are shown beneath them $: chainSections = widgetData.layout.flatMap((layoutGroup) => ("NodeSection" in layoutGroup && layoutGroup.NodeSection.outputWire ? [layoutGroup.NodeSection] : [])); @@ -30,6 +33,8 @@ // Like the Layers panel's expand arrows, a modifier key applies the toggle recursively to the sections nested within function toggleExpandedWithModifiers(e: MouseEvent) { + if (!expandable) return; + const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey; editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel); } @@ -45,42 +50,46 @@ "output-wire": Boolean(widgetData.outputWire), "output-wire-list": Boolean(widgetData.outputWire?.isList), "node-reference": widgetData.nodeReference, + "content-wire": Boolean(widgetData.contentWire), + "content-wire-list": Boolean(widgetData.contentWire?.isList), + "content-wire-continues": widgetData.contentWireContinues, collapsed: !expanded, }} styles={{ "--chain-wire-color": widgetData.chainWire && `var(--color-data-${widgetData.chainWire.dataType.toLowerCase()}-dim)`, "--output-wire-color": widgetData.outputWire && `var(--color-data-${widgetData.outputWire.dataType.toLowerCase()}-dim)`, + "--content-wire-color": widgetData.contentWire && `var(--color-data-${widgetData.contentWire.dataType.toLowerCase()}-dim)`, }} data-inspector-reorderable-section={reorderable ? "" : undefined} data-node-id={reorderable ? String(widgetData.id) : undefined} > {#if widgetData.nodeReference} + {#if widgetData.contentWireContinues} +
+ {/if} {#each widgetData.layout as layoutGroup} {#if "Row" in layoutGroup} {/if} {/each} {:else} -
+ {widgetData.name} + {#if reorderable} +
undefined} role="presentation">
+ {/if} {#if expanded} - + {#each widgetData.layout as layoutGroup} {#if "Row" in layoutGroup} @@ -124,7 +136,7 @@ {/each} {#if chainSections.length > 0} - + {#each chainSections as chainSection} {/each} @@ -136,11 +148,32 @@