Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"libraries/math-parser",
"libraries/ipsum",
"libraries/snapping",
"libraries/graph-layout",
"libraries/wgpu-sync",
"libraries/control-protocol",
"node-graph/libraries/graphene-hash",
Expand Down Expand Up @@ -134,6 +135,7 @@
graphene-canvas-utils = { path = "node-graph/libraries/canvas-utils" }
ipsum = { path = "libraries/ipsum" }
snapping = { path = "libraries/snapping" }
graph-layout = { path = "libraries/graph-layout" }

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / regression-corpus

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / test

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / test

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / test

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / migrations

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / build / web

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / build / web

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / build / web

unused workspace dependency `graph-layout`

Check warning on line 138 in Cargo.toml

View workflow job for this annotation

GitHub Actions / build / web

unused workspace dependency `graph-layout`

# Workspace dependencies
rustc-hash = "2.0"
Expand Down
26 changes: 26 additions & 0 deletions libraries/graph-layout/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "graph-layout"
description = "Lays out a node graph in one pass from the placements its nodes store"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true

[lints]
workspace = true

[dependencies]
glam = { workspace = true }
smallvec = { workspace = true }

[dev-dependencies]
criterion = { workspace = true }

[[bench]]
name = "layout"
harness = false
140 changes: 140 additions & 0 deletions libraries/graph-layout/benches/layout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
use criterion::{BatchSize, BenchmarkId, Criterion, criterion_group, criterion_main};
use glam::IVec2;
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
use std::hint::black_box;

const SIZES: [u32; 3] = [1_000, 10_000, 100_000];
const BESIDE: IVec2 = IVec2::new(-7, 0);

type GraphShape = fn(u32) -> Graph;

struct Random(u64);

impl Random {
fn below(&mut self, bound: u32) -> u32 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
u32::try_from(self.0 % u64::from(bound)).unwrap_or_default()
}
}

fn node(placement: Placement) -> Node {
Node {
placement,
kind: NodeKind::Node,
size: IVec2::new(5, 3),
chainable: true,
held: false,
}
}

fn layer(placement: Placement) -> Node {
Node {
kind: NodeKind::Layer,
size: IVec2::new(5, 2),
..node(placement)
}
}

fn wire(source: u32, target: u32, input: u32) -> Wire {
Wire {
source: source.into(),
output: 0,
target: target.into(),
input,
}
}

fn line(node_count: u32) -> Graph {
Graph {
nodes: (0..node_count)
.map(|index| node(if index == 0 { Placement::Absolute(IVec2::ZERO) } else { Placement::Relative(BESIDE) }))
.collect(),
wires: (1..node_count).map(|index| wire(index, index - 1, 0)).collect(),
}
}

fn fan_in(node_count: u32) -> Graph {
let roots = node_count / 2;
let root_nodes = (0..roots).map(|root| node(Placement::Absolute(IVec2::new(0, 3 * root.cast_signed()))));
let line_nodes = (roots..node_count).map(|_| node(Placement::Relative(BESIDE)));
let shared_wires = (0..roots).map(|root| wire(roots, root, 1));
let line_wires = (roots + 1..node_count).map(|index| wire(index, index - 1, 0));

Graph {
nodes: root_nodes.chain(line_nodes).collect(),
wires: shared_wires.chain(line_wires).collect(),
}
}

fn stacked_layers(node_count: u32) -> Graph {
let layers = node_count / 4;
let stacked_layer = |index: u32| layer(if index == 0 { Placement::Absolute(IVec2::ZERO) } else { Placement::Stack(0) });
let chain = |_| [node(Placement::Chain), node(Placement::Chain), node(Placement::Chain)];
let stack_wires = |index: u32| (index > 0).then(|| wire(4 * index, 4 * (index - 1), 0));
let chain_wires = |index: u32| [wire(4 * index + 1, 4 * index, 1), wire(4 * index + 2, 4 * index + 1, 0), wire(4 * index + 3, 4 * index + 2, 0)];

Graph {
nodes: (0..layers).flat_map(|index| std::iter::once(stacked_layer(index)).chain(chain(index))).collect(),
wires: (0..layers).flat_map(|index| stack_wires(index).into_iter().chain(chain_wires(index))).collect(),
}
}

fn random_graph(node_count: u32) -> Graph {
let mut random = Random(0x9E37_79B9_7F4A_7C15);
let mut graph = Graph::default();
for index in 0..node_count {
if index == 0 || random.below(100) == 0 {
let position = IVec2::new(random.below(1_000).cast_signed(), random.below(1_000).cast_signed());
graph.nodes.push(node(Placement::Absolute(position)));
continue;
}

graph.nodes.push(node(Placement::Relative(IVec2::new(-7, random.below(7).cast_signed()))));
for input in 0..=random.below(3) {
graph.wires.push(wire(index, random.below(index), input));
}
}
graph
}

fn bench_layout(criterion: &mut Criterion) {
let shapes: [(&str, GraphShape); 4] = [("line", line), ("fan_in", fan_in), ("stacked_layers", stacked_layers), ("random", random_graph)];

let mut group = criterion.benchmark_group("layout");
for (name, shape) in shapes {
for size in SIZES {
let graph = shape(size);
group.bench_with_input(BenchmarkId::new(name, size), &graph, |bencher, graph| bencher.iter(|| Layout::new(black_box(graph))));
}
}
group.finish();
}

fn bench_drag(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("drag_pointer_move");
for size in [1_000, 10_000] {
let graph = stacked_layers(size);
let bottom_layer = NodeIndex::from(4 * (size / 4 - 1));
let mut warm = Drag::new(graph.clone(), Layout::new(&graph), vec![bottom_layer], false);
let _ = warm.moved(IVec2::new(0, -40));

for (name, offset) in [("one_row_further", IVec2::new(0, -41)), ("back", IVec2::new(0, -20)), ("sideways", IVec2::new(5, -40))] {
group.bench_function(BenchmarkId::new(name, size), |bencher| {
bencher.iter_batched(
|| warm.clone(),
|mut drag| {
let moved = drag.moved(black_box(offset));
(drag, moved)
},
BatchSize::LargeInput,
);
});
}
}
group.finish();
}

criterion_group!(benches, bench_layout, bench_drag);
criterion_main!(benches);
71 changes: 71 additions & 0 deletions libraries/graph-layout/src/chains.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use crate::connections::Connections;
use crate::forest::Forest;
use crate::graph::CHAIN_OFFSET;
use crate::per_node::PerNode;
use crate::{CHAIN_WIDTH, Graph, NodeIndex};
use glam::IVec2;
use std::iter;

pub(crate) type Beside = fn(IVec2, IVec2) -> bool;

/// Whether a node drawn at `position` joins the chain of the node reading it at `reader_position` once a drag releases it.
#[must_use]
pub fn snaps_into_chain(position: IVec2, reader_position: IVec2) -> bool {
position.y == reader_position.y && (reader_position.x - CHAIN_WIDTH - 2..=reader_position.x).contains(&position.x)
}

pub(crate) fn sits_in_chain(position: IVec2, reader_position: IVec2) -> bool {
position == reader_position + CHAIN_OFFSET
}

pub(crate) fn chain_links(graph: &Graph, forest: &Forest) -> PerNode<bool> {
let mut links = PerNode::filled(graph, false);
forest
.order
.iter()
.for_each(|node| links[*node] = forest.owner(*node).is_some_and(|owner| is_chain_link(graph, forest, &links, *node, owner)));
links
}

fn is_chain_link(graph: &Graph, forest: &Forest, links: &PerNode<bool>, node: NodeIndex, owner: NodeIndex) -> bool {
let feeds_chain_input = forest.owner_inputs[node] == graph[owner].chain_input();
let owner_in_chain = graph[owner].is_layer() || links[owner];
graph[node].can_join_chain() && feeds_chain_input && forest.offsets[node] == CHAIN_OFFSET && owner_in_chain
}

pub(crate) struct Chains<'a> {
pub(crate) graph: &'a Graph,
pub(crate) connections: &'a Connections,
pub(crate) positions: &'a PerNode<IVec2>,
pub(crate) beside: Beside,
}

impl Chains<'_> {
pub(crate) fn layers(&self) -> PerNode<Option<NodeIndex>> {
let mut layers = PerNode::filled(self.graph, None);
self.graph
.node_indices()
.filter(|node| self.graph[*node].is_layer())
.flat_map(|layer| self.links(layer).map(move |link| (link, layer)))
.for_each(|(link, layer)| layers[link] = Some(layer));
layers
}

fn links(&self, layer: NodeIndex) -> impl Iterator<Item = NodeIndex> + '_ {
iter::successors(Some(layer), |reader| self.next_link(*reader)).skip(1)
}

fn next_link(&self, reader: NodeIndex) -> Option<NodeIndex> {
let wire = self.connections.inputs(self.graph, reader).find(|wire| wire.input == self.graph[reader].chain_input())?;
let source = wire.source;
let read_once = self.connections.readers(self.graph, source).filter(|wire| wire.is_primary()).count() == 1;
let beside = (self.beside)(self.positions[source], self.positions[reader]);
(self.graph[source].can_join_chain() && wire.is_primary() && read_once && beside).then_some(source)
}
}

pub(crate) fn chain_lengths(graph: &Graph, chain_layers: &PerNode<Option<NodeIndex>>) -> PerNode<u32> {
let mut lengths = PerNode::filled(graph, 0);
chain_layers.iter().flatten().for_each(|layer| lengths[*layer] += 1);
lengths
}
54 changes: 54 additions & 0 deletions libraries/graph-layout/src/connections.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use crate::groups::Groups;
use crate::{Graph, NodeIndex, Placement, Wire};

#[derive(Clone, Debug)]
pub(crate) struct WiresByNode(Groups<u32>);

impl WiresByNode {
pub(crate) fn readers(graph: &Graph) -> Self {
Self::grouped(graph, |wire| wire.source)
}

pub(crate) fn inputs(graph: &Graph) -> Self {
Self::grouped(graph, |wire| wire.target)
}

fn grouped(graph: &Graph, node_of: impl Fn(&Wire) -> NodeIndex) -> Self {
let wire_indices = 0..u32::try_from(graph.wires.len()).unwrap_or(u32::MAX);
Self(Groups::new(graph, wire_indices, |index| node_of(&graph.wires[*index as usize])))
}

pub(crate) fn of<'a>(&'a self, graph: &'a Graph, node: NodeIndex) -> impl Iterator<Item = &'a Wire> + Clone {
self.0.of(node).iter().map(|index| &graph.wires[*index as usize])
}

pub(crate) fn count(&self, node: NodeIndex) -> u32 {
u32::try_from(self.0.of(node).len()).unwrap_or(u32::MAX)
}
}

pub(crate) struct Connections {
pub(crate) readers: WiresByNode,
pub(crate) inputs: WiresByNode,
}

impl Connections {
pub(crate) fn new(graph: &Graph) -> Self {
Self {
readers: WiresByNode::readers(graph),
inputs: WiresByNode::inputs(graph),
}
}

pub(crate) fn readers<'a>(&'a self, graph: &'a Graph, node: NodeIndex) -> impl Iterator<Item = &'a Wire> + Clone {
self.readers.of(graph, node)
}

pub(crate) fn inputs<'a>(&'a self, graph: &'a Graph, node: NodeIndex) -> impl Iterator<Item = &'a Wire> {
self.inputs.of(graph, node)
}

pub(crate) fn is_root(&self, graph: &Graph, node: NodeIndex) -> bool {
self.readers.count(node) == 0 || matches!(graph[node].placement, Placement::Absolute(_))
}
}
57 changes: 57 additions & 0 deletions libraries/graph-layout/src/contour/column.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use smallvec::SmallVec;
use std::ops::Range;

const SPANS_PER_COLUMN: usize = 4;

pub(super) type Column = SmallVec<[Span; 1]>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Span {
pub(super) top: i32,
pub(super) bottom: i32,
}

impl Span {
pub(super) fn moved(self, rows: i32) -> Self {
Self {
top: self.top + rows,
bottom: self.bottom + rows,
}
}

pub(super) fn meets(self, other: Self, rows_apart: i32) -> bool {
self.top < other.bottom + rows_apart && other.top < self.bottom + rows_apart
}
}

pub(super) fn cover(column: &mut Column, span: Span) {
let touching = column.partition_point(|covered| covered.bottom < span.top)..column.partition_point(|covered| covered.top <= span.bottom);
if touching.is_empty() {
insert(column, touching.start, span);
} else {
merge(column, touching, span);
}
}

fn insert(column: &mut Column, index: usize, span: Span) {
column.insert(index, span);
if column.len() > SPANS_PER_COLUMN {
close_smallest_gap(column);
}
}

fn merge(column: &mut Column, touching: Range<usize>, span: Span) {
column[touching.start] = Span {
top: span.top.min(column[touching.start].top),
bottom: span.bottom.max(column[touching.end - 1].bottom),
};
column.drain(touching.start + 1..touching.end);
}

fn close_smallest_gap(column: &mut Column) {
let Some(above_gap) = column.windows(2).enumerate().min_by_key(|(_, pair)| pair[1].top - pair[0].bottom).map(|(index, _)| index) else {
return;
};
column[above_gap].bottom = column[above_gap + 1].bottom;
column.remove(above_gap + 1);
}
Loading
Loading