chip/
ball.rs

1use extend::ToFromC;
2use ffi;
3use na::{Point3, Vector3};
4
5/// A ball simulation.
6///
7/// # Example
8///
9/// ```
10/// # extern crate chip;
11/// # extern crate nalgebra as na;
12/// # use na::{Point3, Vector3};
13/// # use chip::Ball;
14/// let mut ball = Ball::new();
15/// ball.set_pos(Point3::new(0.0, 0.0, 100.0));
16/// ball.set_vel(Vector3::new(300.0, 400.0, 500.0));
17///
18/// ball.step(1.0 / 120.0);
19/// println!("{:?}", ball.pos());
20/// ```
21pub struct Ball(ffi::Ball);
22
23impl Ball {
24    /// Creates a `Ball`.
25    pub fn new() -> Self {
26        Ball(unsafe { ffi::Ball::new() })
27    }
28
29    /// Gets the ball's position.
30    pub fn pos(&self) -> Point3<f32> {
31        Point3::from_c(self.0.x)
32    }
33
34    /// Sets the ball's position.
35    pub fn set_pos(&mut self, pos: Point3<f32>) {
36        self.0.x = pos.to_c();
37    }
38
39    /// Gets the ball's velocity.
40    pub fn vel(&self) -> Vector3<f32> {
41        Vector3::from_c(self.0.v)
42    }
43
44    /// Sets the ball's velocity.
45    pub fn set_vel(&mut self, vel: Vector3<f32>) {
46        self.0.v = vel.to_c();
47    }
48
49    /// Gets the ball's angular velocity.
50    pub fn omega(&self) -> Vector3<f32> {
51        Vector3::from_c(self.0.w)
52    }
53
54    /// Sets the ball's angular velocity.
55    pub fn set_omega(&mut self, omega: Vector3<f32>) {
56        self.0.w = omega.to_c();
57    }
58
59    /// Gets the time elapsed in the simulation.
60    pub fn t(&self) -> f32 {
61        self.0.t
62    }
63
64    /// Sets the time elapsed in the simulation.
65    pub fn set_t(&mut self, t: f32) {
66        self.0.t = t;
67    }
68
69    /// Simulates the next `dt` seconds, and updates the ball's physics values.
70    pub fn step(&mut self, dt: f32) {
71        unsafe { self.0.step(dt) };
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use ball::Ball;
78    use na::{Point3, Vector3};
79
80    #[test]
81    fn ball() {
82        let mut ball = Ball::new();
83        ball.set_pos(Point3::new(0.0, 0.0, 100.0));
84        ball.set_vel(Vector3::new(1000.0, 0.0, 0.0));
85        ball.step(1.0 / 120.0);
86        println!("{:?}", ball.pos());
87        assert!(1.0 < ball.pos().x && ball.pos().x < 10.0);
88        assert!(99.0 < ball.pos().z && ball.pos().z < 99.99);
89    }
90}