seiche 0.0.5

Kernel-free, rapier-backed force-directed graph layout: bodies bound to node keys, themable forces (exclusion, springs, boundary), and quint field couplings. A host feeds node keys + positions; seiche integrates.
Documentation
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! # seiche
//!
//! Rapier-backed force integration for Mere: the crate that realizes the graph's
//! bodies as motion. A *seiche* is the standing-wave oscillation of a lake or bay,
//! the whole body of water rocking rhythmically back and forth; it moves the *mere*
//! (a mere is a lake) the way this crate moves the graph's bodies. Sibling to the
//! `quint` field-algebra crate: `quint` defines the fields and couplings and resolves
//! them into forces; `seiche` integrates those forces (rapier bodies, collision,
//! stepping) into positions.
//!
//! ## Place in the architecture
//!
//! The host's graph is the source of truth for node identity, topology,
//! and the *committed* position used for persistence. seiche holds the rapier
//! world that drives the *projected* position — bodies bound to nodes, forces
//! from pluggable [`Force`] implementors, and a tick that mirrors body
//! translations back to the graph each step.
//!
//! Petgraph (inside kernel) owns topology; seiche owns physical state. Both sit at
//! the substrate tier, consumed by everything above.
//!
//! ## Forces
//!
//! - [`Simulation`] — owns the rapier world, a [`NodeKey`] ↔
//!   [`RigidBodyHandle`] bimap, position-based hit-test / cull, and the
//!   registered forces.
//! - [`Simulation::sync_nodes`] / [`Simulation::sync_edges`] — keep bodies
//!   and edge topology in step with the host's node/edge lists. Idempotent.
//! - [`Simulation::tick`] — apply each registered [`Force`], then step the world.
//! - Built-in forces ([`NodeExclusion`], [`EdgeSpring`], [`Boundary`]) are the
//!   fast Rust default-path; `quint`'s couplings are the general, scriptable
//!   path that compiles to the same [`Force`] contract.
//!
//! Until a [`Force`] is registered, the world ticks empty — bodies settle to
//! rest under damping alone.
//!
//! ## Decomposition
//!
//! The `Simulation` impl is split across files by concern so no one stays over
//! the per-file size ceiling: the struct + `new` + force registration + read
//! model + the [`tick`](Simulation::tick) heartbeat live here; the node-body
//! shape/material axis in [`node_body`], body lifecycle in [`sync`], the rigid
//! scene tier in [`scene_sim`], the fluid seam in [`fluid_coupling`], the
//! force-field tier in [`field`], and emitters in [`emitter`]. (Rust lets an
//! `impl` span modules; private fields stay reachable from these child modules.)

#![doc(html_root_url = "https://docs.rs/seiche/0.0.1")]

use std::collections::HashMap;

use euclid::default::{Box2D, Point2D};
use rapier2d::prelude::*;

/// The opaque identifier seiche binds a body to: petgraph's stable node index, the
/// same type mere's kernel and chartulary use as `NodeKey`. A consumer supplies its
/// own keys (from any graph, or minted directly); seiche never inspects them.
pub type NodeKey = petgraph::stable_graph::NodeIndex;

/// Built-in force forces for the force-directed orrery layout.
pub mod forces;
pub use forces::{Boundary, EdgeSpring, NodeExclusion};

/// Barnes–Hut quadtree for O(n log n) approximate n-body repulsion — harvested
/// from the retired `graph-layout`, for big-graph charge repulsion. The
/// [`barnes_hut::repulsion_forces`] primitive is ready; wiring it as a live
/// [`Force`] is a tuning step (it would supplement [`NodeExclusion`]'s local
/// separation with global spreading).
pub mod barnes_hut;
pub use barnes_hut::{BarnesHutConfig, BarnesHutRepulsion, repulsion_forces};

/// The aether→seiche seam: a [`numen::Coupling`] compiled to a
/// [`Force`] (the general, scriptable path the built-in forces specialize).
pub mod coupling_force;
pub use coupling_force::CouplingForce;

/// The pairwise **affinity** force: a weighted, attract-only spring over a
/// `(a, b, weight)` signal that clusters structurally-similar nodes ("cluster by
/// affinity" on force-directed). (Graph signals — P4.)
pub mod affinity_force;
pub use affinity_force::{
    AffinitySpring, DEFAULT_AFFINITY_REST_LENGTH, DEFAULT_AFFINITY_STIFFNESS,
};

pub mod anchor_force;
pub use anchor_force::{AnchorSpring, DEFAULT_ANCHOR_SLACK, DEFAULT_ANCHOR_STIFFNESS};

/// Position-Based Fluids (PBF): our own small SPH liquid for the orrery (salva lags rapier badly,
/// so we roll our own). The solver lives here; its seam onto the rigid world (loading + the two-way
/// coupling) is [`Simulation`]'s fluid tier in [`fluid_coupling`]. (Physics scenes P4c.)
pub mod fluid;
pub use fluid::{Basin, ContactShape, Fluid, FluidContact, FluidParams};

/// The declarative scene library: ready-made [`SceneSpec`]s the orrery loads behind the
/// graph (drop-bowl, pyramid, dominoes, Galton board, funnel, drift, chain, whirlpool, fountain).
/// Data, not engine code; the growing catalog lives here to keep `lib.rs` under the size ceiling.
pub mod scenes;
pub use scenes::{
    ball_and_chain_scene, bridge_scene, chain_scene, cradle_scene, domino_scene, drift_scene,
    drop_bowl_scene, fountain_scene, funnel_scene, galton_scene, mixer_scene, pyramid_scene,
    whirlpool_scene,
};

/// The declarative scene **format**: the data types a [`SceneSpec`] is built from (bodies,
/// joints, world settings). Split from `lib.rs` because the format grows independently of the
/// simulation core. (Physics scenes P4b.)
mod scene_spec;
pub use scene_spec::{
    JointMotorSpec, SceneBodyId, SceneBodySpec, SceneBodyType, SceneEmitter, SceneField,
    SceneJoint, SceneJointSpec, SceneSpec,
};

/// The node-body axis: a node's collider **shape** ([`NodeCollider`]) and physical **material**
/// ([`NodeMaterial`]), and the [`Simulation`] methods that re-apply each to live bodies. (Node-rep.)
mod node_body;
pub use node_body::{NodeCollider, NodeMaterial};

/// The **sieve**: collision predicates as data — nodes carry [`Kinds`], a sieve scene body
/// blocks the kinds it names and passes the rest, computed by rapier's interaction groups
/// with no per-frame work. (Tactile tier T2.)
mod sift;
pub use sift::Kinds;

/// Node-body lifecycle on [`Simulation`]: reconciling the body set with the graph (`sync_*`),
/// the spring-edge topology, and the body accessors the read model is built from.
mod sync;

/// Read-only geometric **proposals** ("physics proposes, the record disposes"): containments
/// and supports, for the host to promote to facts at explicit commitments. (P1 + tactile T3.)
mod propose;
pub use propose::Support;

/// The rigid **scene** tier on [`Simulation`]: scene-decoration bodies, declarative [`SceneSpec`]
/// loading + joints, world gravity, and the per-node tangibility lever.
mod scene_sim;

/// The **fluid** tier on [`Simulation`]: loading the PBF pool and the two-way coupling between
/// pool and rapier bodies (the solver itself is [`fluid`]).
mod fluid_coupling;

/// The force-**field** tier on [`Simulation`] (a whirlpool / well) plus the actor's keep-ticking
/// predicate [`Simulation::wants_continuous_tick`].
mod field;

/// Continuous body **emitters** (fountains / streams) on [`Simulation`].
mod emitter;
use emitter::LiveEmitter;

/// Scene-geometry queries for the orrery canvas: edge geometry, edge picking,
/// and marquee rect-select (node point-pick + cull live on `Simulation`
/// directly). Split out to keep `lib.rs` under the per-file size ceiling.
mod query;

/// The rapier-free read model — a position-only [`LayoutView`] the host renders
/// and hit-tests from, plus the [`LayoutSnapshot`] a physics actor emits to
/// refresh it. The seam that lets the simulation run off the UI thread.
mod view;
pub use view::{LayoutSnapshot, LayoutView, RectSelection, SceneBodyView};

/// Physical radius used for every node body's collider.
///
/// Mirrors `platen::CanvasSceneOptions::default()`'s
/// `default_node_radius` so simulation-driven separation matches
/// the renderer's drawn radius. When per-node radii become a real
/// thing, this constant will get replaced by a per-node lookup.
pub const NODE_BODY_RADIUS: f32 = 18.0;

/// Density for node-body colliders, chosen so each node's mass is ~= 1.0
/// (mass = density * pi * r^2 ~= 0.001 * pi * 18^2 ~= 1.0). The layout forces in
/// [`forces`] are then intuitive accelerations rather than being swamped by the
/// large mass a default density would give an 18px ball.
pub const NODE_BODY_DENSITY: f32 = 0.001;

/// Linear damping applied to every node body. Tuned for a slippery,
/// inertial feel: a released node coasts a moment before settling, rather
/// than stopping dead. Low enough to glide, high enough that the layout
/// still comes to rest without continuous input.
const DEFAULT_LINEAR_DAMPING: f32 = 2.5;

/// Angular damping. Bodies don't visibly rotate in the orrery
/// renderer (circles are isotropic), but rapier still tracks angular
/// velocity; high damping prevents the integrator from accumulating
/// spurious spin.
const DEFAULT_ANGULAR_DAMPING: f32 = 4.0;

/// Upper bound on bodies a single [`SceneSpec`] loads (and a live emitter spawns), so a runaway
/// scene can't swamp the physics actor's per-tick budget. (Physics scenes P3.)
const SCENE_BODY_CAP: usize = 200;

/// Collision groups that keep the graph and the scene from hard-colliding by
/// default. Node colliders are in [`NODE_GROUP`] and collide only with other nodes
/// (intangible to the scene); scene colliders are in [`SCENE_GROUP`] and collide
/// with each other while *admitting* nodes — so a node opts into touching the scene
/// by adding [`SCENE_GROUP`] to its own filter (the tangibility lever, P2). rapier's
/// pairwise test needs both sides to admit the other, so the node's filter alone
/// gates node-scene contact. (Physics scenes P1.)
const NODE_GROUP: Group = Group::GROUP_1;
const SCENE_GROUP: Group = Group::GROUP_2;

/// Interaction groups for a scene-decoration collider: member of [`SCENE_GROUP`],
/// colliding with the scene and admitting nodes (a node still passes through unless
/// its own filter opts in).
fn scene_groups() -> InteractionGroups {
    InteractionGroups::new(
        SCENE_GROUP,
        SCENE_GROUP | NODE_GROUP,
        InteractionTestMode::And,
    )
}

/// A pluggable force-applier. Forces read the body store and apply
/// forces / impulses; seiche's tick walks every registered force
/// before stepping the world.
///
/// Implementors should be cheap — the tick budget is ~16ms total —
/// and write through `bodies.get_mut(...).add_force(...)` or
/// equivalent. Forces are queried in registration order each tick.
pub trait Force: Send {
    fn apply(&self, ctx: &mut ForceContext<'_>, dt: f32);
}

/// The complete law a [`RepulsionSolver`] must preserve.
///
/// A solver receives this rather than loose constants so it cannot quietly omit
/// `NodeExclusion`'s cutoff or substitute smooth softening for its hard floor.
#[derive(Clone, Copy, Debug)]
pub struct RepulsionRequest {
    pub strength: f32,
    pub cutoff: f32,
    pub min_distance: f32,
}

/// A validated force vector returned by a [`RepulsionSolver`].
#[derive(Clone, Debug)]
pub struct RepulsionForces {
    x: Vec<f32>,
    y: Vec<f32>,
}

impl RepulsionForces {
    /// Construct output for exactly `expected` bodies, rejecting a bad or
    /// non-finite result before it can enter Rapier.
    pub fn new(expected: usize, x: Vec<f32>, y: Vec<f32>) -> Result<Self, RepulsionSolverError> {
        if x.len() != expected || y.len() != expected {
            return Err(RepulsionSolverError::OutputLength {
                expected,
                x: x.len(),
                y: y.len(),
            });
        }
        for (index, value) in x.iter().enumerate() {
            if !value.is_finite() {
                return Err(RepulsionSolverError::NonFinite {
                    index,
                    component: RepulsionComponent::X,
                });
            }
        }
        for (index, value) in y.iter().enumerate() {
            if !value.is_finite() {
                return Err(RepulsionSolverError::NonFinite {
                    index,
                    component: RepulsionComponent::Y,
                });
            }
        }
        Ok(Self { x, y })
    }

    pub fn components(&self) -> (&[f32], &[f32]) {
        (&self.x, &self.y)
    }
}

/// One component of an invalid solver result.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RepulsionComponent {
    X,
    Y,
}

/// A solver result that was unsafe to apply to the Rapier world.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RepulsionSolverError {
    OutputLength {
        expected: usize,
        x: usize,
        y: usize,
    },
    NonFinite {
        index: usize,
        component: RepulsionComponent,
    },
    Backend(String),
}

impl std::fmt::Display for RepulsionSolverError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::OutputLength { expected, x, y } => write!(
                formatter,
                "repulsion solver returned {x} x-forces and {y} y-forces for {expected} bodies"
            ),
            Self::NonFinite { index, component } => {
                write!(
                    formatter,
                    "repulsion solver returned non-finite {component:?} force at {index}"
                )
            }
            Self::Backend(error) => write!(formatter, "repulsion solver failed: {error}"),
        }
    }
}

impl std::error::Error for RepulsionSolverError {}

/// A host-injected, CPU-integrator pairwise-repulsion solver.
///
/// This is a staging seam: positions are supplied as host slices and validated
/// forces return to Rapier. It is not the GPU-resident simulation interface;
/// resident hosts keep buffers and scheduling at `quint::resident` instead.
/// [`NodeExclusion`] routes to it above [`Simulation::set_repulsion_solver`]'s
/// threshold, falling back to its CPU law if it fails.
pub type RepulsionSolver = std::sync::Arc<
    dyn Fn(&[f32], &[f32], RepulsionRequest) -> Result<RepulsionForces, RepulsionSolverError>
        + Send
        + Sync,
>;

/// Default node count above which [`NodeExclusion`] uses an installed
/// [`RepulsionSolver`]. This is only a host-configurable staging guard, not a
/// residency or Barnes–Hut crossover claim; hosts set it from their own receipt.
pub const DEFAULT_GPU_REPULSION_THRESHOLD: usize = 1_000;

/// Per-tick view a [`Force`] sees: mutable access to the rapier body
/// store plus the NodeKey ↔ handle bimap so forces can reason about
/// pairs / topology when they need to.
pub struct ForceContext<'a> {
    pub bodies: &'a mut RigidBodySet,
    pub colliders: &'a ColliderSet,
    pub joints: &'a mut ImpulseJointSet,
    pub bodies_by_node: &'a HashMap<NodeKey, RigidBodyHandle>,
    /// Topology the layout forces pull along (e.g. [`EdgeSpring`]). Node-key
    /// pairs, set via [`Simulation::sync_edges`]; seiche stays relation-taxonomy
    /// agnostic, so the caller decides which edge families feed the layout.
    pub edges: &'a [(NodeKey, NodeKey)],
    /// Host-injected staging solver + the threshold above which
    /// [`NodeExclusion`] routes to it, threaded from the [`Simulation`]. `None`
    /// = always the native CPU scan.
    pub repulsion_solver: Option<&'a RepulsionSolver>,
    pub gpu_repulsion_threshold: usize,
}

/// One rapier world + bookkeeping. The host owns one of these per
/// graph; seiche stays pure (no global state, no static handles).
pub struct Simulation {
    pipeline: PhysicsPipeline,
    parameters: IntegrationParameters,
    gravity: Vector,
    islands: IslandManager,
    broad_phase: DefaultBroadPhase,
    narrow_phase: NarrowPhase,
    bodies: RigidBodySet,
    colliders: ColliderSet,
    impulse_joints: ImpulseJointSet,
    multibody_joints: MultibodyJointSet,
    ccd_solver: CCDSolver,
    bodies_by_node: HashMap<NodeKey, RigidBodyHandle>,
    edges: Vec<(NodeKey, NodeKey)>,
    forces: Vec<Box<dyn Force>>,
    /// Field couplings as a separately-replaceable force list (built-in layout
    /// forces stay in `forces`). A `CouplingForce` snapshots its target node set at
    /// build time, so a field move / resize / new node needs the whole set
    /// re-resolved — the host rebuilds these wholesale via
    /// [`set_coupling_forces`](Self::set_coupling_forces). (Field regions —
    /// rebuild-on-mutation.)
    coupling_forces: Vec<CouplingForce>,
    /// The pairwise **affinity** force, if installed: a weighted attract-only spring that clusters
    /// structurally-similar nodes ("cluster by affinity"). Like the couplings it is a snapshot —
    /// the host rebuilds it wholesale via [`set_affinity_force`](Self::set_affinity_force) when the
    /// affinity signal recomputes — and it applies in the same reset window as the built-ins.
    /// `None` = off (the default). (Graph signals — P4.)
    affinity_force: Option<AffinitySpring>,
    /// Per-node springs toward arrangement-chosen slots: the layout as a
    /// participant in the simulation rather than an override of it. Rebuilt
    /// wholesale via [`set_anchor_force`](Self::set_anchor_force).
    anchor_force: Option<AnchorSpring>,
    /// Optional host-injected staging solver + the node count above which
    /// [`NodeExclusion`] routes to it instead of its native CPU scan. `None` =
    /// always native (the default). This does not give Rapier resident ownership.
    repulsion_solver: Option<RepulsionSolver>,
    gpu_repulsion_threshold: usize,
    /// Linear damping applied to every node body — runtime-tunable (the "inertia"
    /// the physics settings expose): lower keeps more drift after a settle, higher
    /// brings nodes to rest sooner. New bodies take this; [`set_linear_damping`]
    /// also re-applies it to the live ones. (Physics settings.)
    linear_damping: f32,
    /// Non-graph scene-decoration bodies sharing this world (the "living backdrop" /
    /// interactive scene), each stored as `(handle, collider shape)` keyed by a
    /// [`SceneBodyId`]. The shape rides along so the host can paint the true face (P4b).
    /// They tick and collide like any body but carry no [`NodeKey`], so the layout forces
    /// (which key off `bodies_by_node`) ignore them. (Physics scenes P1.)
    scene_bodies: HashMap<SceneBodyId, (RigidBodyHandle, NodeCollider)>,
    /// Sparse sprite handles for scene bodies that wear one (a textured crate / barrel), keyed by
    /// [`SceneBodyId`]. An opaque host key seiche never interprets — it rides through to the body's
    /// [`SceneBodyView`] for the paint, like the collider shape. Most props have none. (Scene-prop
    /// sprites.)
    scene_sprites: HashMap<SceneBodyId, String>,
    /// Monotonic id source for [`scene_bodies`](Self::scene_bodies).
    next_scene_id: u64,
    /// Whether the loaded scene wants to keep moving forever (a perpetual backdrop) rather
    /// than settle — the physics actor reads this via [`Self::scene_perpetual`] to keep
    /// ticking instead of parking at rest. Reset by [`Self::clear_scene`]. (Physics scenes P4a.)
    scene_perpetual: bool,
    /// The liquid pool sharing this world, if any ([`fluid`] PBF). `None` until one is loaded;
    /// stepped each [`Self::tick`] and emitted in the snapshot for rendering. (Physics scenes P4c.)
    fluid: Option<Fluid>,
    /// Scene-wide tangibility lever state (mirrors [`Self::set_nodes_tangible`]): when `true`, node
    /// bodies couple to the fluid (the graph stirs the pool); when `false` they pass through. (P4c.)
    nodes_tangible: bool,
    /// The sieve state (tactile T2): each node's declared [`Kinds`] and each sieve scene
    /// body's blocked set, remembered so body re-syncs and tangibility remasks compose.
    sift: sift::Sift,
    /// Per-node material overrides (tactile T1), remembered so a re-synced body comes back
    /// with the material it was tuned to, not the spawn defaults.
    node_materials: HashMap<NodeKey, NodeMaterial>,
    /// A continuous force-field over the scene's dynamic bodies (a whirlpool / well), if any. Keeps
    /// the actor ticking while set; cleared by [`Self::clear_scene`]. (Physics scenes P4 fields.)
    scene_field: Option<SceneField>,
    /// Continuous body emitters (fountains / streams). Stepped each tick: spawn by rate, reap by
    /// age. Keep the actor ticking while present. (Physics scenes — emitters.)
    emitters: Vec<LiveEmitter>,
}

impl Default for Simulation {
    fn default() -> Self {
        Self::new()
    }
}

impl Simulation {
    pub fn new() -> Self {
        let mut parameters = IntegrationParameters::default();
        // Mere lives at world-coordinate scale where 1 unit ≈ 1
        // pixel — the default 1/60s timestep is fine, but we also
        // expose `tick(dt)` so callers can vary it.
        parameters.dt = 1.0 / 60.0;
        Self {
            pipeline: PhysicsPipeline::new(),
            parameters,
            // No global gravity — forces supply directional forces
            // when they want them. A "gravity" force is just another
            // Force impl.
            gravity: Vector::ZERO,
            islands: IslandManager::new(),
            broad_phase: DefaultBroadPhase::new(),
            narrow_phase: NarrowPhase::new(),
            bodies: RigidBodySet::new(),
            colliders: ColliderSet::new(),
            impulse_joints: ImpulseJointSet::new(),
            multibody_joints: MultibodyJointSet::new(),
            ccd_solver: CCDSolver::new(),
            bodies_by_node: HashMap::new(),
            edges: Vec::new(),
            forces: Vec::new(),
            coupling_forces: Vec::new(),
            affinity_force: None,
            anchor_force: None,
            repulsion_solver: None,
            gpu_repulsion_threshold: DEFAULT_GPU_REPULSION_THRESHOLD,
            linear_damping: DEFAULT_LINEAR_DAMPING,
            scene_bodies: HashMap::new(),
            scene_sprites: HashMap::new(),
            next_scene_id: 0,
            scene_perpetual: false,
            fluid: None,
            nodes_tangible: false,
            sift: sift::Sift::default(),
            node_materials: HashMap::new(),
            scene_field: None,
            emitters: Vec::new(),
        }
    }

    /// The linear damping every node body carries (the "inertia" tunable).
    pub fn linear_damping(&self) -> f32 {
        self.linear_damping
    }

    /// Set the linear damping for new node bodies and re-apply it to every live
    /// one, so a settings change takes effect immediately rather than only for
    /// nodes added afterward. (Physics settings.)
    pub fn set_linear_damping(&mut self, damping: f32) {
        self.linear_damping = damping;
        for (_, body) in self.bodies.iter_mut() {
            body.set_linear_damping(damping);
        }
    }

    /// Register a force. Forces apply in registration order on every
    /// tick.
    pub fn add_force<F: Force + 'static>(&mut self, force: F) {
        self.forces.push(Box::new(force));
    }

    pub fn force_count(&self) -> usize {
        self.forces.len()
    }

    /// Replace the field-coupling forces wholesale (the built-in layout forces in
    /// `forces` are untouched). The host re-resolves every coupling against the
    /// current graph + node set and hands the fresh set here — the move / resize /
    /// new-node rebuild. Position-preserving: forces never touch body state, so
    /// swapping them leaves the layout exactly where it is. (Field regions.)
    pub fn set_coupling_forces(&mut self, forces: Vec<CouplingForce>) {
        self.coupling_forces = forces;
    }

    /// Number of field-coupling forces currently applied.
    pub fn coupling_force_count(&self) -> usize {
        self.coupling_forces.len()
    }

    /// Install (or clear, with `None`) the host's staging repulsion solver and its
    /// routing threshold. The closure receives the complete [`RepulsionRequest`]
    /// and must return validated output; failure falls back to the native CPU law.
    /// This does not make this Rapier simulation GPU-resident. See
    /// [`RepulsionSolver`].
    pub fn set_repulsion_solver(&mut self, solver: Option<RepulsionSolver>, threshold: usize) {
        self.repulsion_solver = solver;
        self.gpu_repulsion_threshold = threshold.max(1);
    }

    /// Install (or clear, with `None`) the pairwise **affinity** force wholesale — the rebuild a
    /// fresh affinity signal triggers. Position-preserving (forces never touch body state), so
    /// swapping it leaves the layout exactly where it is; the host follows with a `settle` to let
    /// the new equilibrium take. (Graph signals — P4.)
    pub fn set_affinity_force(&mut self, force: Option<AffinitySpring>) {
        self.affinity_force = force;
    }

    /// Install (or clear, with `None`) per-node **anchor** springs toward an
    /// arrangement's chosen slots. This is how a layout composes with running
    /// physics: rather than overriding positions, it pulls toward them while
    /// repulsion, edge springs, collisions, coupled fields, and drag keep
    /// acting. Position-preserving, like every other force swap; the host
    /// follows with a `settle` to let the new equilibrium take.
    pub fn set_anchor_force(&mut self, force: Option<AnchorSpring>) {
        self.anchor_force = force;
    }

    /// How many nodes the installed anchor force pulls (`0` when none is set).
    pub fn anchor_count(&self) -> usize {
        self.anchor_force.as_ref().map_or(0, AnchorSpring::len)
    }

    /// Number of affinity pairs the installed affinity force pulls along (`0` when none is set).
    pub fn affinity_pair_count(&self) -> usize {
        self.affinity_force
            .as_ref()
            .map_or(0, AffinitySpring::pair_count)
    }

    /// A rapier-free [`LayoutView`] over the current layout: the live positions,
    /// the spring edge topology, and the node radius the picks/cull use. The host
    /// reads node picks, edge picks, and cull from this rather than the rapier
    /// query index, so those reads can run on the UI thread while the simulation
    /// itself ticks elsewhere (the always-offload physics actor, P6).
    pub fn view(&self) -> LayoutView {
        LayoutView::from_parts(
            self.positions(),
            self.edges.iter().copied(),
            NODE_BODY_RADIUS,
        )
    }

    /// A `Send` [`LayoutSnapshot`] of the current positions, stamped with
    /// `generation` — the payload a physics actor emits each tick for the host to
    /// fold into its [`LayoutView`]. Positions only; edges stay with the host's
    /// graph, so they need not cross the actor boundary every frame.
    pub fn snapshot(&self, generation: u64) -> LayoutSnapshot {
        LayoutSnapshot {
            positions: self.positions().collect(),
            scene: self.scene_bodies().collect(),
            fluid: self
                .fluid
                .as_ref()
                .map(|f| f.positions().collect())
                .unwrap_or_default(),
            fluid_radius: self
                .fluid
                .as_ref()
                .map(|f| f.params().particle_radius)
                .unwrap_or(0.0),
            generation,
        }
    }

    /// Retained for call-site compatibility; a no-op now. [`Self::hit_test`] and
    /// [`Self::cull_aabb`] read live body translations directly (the rapier
    /// `QueryPipeline` went ephemeral in rapier 0.33), so there is no separate
    /// index to refresh after moving bodies outside a tick.
    pub fn refresh_spatial_index(&mut self) {}

    /// Hit-test a world-space point: the node whose body lies within
    /// [`NODE_BODY_RADIUS`] of it, or `None`. Reads live positions, so it always
    /// reflects the most recent [`Self::tick`]. Node bodies are kept separated,
    /// so on the rare overlap this returns one of the hits, not a defined
    /// "topmost".
    ///
    /// Position-and-radius, matching the rapier-free [`LayoutView`] the orrery
    /// actually picks from on the UI thread — the two stay consistent. (Restore
    /// shape-accurate, collider-true picking in `LayoutView` if a non-ball node
    /// face ever needs it; that is the live path, not this in-thread helper.)
    pub fn hit_test(&self, point: Point2D<f32>) -> Option<NodeKey> {
        let r2 = NODE_BODY_RADIUS * NODE_BODY_RADIUS;
        self.positions()
            .find(|(_, p)| (*p - point).square_length() <= r2)
            .map(|(node, _)| node)
    }

    /// Frustum cull: every node whose body (center ± [`NODE_BODY_RADIUS`])
    /// intersects `region` (world space). Reads live positions. Order is
    /// unspecified.
    pub fn cull_aabb(&self, region: Box2D<f32>) -> Vec<NodeKey> {
        let r = NODE_BODY_RADIUS;
        self.positions()
            .filter(|(_, p)| {
                Box2D::new(
                    Point2D::new(p.x - r, p.y - r),
                    Point2D::new(p.x + r, p.y + r),
                )
                .intersects(&region)
            })
            .map(|(node, _)| node)
            .collect()
    }

    /// Advance the simulation by `dt` seconds. Walks every registered
    /// [`Force`] first (so forces accumulate), then steps the world. Reading
    /// the settled layout back is a separate call — [`Simulation::positions`]
    /// — so callers use the positions for whatever they like (write them into
    /// their own graph, draw debug overlays, and so on).
    pub fn tick(&mut self, dt: f32) {
        if !dt.is_finite() || dt <= 0.0 {
            return;
        }
        self.parameters.dt = dt;

        // Emitters spawn / reap scene bodies before the step, so fresh droplets are simulated this
        // frame. (Physics scenes — emitters.)
        self.step_emitters(dt);

        // rapier's `add_force` is a *persistent* force (it survives across
        // steps until reset), so clear last tick's force forces before this
        // tick's forces set fresh ones. Without this, per-tick forces compound
        // and the layout goes unstable.
        if !self.forces.is_empty()
            || !self.coupling_forces.is_empty()
            || self.affinity_force.is_some()
            || self.anchor_force.is_some()
            || self.scene_field.is_some()
        {
            for (_, body) in self.bodies.iter_mut() {
                body.reset_forces(false);
            }
            let mut ctx = ForceContext {
                bodies: &mut self.bodies,
                colliders: &self.colliders,
                joints: &mut self.impulse_joints,
                bodies_by_node: &self.bodies_by_node,
                edges: &self.edges,
                repulsion_solver: self.repulsion_solver.as_ref(),
                gpu_repulsion_threshold: self.gpu_repulsion_threshold,
            };
            for force in &self.forces {
                force.apply(&mut ctx, dt);
            }
            // Field couplings apply after the built-ins, in the same reset window.
            for force in &self.coupling_forces {
                force.apply(&mut ctx, dt);
            }
            // The affinity force (if installed) applies last, over the same context — a weighted
            // clustering pull on top of the topology springs. (Graph signals — P4.)
            if let Some(force) = &self.affinity_force {
                force.apply(&mut ctx, dt);
            }
            // Anchor springs last: the arrangement's pull sits on top of the
            // graph's own forces, so stiffness reads as "how much does the
            // arrangement win". (Arrangement as attractor.)
            if let Some(force) = &self.anchor_force {
                force.apply(&mut ctx, dt);
            }
        }

        // The scene force-field (a whirlpool / well) drives the dynamic scene bodies — applied after
        // the force loops (so the body borrow is free), still before the step. (Physics scenes P4.)
        self.apply_scene_field();

        let physics_hooks = ();
        let event_handler = ();
        self.pipeline.step(
            self.gravity,
            &self.parameters,
            &mut self.islands,
            &mut self.broad_phase,
            &mut self.narrow_phase,
            &mut self.bodies,
            &mut self.colliders,
            &mut self.impulse_joints,
            &mut self.multibody_joints,
            &mut self.ccd_solver,
            &physics_hooks,
            &event_handler,
        );

        // Step the liquid pool (if any) after the rigid world; it reads the same dt and folds into
        // the same snapshot. (Physics scenes P4c.)
        if let Some(fluid) = &mut self.fluid {
            fluid.step(dt);
        }
        // Two-way coupling: the pool bounces off the scene bodies + (when the graph is tangible) the
        // node bodies, and shoves the dynamic ones back. (Physics scenes P4c.)
        self.couple_fluid_to_bodies();
    }

    // `write_positions_to(&mut Graph)` — which copied each body's translation back
    // onto its graph node — left when seiche became kernel-free (it had no mere
    // consumer). The host reads [`Self::positions`] and writes them into its own
    // graph; mere's position write-back is a host concern (and a node-dissolution
    // target).

    /// True when every body's linear velocity is below
    /// `velocity_epsilon`. Useful for "suspend the tick when the
    /// graph is at rest" idle-detection.
    pub fn is_at_rest(&self, velocity_epsilon: f32) -> bool {
        let eps_sq = velocity_epsilon * velocity_epsilon;
        for (_, body) in self.bodies.iter() {
            let v = body.linvel();
            if v.x * v.x + v.y * v.y > eps_sq {
                return false;
            }
        }
        true
    }

    /// Pin a node's body to a position via a kinematic-position
    /// override. Use this during a drag: call `pin` while the user
    /// holds the mouse, then `unpin` on release so other forces can
    /// react to the final position again.
    pub fn pin(&mut self, node: NodeKey, position: Point2D<f32>) {
        let Some(handle) = self.bodies_by_node.get(&node).copied() else {
            return;
        };
        let Some(body) = self.bodies.get_mut(handle) else {
            return;
        };
        body.set_body_type(RigidBodyType::KinematicPositionBased, true);
        body.set_next_kinematic_translation(Vector::new(position.x, position.y));
    }

    pub fn unpin(&mut self, node: NodeKey) {
        let Some(handle) = self.bodies_by_node.get(&node).copied() else {
            return;
        };
        let Some(body) = self.bodies.get_mut(handle) else {
            return;
        };
        body.set_body_type(RigidBodyType::Dynamic, true);
    }
}

// The simulation must be `Send` so a host can build it on, and run its tick on,
// a dedicated physics actor thread (P6 always-offload). It is intentionally not
// required to be `Sync` — only one thread (the actor) ever touches it.
const _: fn() = || {
    fn assert_send<T: Send>() {}
    assert_send::<Simulation>();
    assert_send::<LayoutSnapshot>();
};

// The simulation + built-in-force test suite, now kernel-free (drives the
// physics through `sync_nodes` / `sync_edges`, not a mere `Graph`).
#[cfg(test)]
mod tests;

/// Integration tests for the scene / fluid / field / emitter tiers (split alongside them).
#[cfg(test)]
mod scene_tests;