nphysics3d/force_generator/
constant_acceleration.rs

1use na::RealField;
2
3use crate::force_generator::ForceGenerator;
4use crate::math::{Force, ForceType, Vector, Velocity};
5use crate::object::{BodyHandle, BodyPartHandle, BodySet};
6use crate::solver::IntegrationParameters;
7
8/// Force generator adding a constant acceleration
9/// at the center of mass of a set of body parts.
10pub struct ConstantAcceleration<N: RealField + Copy, Handle: BodyHandle> {
11    parts: Vec<BodyPartHandle<Handle>>,
12    acceleration: Velocity<N>,
13}
14
15impl<N: RealField + Copy, Handle: BodyHandle> ConstantAcceleration<N, Handle> {
16    /// Adds a new constant acceleration generator.
17    ///
18    /// The acceleration is expressed in world-space.
19    #[cfg(feature = "dim3")]
20    pub fn new(linear_acc: Vector<N>, angular_acc: Vector<N>) -> Self {
21        ConstantAcceleration {
22            parts: Vec::new(),
23            acceleration: Velocity::new(linear_acc, angular_acc),
24        }
25    }
26
27    /// Adds a new constant acceleration generator.
28    ///
29    /// The acceleration is expressed in world-space.
30    #[cfg(feature = "dim2")]
31    pub fn new(linear_acc: Vector<N>, angular_acc: N) -> Self {
32        ConstantAcceleration {
33            parts: Vec::new(),
34            acceleration: Velocity::new(linear_acc, angular_acc),
35        }
36    }
37
38    /// Add a body part to be affected by this force generator.
39    pub fn add_body_part(&mut self, body: BodyPartHandle<Handle>) {
40        self.parts.push(body)
41    }
42}
43
44impl<N: RealField + Copy, Handle: BodyHandle> ForceGenerator<N, Handle>
45    for ConstantAcceleration<N, Handle>
46{
47    fn apply(
48        &mut self,
49        _: &IntegrationParameters<N>,
50        bodies: &mut dyn BodySet<N, Handle = Handle>,
51    ) {
52        let acceleration = self.acceleration;
53        self.parts.retain(|h| {
54            if let Some(body) = bodies.get_mut(h.0) {
55                body.apply_force(
56                    h.1,
57                    &Force::new(acceleration.linear, acceleration.angular),
58                    ForceType::AccelerationChange,
59                    false,
60                );
61                true
62            } else {
63                false
64            }
65        });
66    }
67}