1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//! Node-body lifecycle on [`Simulation`]: reconciling the rapier body set with the graph
//! (`sync_with_graph` / `sync_nodes`), the spring-edge topology (`sync_edges`), and the body
//! accessors (`positions` / `position_of` / `body_for`) the read model is built from. Split from
//! `lib.rs` to keep the simulation core under the per-file size ceiling.
use std::collections::HashSet;
use crate::NodeKey;
use euclid::default::Point2D;
use rapier2d::prelude::*;
use crate::{DEFAULT_ANGULAR_DAMPING, NODE_BODY_RADIUS, Simulation};
impl Simulation {
/// Replace the topology the layout forces pull along (see
/// [`ForceContext::edges`](crate::ForceContext::edges)). Caller-chosen node-key pairs: seiche
/// does not read graph edges itself, so the caller filters to the relation families that
/// should shape the layout (e.g. semantic edges, not arrangement). Idempotent; replaces the
/// whole edge list.
pub fn sync_edges(&mut self, edges: impl IntoIterator<Item = (NodeKey, NodeKey)>) {
self.edges.clear();
self.edges.extend(edges);
}
/// Number of edges currently feeding the layout forces.
pub fn edge_count(&self) -> usize {
self.edges.len()
}
/// Number of currently-tracked bodies. Useful for traces / tests.
pub fn body_count(&self) -> usize {
self.bodies_by_node.len()
}
/// Look up the body handle for a node, if any. Force implementors
/// already get the bimap through [`ForceContext`](crate::ForceContext); this is for
/// external callers (host drag handlers, etc.).
pub fn body_for(&self, node: NodeKey) -> Option<RigidBodyHandle> {
self.bodies_by_node.get(&node).copied()
}
/// Current projected position of a node's body, if it has one. Reads the
/// live rapier translation, so it reflects the most recent [`Self::tick`].
pub fn position_of(&self, node: NodeKey) -> Option<Point2D<f32>> {
let handle = *self.bodies_by_node.get(&node)?;
let t = self.bodies.get(handle)?.translation();
Some(Point2D::new(t.x, t.y))
}
/// Seed (override) the positions of existing node bodies, e.g. from a
/// cartography projection's positioned nodes, so a real layout strategy
/// (radial, astroid, a converged force-directed pass) becomes the physics
/// starting point instead of the graph's stored positions. Resets each
/// seeded body's velocity so the settle starts clean. Nodes without a body
/// are skipped (seed after [`Self::sync_nodes`]).
///
/// Takes plain `(NodeKey, Point2D)` rather than a `cartography::Projection`
/// on purpose: seiche is a kernel-tier substrate and must not depend on the
/// projection layer above it. The caller maps `Projection.nodes` to these
/// pairs (see the cartography-seiche layout seam doc).
pub fn seed_positions(&mut self, positions: impl IntoIterator<Item = (NodeKey, Point2D<f32>)>) {
for (node, pos) in positions {
let Some(&handle) = self.bodies_by_node.get(&node) else {
continue;
};
if let Some(body) = self.bodies.get_mut(handle) {
body.set_translation(Vector::new(pos.x, pos.y), true);
body.set_linvel(Vector::ZERO, true);
}
}
}
/// Iterate the current `(node, position)` of every node body — the live
/// layout, e.g. for the caller to build a cartography projection for
/// downstream consumers. Reflects the most recent [`Self::tick`]; order is
/// unspecified.
pub fn positions(&self) -> impl Iterator<Item = (NodeKey, Point2D<f32>)> + '_ {
self.bodies_by_node.iter().filter_map(|(&node, &handle)| {
self.bodies
.get(handle)
.map(|b| (node, Point2D::new(b.translation().x, b.translation().y)))
})
}
// `sync_with_graph(&Graph)` — the thin wrapper that read each node's projected
// position from a mere `Graph` and forwarded to [`Self::sync_nodes`] — left when
// seiche became kernel-free. The host reads its graph and calls `sync_nodes` with
// the `(NodeKey, position)` list (mere-canvas's `build::sync_sim_with_graph`).
/// Reconcile the body set to exactly `nodes` (keyed by [`NodeKey`]): spawn a
/// body at the given position for every key without one, remove bodies whose
/// key is absent. The position is only used for *new* bodies (an existing
/// body keeps its simulated position; use [`Self::seed_positions`] to move
/// one).
///
/// Decoupled from any graph on purpose: a physics actor drives the sim from a
/// `Send` node list the host computed, so the graph never crosses the actor
/// boundary. Idempotent.
pub fn sync_nodes(&mut self, nodes: impl IntoIterator<Item = (NodeKey, Point2D<f32>)>) {
// 1. Add bodies for new nodes (at the supplied position).
let mut seen = HashSet::with_capacity(self.bodies_by_node.len());
for (key, position) in nodes {
seen.insert(key);
if self.bodies_by_node.contains_key(&key) {
continue;
}
// A re-synced body comes back with the material and kinds it was tuned to,
// not the spawn defaults — both are remembered per node. The default material
// keeps gravity scale 0: nodes never fall unless weight was opted into, so the
// graph layout is unaffected by a gravity scene. (Physics scenes P3; tactile T1/T2.)
let material = self.node_materials.get(&key).copied().unwrap_or_default();
let body = RigidBodyBuilder::dynamic()
.translation(Vector::new(position.x, position.y))
.linear_damping(self.linear_damping)
.angular_damping(DEFAULT_ANGULAR_DAMPING)
.gravity_scale(material.gravity_scale)
.build();
let handle = self.bodies.insert(body);
let kinds = self.sift.node_kinds.get(&key).copied().unwrap_or_default();
let collider = ColliderBuilder::ball(NODE_BODY_RADIUS)
.density(material.density)
.restitution(material.restitution)
.friction(material.friction)
.collision_groups(crate::sift::node_mask(kinds, self.nodes_tangible))
.build();
self.colliders
.insert_with_parent(collider, handle, &mut self.bodies);
self.bodies_by_node.insert(key, handle);
}
// 2. Remove bodies whose nodes are gone.
let stale: Vec<NodeKey> = self
.bodies_by_node
.keys()
.copied()
.filter(|key| !seen.contains(key))
.collect();
for key in stale {
if let Some(handle) = self.bodies_by_node.remove(&key) {
self.bodies.remove(
handle,
&mut self.islands,
&mut self.colliders,
&mut self.impulse_joints,
&mut self.multibody_joints,
/* remove_attached_colliders */ true,
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::NodeExclusion;
/// Physics runs on abstract node keys with no graph at all: seiche's graph-free
/// surface (`sync_nodes` / `sync_edges` / `position_of` / `positions`) is the
/// primary interface, so any app (a raw chartulary graph, a bespoke store) drives
/// the simulation by feeding `(key, position)` pairs and reading positions back,
/// with no `Graph` in sight. Two nodes nearly on top of each other are pushed apart
/// by exclusion. (The graph-convenience suite is in `tests.rs`, behind
/// `kernel-bridge`.)
#[test]
fn physics_runs_on_abstract_nodes_without_a_graph() {
// Keys are minted directly (petgraph indices), not read from any graph.
let a = NodeKey::new(0);
let b = NodeKey::new(1);
let mut sim = Simulation::new();
sim.add_force(NodeExclusion::default());
sim.sync_nodes([(a, Point2D::new(0.0, 0.0)), (b, Point2D::new(1.0, 0.0))]);
let before = (sim.position_of(a).unwrap() - sim.position_of(b).unwrap()).length();
for _ in 0..120 {
sim.tick(1.0 / 60.0);
}
let after = (sim.position_of(a).unwrap() - sim.position_of(b).unwrap()).length();
assert!(
after > before,
"exclusion pushed the two nodes apart with no graph ({after} > {before})"
);
assert_eq!(
sim.positions().count(),
2,
"positions read back, still no graph"
);
}
}