use crate::NodeKey;
use crate::{Force, ForceContext};
pub const DEFAULT_AFFINITY_STIFFNESS: f32 = 5.0;
pub const DEFAULT_AFFINITY_REST_LENGTH: f32 = 120.0;
#[derive(Clone, Debug)]
pub struct AffinitySpring {
pairs: Vec<(NodeKey, NodeKey, f32)>,
pub stiffness: f32,
pub rest_length: f32,
}
impl AffinitySpring {
pub fn new(pairs: impl IntoIterator<Item = (NodeKey, NodeKey, f32)>) -> Self {
Self {
pairs: pairs.into_iter().collect(),
stiffness: DEFAULT_AFFINITY_STIFFNESS,
rest_length: DEFAULT_AFFINITY_REST_LENGTH,
}
}
pub fn pair_count(&self) -> usize {
self.pairs.len()
}
pub fn is_empty(&self) -> bool {
self.pairs.is_empty()
}
}
impl Force for AffinitySpring {
fn apply(&self, ctx: &mut ForceContext<'_>, _dt: f32) {
for &(a, b, weight) in &self.pairs {
if a == b || weight <= 0.0 {
continue; }
let (Some(&ha), Some(&hb)) = (ctx.bodies_by_node.get(&a), ctx.bodies_by_node.get(&b))
else {
continue; };
let (Some(pa), Some(pb)) = (
ctx.bodies.get(ha).map(|x| x.translation()),
ctx.bodies.get(hb).map(|x| x.translation()),
) else {
continue;
};
let delta = pb - pa;
let dist = delta.length();
if dist <= self.rest_length || dist < 1e-3 {
continue;
}
let pull = delta / dist * (self.stiffness * weight * (dist - self.rest_length));
if let Some(body) = ctx.bodies.get_mut(ha) {
body.add_force(pull, true);
}
if let Some(body) = ctx.bodies.get_mut(hb) {
body.add_force(-pull, true);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{NodeExclusion, Simulation};
use euclid::default::Point2D;
#[derive(Default)]
struct Nodes {
list: Vec<(NodeKey, Point2D<f32>)>,
}
impl Nodes {
fn at(&mut self, x: f32, y: f32) -> NodeKey {
let key = NodeKey::new(self.list.len());
self.list.push((key, Point2D::new(x, y)));
key
}
fn sync(&self, sim: &mut Simulation) {
sim.sync_nodes(self.list.iter().copied());
}
}
fn distance(sim: &Simulation, a: NodeKey, b: NodeKey) -> f32 {
(sim.position_of(a).unwrap() - sim.position_of(b).unwrap()).length()
}
#[test]
fn a_high_affinity_pair_is_pulled_together() {
let mut g = Nodes::default();
let a = g.at(-300.0, 0.0);
let b = g.at(300.0, 0.0);
let mut sim = Simulation::new();
g.sync(&mut sim);
let start = distance(&sim, a, b);
sim.set_affinity_force(Some(AffinitySpring::new([(a, b, 1.0)])));
for _ in 0..240 {
sim.tick(1.0 / 60.0);
}
let end = distance(&sim, a, b);
assert!(
end < start,
"affinity should pull the pair closer: {start} -> {end}"
);
}
#[test]
fn a_zero_affinity_pair_exerts_no_force() {
let mut g = Nodes::default();
let a = g.at(-300.0, 0.0);
let b = g.at(300.0, 0.0);
let mut sim = Simulation::new();
g.sync(&mut sim);
let start = distance(&sim, a, b);
sim.set_affinity_force(Some(AffinitySpring::new([(a, b, 0.0)])));
for _ in 0..120 {
sim.tick(1.0 / 60.0);
}
assert!(
(distance(&sim, a, b) - start).abs() < 1.0,
"a zero-weight pair should not move"
);
}
#[test]
fn attract_only_does_not_push_a_close_pair_apart() {
let mut g = Nodes::default();
let a = g.at(-20.0, 0.0);
let b = g.at(20.0, 0.0); let mut sim = Simulation::new();
g.sync(&mut sim);
let start = distance(&sim, a, b);
sim.set_affinity_force(Some(AffinitySpring::new([(a, b, 1.0)])));
for _ in 0..120 {
sim.tick(1.0 / 60.0);
}
assert!(
(distance(&sim, a, b) - start).abs() < 2.0,
"attract-only force must not push a close pair apart: {start} -> {}",
distance(&sim, a, b)
);
}
#[test]
fn a_high_affinity_pair_draws_in_more_than_a_low_affinity_pair() {
let mut g = Nodes::default();
let a = g.at(-250.0, -200.0);
let b = g.at(250.0, -200.0);
let c = g.at(-250.0, 200.0);
let d = g.at(250.0, 200.0);
let mut sim = Simulation::new();
g.sync(&mut sim);
sim.add_force(NodeExclusion::default());
sim.set_affinity_force(Some(AffinitySpring::new([(a, b, 0.9), (c, d, 0.1)])));
for _ in 0..300 {
sim.tick(1.0 / 60.0);
}
let strong = distance(&sim, a, b);
let weak = distance(&sim, c, d);
assert!(
strong < weak,
"the higher-affinity pair should end closer: strong={strong}, weak={weak}"
);
}
#[test]
fn clearing_the_force_leaves_the_layout_in_place() {
let mut g = Nodes::default();
let a = g.at(-300.0, 0.0);
let b = g.at(300.0, 0.0);
let mut sim = Simulation::new();
g.sync(&mut sim);
sim.set_affinity_force(Some(AffinitySpring::new([(a, b, 1.0)])));
for _ in 0..120 {
sim.tick(1.0 / 60.0);
}
let before = distance(&sim, a, b);
sim.set_affinity_force(None);
let after = distance(&sim, a, b);
assert_eq!(before, after, "clearing the force must not move bodies");
assert_eq!(sim.affinity_pair_count(), 0, "the force is gone");
}
}