Skip to main content

plot_gravity/
plot_gravity.rs

1use plotters::prelude::*;
2use fennel_physics::body::Body;
3use fennel_physics::shapes_2d::rigid_body::RigidBody;
4use fennel_physics::world::PhysicsWorld;
5
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let mut world = PhysicsWorld::new();
8    let mut body = RigidBody::new();
9    body.set_mass(1.0);
10    body.set_position(nalgebra::Vector2::new(0.0, 100.0));
11    world.add_body(Box::new(body));
12
13    let dt = 1.0 / 60.0_f32;
14    let steps = 600;
15    let mut samples: Vec<(f32, f32)> = Vec::with_capacity(steps + 1);
16
17    let t0 = 0.0_f32;
18    let y0 = world.bodies[0].get_position().y;
19    samples.push((t0, y0));
20
21    for i in 1..=steps {
22        world.step(dt);
23        let t = i as f32 * dt;
24        let y = world.bodies[0].get_position().y;
25        println!("step: {}, y: {}", i, y);
26        samples.push((t, y));
27    }
28
29    let out_path = "free_fall.png";
30    let root = BitMapBackend::new(out_path, (800, 600)).into_drawing_area();
31    root.fill(&WHITE)?;
32
33    let t_min = samples.first().unwrap().0;
34    let t_max = samples.last().unwrap().0;
35    let y_min = samples.iter().map(|s| s.1).fold(f32::INFINITY, f32::min);
36    let y_max = samples.iter().map(|s| s.1).fold(f32::NEG_INFINITY, f32::max);
37
38    let mut chart = ChartBuilder::on(&root)
39        .caption("Free Fall", ("sans-serif", 30).into_font())
40        .margin(10)
41        .x_label_area_size(40)
42        .y_label_area_size(60)
43        .build_cartesian_2d(t_min..t_max, (y_min - 1.0)..(y_max + 1.0))?;
44
45    chart.configure_mesh().x_desc("time (s)").y_desc("y (m)").draw()?;
46
47    chart
48        .draw_series(LineSeries::new(
49            samples.into_iter(),
50            &BLUE,
51        ))?
52        .label("y(t)")
53        .legend(|(x, y)| PathElement::new(vec![(x, y), (x + 20, y)], BLUE));
54
55    chart.configure_series_labels().background_style(WHITE.mix(0.8)).border_style(BLACK).draw()?;
56
57    root.present()?;
58    println!("Wrote {}", out_path);
59
60    Ok(())
61}