]> git.tdb.fi Git - r2c2.git/blob - simplecontroller.cpp
7f8b3362087ed0cee7a37eb03c55875cc31a4f20
[r2c2.git] / simplecontroller.cpp
1 /* $Id$
2
3 This file is part of R²C²
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 "simplecontroller.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace R2C2 {
16
17 SimpleController::SimpleController():
18         target_speed(Control::continuous("speed", 0, 1000)),
19         reverse(Control::binary("reverse")),
20         accel(0.07),
21         speed(0)
22 {
23         target_speed.set(0);
24 }
25
26 void SimpleController::set_control(const string &name, float v)
27 {
28         if(name=="speed")
29         {
30                 target_speed.set(v);
31                 signal_control_changed.emit(target_speed);
32         }
33         else if(name=="reverse")
34         {
35                 if(target_speed.value || speed)
36                         throw InvalidState("Must be stopped to change reverse");
37                 reverse.set(v);
38                 signal_control_changed.emit(reverse);
39         }
40 }
41
42 const Controller::Control &SimpleController::get_control(const string &name) const
43 {
44         if(name=="speed")
45                 return target_speed;
46         else if(name=="reverse")
47                 return reverse;
48         else
49                 throw KeyError("Unknown control", name);
50 }
51
52 float SimpleController::get_braking_distance() const
53 {
54         return speed*speed/(2*accel);
55 }
56
57 void SimpleController::tick(const Time::TimeDelta &dt)
58 {
59         float secs = dt/Time::sec;
60         if(speed<target_speed.value)
61         {
62                 speed += secs*accel;
63                 if(speed>target_speed.value)
64                         speed = target_speed.value;
65         }
66         else if(speed>target_speed.value)
67         {
68                 speed -= secs*accel;
69                 if(speed<target_speed.value)
70                         speed = target_speed.value;
71         }
72 }
73
74 } // namespace R2C2