use super::*;
#[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 keys(&self) -> Vec<NodeKey> {
self.list.iter().map(|(k, _)| *k).collect()
}
fn sync(&self, sim: &mut Simulation) {
sim.sync_nodes(self.list.iter().copied());
}
}
fn two_nodes() -> Nodes {
let mut n = Nodes::default();
n.at(0.0, 0.0);
n.at(100.0, 0.0);
n
}
fn n_nodes(count: usize) -> Nodes {
let mut n = Nodes::default();
for i in 0..count {
n.at(i as f32 * 10.0, 0.0);
}
n
}
fn separation(sim: &Simulation, a: NodeKey, b: NodeKey) -> f32 {
(sim.position_of(a).unwrap() - sim.position_of(b).unwrap()).length()
}
fn radius_from_origin(sim: &Simulation, a: NodeKey) -> f32 {
sim.position_of(a).unwrap().to_vector().length()
}
fn recording_push_solver(calls: std::sync::Arc<std::sync::atomic::AtomicUsize>) -> RepulsionSolver {
std::sync::Arc::new(move |xs: &[f32], _ys: &[f32], _request: RepulsionRequest| {
calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
RepulsionForces::new(xs.len(), vec![1_000_000.0; xs.len()], vec![0.0; xs.len()])
})
}
#[test]
fn repulsion_solver_routes_only_above_threshold() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let mut sim = Simulation::new();
sim.add_force(NodeExclusion::default());
n_nodes(3).sync(&mut sim);
let calls = Arc::new(AtomicUsize::new(0));
sim.set_repulsion_solver(Some(recording_push_solver(calls.clone())), 10);
for _ in 0..5 {
sim.tick(1.0 / 60.0);
}
assert_eq!(
calls.load(Ordering::SeqCst),
0,
"below threshold stays naive"
);
let mut sim = Simulation::new();
sim.add_force(NodeExclusion::default());
let nodes = n_nodes(3);
nodes.sync(&mut sim);
let calls = Arc::new(AtomicUsize::new(0));
sim.set_repulsion_solver(Some(recording_push_solver(calls.clone())), 3);
for _ in 0..10 {
sim.tick(1.0 / 60.0);
}
let keys = nodes.keys();
let mean_x: f32 = keys
.iter()
.filter_map(|&k| sim.position_of(k).map(|p| p.x))
.sum::<f32>()
/ keys.len() as f32;
assert!(
calls.load(Ordering::SeqCst) >= 10,
"solver consulted each tick"
);
assert!(
mean_x > 0.0,
"the solver's +x push moved the layout right: {mean_x}"
);
}
#[test]
fn repulsion_solver_output_is_checked_before_rapier_sees_it() {
assert!(matches!(
RepulsionForces::new(2, vec![1.0], vec![0.0, 0.0]),
Err(RepulsionSolverError::OutputLength {
expected: 2,
x: 1,
y: 2,
})
));
assert!(matches!(
RepulsionForces::new(1, vec![f32::NAN], vec![0.0]),
Err(RepulsionSolverError::NonFinite {
component: RepulsionComponent::X,
index: 0,
})
));
}
#[cfg(feature = "gpu-bench")]
#[test]
#[ignore]
fn settle_timing_naive_vs_gpu_solver() {
use std::sync::Arc;
const TICKS: usize = 20;
let solver: RepulsionSolver = Arc::new(|xs: &[f32], ys: &[f32], request: RepulsionRequest| {
quint::forces::node_exclusion_wgpu_roundtrip(
xs,
ys,
quint::forces::NodeExclusionParams {
strength: request.strength,
cutoff: request.cutoff,
min_distance: request.min_distance,
},
)
.map_err(|error| RepulsionSolverError::Backend(error.to_string()))
.and_then(|(fx, fy)| RepulsionForces::new(xs.len(), fx, fy))
});
for n in [1_000usize, 2_000, 4_000] {
let nodes = n_nodes(n);
let build = || {
let mut sim = Simulation::new();
sim.add_force(NodeExclusion::default());
sim.add_force(EdgeSpring::default());
sim.add_force(Boundary::default());
nodes.sync(&mut sim);
sim
};
let mut cpu = build();
let t = std::time::Instant::now();
for _ in 0..TICKS {
cpu.tick(1.0 / 60.0);
}
let cpu_ms = t.elapsed().as_millis() as f64 / TICKS as f64;
let mut gpu = build();
gpu.set_repulsion_solver(Some(solver.clone()), 0);
gpu.tick(1.0 / 60.0); let t = std::time::Instant::now();
for _ in 0..TICKS {
gpu.tick(1.0 / 60.0);
}
let gpu_ms = t.elapsed().as_millis() as f64 / TICKS as f64;
println!(
"N={n}: cpu={cpu_ms:.2}ms/tick burn-roundtrip={gpu_ms:.2}ms/tick ({:.2}x)",
cpu_ms / gpu_ms
);
}
}
#[test]
fn sync_creates_bodies_for_new_nodes() {
let mut sim = Simulation::new();
let nodes = two_nodes();
nodes.sync(&mut sim);
assert_eq!(sim.body_count(), 2);
for key in nodes.keys() {
assert!(sim.body_for(key).is_some());
}
}
#[test]
fn sync_is_idempotent() {
let mut sim = Simulation::new();
let nodes = two_nodes();
nodes.sync(&mut sim);
nodes.sync(&mut sim);
nodes.sync(&mut sim);
assert_eq!(sim.body_count(), 2);
}
#[test]
fn empty_simulation_settles_to_rest() {
let mut sim = Simulation::new();
two_nodes().sync(&mut sim);
for _ in 0..120 {
sim.tick(1.0 / 60.0);
}
assert!(sim.is_at_rest(0.01));
}
#[test]
fn hit_test_and_cull_resolve_nodes_by_position() {
let mut sim = Simulation::new();
two_nodes().sync(&mut sim);
sim.refresh_spatial_index();
let a = sim
.hit_test(Point2D::new(0.0, 0.0))
.expect("point inside node a");
let b = sim
.hit_test(Point2D::new(100.0, 0.0))
.expect("point inside node b");
assert_ne!(a, b, "the two centers resolve to different nodes");
assert!(
sim.hit_test(Point2D::new(5000.0, 5000.0)).is_none(),
"empty space hits nothing"
);
let near_origin = sim.cull_aabb(Box2D::new(
Point2D::new(-10.0, -10.0),
Point2D::new(10.0, 10.0),
));
assert_eq!(near_origin, vec![a]);
let everything = sim.cull_aabb(Box2D::new(
Point2D::new(-1000.0, -1000.0),
Point2D::new(1000.0, 1000.0),
));
assert_eq!(everything.len(), 2);
assert!(everything.contains(&a) && everything.contains(&b));
}
#[test]
fn node_exclusion_pushes_apart() {
let mut sim = Simulation::new();
let mut nodes = Nodes::default();
let a = nodes.at(0.0, 0.0);
let b = nodes.at(50.0, 0.0);
nodes.sync(&mut sim);
sim.add_force(NodeExclusion::default());
let before = separation(&sim, a, b);
for _ in 0..60 {
sim.tick(1.0 / 60.0);
}
assert!(
separation(&sim, a, b) > before,
"repulsion should increase separation"
);
}
#[test]
fn edge_spring_pulls_together() {
let mut sim = Simulation::new();
let mut nodes = Nodes::default();
let a = nodes.at(0.0, 0.0);
let b = nodes.at(400.0, 0.0);
nodes.sync(&mut sim);
sim.sync_edges([(a, b)]);
assert_eq!(sim.edge_count(), 1);
sim.add_force(EdgeSpring::default());
let before = separation(&sim, a, b);
for _ in 0..60 {
sim.tick(1.0 / 60.0);
}
assert!(
separation(&sim, a, b) < before,
"a stretched spring should contract"
);
}
#[test]
fn boundary_centers_toward_origin() {
let mut sim = Simulation::new();
let mut nodes = Nodes::default();
let a = nodes.at(500.0, 0.0);
nodes.sync(&mut sim);
sim.add_force(Boundary::default());
let before = radius_from_origin(&sim, a);
for _ in 0..60 {
sim.tick(1.0 / 60.0);
}
assert!(
radius_from_origin(&sim, a) < before,
"centering should pull the node toward the origin"
);
}
#[test]
fn full_layout_settles_separated_and_bounded() {
let mut sim = Simulation::new();
let mut nodes = Nodes::default();
let a = nodes.at(10.0, 0.0);
let b = nodes.at(-5.0, 8.0);
let c = nodes.at(-5.0, -8.0);
nodes.sync(&mut sim);
sim.sync_edges([(a, b), (b, c), (c, a)]);
sim.add_force(NodeExclusion::default());
sim.add_force(EdgeSpring::default());
sim.add_force(Boundary::default());
for _ in 0..4000 {
sim.tick(1.0 / 60.0);
}
assert!(
sim.is_at_rest(0.5),
"the layout should settle to rest under damping"
);
for (x, y) in [(a, b), (b, c), (c, a)] {
let d = separation(&sim, x, y);
assert!(d.is_finite(), "non-finite separation");
assert!(d >= 2.0 * NODE_BODY_RADIUS, "nodes overlap: {d}");
}
for k in [a, b, c] {
assert!(
radius_from_origin(&sim, k) < 5_000.0,
"centering failed; node escaped"
);
}
}
#[test]
fn node_queries_handle_orrery_scale() {
let mut sim = Simulation::new();
let n: usize = 32;
let spacing = 60.0_f32;
let mut nodes = Nodes::default();
let mut keys = Vec::new();
for i in 0..n {
for j in 0..n {
keys.push(nodes.at(i as f32 * spacing, j as f32 * spacing));
}
}
nodes.sync(&mut sim);
sim.refresh_spatial_index();
assert_eq!(sim.body_count(), n * n);
let target = keys[500];
let at = sim.position_of(target).unwrap();
assert_eq!(sim.hit_test(at), Some(target));
assert!(sim.hit_test(Point2D::new(-500.0, -500.0)).is_none());
let window = sim.cull_aabb(Box2D::new(
Point2D::new(-10.0, -10.0),
Point2D::new(190.0, 190.0),
));
assert!(
(9..64).contains(&window.len()),
"cull window not selective at scale: {}",
window.len()
);
}
#[test]
fn seed_positions_overrides_placement_and_round_trips() {
let mut sim = Simulation::new();
let nodes = two_nodes(); nodes.sync(&mut sim);
let keys = nodes.keys();
sim.seed_positions([
(keys[0], Point2D::new(300.0, 300.0)),
(keys[1], Point2D::new(-300.0, -300.0)),
]);
assert_eq!(sim.position_of(keys[0]), Some(Point2D::new(300.0, 300.0)));
assert_eq!(sim.position_of(keys[1]), Some(Point2D::new(-300.0, -300.0)));
let read: Vec<(NodeKey, Point2D<f32>)> = sim.positions().collect();
assert!(read.contains(&(keys[0], Point2D::new(300.0, 300.0))));
assert!(read.contains(&(keys[1], Point2D::new(-300.0, -300.0))));
}
#[test]
fn seeded_overlap_separates_under_physics() {
let mut sim = Simulation::new();
let mut nodes = Nodes::default();
let a = nodes.at(0.0, 0.0);
let b = nodes.at(0.0, 0.0);
nodes.sync(&mut sim);
sim.seed_positions([(a, Point2D::new(0.0, 0.0)), (b, Point2D::new(1.0, 0.0))]);
sim.add_force(NodeExclusion::default());
for _ in 0..240 {
sim.tick(1.0 / 60.0);
}
assert!(
separation(&sim, a, b) >= 2.0 * NODE_BODY_RADIUS,
"physics should separate a seeded overlap"
);
}
#[test]
fn node_exclusion_scales_to_many_nodes() {
let mut sim = Simulation::new();
let mut nodes = Nodes::default();
for i in 0..10 {
for j in 0..10 {
nodes.at((i as f32 - 4.5) * 50.0, (j as f32 - 4.5) * 50.0);
}
}
nodes.sync(&mut sim);
sim.add_force(NodeExclusion::default());
sim.add_force(Boundary::default());
let keys = nodes.keys();
assert_eq!(keys.len(), 100);
for _ in 0..60 {
sim.tick(1.0 / 60.0);
}
let mut max_radius = 0.0_f32;
for &k in &keys {
let p = sim.position_of(k).unwrap();
assert!(p.x.is_finite() && p.y.is_finite(), "non-finite position");
let r = radius_from_origin(&sim, k);
assert!(r < 50_000.0, "node escaped: {r}");
max_radius = max_radius.max(r);
}
assert!(max_radius > 50.0, "layout failed to spread: {max_radius}");
}
#[test]
fn node_collider_lowers_to_the_matching_parry_shape() {
assert_eq!(
NodeCollider::Ball { radius: 10.0 }
.to_shared_shape()
.shape_type(),
ShapeType::Ball
);
assert_eq!(
NodeCollider::Square { half: 10.0 }
.to_shared_shape()
.shape_type(),
ShapeType::Cuboid
);
assert_eq!(
NodeCollider::RoundedSquare {
half: 10.0,
border: 3.0
}
.to_shared_shape()
.shape_type(),
ShapeType::RoundCuboid,
);
let square_hull = NodeCollider::Hull {
points: vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)],
fallback: 5.0,
};
assert_eq!(
square_hull.to_shared_shape().shape_type(),
ShapeType::ConvexPolygon
);
let degenerate = NodeCollider::Hull {
points: vec![(0.0, 0.0)],
fallback: 5.0,
};
assert_eq!(degenerate.to_shared_shape().shape_type(), ShapeType::Ball);
}