]> git.tdb.fi Git - r2c2.git/blobdiff - source/libmarklin/simplephysics.cpp
Foundations of using physics simulation for trains
[r2c2.git] / source / libmarklin / simplephysics.cpp
diff --git a/source/libmarklin/simplephysics.cpp b/source/libmarklin/simplephysics.cpp
new file mode 100644 (file)
index 0000000..3dc8e2e
--- /dev/null
@@ -0,0 +1,61 @@
+/* $Id$
+
+This file is part of the MSP Märklin suite
+Copyright © 2010  Mikkosoft Productions, Mikko Rasa
+Distributed under the GPL
+*/
+
+#include <msp/core/except.h>
+#include <msp/time/units.h>
+#include "simplephysics.h"
+
+using namespace std;
+using namespace Msp;
+
+namespace Marklin {
+
+SimplePhysics::SimplePhysics():
+       target_speed(TrainControl::continuous("speed", -1000, 1000)),
+       accel(0.07),
+       speed(0)
+{
+       target_speed.set(0);
+}
+
+void SimplePhysics::set_control(const string &name, float v)
+{
+       if(name=="speed")
+               target_speed.set(v);
+}
+
+const TrainControl &SimplePhysics::get_control(const string &name) const
+{
+       if(name=="speed")
+               return target_speed;
+       else
+               throw KeyError("Unknown control", name);
+}
+
+float SimplePhysics::get_braking_distance() const
+{
+       return speed*speed/(2*accel);
+}
+
+void SimplePhysics::tick(const Time::TimeDelta &dt)
+{
+       float secs = dt/Time::sec;
+       if(speed<target_speed.value)
+       {
+               speed += secs*accel;
+               if(speed>target_speed.value)
+                       speed = target_speed.value;
+       }
+       else if(speed>target_speed.value)
+       {
+               speed -= secs*accel;
+               if(speed<target_speed.value)
+                       speed = target_speed.value;
+       }
+}
+
+} // namespace Marklin