Compare commits

..
Author SHA1 Message Date
TimonandDennis Kobert 33dd5e545a Move the node graph's hit testing and bounds to the layout (#5049)
* Cache the measured width of a layer's name along with the layer's width

* Derive network bounds and import/export clearance from the layout

* Hit-test node graph nodes with analytic click targets built from the layout

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-12-01 13:21:21 +00:00
24 changed files with 527 additions and 936 deletions

No files matched your search

@@ -4,6 +4,5 @@ mod mandelbrot_v1;
mod mandelbrot_v2;
mod mix_colors_from_mix_node;
mod noise_pattern_v1;
mod noise_pattern_v2;
mod pattern_square;
mod renames;
@@ -1,185 +0,0 @@
use migration_core::attr::node::VISIBLE;
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
}
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let gamma_correction = downstream.add_node(NewNode {
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
});
for consumer in consumers {
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !node.attributes().get_or(VISIBLE, true) {
attributes.set(gamma_correction, VISIBLE, &false);
}
// The Gamma Correction takes the pattern's place, with the pattern before it
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(gamma_correction, POSITION, &stored);
}
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
use migration_core::Declaration;
use migration_core::attr::node::ui::IS_LAYER;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
fn contract() -> SourceContract {
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
}
fn noise_inputs() -> Vec<NodeInput> {
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn rewrites_history() {
check_commutation(&NoisePatternV2, &contract());
check_undo(&NoisePatternV2, &contract());
}
#[test]
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
fixture.export(wire(noise));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
panic!("the consumer should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
assert_eq!(migrated.node_instances.len(), 4);
}
#[test]
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
let visibility_of_gamma_correction = |visible: bool| {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
if !visible {
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
}
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
panic!("the consumer should read a node")
};
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
};
// Visible is the default, so only a disabled pattern writes it
assert_eq!(visibility_of_gamma_correction(false), Some(false));
assert_eq!(visibility_of_gamma_correction(true), None);
}
#[test]
fn an_unread_pattern_gains_no_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(migrated.node_instances.len(), 1);
}
#[test]
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
let mut fixture = Fixture::new(&NoisePatternV2);
// A custom subgraph exporting the pattern, read by the root network's export
let (subgraph, instance) = (NetworkId(100), NodeId(100));
fixture.registry.networks.insert(subgraph, Network::default());
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
fixture.registry.node_instances.insert(instance, instance_node);
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
fixture.export_from(subgraph, wire(noise));
fixture.export(wire(instance));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
panic!("the subgraph's export should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
}
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
let (reader, slot) = if read_by_layer {
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
(layer, 1)
} else {
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
};
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
panic!("slot {slot} of the reader should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
}
#[test]
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
}
}
}
@@ -2687,7 +2687,6 @@ impl DocumentMessageHandler {
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
for path in self.network_interface.paths_reaching(&reconciled.networks) {
self.network_interface.unload_import_export_ports(&path);
self.network_interface.unload_all_nodes_bounding_box(&path);
self.network_interface.unload_outward_wires(&path);
}
self.network_interface.load_structure();
@@ -807,9 +807,6 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
// Set positions for all imported descendants in a single O(n) pass
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
// Invalidate caches once after all positions are set
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
}
usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
@@ -24,14 +24,12 @@ 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 glam::{DAffine2, DVec2, IVec2};
use glam::{DVec2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
use graphene_std::*;
use kurbo::{DEFAULT_ACCURACY, Shape};
use renderer::Quad;
#[derive(Debug, ExtractField)]
pub struct NodeGraphMessageContext<'a> {
@@ -2539,13 +2537,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
HashSet::new()
};
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
for node_id in all_nodes {
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
log::error!("Could not get transient metadata for node {node_id}");
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
log::error!("Could not get the body of node {node_id}");
continue;
};
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
if body.overlaps(selection_min, selection_max) {
if alt {
nodes.remove(&node_id);
} else {
@@ -1,7 +1,7 @@
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
use super::test_support::open_demo;
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use glam::DVec2;
use graphene_std::uuid::NodeId;
@@ -20,20 +20,32 @@ const DEMOS: [&str; 8] = [
const REPETITIONS: u32 = 200;
#[test]
fn wire_anchors_match_the_ports_of_every_demo_node() {
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
for demo in DEMOS {
let document = open_demo(demo);
let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() {
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
let on_port = |wanted: Part, anchor: Option<DVec2>| {
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
match (port, anchor) {
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
(Some(port), Some(anchor)) => port.contains(anchor),
(None, None) => true,
_ => false,
}
};
for index in 0..interface.number_of_inputs(node_id, &[]) {
let input = InputConnector::node_at_index(*node_id, index);
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
}
for index in 0..interface.number_of_outputs(node_id, &[]) {
let output = OutputConnector::node(*node_id, index);
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
}
}
}
@@ -60,7 +72,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now();
for _ in 0..REPETITIONS {
for node_id in &node_ids {
std::hint::black_box(interface.node_click_targets(node_id, &[]));
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
}
}
let all_click_targets = start.elapsed() / REPETITIONS;
@@ -35,7 +35,6 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_absolute_position(*position);
}
interface.invalidate_positions(network_path);
}
}
@@ -172,14 +171,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
interface.finish_drag(&[]);
let kept = interface.positions(node_ids.iter().copied(), &[]);
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
panic!("the root network is laid out")
};
let fresh = graph_layout::Layout::new(&graph);
for (other, position) in kept {
assert_eq!(
Some(position),
indices.get(&other).map(|index| fresh.node(*index).position),
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
);
}
@@ -22,6 +22,7 @@ mod layout;
mod layout_pass;
mod memo_network;
mod mutations;
mod node_parts;
mod queries;
mod reconcile;
mod resolved_types;
@@ -36,6 +37,7 @@ mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use layout_pass::NetworkLayout;
pub use node_parts::{Part, PartTarget};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
@@ -88,34 +88,15 @@ impl NodeNetworkInterface {
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
}
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
self.load_import_export_ports(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
}
/// Reads the import/export ports through &self, loading them first if needed.
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
self.network_metadata(network_path)?
.transient_metadata
.import_export_ports
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
}
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
cache.unload();
}
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
}
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
@@ -126,78 +107,13 @@ impl NodeNetworkInterface {
transient.import_export_ports.unload();
}
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
return None;
};
let bounding_box = network_metadata
.transient_metadata
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
/// The combined bounds of every node in the network, in node graph space.
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let network_metadata = self.network_metadata(network_path)?;
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
Some(
nodes
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
)
}
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
return;
};
transient.all_nodes_bounding_box.unload();
transient.import_export_clearance.unload();
self.unload_import_export_ports(network_path);
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_layout(network_path, NetworkLayout::bounds)
}
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in import_export_clearance");
return None;
};
network_metadata
.transient_metadata
.import_export_clearance
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
}
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let network_metadata = self.network_metadata(network_path)?;
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut clearance = ImportExportClearance::default();
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
continue;
};
if self.is_redirect_dot(node_id, network_path) {
let center = (top_left.x + bottom_right.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
}
}
Some(clearance)
self.with_layout(network_path, NetworkLayout::clearance)
}
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
@@ -364,6 +280,10 @@ impl NodeNetworkInterface {
}
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
}
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in layer_width");
return None;
@@ -376,7 +296,7 @@ impl NodeNetworkInterface {
node_metadata
.transient_metadata
.layer_width
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
}
/// Unloads layer width if the node is a layer.
@@ -549,17 +469,10 @@ impl NodeNetworkInterface {
}
/// The node's body, ports, and handles, built where it is drawn now.
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
self.compute_node_click_targets(node_id, network_path)
}
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
}
/// The box around the node's body where it sits in its grid cell, in node graph space.
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
Some([body.min, body.max])
}
}
@@ -330,7 +330,6 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
}
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
network_interface.invalidate_positions(&[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
@@ -46,193 +46,6 @@ impl NodeNetworkInterface {
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
}
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_ports for node {node_id}");
return None;
};
let document_node = self.document_node(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut ports = Ports::new();
if self.is_redirect_dot(node_id, network_path) {
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
} else if !self.is_layer(node_id, network_path) {
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
ports.insert_node_input(input_index, input_row_count, node_top_left);
}
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
ports.insert_node_output(output_index, node_top_left);
}
} else {
ports.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
ports.insert_layer_input(1, node_top_left);
}
ports.insert_layer_output(node_top_left);
}
Some(ports)
}
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
return None;
};
let node_metadata = self.node_metadata(node_id, network_path)?;
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
if self.is_redirect_dot(node_id, network_path) {
const DOT_HALF_WIDTH: f64 = 15.;
const DOT_HALF_HEIGHT: f64 = 8.;
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
let path = rounded_rectangle_path(
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
[DOT_HALF_HEIGHT; 4],
);
return Some(DocumentNodeClickTargets {
node_click_target: ClickTarget::new_with_path(path, 0.),
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
});
}
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
Some(document_node_click_targets)
}
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
/// Laid out as the frontend draws them, just past the connector.
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
@@ -339,9 +152,9 @@ impl NodeNetworkInterface {
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
}
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
/// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
@@ -356,7 +169,7 @@ impl NodeNetworkInterface {
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
((layer_width_pixels / 24.).ceil() as u32).max(8)
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
@@ -48,6 +48,24 @@ impl NodeNetworkInterface {
Some(&mut navigation.node_graph_ptz)
}
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
/// grid cell, and an input by its index rather than the row a node draws it in.
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
self.with_layout(network_path, |layout| {
layout.find_part(node_id, |target| {
let part = match target.part {
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
part => part,
};
find(part, target)
})
})
.flatten()
}
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
let Some(network_metadata) = self.network_metadata(network_path) else {
@@ -58,16 +76,13 @@ impl NodeNetworkInterface {
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
// Each node is pressed where it's drawn, even while gliding into its grid cell
let glide_offsets = self.glide_offsets(network_path);
let clicked_nodes = self
.nodes_reaching(point, network_path)
.iter()
.filter(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
}) == Some(true)
})
.cloned()
.collect::<Vec<_>>();
let reaching = self.nodes_reaching(point, network_path);
let clicked_nodes = self.with_layout(network_path, |layout| {
reaching
.into_iter()
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
.collect::<Vec<_>>()
})?;
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
let drawing_layer = |node_id: &NodeId| {
if self.is_redirect_dot(node_id, network_path) {
@@ -90,25 +105,18 @@ impl NodeNetworkInterface {
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
self.nodes_reaching(point, network_path)
.iter()
.filter_map(|node_id| {
let point = point - glide_offsets.node(node_id);
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
match click_target_type {
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
}
} else {
None
}
})
.flatten()
})
.next()
let wanted = match click_target_type {
LayerClickTargetTypes::Visibility => Part::Visibility,
LayerClickTargetTypes::Lock => Part::Lock,
LayerClickTargetTypes::Grip => Part::Grip,
LayerClickTargetTypes::Name => Part::Name,
};
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
.is_some()
})
}
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
@@ -194,13 +202,11 @@ impl NodeNetworkInterface {
.iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata
.port_click_targets
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
.map(|port| InputConnector::node_at_index(*node_id, port))
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| match part {
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
_ => None,
})
.flatten()
})
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
.or_else(|| {
@@ -227,13 +233,11 @@ impl NodeNetworkInterface {
.iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata
.port_click_targets
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
.map(|output_index| OutputConnector::node(*node_id, output_index))
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| match part {
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
_ => None,
})
.flatten()
})
.next()
.or_else(|| {
@@ -351,3 +355,17 @@ impl NodeNetworkInterface {
(layer_widths, chain_widths, has_left_input_wire)
}
}
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
let mut current_row = 0;
for (index, input) in inputs.iter().enumerate() {
if input.is_exposed() && current_row == row {
return Some(index);
}
if index == 0 || input.is_exposed() {
current_row += 1;
}
}
None
}
@@ -6,10 +6,6 @@
use super::*;
impl NodeNetworkInterface {
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
self.unload_all_nodes_bounding_box(network_path);
}
/// Unloads the network's import and export ports.
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
self.unload_import_export_ports(network_path);
@@ -17,6 +13,5 @@ impl NodeNetworkInterface {
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path);
self.unload_all_nodes_bounding_box(network_path);
}
}
@@ -52,7 +52,6 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.invalidate_positions(network_path);
}
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
@@ -145,7 +144,6 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.invalidate_positions(network_path);
}
/// Sets the position of a layer to a stack position
@@ -159,8 +157,6 @@ impl NodeNetworkInterface {
} else if node.set_stack_position(y_offset) {
self.transaction_modified();
}
self.invalidate_positions(network_path);
}
/// Sets the position of a node to a stack position without changing its y offset
@@ -371,7 +367,6 @@ impl NodeNetworkInterface {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
if node.shift_absolute_position(position - current_position) {
self.transaction_modified();
self.invalidate_positions(network_path);
}
}
@@ -1,7 +1,9 @@
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
use super::*;
use glam::UVec2;
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
const REACH_MARGIN: f64 = 16.;
@@ -9,13 +11,53 @@ const REACH_MARGIN: f64 = 16.;
#[derive(Debug, Clone)]
pub struct NetworkLayout {
revision: u64,
generation: u64,
node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>,
graph: Graph,
shapes: Vec<NodeShape>,
layout: Layout,
bounds: [DVec2; 2],
clearance: ImportExportClearance,
}
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
impl NetworkLayout {
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let mut network_layout = Self {
revision,
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
node_ids,
indices,
graph,
shapes,
layout,
bounds: [DVec2::ZERO; 2],
clearance: ImportExportClearance::default(),
};
network_layout.measure_bounds_and_clearance();
network_layout
}
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
let Self {
node_ids,
indices,
shapes,
graph,
layout,
..
} = self;
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
}
pub fn generation(&self) -> u64 {
self.generation
}
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
Some(self.node(node_id)?.position)
}
@@ -53,6 +95,33 @@ impl NetworkLayout {
self.node(layer).map_or(0, |node| node.chain_length)
}
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
pub fn bounds(&self) -> [DVec2; 2] {
self.bounds
}
/// What the imports and exports keep their distance from horizontally.
pub(crate) fn clearance(&self) -> ImportExportClearance {
self.clearance
}
/// The node's body where it sits in its grid cell, in node graph space.
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
Some(self.placed(*self.indices.get(node_id)?).body())
}
/// The first of the node's parts, its body last, that `find` picks something from.
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
let placed = self.placed(*self.indices.get(node_id)?);
let mut found = None;
placed.parts(|target| {
if found.is_none() {
found = find(&target);
}
});
found
}
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
let Some(index) = self.indices.get(node_id) else { return false };
@@ -62,6 +131,38 @@ impl NetworkLayout {
point.cmpge(min).all() && point.cmplt(max).all()
}
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
let node_layout = self.layout.node(index);
PlacedNode {
node: &self.graph[index],
shape: &self.shapes[index.index()],
position: node_layout.position,
chain_length: node_layout.chain_length,
}
}
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
fn measure_bounds_and_clearance(&mut self) {
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut bounds: Option<[DVec2; 2]> = None;
let mut clearance = ImportExportClearance::default();
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
let body = self.placed(index).body();
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
if self.graph[index].kind == NodeKind::Waypoint {
let center = (body.min.x + body.max.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
}
}
self.bounds = bounds.unwrap_or_default();
self.clearance = clearance;
}
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
Some(self.layout.node(*self.indices.get(node_id)?))
}
@@ -86,12 +187,14 @@ struct DragOrigin {
keep_upstream: bool,
node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
start: Graph,
drag: Drag,
}
impl DragOrigin {
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
Self {
revision,
@@ -99,6 +202,7 @@ impl DragOrigin {
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
node_ids,
indices,
shapes,
start,
}
}
@@ -154,7 +258,6 @@ impl NodeNetworkInterface {
}
}
transient.layout.unload();
self.invalidate_positions(network_path);
}
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
@@ -178,9 +281,14 @@ impl NodeNetworkInterface {
.filter(|((before, after), _)| before.placement != after.placement)
.map(|((_, after), node_id)| (*node_id, after.placement))
.collect();
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
let laid_out = LaidOutNodes {
node_ids: std::mem::take(&mut origin.node_ids),
indices: std::mem::take(&mut origin.indices),
shapes: std::mem::take(&mut origin.shapes),
};
(moved_placements, laid_out, moved)
});
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
let Some((moved_placements, laid_out, graph)) = finished else { return };
let mut stored_all = true;
for (node_id, placement) in moved_placements {
@@ -189,13 +297,7 @@ impl NodeNetworkInterface {
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
let layout = Layout::new(&graph);
network_metadata.transient_metadata.layout.store(NetworkLayout {
revision: store::revision(),
layout,
graph,
node_ids,
indices,
});
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
}
}
@@ -208,16 +310,15 @@ impl NodeNetworkInterface {
let transient = self.network_transient_mut(network_path)?;
let drag = transient.drag.take()?;
transient.layout.unload();
self.invalidate_positions(network_path);
Some(drag)
}
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
let mut origin = drag.origin.borrow_mut();
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
let (node_ids, indices, start) = self.layout_graph(network_path)?;
let (laid_out, start) = self.layout_graph(network_path)?;
let start_layout = Layout::new(&start);
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
}
origin.as_mut().map(read)
}
@@ -227,8 +328,8 @@ impl NodeNetworkInterface {
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
let (laid_out, graph, layout) = cached.into_parts();
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
}
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
@@ -246,40 +347,38 @@ impl NodeNetworkInterface {
};
if node.set_node_type(node_type) {
self.transaction_modified();
self.invalidate_positions(network_path);
}
true
}
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
let (graph, mut layout) = origin.drag.moved(drag.offset);
layout.snap_chains(&graph);
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
let laid_out = LaidOutNodes {
node_ids: origin.node_ids.clone(),
indices: origin.indices.clone(),
shapes: origin.shapes.clone(),
};
(laid_out, graph, layout)
})?,
None => {
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
let (laid_out, graph) = self.layout_graph(network_path)?;
let layout = Layout::new(&graph);
(node_ids, indices, graph, layout)
(laid_out, graph, layout)
}
};
Some(NetworkLayout {
revision,
layout,
graph,
node_ids,
indices,
})
Some(NetworkLayout::new(revision, laid_out, graph, layout))
}
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
let network = self.nested_network(network_path)?;
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
let wires = node_ids
.iter()
.enumerate()
@@ -297,10 +396,10 @@ impl NodeNetworkInterface {
})
.collect();
Some((node_ids, indices, Graph { nodes, wires }))
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
}
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
let metadata = self.node_metadata(node_id, network_path)?;
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
@@ -314,17 +413,40 @@ impl NodeNetworkInterface {
};
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
let (layer_width, name_width) = if is_layer {
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
} else {
(0, 0.)
};
let (kind, size) = match (is_layer, is_redirect_dot) {
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
};
Some(Node {
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
let node = Node {
placement,
kind,
size: size.as_ivec2(),
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
chainable: !is_redirect_dot && !primary_output_hidden,
held: false,
})
};
let shape = NodeShape {
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
outputs: self.number_of_outputs(node_id, network_path) as u32,
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
primary_output_hidden,
name_width,
locked: self.is_locked(node_id, network_path),
};
Some((node, shape))
}
}
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
pub(crate) struct LaidOutNodes {
pub(crate) node_ids: Vec<NodeId>,
pub(crate) indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
}
@@ -94,11 +94,9 @@ impl NodeNetworkInterface {
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
}
// Update the outward wires and bounding box for all nodes in the encapsulating network
// Update the outward wires for all nodes in the encapsulating network
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
encapsulating_transient.outward_wires.unload();
encapsulating_transient.all_nodes_bounding_box.unload();
encapsulating_transient.import_export_clearance.unload();
}
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
@@ -141,7 +139,6 @@ impl NodeNetworkInterface {
// Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
}
if affects_document_structure {
@@ -179,7 +176,6 @@ impl NodeNetworkInterface {
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
// Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
}
@@ -572,8 +568,7 @@ impl NodeNetworkInterface {
/// 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
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
@@ -673,8 +668,6 @@ impl NodeNetworkInterface {
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
// Exposing or hiding a value input changes the node's port count
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
self.unload_all_nodes_bounding_box(network_path);
// A nested network draws its interior ports from the encapsulating node's inputs
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
let nested_path = [network_path, &[*node_id]].concat();
@@ -904,7 +897,6 @@ impl NodeNetworkInterface {
self.transaction_modified();
}
self.unload_all_nodes_bounding_box(network_path);
self.unload_outward_wires(network_path);
}
@@ -927,7 +919,6 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
previous_entry
}
@@ -1092,7 +1083,6 @@ impl NodeNetworkInterface {
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
}
self.unload_all_nodes_bounding_box(network_path);
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
return;
@@ -1365,7 +1355,6 @@ impl NodeNetworkInterface {
transient.layer_width.unload();
self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
self.invalidate_import_export(network_path);
self.load_structure();
}
@@ -0,0 +1,231 @@
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
use glam::{DVec2, IVec2};
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
const GRID: f64 = GRID_SIZE as f64;
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
const SIDE_PORT_INWARD_REACH: f64 = 8.;
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
const GRIP_WIDTH: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
/// What a node draws beyond the size the layout gives it.
#[derive(Clone, Copy, Debug, Default)]
pub struct NodeShape {
/// How many inputs have a port, which doesn't count a hidden primary input.
pub inputs: u32,
pub outputs: u32,
/// Whether a node's primary input has no port, though its row is still drawn.
pub primary_input_hidden: bool,
pub primary_output_hidden: bool,
/// The width of a layer's name in pixels.
pub name_width: f64,
pub locked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
/// A rounded rectangle of a node that reacts to the pointer.
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
/// A port on the left side of a node, reaching further out than over the node.
fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Input(input),
}
}
/// A port on the right side of a node, reaching further out than over the node.
fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Output(output),
}
}
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
/// Whether `point` is inside the rounded rectangle.
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
#[derive(Clone, Copy, Debug)]
pub struct PlacedNode<'a> {
pub node: &'a Node,
pub shape: &'a NodeShape,
pub position: IVec2,
pub chain_length: u32,
}
impl PlacedNode<'_> {
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
pub fn body(&self) -> PartTarget {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
match self.node.kind {
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: top_left - DVec2::new(self.chain_width(), 0.),
max: top_left + size,
corner_radius: 10.,
part: Part::Body,
},
NodeKind::Node => {
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
PartTarget {
min: body_top_left,
max: body_top_left + size - DVec2::new(0., GRID),
corner_radius: 3.,
part: Part::Body,
}
}
}
}
/// Calls `visit` with each part, the body last.
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.node.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.top_left() + DVec2::new(0., GRID);
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let width = self.node.size.x as f64 * GRID;
let row_center = |row: u32| GRID * (row as f64 + 1.);
let first_input_row = u32::from(self.shape.primary_input_hidden);
for row in first_input_row..first_input_row + self.shape.inputs {
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
}
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
}
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
let icon_half_size = DVec2::splat(HALF_GRID);
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
if self.shape.locked {
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
}
let icons_width = if self.shape.locked { GRID } else { 0. };
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
let handle_top = top_left.y + HALF_GRID;
let handle_bottom = top_left.y + GRID + HALF_GRID;
visit(PartTarget {
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
max: DVec2::new(grip_right, handle_bottom),
corner_radius: 0.,
part: Part::Grip,
});
let name_left = top_left.x + NAME_LEFT_OFFSET;
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, handle_top),
max: DVec2::new(name_right, handle_bottom),
corner_radius: 3.,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.position.as_dvec2() * GRID
}
fn has_side_input(&self) -> bool {
self.shape.inputs > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
}
}
@@ -14,16 +14,6 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
}
/// Ellipse inscribed in the box spanning the two opposite corners.
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
path.close_path();
path
}
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ChainNodeCopy {
@@ -287,13 +277,6 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
}
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
[center - HALF_SIZE, center + HALF_SIZE]
}
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
const CORNER_RADIUS: f64 = 4.;
@@ -336,51 +319,15 @@ impl Ports {
}
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
self.input_anchors.push((input_index, center));
}
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
self.input_ports.push((input_index, click_target));
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
self.output_anchors.push((output_index, center));
}
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
self.output_ports.push((output_index, click_target));
}
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
self.insert_input_port_at_center(input_index, center);
}
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
self.insert_output_port_at_center(output_index, center);
}
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
if input_index == 0 {
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
} else {
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
}
}
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
// The center of the click target is 8 px above the layer, over its thumbnail
let center = node_top_left + DVec2::new(2. * 24., -8.);
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
}
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
}
@@ -389,37 +336,12 @@ impl Ports {
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
}
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
const GUTTER_OFFSET: f64 = 10.;
const GUTTER_RADIUS: f64 = 5.;
let gutter = |x_offset: f64| {
let gutter_center = center + DVec2::new(x_offset, 0.);
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
};
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
self.input_anchors.push((0, center));
self.output_anchors.push((0, center));
}
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
return Some(*anchor);
}
self.input_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
}
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
return Some(*anchor);
}
self.output_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
}
}
@@ -735,16 +657,12 @@ impl<T> TransientCache<T> {
#[derive(Debug, Default, Clone)]
pub struct NodeNetworkTransientMetadata {
pub selected_nodes: SelectedNodes,
/// Cache for the bounding box around all nodes in node graph space.
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
/// Cache for all outward wire connections
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
pub(crate) layout: TransientCache<NetworkLayout>,
pub(crate) drag: Option<super::layout_pass::DragPreview>,
/// All export connector click targets
pub(crate) import_export_ports: TransientCache<Ports>,
/// The import and export connector click targets, with the generation of the layout they were placed by.
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
@@ -1161,40 +1079,8 @@ impl From<LegacyNodePosition> for NodePosition {
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
#[derive(Debug, Default, Clone)]
pub struct DocumentNodeTransientMetadata {
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<u32>,
}
#[derive(Debug, Clone)]
pub struct DocumentNodeClickTargets {
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
pub node_click_target: ClickTarget,
/// Stores all port click targets in node graph space.
pub port_click_targets: Ports,
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
pub node_type_metadata: NodeTypeClickTargets,
}
#[derive(Debug, Clone)]
pub enum NodeTypeClickTargets {
Layer(Box<LayerClickTargets>),
Node, // No transient click targets are stored exclusively for nodes
}
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone)]
pub struct LayerClickTargets {
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
pub visibility_click_target: ClickTarget,
/// Cache for the lock icon button, only present when the layer is locked.
pub lock_click_target: Option<ClickTarget>,
/// Cache for the grip icon, which is next to the visibility button.
pub grip_click_target: ClickTarget,
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
/// `None` for layers whose display name is empty.
pub name_click_target: Option<ClickTarget>,
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<(u32, f64)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -1901,13 +1901,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
continue;
};
// The primary input comes before the Clip toggle where there is one, and the noise settings follow it in the current inputs' order
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
if let Some(clip_index) = clip_index {
if *clip_index == 1
&& let Some(primary) = old_inputs.first()
{
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), primary.clone(), network_path);
}
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
}
@@ -1919,11 +1914,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
move_mandelbrot_to_old_origin(document, node_id, network_path);
}
// Only a Noise Pattern old enough to have the Clip toggle is surely from before it wrote gamma-encoded grays
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
read_noise_through_gamma_correction(document, node_id, network_path);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
@@ -1996,9 +1986,6 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
.cloned()
.unwrap_or_default();
if downstream_consumers.is_empty() {
return Some(());
}
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
@@ -2100,48 +2087,6 @@ fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbr
Some(())
}
/// Keeps an old Noise Pattern's look now that it writes its value as the gray at that gamma-encoded level rather than as linear light,
/// with a Gamma Correction at its default gamma of 2.2 turning the new gray back into about the old one wherever the pattern was read.
fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, noise_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*noise_node_id, 0)))
.cloned()
.unwrap_or_default();
if downstream_consumers.is_empty() {
return Some(());
}
let was_in_chain = document.network_interface.is_chain(noise_node_id, network_path);
let position = document.network_interface.position(noise_node_id, network_path);
let gamma_correction_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER))?.default_node_template();
let gamma_correction_id = NodeId::new();
document.network_interface.insert_node(gamma_correction_id, gamma_correction_template, network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(gamma_correction_id, 0), NodeInput::node(*noise_node_id, 0), network_path);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(gamma_correction_id, 0), network_path);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !document.network_interface.is_visible(noise_node_id, network_path) {
document.network_interface.set_visibility(&gamma_correction_id, network_path, false);
}
// The Gamma Correction takes the pattern's place, and the pattern moves before it
if was_in_chain {
document.network_interface.force_set_upstream_to_chain(&gamma_correction_id, network_path);
} else if let Some(position) = position {
document.network_interface.set_absolute_position(&gamma_correction_id, position, network_path);
document.network_interface.set_absolute_position(noise_node_id, position + IVec2::new(-7, 0), network_path);
}
Some(())
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -6466,9 +6411,6 @@ mod tests {
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
read = upstream(read, 0).expect("the origin transform should read the pattern");
}
if pattern == noise {
read = upstream(read, 0).expect("the Gamma Correction should read the pattern");
}
assert_eq!(read, pattern);
}
@@ -6482,130 +6424,6 @@ mod tests {
);
}
// Noise Pattern once wrote its value as linear light, so whatever read an old one reads it through a Gamma Correction giving back about the old gray
#[tokio::test]
async fn old_noise_patterns_are_read_through_a_gamma_correction() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::adjustments::gamma_correction;
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::transform_nodes::transform;
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Old patterns read by two nodes and the export, in a layer's chain, disabled, and unread, plus a current one in the new look
let read_thrice = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 0).await;
let readers = [
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 0).await,
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 5).await,
];
let chained = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 15, 20).await;
let layer = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 20, 20).await;
let disabled = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 30).await;
let disabled_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 30).await;
let disabled_primary = editor.create_node_by_name_at(proto(transform::IDENTIFIER), -10, 30).await;
let unread = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 40).await;
let unread_clipped = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 45).await;
let current = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 50).await;
let current_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 50).await;
let interface = &mut editor.active_document_mut().network_interface;
for reader in readers {
interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(read_thrice, 0), &[]);
}
interface.create_wire(&OutputConnector::primary_output(read_thrice), &InputConnector::Export(0), &[]);
interface.set_to_node_or_layer(&layer, &[], true);
interface.create_wire(&OutputConnector::primary_output(chained), &InputConnector::layer_secondary_input(layer), &[]);
interface.set_input(&InputConnector::node_at_index(disabled_reader, 0), NodeInput::node(disabled, 0), &[]);
interface.set_input(&InputConnector::node_at_index(disabled, 0), NodeInput::node(disabled_primary, 0), &[]);
interface.set_visibility(&disabled, &[], false);
interface.set_input(&InputConnector::node_at_index(current_reader, 0), NodeInput::node(current, 0), &[]);
assert!(interface.is_chain(&chained, &[]), "the pattern should be in the layer's chain: fixture is wrong");
// A pattern exported from a subgraph
let subgraph = editor.create_empty_subgraph_at(0, 60).await;
editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
let nested = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 10, 0).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(nested),
input_connector: InputConnector::Export(0),
})
.await;
// Save the old patterns as an older editor did, with their Clip toggle off except on one of the unread ones
let document = editor.active_document_mut();
let old_patterns = [
(read_thrice, vec![], false),
(chained, vec![], false),
(disabled, vec![], false),
(unread, vec![], false),
(unread_clipped, vec![], true),
(nested, vec![subgraph], false),
];
for (node_id, network_path, clip) in old_patterns {
let mut inputs = document.network_interface.document_node(&node_id, &network_path).unwrap().inputs.clone();
inputs.insert(1, NodeInput::value(TaggedValue::Bool(clip), false));
let mut legacy = NodeTemplate { inputs, ..Default::default() };
legacy.normalize_input_metadata();
document.network_interface.replace_inputs(&node_id, &network_path, &mut legacy);
}
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let upstream = |connector: InputConnector, network_path: &[NodeId]| interface.upstream_output_connector(&connector, network_path).and_then(|output| output.node_id());
// The Gamma Correction a reader of `pattern` reads instead, at the default gamma and reading the pattern
let gamma_correction_between = |pattern: NodeId, reader: InputConnector, network_path: &[NodeId]| {
let inserted = upstream(reader, network_path).expect("the reader should read a node");
assert_eq!(interface.reference(&inserted, network_path), Some(proto(gamma_correction::IDENTIFIER)));
let node = interface.document_node(&inserted, network_path).unwrap();
assert_eq!(node.input_value(gamma_correction::GammaInput), Some(&TaggedValue::Number(2.2)));
assert_eq!(node.input_value(gamma_correction::InverseInput), Some(&TaggedValue::Bool(false)));
assert_eq!(upstream(InputConnector::node_at_index(inserted, 0), network_path), Some(pattern));
inserted
};
// Every reader of the pattern read three times shares one Gamma Correction, which takes the pattern's place with the pattern before it
let shared = gamma_correction_between(read_thrice, InputConnector::Export(0), &[]);
for reader in readers {
assert_eq!(upstream(InputConnector::node_at_index(reader, 0), &[]), Some(shared));
}
let position = |node_id: NodeId| interface.position(&node_id, &[]).expect("the node should have a position");
assert_eq!(position(read_thrice) + IVec2::new(7, 0), position(shared));
let in_chain = gamma_correction_between(chained, InputConnector::layer_secondary_input(layer), &[]);
assert!(interface.is_chain(&in_chain, &[]) && interface.is_chain(&chained, &[]), "the layer's chain should hold both");
// Only a disabled pattern's Gamma Correction is disabled too, and the pattern keeps the primary input it passes through
let behind_disabled = gamma_correction_between(disabled, InputConnector::node_at_index(disabled_reader, 0), &[]);
assert!(!interface.is_visible(&behind_disabled, &[]) && interface.is_visible(&shared, &[]));
assert_eq!(upstream(InputConnector::node_at_index(disabled, 0), &[]), Some(disabled_primary));
gamma_correction_between(nested, InputConnector::Export(0), &[subgraph]);
assert_eq!(upstream(InputConnector::node_at_index(current_reader, 0), &[]), Some(current));
// Unread patterns gain nothing reading them, clipped or not
let read = |pattern: NodeId| interface.document_network().nodes.values().any(|node| node.inputs.iter().any(|input| input.as_node() == Some(pattern)));
assert!(!read(unread) && !read(unread_clipped));
// Reopening the upgraded document, as restoring an autosave does, inserts no more
let gamma_corrections = |document: &DocumentMessageHandler| {
let implementation = DocumentNodeImplementation::ProtoNode(gamma_correction::IDENTIFIER);
let nodes = document.network_interface.document_network().recursive_nodes();
nodes.filter(|(_, node, _)| node.implementation == implementation).count()
};
assert_eq!(gamma_corrections(&opened), 4);
let reopened = load_legacy_document(opened.serialize_document(), &HashMapResourceStorage::new(), false).expect("the upgraded document should open");
assert_eq!(gamma_corrections(&reopened), 4);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
#[tokio::test]
async fn marbled_mandelbrot_renders_after_migration() {
@@ -24,7 +24,7 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
fill_rows(&mut image.data, width as usize, |y, row| {
row.iter_mut().enumerate().for_each(|(x, pixel)| {
*pixel = pattern_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
*pixel = mandelbrot_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
});
});
}
@@ -60,18 +60,18 @@ pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color +
};
move |point| match &sampler {
Sampler::Noise(noise) => pattern_gray(noise.sample(point)),
Sampler::Mandelbrot(setup) => pattern_gray(setup.sample(setup.plane_point(point), None, false)),
Sampler::Noise(noise) => Color::from_luminance(noise.sample(point)),
Sampler::Mandelbrot(setup) => mandelbrot_gray(setup.sample(setup.plane_point(point), None, false)),
}
}
/// A pattern's value from 0 to 1 as the gray at that gamma-encoded level, so middle values show as middle gray and a Gradient Map takes the value as the position along its gradient.
fn pattern_gray(value: f32) -> Color {
let value = value.clamp(0., 1.);
/// The Mandelbrot brightness as a gray, gamma-encoded so a Gradient Map takes it as the position along its gradient.
fn mandelbrot_gray(brightness: f32) -> Color {
let value = brightness.clamp(0., 1.);
Color::from_gamma_srgb_channels(value, value, value, 1.)
}
/// Samples a noise pattern's value, from 0 to 1, at positions in its space.
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
struct NoiseSampler {
noise: fastnoise_lite::FastNoiseLite,
white_noise_seed: Option<i32>,
@@ -221,18 +221,6 @@ mod tests {
}
}
#[test]
fn pattern_values_show_as_the_gray_at_that_level() {
for value in [0., 0.25, 0.5, 0.75, 1.] {
let [red, green, blue, alpha] = pattern_gray(value).to_gamma_srgb_channels();
assert!([red, green, blue].iter().all(|channel| (channel - value).abs() < 1e-5) && alpha == 1., "{value} shows as {red}");
}
// Values out of range clamp
assert_eq!(pattern_gray(1.5).to_gamma_srgb_channels()[0], 1.);
assert_eq!(pattern_gray(-0.5).to_gamma_srgb_channels()[0], 0.);
}
#[test]
fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() {
let white_noise = |seed| {
@@ -8,7 +8,10 @@ fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
return vec4<f32>(corner * 2. - 1., 0., 1.);
}
// A value from 0 to 1 written directly as the gray's gamma-encoded level, clamped to the range the CPU encodes, which takes NaN as 0
fn gray_level(unclamped: f32) -> f32 {
return select(0., min(unclamped, 1.), unclamped >= 0.);
// Clamped to the range the CPU encodes, which takes NaN as 0
fn linear_to_srgb(unclamped: f32) -> f32 {
let linear = select(0., min(unclamped, 1.), unclamped >= 0.);
let low = linear * 12.92;
let high = 1.055 * pow(linear, 1. / 2.4) - 0.055;
return select(high, low, linear <= 0.0031308);
}
@@ -17,7 +17,7 @@ fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
if parameters.domain_warp != 0u {
fnlDomainWarp2D(parameters.noise, &x, &y);
}
let value = (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
let luminance = (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
return vec4<f32>(vec3<f32>(gray_level(value)), 1.);
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
}
@@ -21,9 +21,9 @@ fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let hash = pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed)));
// The top 24 bits, which an f32 holds exactly
let value = f32(hash.x >> 8u) / 16777216.;
let luminance = f32(hash.x >> 8u) / 16777216.;
return vec4<f32>(vec3<f32>(gray_level(value)), 1.);
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
}
// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result
+1 -1
View File
@@ -200,7 +200,7 @@ fn image(
}
/// Generates customizable procedural noise patterns.
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"), version(3))]
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"), version(2))]
#[allow(clippy::too_many_arguments)]
fn noise_pattern(
_: impl Ctx,