]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/simplephysics.cpp
Foundations of using physics simulation for trains
[r2c2.git] / source / libmarklin / simplephysics.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2010  Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <msp/core/except.h>
9 #include <msp/time/units.h>
10 #include "simplephysics.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace Marklin {
16
17 SimplePhysics::SimplePhysics():
18         target_speed(TrainControl::continuous("speed", -1000, 1000)),
19         accel(0.07),
20         speed(0)
21 {
22         target_speed.set(0);
23 }
24
25 void SimplePhysics::set_control(const string &name, float v)
26 {
27         if(name=="speed")
28                 target_speed.set(v);
29 }
30
31 const TrainControl &SimplePhysics::get_control(const string &name) const
32 {
33         if(name=="speed")
34                 return target_speed;
35         else
36                 throw KeyError("Unknown control", name);
37 }
38
39 float SimplePhysics::get_braking_distance() const
40 {
41         return speed*speed/(2*accel);
42 }
43
44 void SimplePhysics::tick(const Time::TimeDelta &dt)
45 {
46         float secs = dt/Time::sec;
47         if(speed<target_speed.value)
48         {
49                 speed += secs*accel;
50                 if(speed>target_speed.value)
51                         speed = target_speed.value;
52         }
53         else if(speed>target_speed.value)
54         {
55                 speed -= secs*accel;
56                 if(speed<target_speed.value)
57                         speed = target_speed.value;
58         }
59 }
60
61 } // namespace Marklin