3 This file is part of R²C²
4 Copyright © 2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
18 AIControl::AIControl(Train &t, Controller *n):
21 target_speed(Control::continuous("speed", 0, 1000)),
26 train.signal_arrived.connect(sigc::mem_fun(this, &AIControl::arrived));
27 next_ctrl->signal_control_changed.connect(sigc::mem_fun(this, &AIControl::control_changed));
30 AIControl::~AIControl()
35 void AIControl::set_control(const string &n, float v)
39 if(v && !train.is_active())
40 train.set_active(true);
45 float approach_speed = 5*train.get_layout().get_catalogue().get_scale();
46 if(state==APPROACH && target_speed.value>approach_speed)
47 next_ctrl->set_control("speed", approach_speed);
49 next_ctrl->set_control("speed", target_speed.value);
52 signal_control_changed.emit(target_speed);
55 next_ctrl->set_control(n, v);
58 const Controller::Control &AIControl::get_control(const string &n) const
63 return next_ctrl->get_control(n);
66 float AIControl::get_speed() const
68 return next_ctrl->get_speed();
71 bool AIControl::get_reverse() const
73 return next_ctrl->get_reverse();
76 float AIControl::get_braking_distance() const
78 return next_ctrl->get_braking_distance();
81 void AIControl::tick(const Time::TimeDelta &dt)
83 float scale = train.get_layout().get_catalogue().get_scale();
84 float rsv_dist = train.get_reserved_distance();
85 float brake_dist = next_ctrl->get_braking_distance();
86 float approach_margin = 50*scale;
87 float approach_speed = 5*scale;
88 float margin = 10*scale;
90 State old_state = state;
92 if(state==FOLLOW && !train.get_preceding_train())
95 if(rsv_dist<brake_dist+margin)
97 else if(rsv_dist>brake_dist+margin*2 && rsv_dist<brake_dist*1.3+approach_margin)
99 else if(rsv_dist>brake_dist*1.3+approach_margin*2)
102 if(state==NORMAL && train.get_preceding_train())
105 if(state!=old_state || state==FOLLOW)
107 float speed_limit = -1;
110 else if(state==APPROACH)
111 speed_limit = approach_speed;
112 else if(state==FOLLOW)
113 speed_limit = train.get_preceding_train()->get_speed();
115 if(speed_limit>=0 && target_speed.value>speed_limit)
116 next_ctrl->set_control("speed", speed_limit);
118 next_ctrl->set_control("speed", target_speed.value);
123 if(!target_speed.value && !next_ctrl->get_speed() && train.is_active())
124 train.set_active(false);
127 void AIControl::control_changed(const Control &ctrl)
129 if(ctrl.name!="speed")
130 signal_control_changed.emit(ctrl);
133 void AIControl::arrived()
135 set_control("speed", 0);