1 // FGAIShip - FGAIBase-derived class creates an AI ship
3 // Written by David Culp, started October 2003.
4 // with major amendments and additions by Vivian Meazza, 2004 - 2007
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 double fgIsFinite(double x) { return _finite(x); }
30 double fgIsFinite(double x) { return std::isfinite(x); }
33 #include <simgear/sg_inlines.h>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/math/sg_random.h>
38 #include <simgear/scene/util/SGNodeMasks.hxx>
39 #include <Scenery/scenery.hxx>
40 #include <Main/globals.hxx>
46 FGAIShip::FGAIShip(object_type ot) :
47 // allow HOT to be enabled
54 _initial_tunnel(false),
65 _roll_constant(0.001),
66 _roll_factor(-0.0083335),
82 FGAIShip::~FGAIShip() {
85 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
90 FGAIBase::readFromScenario(scFileNode);
92 setRudder(scFileNode->getFloatValue("rudder", 0.0));
93 setName(scFileNode->getStringValue("name", "Titanic"));
94 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
95 const std::string& flightplan = scFileNode->getStringValue("flightplan");
96 setRepeat(scFileNode->getBoolValue("repeat", false));
97 setRestart(scFileNode->getBoolValue("restart", false));
98 setStartTime(scFileNode->getStringValue("time", ""));
99 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
100 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
101 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
102 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
103 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
104 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
105 setSMPath(scFileNode->getStringValue("submodel-path", ""));
106 setRollFactor(scFileNode->getDoubleValue("roll-factor", 1));
108 if (!flightplan.empty()) {
109 SG_LOG(SG_AI, SG_ALERT, "getting flightplan: " << _name );
111 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
117 bool FGAIShip::init(bool search_in_AI_path) {
119 return FGAIBase::init(search_in_AI_path);
122 void FGAIShip::reinit()
124 prev = 0; // the one behind you
125 curr = 0; // the one ahead
126 next = 0; // the next plus 1
128 props->setStringValue("name", _name.c_str());
129 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
130 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
131 props->setStringValue("waypoint/name-next", _next_name.c_str());
132 props->setStringValue("submodels/path", _path.c_str());
133 props->setStringValue("waypoint/start-time", _start_time.c_str());
134 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
140 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
143 _fp_init = initFlightPlan();
148 void FGAIShip::bind() {
151 tie("surface-positions/rudder-pos-deg",
152 SGRawValuePointer<float>(&_rudder));
153 tie("controls/heading-lock",
154 SGRawValuePointer<bool>(&_hdg_lock));
155 tie("controls/tgt-speed-kts",
156 SGRawValuePointer<double>(&tgt_speed));
157 tie("controls/tgt-heading-degs",
158 SGRawValuePointer<double>(&tgt_heading));
159 tie("controls/constants/roll-factor",
160 SGRawValuePointer<double>(&_roll_factor));
161 tie("controls/constants/roll",
162 SGRawValuePointer<double>(&_roll_constant));
163 tie("controls/constants/rudder",
164 SGRawValuePointer<double>(&_rudder_constant));
165 tie("controls/constants/speed",
166 SGRawValuePointer<double>(&_speed_constant));
167 tie("waypoint/range-nm",
168 SGRawValuePointer<double>(&_wp_range));
169 tie("waypoint/brg-deg",
170 SGRawValuePointer<double>(&_course));
171 tie("waypoint/rangerate-nm-sec",
172 SGRawValuePointer<double>(&_range_rate));
174 SGRawValuePointer<bool>(&_new_waypoint));
175 tie("waypoint/missed",
176 SGRawValuePointer<bool>(&_missed));
177 tie("waypoint/missed-count-sec",
178 SGRawValuePointer<double>(&_missed_count));
179 tie("waypoint/missed-range-nm",
180 SGRawValuePointer<double>(&_missed_range));
181 tie("waypoint/missed-time-sec",
182 SGRawValuePointer<double>(&_missed_time_sec));
183 tie("waypoint/wait-count-sec",
184 SGRawValuePointer<double>(&_wait_count));
185 tie("waypoint/xtrack-error-ft",
186 SGRawValuePointer<double>(&_xtrack_error));
187 tie("waypoint/waiting",
188 SGRawValuePointer<bool>(&_waiting));
189 tie("waypoint/lead-angle-deg",
190 SGRawValuePointer<double>(&_lead_angle));
191 tie("waypoint/tunnel",
192 SGRawValuePointer<bool>(&_tunnel));
193 tie("waypoint/alt-curr-m",
194 SGRawValuePointer<double>(&_curr_alt));
195 tie("waypoint/alt-prev-m",
196 SGRawValuePointer<double>(&_prev_alt));
197 tie("submodels/serviceable",
198 SGRawValuePointer<bool>(&_serviceable));
199 tie("controls/turn-radius-ft",
200 SGRawValuePointer<double>(&turn_radius_ft));
201 tie("controls/turn-radius-corrected-ft",
202 SGRawValuePointer<double>(&_rd_turn_radius_ft));
203 tie("controls/constants/lead-angle/gain",
204 SGRawValuePointer<double>(&_lead_angle_gain));
205 tie("controls/constants/lead-angle/limit-deg",
206 SGRawValuePointer<double>(&_lead_angle_limit));
207 tie("controls/constants/lead-angle/proportion",
208 SGRawValuePointer<double>(&_proportion));
209 tie("controls/fixed-turn-radius-ft",
210 SGRawValuePointer<double>(&_fixed_turn_radius));
211 tie("controls/restart",
212 SGRawValuePointer<bool>(&_restart));
213 tie("velocities/speed-kts",
214 SGRawValuePointer<double>(&speed));
217 void FGAIShip::update(double dt) {
218 //SG_LOG(SG_AI, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
219 // For computation of rotation speeds we just use finite differences here.
220 // That is perfectly valid since this thing is not driven by accelerations
221 // but by just apply discrete changes at its velocity variables.
222 // Update the velocity information stored in those nodes.
223 // Transform that one to the horizontal local coordinate system.
224 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
225 // The orientation of the ship wrt the horizontal local frame
226 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
227 // and postrotate the orientation of the AIModel wrt the horizontal
229 SGQuatd ec2body = ec2hl*hl2body;
230 // The cartesian position of the ship in the wgs84 world
231 //SGVec3d cartPos = SGVec3d::fromGeod(pos);
233 // The simulation time this transform is meant for
234 aip.setReferenceTime(globals->get_sim_time_sec());
236 // Compute the velocity in m/s in the body frame
237 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
239 FGAIBase::update(dt);
245 // Only change these values if we are able to compute them safely
246 if (SGLimits<double>::min() < dt) {
247 // Now here is the finite difference ...
249 // Transform that one to the horizontal local coordinate system.
250 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
251 // compute the new orientation
252 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
253 // The rotation difference
254 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
255 SGVec3d dOrAngleAxis;
256 dOr.getAngleAxis(dOrAngleAxis);
257 // divided by the time difference provides a rotation speed vector
260 aip.setBodyAngularVelocity(dOrAngleAxis);
264 void FGAIShip::Run(double dt) {
266 ProcessFlightPlan(dt);
268 const string& type = getTypeString();
275 double speed_diff = tgt_speed - speed;
277 if (fabs(speed_diff) > 0.1) {
279 if (speed_diff > 0.0)
280 speed += _speed_constant * dt;
282 if (speed_diff < 0.0)
283 speed -= _speed_constant * dt;
287 // do not allow unreasonable speeds
288 SG_CLAMP_RANGE(speed, -_limit * 0.75, _limit);
290 // convert speed to degrees per second
291 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
292 * speed * 1.686 / ft_per_deg_lat;
293 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
294 * speed * 1.686 / ft_per_deg_lon;
297 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
298 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
299 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
300 pos.setElevationFt(tgt_altitude_ft);
303 // adjust heading based on current _rudder angle
304 if (turn_radius_ft <= 0)
305 turn_radius_ft = 0; // don't allow nonsense values
314 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
315 if(type == "ship" || type == "carrier" || type == "escort"){
318 _sp_turn_radius_ft = _fixed_turn_radius;
320 // adjust turn radius for speed. The equation is very approximate.
321 // we need to allow for negative speeds
322 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
327 if (fabs(speed) <= 40)
328 _sp_turn_radius_ft = _fixed_turn_radius;
330 // adjust turn radius for speed.
331 _sp_turn_radius_ft = turn_radius_ft;
336 if (_rudder <= -0.25 || _rudder >= 0.25) {
337 // adjust turn radius for _rudder angle. The equation is even more approximate.
342 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
344 // calculate the angle, alpha, subtended by the arc traversed in time dt
345 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
346 //cout << _name << " alpha " << alpha << endl;
347 // make sure that alpha is applied in the right direction
348 hdg += alpha * sign(_rudder);
350 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
352 //adjust roll for rudder angle and speed. Another bit of voodoo
353 raw_roll = _roll_factor * speed * _rudder;
355 // _rudder angle is 0
363 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
365 // adjust target _rudder angle if heading lock engaged
366 double rudder_diff = 0.0;
368 double rudder_sense = 0.0;
369 double diff = fabs(hdg - tgt_heading);
370 //cout << "_rudder diff" << diff << endl;
372 diff = fabs(diff - 360);
374 double sum = hdg + diff;
379 if (fabs(sum - tgt_heading)< 1.0)
385 rudder_sense = -rudder_sense;
388 _tgt_rudder = diff * rudder_sense;
390 _tgt_rudder = 45 * rudder_sense;
392 rudder_diff = _tgt_rudder - _rudder;
395 // set the _rudder limit by speed
396 if (type == "ship" || type == "carrier" || type == "escort"){
399 rudder_limit = (-0.825 * speed) + 35;
406 if (fabs(rudder_diff)> 0.1) { // apply dead zone
408 if (rudder_diff > 0.0) {
409 _rudder += _rudder_constant * dt;
411 if (_rudder > rudder_limit) // apply the _rudder limit
412 _rudder = rudder_limit;
414 } else if (rudder_diff < 0.0) {
415 _rudder -= _rudder_constant * dt;
417 if (_rudder < -rudder_limit)
418 _rudder = -rudder_limit;
422 // do calculations for radar
423 UpdateRadar(manager);
427 void FGAIShip::AccelTo(double speed) {
431 void FGAIShip::PitchTo(double angle) {
435 void FGAIShip::RollTo(double angle) {
439 void FGAIShip::YawTo(double angle) {
442 void FGAIShip::ClimbTo(double altitude) {
443 tgt_altitude_ft = altitude;
444 _setAltitude(altitude);
447 void FGAIShip::TurnTo(double heading) {
448 tgt_heading = heading - _lead_angle + _tow_angle;
449 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
453 double FGAIShip::sign(double x) {
460 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
464 void FGAIShip::setStartTime(const string& st) {
468 void FGAIShip::setUntilTime(const string& ut) {
470 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
473 void FGAIShip::setCurrName(const string& c) {
475 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
478 void FGAIShip::setNextName(const string& n) {
480 props->setStringValue("waypoint/name-next", _next_name.c_str());
483 void FGAIShip::setPrevName(const string& p) {
485 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
488 void FGAIShip::setRepeat(bool r) {
492 void FGAIShip::setRestart(bool r) {
496 void FGAIShip::setMissed(bool m) {
498 props->setBoolValue("waypoint/missed", _missed);
501 void FGAIShip::setRudder(float r) {
505 void FGAIShip::setRoll(double rl) {
509 void FGAIShip::setLeadAngleGain(double g) {
510 _lead_angle_gain = g;
513 void FGAIShip::setLeadAngleLimit(double l) {
514 _lead_angle_limit = l;
517 void FGAIShip::setLeadAngleProp(double p) {
521 void FGAIShip::setRudderConstant(double rc) {
522 _rudder_constant = rc;
525 void FGAIShip::setSpeedConstant(double sc) {
526 _speed_constant = sc;
529 void FGAIShip::setFixedTurnRadius(double ftr) {
530 _fixed_turn_radius = ftr;
533 void FGAIShip::setRollFactor(double rf) {
534 _roll_factor = rf * -0.0083335;
537 void FGAIShip::setInitialTunnel(bool t) {
539 setTunnel(_initial_tunnel);
542 void FGAIShip::setTunnel(bool t) {
546 void FGAIShip::setWPNames() {
549 setPrevName(prev->getName());
554 setCurrName(curr->getName());
557 SG_LOG(SG_AI, SG_ALERT, "AIShip: current wp name error" );
561 setNextName(next->getName());
565 SG_LOG(SG_AI, SG_DEBUG, "AIShip: prev wp name " << prev->getName());
566 SG_LOG(SG_AI, SG_DEBUG, "AIShip: current wp name " << curr->getName());
567 SG_LOG(SG_AI, SG_DEBUG, "AIShip: next wp name " << next->getName());
571 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
573 double course, distance, az2;
575 //calculate the bearing and range of the second pos from the first
576 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
577 distance *= SG_METER_TO_NM;
581 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
583 double course, distance, recip;
585 //calculate the bearing and range of the second pos from the first
586 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
587 if (tgt_speed >= 0) {
589 SG_LOG(SG_AI, SG_DEBUG, "AIShip: course " << course);
592 SG_LOG(SG_AI, SG_DEBUG, "AIShip: recip " << recip);
596 void FGAIShip::ProcessFlightPlan(double dt) {
598 if ( dt < 0.00001 ) {
602 double time_sec = getDaySeconds();
606 ///////////////////////////////////////////////////////////////////////////
607 // Check Execution time (currently once every 1 sec)
608 // Add a bit of randomization to prevent the execution of all flight plans
609 // in synchrony, which can add significant periodic framerate flutter.
610 ///////////////////////////////////////////////////////////////////////////
612 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
613 if (_dt_count < _next_run && _start_sec < time_sec)
616 _next_run = 0.05 + (0.025 * sg_random());
618 double until_time_sec = 0;
621 // check to see if we've reached the point for our next turn
622 // if the range to the waypoint is less than the calculated turn
623 // radius we can start the turn to the next leg
624 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
625 _range_rate = (_wp_range - _old_range) / _dt_count;
626 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
627 // we need to try to identify a _missed waypoint
629 // calculate the time needed to turn through an arc of 90 degrees,
630 // and allow a time error
632 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
634 _missed_time_sec = 10;
636 _missed_range = 4 * sp_turn_radius_nm;
638 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
639 //if ((_range_rate > 0) && !_new_waypoint){
640 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
641 _missed_count += _dt_count;
644 if (_missed_count >= 120)
646 else if (_missed_count >= _missed_time_sec)
651 _old_range = _wp_range;
654 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
656 if (_next_name == "TUNNEL"){
659 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " " << sp_turn_radius_nm );
661 fp->IncrementWaypoint(false);
662 next = fp->getNextWaypoint();
664 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
665 || next->getName() == "END" || next->getName() == "TUNNEL")
669 fp->IncrementWaypoint(false);
670 curr = fp->getCurrentWaypoint();
671 next = fp->getNextWaypoint();
673 }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
676 SG_LOG(SG_AI, SG_INFO, "AIShip: "<< _name << " Flightplan repeating ");
679 curr = fp->getCurrentWaypoint();
680 next = fp->getNextWaypoint();
682 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
683 _old_range = _wp_range;
685 _new_waypoint = true;
688 AccelTo(prev->getSpeed());
689 } else if (_restart){
690 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " Flightplan restarting ");
694 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
700 } else if (_next_name == "WAIT") {
702 if (_wait_count < next->getTime_sec()) {
703 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " waiting ");
706 _wait_count += _dt_count;
711 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name
712 << " wait done: getting new waypoints ");
715 fp->IncrementWaypoint(false);
716 next = fp->getNextWaypoint();
718 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
719 || next->getName() == "END" || next->getName() == "TUNNEL")
723 fp->IncrementWaypoint(false);
724 curr = fp->getCurrentWaypoint();
725 next = fp->getNextWaypoint();
728 } else if (_next_name == "WAITUNTIL") {
729 time_sec = getDaySeconds();
730 until_time_sec = processTimeString(next->getTime());
731 _until_time = next->getTime();
732 setUntilTime(next->getTime());
733 if (until_time_sec > time_sec) {
734 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " "
735 << curr->getName() << " waiting until: "
736 << _until_time << " " << until_time_sec << " now " << time_sec );
742 SG_LOG(SG_AI, SG_INFO, "AIShip: "
743 << _name << " wait until done: getting new waypoints ");
745 fp->IncrementWaypoint(false);
747 while (next->getName() == "WAITUNTIL") {
748 fp->IncrementWaypoint(false);
749 next = fp->getNextWaypoint();
752 if (next->getName() == "WAIT")
756 fp->IncrementWaypoint(false);
757 curr = fp->getCurrentWaypoint();
758 next = fp->getNextWaypoint();
763 //now reorganise the waypoints, so that next becomes current and so on
764 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
765 fp->IncrementWaypoint(false);
766 prev = fp->getPreviousWaypoint(); //first waypoint
767 curr = fp->getCurrentWaypoint(); //second waypoint
768 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
772 _new_waypoint = true;
776 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
777 _old_range = _wp_range;
779 object_type type = getType();
782 AccelTo(prev->getSpeed());
784 _curr_alt = curr->getAltitude();
785 _prev_alt = prev->getAltitude();
788 _new_waypoint = false;
791 // now revise the required course for the next way point
792 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
794 if (fgIsFinite(_course))
797 SG_LOG(SG_AI, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
800 } // end Processing FlightPlan
802 bool FGAIShip::initFlightPlan() {
804 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
808 _tunnel = _initial_tunnel;
811 fp->IncrementWaypoint(false);
813 prev = fp->getPreviousWaypoint(); //first waypoint
814 curr = fp->getCurrentWaypoint(); //second waypoint
815 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
817 while (curr->getName() == "WAIT" || curr->getName() == "WAITUNTIL") { // don't wait when initialising
818 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
819 fp->IncrementWaypoint(false);
820 curr = fp->getCurrentWaypoint();
821 next = fp->getNextWaypoint();
824 if (!_start_time.empty()){
825 _start_sec = processTimeString(_start_time);
826 double day_sec = getDaySeconds();
828 if (_start_sec < day_sec){
829 //cout << "flight plan has already started " << _start_time << endl;
830 init = advanceFlightPlan(_start_sec, day_sec);
832 } else if (_start_sec > day_sec && _repeat) {
833 //cout << "flight plan has not started, " << _start_time;
834 //cout << "offsetting start time by -24 hrs" << endl;
836 init = advanceFlightPlan(_start_sec, day_sec);
840 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
843 fp->IncrementWaypoint(false);
844 prev = fp->getPreviousWaypoint();
845 curr = fp->getCurrentWaypoint();
846 next = fp->getNextWaypoint();
851 setLatitude(prev->getLatitude());
852 setLongitude(prev->getLongitude());
853 setSpeed(prev->getSpeed());
857 setHeading(getCourse(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude()));
858 _wp_range = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
859 _old_range = _wp_range;
864 _new_waypoint = true;
866 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " done initialising waypoints " << _tunnel);
875 } // end of initialization
878 double FGAIShip::processTimeString(const string& theTime) {
884 // first split theTime string into
885 // hour, minute, second and convert to int;
886 Hour = atoi(theTime.substr(0,2).c_str());
887 Minute = atoi(theTime.substr(3,5).c_str());
888 Second = atoi(theTime.substr(6,8).c_str());
890 // offset by a day-sec to allow for starting a day earlier
891 double time_seconds = Hour * 3600
898 double FGAIShip::getDaySeconds () {
900 struct tm *t = globals->get_time_params()->getGmt();
902 double day_seconds = t->tm_hour * 3600
909 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
911 double elapsed_sec = start_sec;
912 double distance_nm = 0;
914 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
916 while ( elapsed_sec < day_sec ) {
918 if (next->getName() == "END" || fp->getNextWaypoint() == 0) {
921 //cout << _name << ": " << "restarting flightplan" << endl;
923 curr = fp->getCurrentWaypoint();
924 next = fp->getNextWaypoint();
926 //cout << _name << ": " << "ending flightplan" << endl;
931 } else if (next->getName() == "WAIT") {
932 //cout << _name << ": begin WAIT: " << prev->name << " ";
933 //cout << curr->name << " " << next->name << endl;
935 elapsed_sec += next->getTime_sec();
937 if ( elapsed_sec >= day_sec)
940 fp->IncrementWaypoint(false);
941 next = fp->getNextWaypoint();
943 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT"
944 && next->getName() != "END") {
946 fp->IncrementWaypoint(false);
947 curr = fp->getCurrentWaypoint();
948 next = fp->getNextWaypoint();
951 } else if (next->getName() == "WAITUNTIL") {
952 double until_sec = processTimeString(next->getTime());
954 if (until_sec > _start_sec && start_sec < 0)
957 if (elapsed_sec < until_sec)
958 elapsed_sec = until_sec;
960 if (elapsed_sec >= day_sec )
963 fp->IncrementWaypoint(false);
964 next = fp->getNextWaypoint();
966 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT") {
968 fp->IncrementWaypoint(false);
969 curr = fp->getCurrentWaypoint();
970 next = fp->getNextWaypoint();
973 //cout << _name << ": end WAITUNTIL: ";
974 //cout << prev->name << " " << curr->name << " " << next->name << endl;
977 distance_nm = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
978 elapsed_sec += distance_nm * 60 * 60 / prev->getSpeed();
980 if (elapsed_sec >= day_sec)
983 fp->IncrementWaypoint(false);
984 prev = fp->getPreviousWaypoint();
985 curr = fp->getCurrentWaypoint();
986 next = fp->getNextWaypoint();
991 // the required position lies between the previous and current waypoints
992 // so we will calculate the distance back up the track from the current waypoint
993 // then calculate the lat and lon.
995 //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
996 // << " " << day_sec << endl;
998 double time_diff = elapsed_sec - day_sec;
999 double lat, lon, recip;
1001 //cout << " time diff " << time_diff << endl;
1003 if (next->getName() == "WAIT" ){
1005 lat = curr->getLatitude();
1006 lon = curr->getLongitude();
1007 _wait_count= time_diff;
1009 } else if (next->getName() == "WAITUNTIL") {
1011 lat = curr->getLatitude();
1012 lon = curr->getLongitude();
1015 setSpeed(prev->getSpeed());
1016 distance_nm = speed * time_diff / (60 * 60);
1017 double brg = getCourse(curr->getLatitude(), curr->getLongitude(), prev->getLatitude(), prev->getLongitude());
1019 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1020 // << " lat " << curr->latitude << " lon " << curr->longitude
1021 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1023 lat = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1024 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1025 lon = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1026 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1027 recip = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1028 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1037 void FGAIShip::setWPPos() {
1039 if (curr->getName() == "END" || curr->getName() == "WAIT"
1040 || curr->getName() == "WAITUNTIL" || curr->getName() == "TUNNEL"){
1041 //cout << curr->name << " returning" << endl;
1045 double elevation_m = 0;
1046 wppos.setLatitudeDeg(curr->getLatitude());
1047 wppos.setLongitudeDeg(curr->getLongitude());
1048 wppos.setElevationM(0);
1050 if (curr->getOn_ground()){
1052 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 3000),
1053 elevation_m, NULL, 0)){
1054 wppos.setElevationM(elevation_m);
1057 //cout << curr->name << " setting measured elev " << elevation_m << endl;
1060 wppos.setElevationM(curr->getAltitude());
1061 //cout << curr->name << " setting FP elev " << elevation_m << endl;
1064 curr->setAltitude(wppos.getElevationM());
1068 void FGAIShip::setXTrackError() {
1070 double course = getCourse(prev->getLatitude(), prev->getLongitude(),
1071 curr->getLatitude(), curr->getLongitude());
1072 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1073 curr->getLatitude(), curr->getLongitude());
1074 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1075 double factor = -0.0045 * speed + 1;
1076 double limit = _lead_angle_limit * factor;
1079 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1083 _lead_angle *= _lead_angle_gain * factor;
1084 _xtrack_error = xtrack_error_nm * 6076.1155;
1086 SG_CLAMP_RANGE(_lead_angle, -limit, limit);