diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index dd542fb41b..58729b7461 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -699,6 +699,7 @@ impl MessageHandler> for DocumentMes self.network_interface.cancel_drag(&self.selection_network_path); self.node_graph_handler.select_if_not_dragged = None; self.node_graph_handler.nodes_added_in_drag = false; + self.node_graph_handler.graph_ui.stop_animations(responses); responses.add(NodeGraphMessage::UpdateWireInsertionPreview); responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); } @@ -3118,6 +3119,7 @@ impl DocumentMessageHandler { } let Some(past) = self.history.interface_at(rev) else { return }; + self.node_graph_handler.graph_ui.stop_animations(responses); responses.add(EventMessage::ToolAbort); let replaced = self.install_history_snapshot(past, viewport); let current = self.history_preview.take().map_or(replaced, |preview| preview.current); @@ -3205,6 +3207,7 @@ impl DocumentMessageHandler { /// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`. fn follow_storage_changes(&mut self, name_before: Option, responses: &mut VecDeque) { + self.node_graph_handler.graph_ui.stop_animations(responses); if let Some(gdd) = self.history.storage_mut() { let changes = gdd.take_remote_changes(); self.pending_remote.extend(changes); diff --git a/editor/src/messages/portfolio/document/node_graph/graph_ui.rs b/editor/src/messages/portfolio/document/node_graph/graph_ui.rs index 41d3259c66..d7e46eec32 100644 --- a/editor/src/messages/portfolio/document/node_graph/graph_ui.rs +++ b/editor/src/messages/portfolio/document/node_graph/graph_ui.rs @@ -1,3 +1,4 @@ +mod animation; mod name_field; mod pointer; @@ -12,6 +13,7 @@ use crate::messages::prelude::{Message, PortfolioMessage, Responses}; use glam::DVec2; use graph_craft::document::NodeId; use graph_ui::GraphUiConfig; +use graph_ui::animation::{Glided, Glides}; use graph_ui::card::{Card, Connector, DataType, Selection}; use graph_ui::dot::Dot; use graph_ui::error_badge::ErrorBadge; @@ -88,9 +90,10 @@ impl<'a> GraphUiSceneBuilder<'a> { match part { GraphUiPart::All => { let dragging = self.network_interface.dragging(self.network_path); - replace_rows(self.cards(), dragging, &mut scene.settled.cards, &mut scene.moving.cards); - replace_rows(self.layers(), dragging, &mut scene.settled.layers, &mut scene.moving.layers); - replace_rows(self.dots(), dragging, &mut scene.settled.dots, &mut scene.moving.dots); + let glides = &self.node_graph_handler.graph_ui.glides; + replace_rows(self.cards(), dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards); + replace_rows(self.layers(), dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers); + replace_rows(self.dots(), dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots); place_wires(self.wires(), scene); scene.network_connectors.replace_all(self.network_connectors()); scene.errors.replace_all(self.errors()); @@ -280,12 +283,13 @@ impl<'a> GraphUiSceneBuilder<'a> { fn place_node_rows(&self, nodes: impl IntoIterator, scene: &mut GraphUiSceneEdit) { let (network_interface, network_path) = (self.network_interface, self.network_path); let dragging = network_interface.dragging(network_path); + let glides = &self.node_graph_handler.graph_ui.glides; for node in nodes { let Some(NodeGeometry { cell, chain_length, .. }) = self.geometry(node) else { continue }; - let placed = replace_row(node, dragging, &mut scene.settled.cards, &mut scene.moving.cards, |card| { + let placed = replace_row(node, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards, |card| { (card.cell != cell).then(|| Placed { cell, look: card.look.clone() }) - }) || replace_row(node, dragging, &mut scene.settled.layers, &mut scene.moving.layers, |layer| { + }) || replace_row(node, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers, |layer| { let has_left_input_wire = network_interface.has_left_input_wire(&node, network_path); let changed = (layer.cell, layer.look.chain_length, layer.look.has_left_input_wire) != (cell, chain_length, has_left_input_wire); let look = || Layer { @@ -294,7 +298,7 @@ impl<'a> GraphUiSceneBuilder<'a> { ..layer.look.clone() }; changed.then(|| Placed { cell, look: look() }) - }) || replace_row(node, dragging, &mut scene.settled.dots, &mut scene.moving.dots, |dot| { + }) || replace_row(node, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots, |dot| { (dot.cell != cell).then(|| Placed { cell, look: dot.look.clone() }) }); if !placed { @@ -304,14 +308,15 @@ impl<'a> GraphUiSceneBuilder<'a> { } fn put_node_rows(&self, node: NodeId, dragging: bool, scene: &mut GraphUiSceneEdit) { + let glides = &self.node_graph_handler.graph_ui.glides; if let Some(card) = self.card(node) { - place_row(card, dragging, &mut scene.settled.cards, &mut scene.moving.cards); + place_row(card, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards); } if let Some(layer) = self.layer(node) { - place_row(layer, dragging, &mut scene.settled.layers, &mut scene.moving.layers); + place_row(layer, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers); } if let Some(dot) = self.dot(node) { - place_row(dot, dragging, &mut scene.settled.dots, &mut scene.moving.dots); + place_row(dot, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots); } } @@ -357,19 +362,19 @@ impl<'a> GraphUiSceneBuilder<'a> { } } -fn stays + PartialEq>(row: &T, dragging: bool, settled: &ReplicatedMap) -> bool { - !dragging || settled.get(&row.key()) == Some(row) +fn stays + PartialEq>(row: &T, dragging: bool, glides: &Glides, settled: &ReplicatedMap) -> bool { + !glides.rows.contains_key(&Glided::Node(row.key())) && (!dragging || settled.get(&row.key()) == Some(row)) } -fn replace_rows + PartialEq>(rows: Vec, dragging: bool, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit) { - let (still, moved): (Vec, Vec) = rows.into_iter().partition(|row| stays(row, dragging, settled)); +fn replace_rows + PartialEq>(rows: Vec, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit) { + let (still, moved): (Vec, Vec) = rows.into_iter().partition(|row| stays(row, dragging, glides, settled)); settled.replace_all(still); moving.replace_all(moved); } -fn place_row + PartialEq>(row: T, dragging: bool, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit) { +fn place_row + PartialEq>(row: T, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit) { let key = row.key(); - if stays(&row, dragging, settled) { + if stays(&row, dragging, glides, settled) { moving.remove(&key); settled.put(row); } else { @@ -381,13 +386,14 @@ fn place_row + PartialEq>(row: T, dragging: bool, settled fn replace_row + PartialEq>( node: NodeId, dragging: bool, + glides: &Glides, settled: &mut ReplicatedMapEdit, moving: &mut ReplicatedMapEdit, replaced: impl FnOnce(&T) -> Option, ) -> bool { let Some(row) = moving.get(&node).or_else(|| settled.get(&node)) else { return false }; if let Some(row) = replaced(row) { - place_row(row, dragging, settled, moving); + place_row(row, dragging, glides, settled, moving); } true } @@ -410,6 +416,9 @@ fn place_wires(wires: Vec, scene: &mut GraphUiSceneEdit) { #[derive(Clone, Debug, Default)] pub struct GraphUiState { highlights: Highlights, + glides: Glides, + animating: bool, + pub(super) time: f64, tooltip: Option<(Option, String, String)>, editing_name: Option, name_field: Option<(GraphName, GraphNameField)>, @@ -418,10 +427,12 @@ pub struct GraphUiState { impl GraphUiState { pub fn change_highlights(&mut self, change: impl FnOnce(&mut Highlights), responses: &mut VecDeque) { - let mut highlights = self.highlights; + let mut highlights = self.highlights.clone(); change(&mut highlights); if self.highlights != highlights { + self.start_grows(&mut highlights); self.highlights = highlights; + self.follow_animations(responses); responses.add(PortfolioMessage::SubmitActiveGraphRender); } } @@ -441,8 +452,9 @@ pub fn config(document: &DocumentMessageHandler, wire_style: WireStyle) -> Optio .box_selection .filter(|(_, dragged)| *dragged) .map(|(corners, _)| corners.map(|corner| view.transform_point2(corner).max(DVec2::ZERO).floor())), - highlights: node_graph_handler.graph_ui.highlights, + highlights: node_graph_handler.graph_ui.highlights.clone(), wire_style, + glides: node_graph_handler.graph_ui.glides.clone(), } }) } diff --git a/editor/src/messages/portfolio/document/node_graph/graph_ui/animation.rs b/editor/src/messages/portfolio/document/node_graph/graph_ui/animation.rs new file mode 100644 index 0000000000..2c259d8d1c --- /dev/null +++ b/editor/src/messages/portfolio/document/node_graph/graph_ui/animation.rs @@ -0,0 +1,88 @@ +use super::*; +use crate::messages::prelude::{BroadcastMessage, EventMessage, NodeGraphMessage}; +use graph_ui::animation::{Animation, GROW_DURATION, Glided}; +use graph_ui::highlights::ConnectorKey; + +impl GraphUiState { + pub fn glide(&mut self, moves: impl IntoIterator, responses: &mut VecDeque) { + for (row, moved) in moves { + let from = moved + self.glides.offset(row, self.time); + match Animation::glide(from, self.time) { + Some(glide) => self.glides.rows.insert(row, glide), + None => self.glides.rows.remove(&row), + }; + } + self.follow_animations(responses); + } + + pub fn stop_animations(&mut self, responses: &mut VecDeque) { + if !self.glides.rows.is_empty() { + self.glides.rows.clear(); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); + } + if !self.highlights.grows.is_empty() { + self.highlights.grows.clear(); + responses.add(PortfolioMessage::SubmitActiveGraphRender); + } + self.follow_animations(responses); + } + + pub fn animation_tick(&mut self, graph_open: bool, responses: &mut VecDeque) { + if !self.animating { + responses.add(animation_frames(false)); + return; + } + if !graph_open { + self.stop_animations(responses); + return; + } + + let time = self.time; + self.highlights.grows.retain(|_, grow| !ended(grow, time)); + if !self.glides.rows.is_empty() && self.glides.rows.values().all(|glide| ended(glide, time)) { + self.glides.rows.clear(); + responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); + } + self.follow_animations(responses); + responses.add(PortfolioMessage::SubmitActiveGraphRender); + } + + pub(super) fn start_grows(&self, highlights: &mut Highlights) { + let keys: BTreeSet = self.highlights.connectors().chain(highlights.connectors()).collect(); + for key in keys { + let grows = highlights.connector(key).is_grown(); + if self.highlights.connector(key).is_grown() == grows { + continue; + } + let (from, to) = (self.highlights.grown(key, self.time), if grows { 1. } else { 0. }); + let grow = Animation { + from, + to, + start: self.time, + end: self.time + GROW_DURATION * (to - from).abs(), + }; + highlights.grows.insert(key, grow); + } + } + + pub(super) fn follow_animations(&mut self, responses: &mut VecDeque) { + let animating = !self.glides.rows.is_empty() || !self.highlights.grows.is_empty(); + if self.animating == animating { + return; + } + self.animating = animating; + responses.add(animation_frames(animating)); + } +} + +fn animation_frames(subscribed: bool) -> BroadcastMessage { + let (on, send) = (EventMessage::AnimationFrame, Box::new(NodeGraphMessage::AnimationTick.into())); + match subscribed { + true => BroadcastMessage::SubscribeEvent { on, send }, + false => BroadcastMessage::UnsubscribeEvent { on, send }, + } +} + +fn ended(animation: &Animation, time: f64) -> bool { + time >= animation.end || time < animation.start +} 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 73bad156e0..e00d1934f7 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 @@ -175,6 +175,7 @@ pub enum NodeGraphMessage { MiddleClick, /// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes. WireHoverTick, + AnimationTick, ShakeNode, UpdateNodeGraphWidth, RemoveImport { @@ -430,6 +431,7 @@ impl NodeGraphMessage { | Self::PointerOutsideViewport { .. } | Self::MiddleClick | Self::WireHoverTick + | Self::AnimationTick | Self::UpdateNodeGraphWidth | Self::RunDocumentGraph | Self::ForceRunDocumentGraph 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 c0ad82aa3c..5257d31f4d 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 @@ -24,6 +24,7 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion}; use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo}; use crate::messages::viewport::Position; +use ::graph_ui::animation::Glided; use ::graph_ui::geometry::WireEnd; use ::graph_ui::highlights::NodePart; use ::graph_ui::metrics::{INPUT_CONNECTOR_LEFT, OUTPUT_CONNECTOR_RIGHT}; @@ -159,6 +160,7 @@ impl<'a> MessageHandler> for NodeG } = context; self.in_read_only_network = network_interface.is_read_only(selection_network_path); + self.graph_ui.time = ipp.time as f64; if message .edited_network(selection_network_path, breadcrumb_network_path) .is_some_and(|edited_network| network_interface.is_read_only(edited_network)) @@ -1809,6 +1811,7 @@ impl<'a> MessageHandler> for NodeG NodeGraphMessage::WireHoverTick => { self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses); } + NodeGraphMessage::AnimationTick => self.graph_ui.animation_tick(graph_view_overlay_open, responses), NodeGraphMessage::ShakeNode => { let Some((drag_start, _)) = &mut self.drag_start else { log::error!("Drag start should be initialized when shaking a node"); @@ -2139,7 +2142,15 @@ impl<'a> MessageHandler> for NodeG responses.add(DocumentMessage::EndTransaction); } NodeGraphMessage::ShiftSelectedNodes { direction } => { - responses.add(NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta: direction.offset() }); + let positions_before = graph_view_overlay_open.then(|| Self::glide_positions(network_interface, selection_network_path)); + network_interface.shift_selected_nodes(direction.offset(), self.keep_upstream_in_place, selection_network_path); + + if let Some(positions_before) = positions_before { + self.begin_glide(positions_before, network_interface, selection_network_path, responses); + responses.add(NodeGraphMessage::SendGraph); + responses.add(DocumentMessage::RenderRulers); + responses.add(DocumentMessage::RenderScrollbars); + } } NodeGraphMessage::ShiftSelectedNodesByAmount { graph_delta } => { network_interface.shift_selected_nodes(graph_delta, self.keep_upstream_in_place, selection_network_path); @@ -2156,15 +2167,11 @@ impl<'a> MessageHandler> for NodeG return; } - let positions_before = graph_view_overlay_open.then(|| Self::node_positions(network_interface, selection_network_path)); + let positions_before = graph_view_overlay_open.then(|| Self::glide_positions(network_interface, selection_network_path)); network_interface.drag_selected_nodes(offset, keep_upstream, selection_network_path); if let Some(positions_before) = positions_before { - let moved = Self::node_positions(network_interface, selection_network_path) - .into_iter() - .filter(|(node_id, position)| positions_before.get(node_id).is_some_and(|before| before != position)) - .map(|(node_id, _)| node_id) - .collect(); + let moved = self.begin_glide(positions_before, network_interface, selection_network_path, responses); responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::Moved { nodes: moved }, }); @@ -2747,6 +2754,7 @@ impl NodeGraphMessageHandler { self.select_if_not_dragged = None; self.nodes_added_in_drag = false; self.clear_wire_insertion_preview(responses); + self.graph_ui.stop_animations(responses); responses.add(DocumentMessage::AbortTransaction); responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All }); true @@ -2793,6 +2801,7 @@ impl NodeGraphMessageHandler { } self.abort_node_drag(network_interface, network_path, responses); self.clear_wire_insertion_preview(responses); + self.graph_ui.stop_animations(responses); if self.context_menu.take().is_some() { responses.add(FrontendMessage::UpdateContextMenuInformation { context_menu_information: None }); } @@ -2980,6 +2989,32 @@ impl NodeGraphMessageHandler { network_interface.positions(node_ids, network_path).into_iter().collect() } + fn glide_positions(network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (HashMap, Option<(IVec2, IVec2)>) { + (Self::node_positions(network_interface, network_path), network_interface.import_export_position(network_path)) + } + + fn begin_glide( + &mut self, + (nodes_before, edges_before): (HashMap, Option<(IVec2, IVec2)>), + network_interface: &NodeNetworkInterface, + network_path: &[NodeId], + responses: &mut VecDeque, + ) -> Vec { + let (nodes, edges) = Self::glide_positions(network_interface, network_path); + let moved: Vec<(NodeId, IVec2)> = nodes + .into_iter() + .filter_map(|(node_id, position)| Some((node_id, *nodes_before.get(&node_id).filter(|before| **before != position)? - position))) + .collect(); + let nodes = moved.iter().map(|(node_id, cells)| (Glided::Node(*node_id), cells.as_dvec2() * GRID_SIZE as f64)); + let edges = edges_before + .zip(edges) + .into_iter() + .flat_map(|((imports_before, exports_before), (imports, exports))| [(Glided::Imports, imports_before - imports), (Glided::Exports, exports_before - exports)]); + let edges = edges.filter(|(_, moved)| *moved != IVec2::ZERO).map(|(row, moved)| (row, moved.as_dvec2())); + self.graph_ui.glide(nodes.chain(edges), responses); + moved.into_iter().map(|(node_id, _)| node_id).collect() + } + fn set_wire_hover_tick_subscribed(&mut self, subscribed: bool, responses: &mut VecDeque) { if self.wire_hover_tick_subscribed == subscribed { return; diff --git a/editor/src/messages/portfolio/portfolio_message_handler.rs b/editor/src/messages/portfolio/portfolio_message_handler.rs index efcd0713a4..5ca74146e2 100644 --- a/editor/src/messages/portfolio/portfolio_message_handler.rs +++ b/editor/src/messages/portfolio/portfolio_message_handler.rs @@ -899,6 +899,7 @@ impl MessageHandler> for Portfolio if self.active_document_id != Some(document_id) && let Some(document) = self.active_document_mut() { + document.node_graph_handler.graph_ui.stop_animations(responses); let wire_ended = document.end_node_graph_wire_in_progress(responses); if wire_ended { responses.add(DocumentMessage::AbortTransaction); diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 3bb083b805..fcbbae0987 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -34,7 +34,7 @@ mod recompile_tests; mod runtime; pub use runtime::*; -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] pub struct ExecutionRequest { execution_id: u64, render_config: RenderConfig, diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 8435fa808c..393b95ddbf 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -297,7 +297,7 @@ impl NodeRuntime { } } - let viewport = if dirty { self.pending } else { None }; + let viewport = if dirty { self.pending.clone() } else { None }; if let Some(document_id) = self.pending_thumbnails.take() && viewport.is_none() @@ -324,7 +324,7 @@ impl NodeRuntime { self.run_viewport(viewport).await; } - if let Some(request) = self.pending { + if let Some(request) = self.pending.clone() { self.draw_overlays(&request); self.draw_graph_ui(&request); } @@ -339,7 +339,7 @@ impl NodeRuntime { self.thumbnails.set_scale(request.render_config.scale); let result = match self.output.clone() { - Some(output) => self.evaluate(&output, request), + Some(output) => self.evaluate(&output, request.clone()), None => Some(ExecutionResult::Uncompiled), }; let Some(mut result) = result else { return }; @@ -390,7 +390,7 @@ impl NodeRuntime { } self.graph_ui_redrawn = true; - let Some(mut config) = request.graph_ui_config else { + let Some(mut config) = request.graph_ui_config.clone() else { self.graph_ui_texture = None; self.graph_ui_network_hash = None; self.graph_ui_output = OutputHandle::default(); @@ -414,7 +414,7 @@ impl NodeRuntime { self.async_runtime().update_sources(self.executor.sources()); } - let context = graph_ui::render_config(config.view, request.render_config).into_context(); + let context = graph_ui::render_config(&config, request.render_config).into_context(); self.graph_ui_texture = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.graph_ui_output, context))) { Ok(Ok(Poll::Final(TaggedValue::RenderOutput(RenderOutput { data: RenderOutputType::Texture(frame), @@ -501,7 +501,7 @@ impl NodeRuntime { async fn run_eyedropper(&mut self, mut request: ExecutionRequest) { // Eyedropper should use the same time and pointer to not invalidate the cache - if let Some(viewport) = self.pending { + if let Some(viewport) = &self.pending { request.render_config.time = viewport.render_config.time; request.render_config.pointer = viewport.render_config.pointer; } diff --git a/node-graph/graph-ui/src/lib.rs b/node-graph/graph-ui/src/lib.rs index e96fe0699b..1e20d72d53 100644 --- a/node-graph/graph-ui/src/lib.rs +++ b/node-graph/graph-ui/src/lib.rs @@ -1,5 +1,5 @@ use graph_ui_types::inputs; -pub use graph_ui_types::{GraphUiConfig, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire}; +pub use graph_ui_types::{GraphUiConfig, animation, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire}; pub use network::{network, render_config}; pub use text::{error_text_size, label_width}; diff --git a/node-graph/graph-ui/src/look.rs b/node-graph/graph-ui/src/look.rs index 21d9e46d6b..64048d6f85 100644 --- a/node-graph/graph-ui/src/look.rs +++ b/node-graph/graph-ui/src/look.rs @@ -77,25 +77,38 @@ pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] { }) } -pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight) -> List { - drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight) +pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight, grown: f64) -> List { + drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight, grown) } -pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List { +pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight, grown: f64) -> List { let [bright, dim] = data_type_colors(data_type); - match highlight { - Highlight::None => List::new_from_item(outlined(outline, top_left, if connected { bright } else { dim })), - Highlight::WireSource => List::new_from_item(outlined(outline, top_left, bright)), - Highlight::Hovered | Highlight::WireTarget => { - let grown = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(HOVERED_CONNECTOR_SCALE, outline.bounding_box().center()) * outline.clone(); - let grown = Vector::item_from_bezpath(&grown); - let ring = Stroke { - join: StrokeJoin::Round, - ..Stroke::new(HOVERED_CONNECTOR_RING * HOVERED_CONNECTOR_SCALE) - }; - List::from_iter([painted(grown.clone(), Coverage::new_stroke(&ring), dim.into()), painted(grown, Coverage::new_fill(), bright.into())]) - } + let resting = if connected || highlight == Highlight::WireSource { bright } else { dim }; + let ringed = highlight.is_grown(); + if grown == 0. && !ringed { + return List::new_from_item(outlined(outline, top_left, resting)); } + + let scale = 1. + (HOVERED_CONNECTOR_SCALE - 1.) * grown; + let grown_outline = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(scale, outline.bounding_box().center()) * outline.clone(); + let grown_outline = Vector::item_from_bezpath(&grown_outline); + let mut graphic = List::new(); + if ringed { + let ring = Stroke { + join: StrokeJoin::Round, + ..Stroke::new(HOVERED_CONNECTOR_RING * scale) + }; + graphic.push(painted(grown_outline.clone(), Coverage::new_stroke(&ring), dim.into())); + } + let channel = |from: u8, to: u8| (from as f64 + (to as f64 - from as f64) * grown).round() as u8; + let fill = SRGBA8::new( + channel(resting.red, bright.red), + channel(resting.green, bright.green), + channel(resting.blue, bright.blue), + channel(resting.alpha, bright.alpha), + ); + graphic.push(painted(grown_outline, Coverage::new_fill(), fill.into())); + graphic } pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item { diff --git a/node-graph/graph-ui/src/network.rs b/node-graph/graph-ui/src/network.rs index 45e5939bee..9cb19cf23e 100644 --- a/node-graph/graph-ui/src/network.rs +++ b/node-graph/graph-ui/src/network.rs @@ -1,8 +1,8 @@ use crate::GraphUiConfig; use crate::inputs::{self, TaggedGraphUiValue, Thumbnails}; use crate::nodes::{ - draw_backdrop, draw_box_selection, draw_cards, draw_dots, draw_errors, draw_grid, draw_highlights, draw_layers, draw_loose_wires, draw_moving, draw_network_connectors, draw_raised, - draw_reorder_bar, draw_thick_wires, draw_thumbnails, draw_wires, texture_layer, + draw_backdrop, draw_box_selection, draw_cards, draw_dots, draw_errors, draw_gliding_wires, draw_grid, draw_grows, draw_highlights, draw_layers, draw_loose_wires, draw_moving, + draw_network_connectors, draw_raised, draw_reorder_bar, draw_thick_wires, draw_thumbnails, draw_wires, glide, texture_layer, }; use crate::scene::GraphUiScene; use core_types::registry::{FieldMetadata, NODE_METADATA, RegistryValueSource}; @@ -33,7 +33,8 @@ pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbn (inputs::BOX_SELECTION, TaggedGraphUiValue::BoxSelection(config.box_selection)), (inputs::FADE_ARTWORK, TaggedGraphUiValue::FadeArtwork(config.fade_artwork)), (inputs::WIRE_STYLE, TaggedGraphUiValue::WireStyle(config.wire_style)), - (inputs::HIGHLIGHTS, TaggedGraphUiValue::Highlights(config.highlights)), + (inputs::HIGHLIGHTS, TaggedGraphUiValue::Highlights(config.highlights.clone())), + (inputs::GLIDES, TaggedGraphUiValue::Glides(config.glides.clone())), ]; let mut network = NodeNetwork::default(); @@ -43,21 +44,43 @@ pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbn network.scope_injections.insert(scope.as_str().to_string(), (id, ty)); } - let [backdrop, above @ ..] = [ - drawn(&mut network, draw_backdrop::IDENTIFIER), - drawn(&mut network, draw_grid::IDENTIFIER), - tiled(&mut network, draw_thick_wires::IDENTIFIER, [draw_layers::IDENTIFIER]), - drawn(&mut network, draw_thumbnails::IDENTIFIER), - drawn(&mut network, draw_loose_wires::IDENTIFIER), - tiled(&mut network, draw_wires::IDENTIFIER, [draw_cards::IDENTIFIER, draw_dots::IDENTIFIER, draw_raised::IDENTIFIER]), - drawn(&mut network, draw_moving::IDENTIFIER), - drawn(&mut network, draw_errors::IDENTIFIER), - drawn(&mut network, draw_network_connectors::IDENTIFIER), - drawn(&mut network, draw_highlights::IDENTIFIER), - drawn(&mut network, draw_reorder_bar::IDENTIFIER), - drawn(&mut network, draw_box_selection::IDENTIFIER), + let [backdrop, grid] = [draw_backdrop::IDENTIFIER, draw_grid::IDENTIFIER].map(|identifier| drawn(&mut network, identifier)); + let layers = tiled(&mut network, draw_thick_wires::IDENTIFIER, [draw_layers::IDENTIFIER]); + let [thumbnails, loose_wires] = [draw_thumbnails::IDENTIFIER, draw_loose_wires::IDENTIFIER].map(|identifier| drawn(&mut network, identifier)); + let nodes = tiled(&mut network, draw_wires::IDENTIFIER, [draw_cards::IDENTIFIER, draw_dots::IDENTIFIER, draw_raised::IDENTIFIER]); + let above_nodes = [ + draw_moving::IDENTIFIER, + draw_errors::IDENTIFIER, + draw_network_connectors::IDENTIFIER, + draw_highlights::IDENTIFIER, + draw_reorder_bar::IDENTIFIER, + draw_box_selection::IDENTIFIER, ]; - let stack = stacked(&mut network, backdrop, above); + let [moving, errors, network_connectors, highlights, reorder_bar, box_selection] = above_nodes.map(|identifier| drawn(&mut network, identifier)); + + let gliding = !config.glides.rows.is_empty(); + let gliding_wires = gliding.then(|| drawn(&mut network, draw_gliding_wires::IDENTIFIER)); + let grows = (!config.highlights.grows.is_empty()).then(|| drawn(&mut network, draw_grows::IDENTIFIER)); + let mut glided = |drawing| match gliding { + true => add(&mut network, node(glide::IDENTIFIER, vec![NodeInput::node(drawing, 0), NodeInput::scope(inputs::GLIDES)])), + false => drawing, + }; + let above = [ + Some(grid), + Some(layers), + Some(thumbnails), + Some(loose_wires), + gliding_wires, + Some(nodes), + Some(glided(moving)), + Some(glided(errors)), + Some(glided(network_connectors)), + grows.map(&mut glided), + Some(glided(highlights)), + Some(reorder_bar), + Some(box_selection), + ]; + let stack = stacked(&mut network, backdrop, above.into_iter().flatten()); let frame = rendered(&mut network, stack); // INDEX is never read; it forces a nullification and cache pair onto the render's wire, so its memo keys on the footprint and the render params only let compile_metadata = Some(NodeCompileMetadata { @@ -74,7 +97,8 @@ pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbn network } -pub fn render_config(view: DAffine2, request: RenderConfig) -> RenderConfig { +pub fn render_config(config: &GraphUiConfig, request: RenderConfig) -> RenderConfig { + let view = config.view; let translation = (view.translation * request.scale).round() / request.scale; let viewport = Footprint { transform: DAffine2 { translation, ..view }, diff --git a/node-graph/graph-ui/src/nodes.rs b/node-graph/graph-ui/src/nodes.rs index b1dd8f5c45..bb42975506 100644 --- a/node-graph/graph-ui/src/nodes.rs +++ b/node-graph/graph-ui/src/nodes.rs @@ -1,3 +1,4 @@ +use crate::animation::{Glided, Glides}; use crate::card::{Card, Connector, DataType, Selection}; use crate::dashes::{border, dashed}; use crate::dot::Dot; @@ -26,9 +27,10 @@ use crate::scene::Rows; use crate::text::{Labels, error_text_size, paragraph_outline}; use crate::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle}; use core_types::color::SRGBA8; -use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, Item, List}; +use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_TRANSFORM, Item, List}; use core_types::transform::ApplyTransform; -use core_types::{Color, Ctx, ExtractFootprint, ExtractVarArgs, Poll}; +use core_types::uuid::NodeId; +use core_types::{Color, Ctx, ExtractFootprint, ExtractRealTime, ExtractVarArgs, Poll}; use glam::{DAffine2, DVec2}; use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graphic_types::raster_types::Raster; @@ -42,6 +44,7 @@ use vello_gpu::kurbo::{BezPath, Circle, Rect, Shape, flatten}; const GRID_DOT_ROUNDING_BIAS: f64 = 1. / 64.; const WIRE_FLATTENING_TOLERANCE: f64 = 0.02; +const ATTR_GLIDED: &str = "glided"; #[node_macro::node(transient)] fn draw_backdrop(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::FADE_ARTWORK)] fade_artwork: Item) -> List { @@ -125,14 +128,18 @@ fn disc_columns(radius: u32) -> BTreeMap<[u32; 2], Vec<[u32; 2]>> { #[node_macro::node(transient, memoize)] fn draw_layers(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> Result, TextToVectorError> { - layers(rows.element()) + joined(layers(rows.element())) } -fn layers(rows: &Rows) -> Result, TextToVectorError> { +fn layers(rows: &Rows) -> impl Iterator), TextToVectorError>> { let mut labels = Labels::default(); + rows.layers.iter().map(move |layer| Ok((layer.look.key, draw_layer(layer, &mut labels)?))) +} + +fn joined(rows: impl Iterator), TextToVectorError>>) -> Result, TextToVectorError> { let mut graphic = List::new(); - for layer in &rows.layers { - graphic.extend(draw_layer(layer, &mut labels)?); + for row in rows { + graphic.extend(row?.1); } Ok(graphic) } @@ -163,10 +170,10 @@ fn draw_layer(layer: &Placed, labels: &mut Labels) -> Result graphic.extend(checkerboard(image_min, image_max)); if let Some(output) = &layer.look.primary_output { - graphic.extend(stack_output(layer, output, Highlight::None)); + graphic.extend(stack_output(layer, output, Highlight::None, 0.)); } match &layer.look.primary_input { - Some(input) => graphic.extend(stack_input(layer, input, Highlight::None)), + Some(input) => graphic.extend(stack_input(layer, input, Highlight::None, 0.)), None => graphic.push(outlined(&STACK_INPUT_OUTLINE, layer.stack_input(), data_type_colors(DataType::General)[1])), } @@ -179,16 +186,16 @@ fn draw_layer(layer: &Placed, labels: &mut Labels) -> Result Ok(graphic) } -fn stack_output(layer: &Placed, output: &Connector, highlight: Highlight) -> List { - let mut graphic = connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output, highlight); +fn stack_output(layer: &Placed, output: &Connector, highlight: Highlight, grown: f64) -> List { + let mut graphic = connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output, highlight, grown); if output.connected && layer.look.primary_output_connected_to_layer && highlight != Highlight::WireSource { graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1])); } graphic } -fn stack_input(layer: &Placed, input: &Connector, highlight: Highlight) -> List { - let mut graphic = connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input, highlight); +fn stack_input(layer: &Placed, input: &Connector, highlight: Highlight, grown: f64) -> List { + let mut graphic = connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input, highlight, grown); if input.connected && layer.look.primary_input_connected_to_layer && highlight != Highlight::WireSource { graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1])); } @@ -197,17 +204,15 @@ fn stack_input(layer: &Placed, input: &Connector, highlight: Highlight) - #[node_macro::node(transient)] fn draw_thumbnails(_: impl Ctx, #[scope(inputs::THUMBNAILS)] thumbnails: Item, #[scope(inputs::SETTLED)] rows: Item) -> List { - layer_thumbnails(thumbnails.element(), rows.element()) + layer_thumbnails(thumbnails.element(), rows.element()).map(|(_, thumbnail)| thumbnail).collect() } -fn layer_thumbnails(thumbnails: &Thumbnails, rows: &Rows) -> List { +fn layer_thumbnails<'a>(thumbnails: &'a Thumbnails, rows: &'a Rows) -> impl Iterator)> + 'a { let thumbnails = thumbnails.iter().filter_map(|(key, thumbnail)| Some((rows.layers.get(key)?, thumbnail))); - thumbnails - .map(|(layer, thumbnail)| { - let [min, max] = layer.thumbnail_image(); - image(thumbnail.clone(), DAffine2::from_scale_angle_translation(max - min, 0., min)) - }) - .collect() + thumbnails.map(|(layer, thumbnail)| { + let [min, max] = layer.thumbnail_image(); + (layer.look.key, image(thumbnail.clone(), DAffine2::from_scale_angle_translation(max - min, 0., min))) + }) } #[node_macro::node(transient)] @@ -223,18 +228,18 @@ fn texture_layer(ctx: impl Ctx + ExtractFootprint, rendered: Item) #[node_macro::node(transient, memoize)] fn draw_raised(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> List { - raised(rows.element()) + raised(rows.element()).flat_map(|(_, graphic)| graphic).collect() } -fn raised(rows: &Rows) -> List { - let raised_parts_of_layers = rows.layers.iter().flat_map(draw_raised_parts_of_layer); - raised_parts_of_layers.chain(rows.cards.iter().flat_map(draw_connectors_of_card)).collect() +fn raised(rows: &Rows) -> impl Iterator)> { + let raised_parts_of_layers = rows.layers.iter().map(|layer| (layer.look.key, draw_raised_parts_of_layer(layer))); + raised_parts_of_layers.chain(rows.cards.iter().map(|card| (card.look.key, draw_connectors_of_card(card)))) } fn draw_raised_parts_of_layer(layer: &Placed) -> List { let mut graphic = List::new(); if let Some(input) = &layer.look.secondary_input { - graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, Highlight::None)); + graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, Highlight::None, 0.)); } graphic.extend(grip(layer, false)); for (_, place, icons) in layer_buttons(layer) { @@ -279,7 +284,7 @@ fn layer_button(layer: &Placed, [min, max]: [DVec2; 2], [resting, hover]: fn draw_connectors_of_card(card: &Placed) -> List { card.inputs() .chain(card.outputs()) - .flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output, Highlight::None)) + .flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output, Highlight::None, 0.)) .collect() } @@ -308,15 +313,40 @@ fn draw_loose_wires( #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>, #[scope(inputs::WIRE_IN_PROGRESS)] wire_in_progress: Item>, #[scope(inputs::WIRE_STYLE)] wire_style: Item, + #[scope(inputs::GLIDES)] glides: Item, ) -> List { - let wire_style = wire_style.into_element(); + let (wire_style, glides) = (wire_style.into_element(), glides.element()); let rows = [moving.element(), settled.element()]; - let loose = wires_with_ends(&moving.element().wires, &rows, network_connectors.element()); + let loose = wires_with_ends(&moving.element().wires, &rows, network_connectors.element()).filter(|(wire, _)| !glides_an_end(wire, glides)); let mut graphic = wire_in_progress.into_element().map_or_else(List::new, draw_wire_in_progress); graphic.extend(loose.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect()); graphic } +#[node_macro::node(transient, memoize)] +fn draw_gliding_wires( + ctx: impl Ctx + ExtractRealTime, + #[scope(inputs::MOVING)] moving: Item, + #[scope(inputs::SETTLED)] settled: Item, + #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>, + #[scope(inputs::WIRE_STYLE)] wire_style: Item, + #[scope(inputs::GLIDES)] glides: Item, +) -> List { + let (wire_style, glides, time) = (wire_style.into_element(), glides.element(), ctx.try_real_time().unwrap_or_default()); + let rows = [moving.element(), settled.element()]; + let gliding = wires_with_ends(&moving.element().wires, &rows, network_connectors.element()).filter(|(wire, _)| glides_an_end(wire, glides)); + let glided = gliding.flat_map(|(wire, [mut from, mut to])| { + from.position += glides.offset(wire.from, time); + to.position += glides.offset(wire.to, time); + draw_wire(wire, [from, to], wire_style) + }); + glided.collect() +} + +fn glides_an_end(wire: &Wire, glides: &Glides) -> bool { + [Glided::from(wire.from), Glided::from(wire.to)].iter().any(|end| glides.rows.contains_key(end)) +} + fn wires_with_ends<'a>(wires: &'a ReplicatedMap, rows: &'a [&'a Rows], network_connectors: &'a ReplicatedMap) -> impl Iterator { wires.iter().filter_map(move |wire| Some((wire, wire_ends(wire, rows, network_connectors)?))) } @@ -356,16 +386,12 @@ fn flattened(path: &BezPath) -> BezPath { #[node_macro::node(transient, memoize)] fn draw_cards(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> Result, TextToVectorError> { - cards(rows.element()) + joined(cards(rows.element())) } -fn cards(rows: &Rows) -> Result, TextToVectorError> { +fn cards(rows: &Rows) -> impl Iterator), TextToVectorError>> { let mut labels = Labels::default(); - let mut graphic = List::new(); - for card in &rows.cards { - graphic.extend(draw_card(card, &mut labels)?); - } - Ok(graphic) + rows.cards.iter().map(move |card| Ok((card.look.key, draw_card(card, &mut labels)?))) } fn draw_card(card: &Placed, labels: &mut Labels) -> Result, TextToVectorError> { @@ -414,28 +440,60 @@ fn draw_card(card: &Placed, labels: &mut Labels) -> Result, T #[node_macro::node(transient, memoize)] fn draw_dots(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> List { - dots(rows.element()) + dots(rows.element()).flat_map(|(_, graphic)| graphic).collect() } -fn dots(rows: &Rows) -> List { - rows.dots.iter().flat_map(|dot| draw_dot(dot, [Highlight::None; 2])).collect() +fn dots(rows: &Rows) -> impl Iterator)> { + rows.dots.iter().map(|dot| (dot.look.key, draw_dot(dot, [Highlight::None; 2]))) } #[node_macro::node(transient, memoize)] fn draw_moving(_: impl Ctx, #[scope(inputs::MOVING)] moving: Item, #[scope(inputs::THUMBNAILS)] thumbnails: Item) -> Result, TextToVectorError> { let moving = moving.element(); - let mut graphic = layers(moving)?; - graphic.extend(layer_thumbnails(thumbnails.element(), moving)); - graphic.extend(cards(moving)?); - graphic.extend(dots(moving)); - graphic.extend(raised(moving)); + let keyed = |(key, graphic): (NodeId, List)| tagged(graphic, key); + let mut graphic = List::new(); + for row in layers(moving) { + graphic.extend(keyed(row?)); + } + for (key, thumbnail) in layer_thumbnails(thumbnails.element(), moving) { + graphic.extend(keyed((key, List::new_from_item(thumbnail)))); + } + for row in cards(moving) { + graphic.extend(keyed(row?)); + } + for row in dots(moving) { + graphic.extend(keyed(row)); + } + for row in raised(moving) { + graphic.extend(keyed(row)); + } Ok(graphic) } +#[node_macro::node(transient, memoize)] +fn glide(ctx: impl Ctx + ExtractRealTime, drawing: List, #[scope(inputs::GLIDES)] glides: Item) -> List { + let (glides, time) = (glides.element(), ctx.try_real_time().unwrap_or_default()); + let offset = |row: Option| row.map_or(DVec2::ZERO, |row| glides.offset(row, time)); + let offsets: Vec = drawing.iter_attribute_values_or_default::>(ATTR_GLIDED).map(offset).collect(); + let mut glided = drawing; + glided.remove_attribute(ATTR_GLIDED); + for (transform, offset) in glided.iter_attribute_values_mut_or_default::(ATTR_TRANSFORM).zip(offsets) { + if offset != DVec2::ZERO { + *transform = DAffine2::from_translation(offset) * *transform; + } + } + glided +} + +fn tagged(mut graphic: List, row: impl Into) -> List { + graphic.set_attribute_values(ATTR_GLIDED, vec![Some(row.into()); graphic.len()]); + graphic +} + fn draw_dot(dot: &Placed, [highlight, output_highlight]: [Highlight; 2]) -> List { let [wired, unwired] = data_type_colors(dot.look.data_type); let center = dot.center(); - let grown = matches!(highlight, Highlight::Hovered | Highlight::WireTarget); + let grown = highlight.is_grown(); let scale = if grown { HOVERED_CONNECTOR_SCALE } else { 1. }; let circle = |radius: f64| Vector::item_from_bezpath(&Circle::new((center.x, center.y), radius * scale).to_path(CIRCLE_TOLERANCE)); let output_shown = output_highlight != Highlight::None; @@ -457,7 +515,8 @@ fn draw_dot(dot: &Placed, [highlight, output_highlight]: [Highlight; 2]) -> } if output_shown { - graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.look.data_type, true, output_highlight)); + let grown = if output_highlight.is_grown() { 1. } else { 0. }; + graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.look.data_type, true, output_highlight, grown)); } graphic } @@ -470,7 +529,9 @@ fn draw_errors( #[scope(inputs::SETTLED)] settled: Item, ) -> Result, TextToVectorError> { let rows = [moving.element(), settled.element()]; - badges_with_anchors(errors.element().iter(), rows).map(|(error, anchor)| draw_error(error, anchor, false)).collect() + badges_with_anchors(errors.element().iter(), rows) + .map(|(error, anchor)| draw_error(error, anchor, false).map(|badge| badge.with_attribute(ATTR_GLIDED, Some(Glided::from(error.key))))) + .collect() } fn badges_with_anchors<'a>(errors: impl Iterator, rows: [&'a Rows; 2]) -> impl Iterator { @@ -506,13 +567,13 @@ fn draw_network_connectors(_: impl Ctx, #[scope(inputs::NETWORK_CONNECTORS)] net let mut labels = Labels::default(); let mut graphic = List::new(); for row in network_connectors.element() { - graphic.extend(draw_network_connector(row, &mut labels)?); + graphic.extend(tagged(draw_network_connector(row, &mut labels)?, row.key)); } Ok(graphic) } fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result, TextToVectorError> { - let mut graphic = row_connector(row, Highlight::None); + let mut graphic = row_connector(row, Highlight::None, 0.); let Some(entry) = &row.connector else { return Ok(graphic) }; let name = labels.label(&entry.name, f64::INFINITY)?; if !row.renaming { @@ -526,10 +587,10 @@ fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result Ok(graphic) } -fn row_connector(row: &NetworkConnector, highlight: Highlight) -> List { +fn row_connector(row: &NetworkConnector, highlight: Highlight, grown: f64) -> List { match &row.connector { - Some(entry) => connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry, highlight), - None => drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, highlight), + Some(entry) => connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry, highlight, grown), + None => drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, highlight, grown), } } @@ -542,27 +603,33 @@ fn draw_highlights( #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>, #[scope(inputs::ERRORS)] errors: Item>, ) -> Result, TextToVectorError> { - let highlights = highlights.into_element(); + let highlights = highlights.element(); let rows = [moving.element(), settled.element()]; let mut graphic = List::new(); for dot in rows.iter().flat_map(|rows| &rows.dots) { let looks = highlights.dot(dot.look.key); if looks != [Highlight::None; 2] { - graphic.extend(draw_dot(dot, looks)); + graphic.extend(tagged(draw_dot(dot, looks), dot.look.key)); } } - let connectors: BTreeSet = highlights.connectors().collect(); + let connectors: BTreeSet = highlights.connectors().filter(|key| !highlights.grows.contains_key(key)).collect(); for key in connectors { - if let Some(drawn) = highlighted_connector(key, highlights.connector(key), rows, network_connectors.element()) { - graphic.extend(drawn); + let highlight = highlights.connector(key); + if highlight == Highlight::None { + continue; + } + let grown = if highlight.is_grown() { 1. } else { 0. }; + if let Some(drawn) = highlighted_connector(key, highlight, grown, rows, network_connectors.element()) { + graphic.extend(tagged(drawn, key)); } } for layer in rows.iter().flat_map(|rows| &rows.layers) { - match highlights.layer_button(layer.look.key) { - Some(LayerButton::Grip) => graphic.extend(grip(layer, true)), + let key = layer.look.key; + match highlights.layer_button(key) { + Some(LayerButton::Grip) => graphic.extend(tagged(grip(layer, true), key)), Some(hovered) if !layer.look.read_only => { for (_, place, icons) in layer_buttons(layer).filter(|(button, ..)| *button == hovered) { - graphic.extend(layer_button(layer, place, icons, true, highlights.clicked)); + graphic.extend(tagged(layer_button(layer, place, icons, true, highlights.clicked), key)); } } _ => {} @@ -570,16 +637,39 @@ fn draw_highlights( } let hovered = errors.element().iter().filter(|error| highlights.badge_hovered(error.key)); for (error, anchor) in badges_with_anchors(hovered, rows) { - graphic.push(draw_error(error, anchor, true)?); + graphic.push(draw_error(error, anchor, true)?.with_attribute(ATTR_GLIDED, Some(Glided::from(error.key)))); } Ok(graphic) } -fn highlighted_connector(key: ConnectorKey, highlight: Highlight, rows: [&Rows; 2], network_connectors: &ReplicatedMap) -> Option> { +#[node_macro::node(transient, memoize)] +fn draw_grows( + ctx: impl Ctx + ExtractRealTime, + #[scope(inputs::HIGHLIGHTS)] highlights: Item, + #[scope(inputs::MOVING)] moving: Item, + #[scope(inputs::SETTLED)] settled: Item, + #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>, +) -> List { + let (highlights, time) = (highlights.element(), ctx.try_real_time().unwrap_or_default()); + let rows = [moving.element(), settled.element()]; + let mut graphic = List::new(); + for &key in highlights.grows.keys() { + let (highlight, grown) = (highlights.connector(key), highlights.grown(key, time)); + if highlight == Highlight::None && grown == 0. { + continue; + } + if let Some(drawn) = highlighted_connector(key, highlight, grown, rows, network_connectors.element()) { + graphic.extend(tagged(drawn, key)); + } + } + graphic +} + +fn highlighted_connector(key: ConnectorKey, highlight: Highlight, grown: f64, rows: [&Rows; 2], network_connectors: &ReplicatedMap) -> Option> { let card = |node| rows.into_iter().find_map(|rows| rows.cards.get(&node)); let layer = |node| rows.into_iter().find_map(|rows| rows.layers.get(&node)); let indexed = |index: usize| move |found: &&Connector| found.index as usize == index; - let on_card = |(top_left, found): (DVec2, &Connector)| connector(&CONNECTOR_OUTLINE, top_left, found, highlight); + let on_card = |(top_left, found): (DVec2, &Connector)| connector(&CONNECTOR_OUTLINE, top_left, found, highlight, grown); match key { ConnectorKey::Input(InputKey::Node { node, index }) => { if let Some(card) = card(node) { @@ -587,20 +677,20 @@ fn highlighted_connector(key: ConnectorKey, highlight: Highlight, rows: [&Rows; } let layer = layer(node)?; if let Some(input) = layer.look.primary_input.as_ref().filter(indexed(index)) { - return Some(stack_input(layer, input, highlight)); + return Some(stack_input(layer, input, highlight, grown)); } let input = layer.look.secondary_input.as_ref().filter(indexed(index))?; - Some(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, highlight)) + Some(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, highlight, grown)) } ConnectorKey::Output(OutputKey::Node { node, index }) => { if let Some(card) = card(node) { return card.outputs().find(|(_, output)| indexed(index)(output)).map(on_card); } let layer = layer(node)?; - layer.look.primary_output.as_ref().filter(indexed(index)).map(|output| stack_output(layer, output, highlight)) + layer.look.primary_output.as_ref().filter(indexed(index)).map(|output| stack_output(layer, output, highlight, grown)) } - ConnectorKey::Input(InputKey::Export(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Export(index))?, highlight)), - ConnectorKey::Output(OutputKey::Import(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Import(index))?, highlight)), + ConnectorKey::Input(InputKey::Export(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Export(index))?, highlight, grown)), + ConnectorKey::Output(OutputKey::Import(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Import(index))?, highlight, grown)), } } diff --git a/node-graph/graph-ui/types/src/animation.rs b/node-graph/graph-ui/types/src/animation.rs new file mode 100644 index 0000000000..584e2efb21 --- /dev/null +++ b/node-graph/graph-ui/types/src/animation.rs @@ -0,0 +1,137 @@ +use crate::highlights::ConnectorKey; +use crate::network_connector::NetworkConnectorKey; +use crate::wire::{InputKey, OutputKey}; +use core_types::uuid::NodeId; +use dyn_any::DynAny; +use glam::DVec2; +use graphene_hash::CacheHash; +use std::collections::BTreeMap; +use std::ops::{Add, Mul, Sub}; + +pub const GROW_DURATION: f64 = 100.; +const GLIDE_TIME_CONSTANT: f64 = 30.; +const GLIDE_END_DISTANCE: f64 = 0.5; +const EASE: [f64; 4] = [0.25, 0.1, 0.25, 1.]; +const EASE_STEPS: usize = 40; + +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct Animation { + pub from: T, + pub to: T, + pub start: f64, + pub end: f64, +} + +#[derive(Clone, Copy, Debug)] +pub enum Curve { + Glide, + Ease, +} + +impl + Sub + Mul> Animation { + pub fn at(&self, time: f64, curve: Curve) -> T { + if time >= self.end { + return self.to; + } + if time <= self.start { + return self.from; + } + let duration = self.end - self.start; + let fraction = (time - self.start) / duration; + let progress = match curve { + Curve::Glide => { + let rate = duration / GLIDE_TIME_CONSTANT; + (1. - (-rate * fraction).exp()) / (1. - (-rate).exp()) + } + Curve::Ease => ease(fraction), + }; + self.from + (self.to - self.from) * progress + } +} + +impl Animation { + pub fn glide(from: DVec2, start: f64) -> Option { + let distance = from.length(); + (distance > GLIDE_END_DISTANCE).then(|| Self { + from, + to: DVec2::ZERO, + start, + end: start + GLIDE_TIME_CONSTANT * (distance / GLIDE_END_DISTANCE).ln(), + }) + } +} + +fn ease(fraction: f64) -> f64 { + let [x1, y1, x2, y2] = EASE; + let bezier = |s: f64, first: f64, second: f64| 3. * (1. - s) * (1. - s) * s * first + 3. * (1. - s) * s * s * second + s * s * s; + let [mut low, mut high] = [0., 1.]; + for _ in 0..EASE_STEPS { + let middle = (low + high) / 2.; + if bezier(middle, x1, x2) < fraction { + low = middle; + } else { + high = middle; + } + } + bezier((low + high) / 2., y1, y2) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] +pub enum Glided { + Node(NodeId), + Imports, + Exports, +} + +impl From for Glided { + fn from(node: NodeId) -> Self { + Self::Node(node) + } +} + +impl From for Glided { + fn from(output: OutputKey) -> Self { + match output { + OutputKey::Node { node, .. } => Self::Node(node), + OutputKey::Import(_) => Self::Imports, + } + } +} + +impl From for Glided { + fn from(input: InputKey) -> Self { + match input { + InputKey::Node { node, .. } => Self::Node(node), + InputKey::Export(_) => Self::Exports, + } + } +} + +impl From for Glided { + fn from(key: NetworkConnectorKey) -> Self { + match key { + NetworkConnectorKey::Import(_) => Self::Imports, + NetworkConnectorKey::Export(_) => Self::Exports, + } + } +} + +impl From for Glided { + fn from(key: ConnectorKey) -> Self { + match key { + ConnectorKey::Input(input) => input.into(), + ConnectorKey::Output(output) => output.into(), + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)] +pub struct Glides { + pub rows: BTreeMap>, +} + +impl Glides { + pub fn offset(&self, row: impl Into, time: f64) -> DVec2 { + self.rows.get(&row.into()).map_or(DVec2::ZERO, |glide| glide.at(time, Curve::Glide)) + } +} diff --git a/node-graph/graph-ui/types/src/highlights.rs b/node-graph/graph-ui/types/src/highlights.rs index 6db05a9410..a00f78333b 100644 --- a/node-graph/graph-ui/types/src/highlights.rs +++ b/node-graph/graph-ui/types/src/highlights.rs @@ -1,8 +1,10 @@ +use crate::animation::{Animation, Curve}; use crate::layer::LayerButton; use crate::wire::{InputKey, OutputKey}; use core_types::uuid::NodeId; use dyn_any::DynAny; use graphene_hash::CacheHash; +use std::collections::BTreeMap; #[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)] pub enum Highlight { @@ -13,6 +15,12 @@ pub enum Highlight { WireTarget, } +impl Highlight { + pub fn is_grown(self) -> bool { + matches!(self, Self::Hovered | Self::WireTarget) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] pub enum ConnectorKey { Input(InputKey), @@ -29,7 +37,7 @@ pub enum NodePart { ErrorBadge(NodeId), } -#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash, DynAny)] +#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)] pub struct Highlights { pub hovered_connector: Option, pub dragged_from: Option, @@ -37,6 +45,7 @@ pub struct Highlights { pub hovered_part: Option, pub pressed_part: Option, pub clicked: bool, + pub grows: BTreeMap>, } impl Highlights { @@ -85,7 +94,15 @@ impl Highlights { } pub fn connectors(&self) -> impl Iterator { - [self.hovered_connector, self.dragged_from, self.snapped_to].into_iter().flatten() + [self.hovered_connector, self.dragged_from, self.snapped_to].into_iter().flatten().chain(self.grows.keys().copied()) + } + + pub fn grown(&self, key: ConnectorKey, time: f64) -> f64 { + match self.grows.get(&key) { + Some(grow) => grow.at(time, Curve::Ease), + None if self.connector(key).is_grown() => 1., + None => 0., + } } pub fn badge_hovered(&self, badge: NodeId) -> bool { diff --git a/node-graph/graph-ui/types/src/inputs.rs b/node-graph/graph-ui/types/src/inputs.rs index a11b5829a1..cbd1316db4 100644 --- a/node-graph/graph-ui/types/src/inputs.rs +++ b/node-graph/graph-ui/types/src/inputs.rs @@ -1,3 +1,4 @@ +use crate::animation::Glides; use crate::error_badge::ErrorBadge; use crate::highlights::Highlights; use crate::network_connector::{NetworkConnector, NetworkConnectorKind}; @@ -25,6 +26,7 @@ pub const BOX_SELECTION: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-u pub const FADE_ARTWORK: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-fade-artwork"); pub const WIRE_STYLE: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-style"); pub const HIGHLIGHTS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-highlights"); +pub const GLIDES: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-glides"); pub type Thumbnails = Arc>; @@ -68,4 +70,5 @@ tagged_graph_ui_value! { FadeArtwork(f64), WireStyle(WireStyle), Highlights(Highlights), + Glides(Glides), } diff --git a/node-graph/graph-ui/types/src/lib.rs b/node-graph/graph-ui/types/src/lib.rs index ca70b84bbe..ed5bfb04d3 100644 --- a/node-graph/graph-ui/types/src/lib.rs +++ b/node-graph/graph-ui/types/src/lib.rs @@ -1,3 +1,4 @@ +use animation::Glides; use glam::{DAffine2, DVec2}; use highlights::Highlights; use network_connector::NetworkConnectorKind; @@ -5,6 +6,7 @@ use wire::{WireInProgress, WireStyle}; pub use inputs::TaggedGraphUiValue; +pub mod animation; pub mod card; pub mod dot; pub mod error_badge; @@ -19,7 +21,7 @@ pub mod replicated_map; pub mod scene; pub mod wire; -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] pub struct GraphUiConfig { pub view: DAffine2, pub fade_artwork: f64, @@ -28,4 +30,5 @@ pub struct GraphUiConfig { pub box_selection: Option<[DVec2; 2]>, pub highlights: Highlights, pub wire_style: WireStyle, + pub glides: Glides, }