#![doc(html_root_url = "https://docs.rs/seiche/0.0.1")]
use std::collections::HashMap;
use euclid::default::{Box2D, Point2D};
use rapier2d::prelude::*;
pub type NodeKey = petgraph::stable_graph::NodeIndex;
pub mod forces;
pub use forces::{Boundary, EdgeSpring, NodeExclusion};
pub mod barnes_hut;
pub use barnes_hut::{BarnesHutConfig, BarnesHutRepulsion, repulsion_forces};
pub mod coupling_force;
pub use coupling_force::CouplingForce;
pub mod affinity_force;
pub use affinity_force::{
AffinitySpring, DEFAULT_AFFINITY_REST_LENGTH, DEFAULT_AFFINITY_STIFFNESS,
};
pub mod fluid;
pub use fluid::{Basin, ContactShape, Fluid, FluidContact, FluidParams};
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,
};
mod scene_spec;
pub use scene_spec::{
JointMotorSpec, SceneBodyId, SceneBodySpec, SceneBodyType, SceneEmitter, SceneField,
SceneJoint, SceneJointSpec, SceneSpec,
};
mod node_body;
pub use node_body::{NodeCollider, NodeMaterial};
mod sync;
mod scene_sim;
mod fluid_coupling;
mod field;
mod emitter;
use emitter::LiveEmitter;
mod query;
mod view;
pub use view::{LayoutSnapshot, LayoutView, RectSelection, SceneBodyView};
pub const NODE_BODY_RADIUS: f32 = 18.0;
pub const NODE_BODY_DENSITY: f32 = 0.001;
const DEFAULT_LINEAR_DAMPING: f32 = 2.5;
const DEFAULT_ANGULAR_DAMPING: f32 = 4.0;
const SCENE_BODY_CAP: usize = 200;
const NODE_GROUP: Group = Group::GROUP_1;
const SCENE_GROUP: Group = Group::GROUP_2;
fn node_groups() -> InteractionGroups {
InteractionGroups::new(NODE_GROUP, NODE_GROUP, InteractionTestMode::And)
}
fn scene_groups() -> InteractionGroups {
InteractionGroups::new(
SCENE_GROUP,
SCENE_GROUP | NODE_GROUP,
InteractionTestMode::And,
)
}
pub trait Force: Send {
fn apply(&self, ctx: &mut ForceContext<'_>, dt: f32);
}
pub type RepulsionSolver =
std::sync::Arc<dyn Fn(&[f32], &[f32], f32, f32) -> (Vec<f32>, Vec<f32>) + Send + Sync>;
pub const DEFAULT_GPU_REPULSION_THRESHOLD: usize = 1_000;
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>,
pub edges: &'a [(NodeKey, NodeKey)],
pub repulsion_solver: Option<&'a RepulsionSolver>,
pub gpu_repulsion_threshold: usize,
}
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>>,
coupling_forces: Vec<CouplingForce>,
affinity_force: Option<AffinitySpring>,
repulsion_solver: Option<RepulsionSolver>,
gpu_repulsion_threshold: usize,
linear_damping: f32,
scene_bodies: HashMap<SceneBodyId, (RigidBodyHandle, NodeCollider)>,
scene_sprites: HashMap<SceneBodyId, String>,
next_scene_id: u64,
scene_perpetual: bool,
fluid: Option<Fluid>,
nodes_tangible: bool,
scene_field: Option<SceneField>,
emitters: Vec<LiveEmitter>,
}
impl Default for Simulation {
fn default() -> Self {
Self::new()
}
}
impl Simulation {
pub fn new() -> Self {
let mut parameters = IntegrationParameters::default();
parameters.dt = 1.0 / 60.0;
Self {
pipeline: PhysicsPipeline::new(),
parameters,
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,
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,
scene_field: None,
emitters: Vec::new(),
}
}
pub fn linear_damping(&self) -> f32 {
self.linear_damping
}
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);
}
}
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()
}
pub fn set_coupling_forces(&mut self, forces: Vec<CouplingForce>) {
self.coupling_forces = forces;
}
pub fn coupling_force_count(&self) -> usize {
self.coupling_forces.len()
}
pub fn set_repulsion_solver(&mut self, solver: Option<RepulsionSolver>, threshold: usize) {
self.repulsion_solver = solver;
self.gpu_repulsion_threshold = threshold.max(1);
}
pub fn set_affinity_force(&mut self, force: Option<AffinitySpring>) {
self.affinity_force = force;
}
pub fn affinity_pair_count(&self) -> usize {
self.affinity_force
.as_ref()
.map_or(0, AffinitySpring::pair_count)
}
pub fn view(&self) -> LayoutView {
LayoutView::from_parts(
self.positions(),
self.edges.iter().copied(),
NODE_BODY_RADIUS,
)
}
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,
}
}
pub fn refresh_spatial_index(&mut self) {}
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)
}
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(®ion)
})
.map(|(node, _)| node)
.collect()
}
pub fn tick(&mut self, dt: f32) {
if !dt.is_finite() || dt <= 0.0 {
return;
}
self.parameters.dt = dt;
self.step_emitters(dt);
if !self.forces.is_empty()
|| !self.coupling_forces.is_empty()
|| self.affinity_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);
}
for force in &self.coupling_forces {
force.apply(&mut ctx, dt);
}
if let Some(force) = &self.affinity_force {
force.apply(&mut ctx, dt);
}
}
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,
);
if let Some(fluid) = &mut self.fluid {
fluid.step(dt);
}
self.couple_fluid_to_bodies();
}
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
}
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);
}
}
const _: fn() = || {
fn assert_send<T: Send>() {}
assert_send::<Simulation>();
assert_send::<LayoutSnapshot>();
};
#[cfg(test)]
mod tests;
#[cfg(test)]
mod scene_tests;