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>
45 FGAIShip::FGAIShip(object_type ot) :
46 // allow HOT to be enabled
53 _initial_tunnel(false),
64 _roll_constant(0.001),
65 _roll_factor(-0.0083335),
81 FGAIShip::~FGAIShip() {
84 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
89 FGAIBase::readFromScenario(scFileNode);
91 setRudder(scFileNode->getFloatValue("rudder", 0.0));
92 setName(scFileNode->getStringValue("name", "Titanic"));
93 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
94 const std::string& flightplan = scFileNode->getStringValue("flightplan");
95 setRepeat(scFileNode->getBoolValue("repeat", false));
96 setRestart(scFileNode->getBoolValue("restart", false));
97 setStartTime(scFileNode->getStringValue("time", ""));
98 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
99 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
100 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
101 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
102 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
103 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
104 setSMPath(scFileNode->getStringValue("submodel-path", ""));
105 setRollFactor(scFileNode->getDoubleValue("roll-factor", 1));
107 if (!flightplan.empty()) {
108 SG_LOG(SG_AI, SG_ALERT, "getting flightplan: " << _name );
110 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
116 bool FGAIShip::init(bool search_in_AI_path) {
118 return FGAIBase::init(search_in_AI_path);
121 void FGAIShip::reinit()
123 prev = 0; // the one behind you
124 curr = 0; // the one ahead
125 next = 0; // the next plus 1
127 props->setStringValue("name", _name.c_str());
128 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
129 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
130 props->setStringValue("waypoint/name-next", _next_name.c_str());
131 props->setStringValue("submodels/path", _path.c_str());
132 props->setStringValue("waypoint/start-time", _start_time.c_str());
133 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
139 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
142 _fp_init = initFlightPlan();
147 void FGAIShip::bind() {
150 tie("surface-positions/rudder-pos-deg",
151 SGRawValuePointer<float>(&_rudder));
152 tie("controls/heading-lock",
153 SGRawValuePointer<bool>(&_hdg_lock));
154 tie("controls/tgt-speed-kts",
155 SGRawValuePointer<double>(&tgt_speed));
156 tie("controls/tgt-heading-degs",
157 SGRawValuePointer<double>(&tgt_heading));
158 tie("controls/constants/roll-factor",
159 SGRawValuePointer<double>(&_roll_factor));
160 tie("controls/constants/roll",
161 SGRawValuePointer<double>(&_roll_constant));
162 tie("controls/constants/rudder",
163 SGRawValuePointer<double>(&_rudder_constant));
164 tie("controls/constants/speed",
165 SGRawValuePointer<double>(&_speed_constant));
166 tie("waypoint/range-nm",
167 SGRawValuePointer<double>(&_wp_range));
168 tie("waypoint/brg-deg",
169 SGRawValuePointer<double>(&_course));
170 tie("waypoint/rangerate-nm-sec",
171 SGRawValuePointer<double>(&_range_rate));
173 SGRawValuePointer<bool>(&_new_waypoint));
174 tie("waypoint/missed",
175 SGRawValuePointer<bool>(&_missed));
176 tie("waypoint/missed-count-sec",
177 SGRawValuePointer<double>(&_missed_count));
178 tie("waypoint/missed-range-nm",
179 SGRawValuePointer<double>(&_missed_range));
180 tie("waypoint/missed-time-sec",
181 SGRawValuePointer<double>(&_missed_time_sec));
182 tie("waypoint/wait-count-sec",
183 SGRawValuePointer<double>(&_wait_count));
184 tie("waypoint/xtrack-error-ft",
185 SGRawValuePointer<double>(&_xtrack_error));
186 tie("waypoint/waiting",
187 SGRawValuePointer<bool>(&_waiting));
188 tie("waypoint/lead-angle-deg",
189 SGRawValuePointer<double>(&_lead_angle));
190 tie("waypoint/tunnel",
191 SGRawValuePointer<bool>(&_tunnel));
192 tie("waypoint/alt-curr-m",
193 SGRawValuePointer<double>(&_curr_alt));
194 tie("waypoint/alt-prev-m",
195 SGRawValuePointer<double>(&_prev_alt));
196 tie("submodels/serviceable",
197 SGRawValuePointer<bool>(&_serviceable));
198 tie("controls/turn-radius-ft",
199 SGRawValuePointer<double>(&turn_radius_ft));
200 tie("controls/turn-radius-corrected-ft",
201 SGRawValuePointer<double>(&_rd_turn_radius_ft));
202 tie("controls/constants/lead-angle/gain",
203 SGRawValuePointer<double>(&_lead_angle_gain));
204 tie("controls/constants/lead-angle/limit-deg",
205 SGRawValuePointer<double>(&_lead_angle_limit));
206 tie("controls/constants/lead-angle/proportion",
207 SGRawValuePointer<double>(&_proportion));
208 tie("controls/fixed-turn-radius-ft",
209 SGRawValuePointer<double>(&_fixed_turn_radius));
210 tie("controls/restart",
211 SGRawValuePointer<bool>(&_restart));
212 tie("velocities/speed-kts",
213 SGRawValuePointer<double>(&speed));
216 void FGAIShip::update(double dt) {
217 //SG_LOG(SG_AI, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
218 // For computation of rotation speeds we just use finite differences here.
219 // That is perfectly valid since this thing is not driven by accelerations
220 // but by just apply discrete changes at its velocity variables.
221 // Update the velocity information stored in those nodes.
222 // Transform that one to the horizontal local coordinate system.
223 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
224 // The orientation of the ship wrt the horizontal local frame
225 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
226 // and postrotate the orientation of the AIModel wrt the horizontal
228 SGQuatd ec2body = ec2hl*hl2body;
229 // The cartesian position of the ship in the wgs84 world
230 //SGVec3d cartPos = SGVec3d::fromGeod(pos);
232 // The simulation time this transform is meant for
233 aip.setReferenceTime(globals->get_sim_time_sec());
235 // Compute the velocity in m/s in the body frame
236 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
238 FGAIBase::update(dt);
244 // Only change these values if we are able to compute them safely
245 if (SGLimits<double>::min() < dt) {
246 // Now here is the finite difference ...
248 // Transform that one to the horizontal local coordinate system.
249 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
250 // compute the new orientation
251 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
252 // The rotation difference
253 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
254 SGVec3d dOrAngleAxis;
255 dOr.getAngleAxis(dOrAngleAxis);
256 // divided by the time difference provides a rotation speed vector
259 aip.setBodyAngularVelocity(dOrAngleAxis);
263 void FGAIShip::Run(double dt) {
265 ProcessFlightPlan(dt);
267 const string& type = getTypeString();
274 double speed_diff = tgt_speed - speed;
276 if (fabs(speed_diff) > 0.1) {
278 if (speed_diff > 0.0)
279 speed += _speed_constant * dt;
281 if (speed_diff < 0.0)
282 speed -= _speed_constant * dt;
286 // do not allow unreasonable speeds
287 SG_CLAMP_RANGE(speed, -_limit * 0.75, _limit);
289 // convert speed to degrees per second
290 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
291 * speed * 1.686 / ft_per_deg_lat;
292 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
293 * speed * 1.686 / ft_per_deg_lon;
296 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
297 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
298 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
299 pos.setElevationFt(tgt_altitude_ft);
302 // adjust heading based on current _rudder angle
303 if (turn_radius_ft <= 0)
304 turn_radius_ft = 0; // don't allow nonsense values
313 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
314 if(type == "ship" || type == "carrier" || type == "escort"){
317 _sp_turn_radius_ft = _fixed_turn_radius;
319 // adjust turn radius for speed. The equation is very approximate.
320 // we need to allow for negative speeds
321 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
326 if (fabs(speed) <= 40)
327 _sp_turn_radius_ft = _fixed_turn_radius;
329 // adjust turn radius for speed.
330 _sp_turn_radius_ft = turn_radius_ft;
335 if (_rudder <= -0.25 || _rudder >= 0.25) {
336 // adjust turn radius for _rudder angle. The equation is even more approximate.
341 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
343 // calculate the angle, alpha, subtended by the arc traversed in time dt
344 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
345 //cout << _name << " alpha " << alpha << endl;
346 // make sure that alpha is applied in the right direction
347 hdg += alpha * sign(_rudder);
349 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
351 //adjust roll for rudder angle and speed. Another bit of voodoo
352 raw_roll = _roll_factor * speed * _rudder;
354 // _rudder angle is 0
362 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
364 // adjust target _rudder angle if heading lock engaged
365 double rudder_diff = 0.0;
367 double rudder_sense = 0.0;
368 double diff = fabs(hdg - tgt_heading);
369 //cout << "_rudder diff" << diff << endl;
371 diff = fabs(diff - 360);
373 double sum = hdg + diff;
378 if (fabs(sum - tgt_heading)< 1.0)
384 rudder_sense = -rudder_sense;
387 _tgt_rudder = diff * rudder_sense;
389 _tgt_rudder = 45 * rudder_sense;
391 rudder_diff = _tgt_rudder - _rudder;
394 // set the _rudder limit by speed
395 if (type == "ship" || type == "carrier" || type == "escort"){
398 rudder_limit = (-0.825 * speed) + 35;
405 if (fabs(rudder_diff)> 0.1) { // apply dead zone
407 if (rudder_diff > 0.0) {
408 _rudder += _rudder_constant * dt;
410 if (_rudder > rudder_limit) // apply the _rudder limit
411 _rudder = rudder_limit;
413 } else if (rudder_diff < 0.0) {
414 _rudder -= _rudder_constant * dt;
416 if (_rudder < -rudder_limit)
417 _rudder = -rudder_limit;
421 // do calculations for radar
422 UpdateRadar(manager);
426 void FGAIShip::AccelTo(double speed) {
430 void FGAIShip::PitchTo(double angle) {
434 void FGAIShip::RollTo(double angle) {
438 void FGAIShip::YawTo(double angle) {
441 void FGAIShip::ClimbTo(double altitude) {
442 tgt_altitude_ft = altitude;
443 _setAltitude(altitude);
446 void FGAIShip::TurnTo(double heading) {
447 tgt_heading = heading - _lead_angle + _tow_angle;
448 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
452 double FGAIShip::sign(double x) {
459 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
463 void FGAIShip::setStartTime(const string& st) {
467 void FGAIShip::setUntilTime(const string& ut) {
469 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
472 void FGAIShip::setCurrName(const string& c) {
474 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
477 void FGAIShip::setNextName(const string& n) {
479 props->setStringValue("waypoint/name-next", _next_name.c_str());
482 void FGAIShip::setPrevName(const string& p) {
484 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
487 void FGAIShip::setRepeat(bool r) {
491 void FGAIShip::setRestart(bool r) {
495 void FGAIShip::setMissed(bool m) {
497 props->setBoolValue("waypoint/missed", _missed);
500 void FGAIShip::setRudder(float r) {
504 void FGAIShip::setRoll(double rl) {
508 void FGAIShip::setLeadAngleGain(double g) {
509 _lead_angle_gain = g;
512 void FGAIShip::setLeadAngleLimit(double l) {
513 _lead_angle_limit = l;
516 void FGAIShip::setLeadAngleProp(double p) {
520 void FGAIShip::setRudderConstant(double rc) {
521 _rudder_constant = rc;
524 void FGAIShip::setSpeedConstant(double sc) {
525 _speed_constant = sc;
528 void FGAIShip::setFixedTurnRadius(double ftr) {
529 _fixed_turn_radius = ftr;
532 void FGAIShip::setRollFactor(double rf) {
533 _roll_factor = rf * -0.0083335;
536 void FGAIShip::setInitialTunnel(bool t) {
538 setTunnel(_initial_tunnel);
541 void FGAIShip::setTunnel(bool t) {
545 void FGAIShip::setWPNames() {
548 setPrevName(prev->getName());
553 setCurrName(curr->getName());
556 SG_LOG(SG_AI, SG_ALERT, "AIShip: current wp name error" );
560 setNextName(next->getName());
564 SG_LOG(SG_AI, SG_DEBUG, "AIShip: prev wp name " << prev->getName());
565 SG_LOG(SG_AI, SG_DEBUG, "AIShip: current wp name " << curr->getName());
566 SG_LOG(SG_AI, SG_DEBUG, "AIShip: next wp name " << next->getName());
570 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
572 double course, distance, az2;
574 //calculate the bearing and range of the second pos from the first
575 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
576 distance *= SG_METER_TO_NM;
580 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
582 double course, distance, recip;
584 //calculate the bearing and range of the second pos from the first
585 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
586 if (tgt_speed >= 0) {
588 SG_LOG(SG_AI, SG_DEBUG, "AIShip: course " << course);
591 SG_LOG(SG_AI, SG_DEBUG, "AIShip: recip " << recip);
595 void FGAIShip::ProcessFlightPlan(double dt) {
597 if ( dt < 0.00001 ) {
601 double time_sec = getDaySeconds();
605 ///////////////////////////////////////////////////////////////////////////
606 // Check Execution time (currently once every 1 sec)
607 // Add a bit of randomization to prevent the execution of all flight plans
608 // in synchrony, which can add significant periodic framerate flutter.
609 ///////////////////////////////////////////////////////////////////////////
611 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
612 if (_dt_count < _next_run && _start_sec < time_sec)
615 _next_run = 0.05 + (0.025 * sg_random());
617 double until_time_sec = 0;
620 // check to see if we've reached the point for our next turn
621 // if the range to the waypoint is less than the calculated turn
622 // radius we can start the turn to the next leg
623 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
624 _range_rate = (_wp_range - _old_range) / _dt_count;
625 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
626 // we need to try to identify a _missed waypoint
628 // calculate the time needed to turn through an arc of 90 degrees,
629 // and allow a time error
631 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
633 _missed_time_sec = 10;
635 _missed_range = 4 * sp_turn_radius_nm;
637 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
638 //if ((_range_rate > 0) && !_new_waypoint){
639 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
640 _missed_count += _dt_count;
643 if (_missed_count >= 120)
645 else if (_missed_count >= _missed_time_sec)
650 _old_range = _wp_range;
653 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
655 if (_next_name == "TUNNEL"){
658 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " " << sp_turn_radius_nm );
660 fp->IncrementWaypoint(false);
661 next = fp->getNextWaypoint();
663 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
664 || next->getName() == "END" || next->getName() == "TUNNEL")
668 fp->IncrementWaypoint(false);
669 curr = fp->getCurrentWaypoint();
670 next = fp->getNextWaypoint();
672 }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
675 SG_LOG(SG_AI, SG_INFO, "AIShip: "<< _name << " Flightplan repeating ");
678 curr = fp->getCurrentWaypoint();
679 next = fp->getNextWaypoint();
681 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
682 _old_range = _wp_range;
684 _new_waypoint = true;
687 AccelTo(prev->getSpeed());
688 } else if (_restart){
689 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " Flightplan restarting ");
693 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
699 } else if (_next_name == "WAIT") {
701 if (_wait_count < next->getTime_sec()) {
702 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " waiting ");
705 _wait_count += _dt_count;
710 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name
711 << " wait done: getting new waypoints ");
714 fp->IncrementWaypoint(false);
715 next = fp->getNextWaypoint();
717 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
718 || next->getName() == "END" || next->getName() == "TUNNEL")
722 fp->IncrementWaypoint(false);
723 curr = fp->getCurrentWaypoint();
724 next = fp->getNextWaypoint();
727 } else if (_next_name == "WAITUNTIL") {
728 time_sec = getDaySeconds();
729 until_time_sec = processTimeString(next->getTime());
730 _until_time = next->getTime();
731 setUntilTime(next->getTime());
732 if (until_time_sec > time_sec) {
733 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " "
734 << curr->getName() << " waiting until: "
735 << _until_time << " " << until_time_sec << " now " << time_sec );
741 SG_LOG(SG_AI, SG_INFO, "AIShip: "
742 << _name << " wait until done: getting new waypoints ");
744 fp->IncrementWaypoint(false);
746 while (next->getName() == "WAITUNTIL") {
747 fp->IncrementWaypoint(false);
748 next = fp->getNextWaypoint();
751 if (next->getName() == "WAIT")
755 fp->IncrementWaypoint(false);
756 curr = fp->getCurrentWaypoint();
757 next = fp->getNextWaypoint();
762 //now reorganise the waypoints, so that next becomes current and so on
763 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
764 fp->IncrementWaypoint(false);
765 prev = fp->getPreviousWaypoint(); //first waypoint
766 curr = fp->getCurrentWaypoint(); //second waypoint
767 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
771 _new_waypoint = true;
775 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
776 _old_range = _wp_range;
778 object_type type = getType();
781 AccelTo(prev->getSpeed());
783 _curr_alt = curr->getAltitude();
784 _prev_alt = prev->getAltitude();
787 _new_waypoint = false;
790 // now revise the required course for the next way point
791 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
793 if (fgIsFinite(_course))
796 SG_LOG(SG_AI, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
799 } // end Processing FlightPlan
801 bool FGAIShip::initFlightPlan() {
803 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
807 _tunnel = _initial_tunnel;
810 fp->IncrementWaypoint(false);
812 prev = fp->getPreviousWaypoint(); //first waypoint
813 curr = fp->getCurrentWaypoint(); //second waypoint
814 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
816 while (curr->getName() == "WAIT" || curr->getName() == "WAITUNTIL") { // don't wait when initialising
817 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
818 fp->IncrementWaypoint(false);
819 curr = fp->getCurrentWaypoint();
820 next = fp->getNextWaypoint();
823 if (!_start_time.empty()){
824 _start_sec = processTimeString(_start_time);
825 double day_sec = getDaySeconds();
827 if (_start_sec < day_sec){
828 //cout << "flight plan has already started " << _start_time << endl;
829 init = advanceFlightPlan(_start_sec, day_sec);
831 } else if (_start_sec > day_sec && _repeat) {
832 //cout << "flight plan has not started, " << _start_time;
833 //cout << "offsetting start time by -24 hrs" << endl;
835 init = advanceFlightPlan(_start_sec, day_sec);
839 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
842 fp->IncrementWaypoint(false);
843 prev = fp->getPreviousWaypoint();
844 curr = fp->getCurrentWaypoint();
845 next = fp->getNextWaypoint();
850 setLatitude(prev->getLatitude());
851 setLongitude(prev->getLongitude());
852 setSpeed(prev->getSpeed());
856 setHeading(getCourse(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude()));
857 _wp_range = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
858 _old_range = _wp_range;
863 _new_waypoint = true;
865 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " done initialising waypoints " << _tunnel);
874 } // end of initialization
877 double FGAIShip::processTimeString(const string& theTime) {
883 // first split theTime string into
884 // hour, minute, second and convert to int;
885 Hour = atoi(theTime.substr(0,2).c_str());
886 Minute = atoi(theTime.substr(3,5).c_str());
887 Second = atoi(theTime.substr(6,8).c_str());
889 // offset by a day-sec to allow for starting a day earlier
890 double time_seconds = Hour * 3600
897 double FGAIShip::getDaySeconds () {
899 struct tm *t = globals->get_time_params()->getGmt();
901 double day_seconds = t->tm_hour * 3600
908 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
910 double elapsed_sec = start_sec;
911 double distance_nm = 0;
913 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
915 while ( elapsed_sec < day_sec ) {
917 if (next->getName() == "END" || fp->getNextWaypoint() == 0) {
920 //cout << _name << ": " << "restarting flightplan" << endl;
922 curr = fp->getCurrentWaypoint();
923 next = fp->getNextWaypoint();
925 //cout << _name << ": " << "ending flightplan" << endl;
930 } else if (next->getName() == "WAIT") {
931 //cout << _name << ": begin WAIT: " << prev->name << " ";
932 //cout << curr->name << " " << next->name << endl;
934 elapsed_sec += next->getTime_sec();
936 if ( elapsed_sec >= day_sec)
939 fp->IncrementWaypoint(false);
940 next = fp->getNextWaypoint();
942 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT"
943 && next->getName() != "END") {
945 fp->IncrementWaypoint(false);
946 curr = fp->getCurrentWaypoint();
947 next = fp->getNextWaypoint();
950 } else if (next->getName() == "WAITUNTIL") {
951 double until_sec = processTimeString(next->getTime());
953 if (until_sec > _start_sec && start_sec < 0)
956 if (elapsed_sec < until_sec)
957 elapsed_sec = until_sec;
959 if (elapsed_sec >= day_sec )
962 fp->IncrementWaypoint(false);
963 next = fp->getNextWaypoint();
965 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT") {
967 fp->IncrementWaypoint(false);
968 curr = fp->getCurrentWaypoint();
969 next = fp->getNextWaypoint();
972 //cout << _name << ": end WAITUNTIL: ";
973 //cout << prev->name << " " << curr->name << " " << next->name << endl;
976 distance_nm = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
977 elapsed_sec += distance_nm * 60 * 60 / prev->getSpeed();
979 if (elapsed_sec >= day_sec)
982 fp->IncrementWaypoint(false);
983 prev = fp->getPreviousWaypoint();
984 curr = fp->getCurrentWaypoint();
985 next = fp->getNextWaypoint();
990 // the required position lies between the previous and current waypoints
991 // so we will calculate the distance back up the track from the current waypoint
992 // then calculate the lat and lon.
994 //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
995 // << " " << day_sec << endl;
997 double time_diff = elapsed_sec - day_sec;
998 double lat, lon, recip;
1000 //cout << " time diff " << time_diff << endl;
1002 if (next->getName() == "WAIT" ){
1004 lat = curr->getLatitude();
1005 lon = curr->getLongitude();
1006 _wait_count= time_diff;
1008 } else if (next->getName() == "WAITUNTIL") {
1010 lat = curr->getLatitude();
1011 lon = curr->getLongitude();
1014 setSpeed(prev->getSpeed());
1015 distance_nm = speed * time_diff / (60 * 60);
1016 double brg = getCourse(curr->getLatitude(), curr->getLongitude(), prev->getLatitude(), prev->getLongitude());
1018 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1019 // << " lat " << curr->latitude << " lon " << curr->longitude
1020 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1022 lat = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1023 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1024 lon = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1025 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1026 recip = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1027 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1036 void FGAIShip::setWPPos() {
1038 if (curr->getName() == "END" || curr->getName() == "WAIT"
1039 || curr->getName() == "WAITUNTIL" || curr->getName() == "TUNNEL"){
1040 //cout << curr->name << " returning" << endl;
1044 double elevation_m = 0;
1045 wppos.setLatitudeDeg(curr->getLatitude());
1046 wppos.setLongitudeDeg(curr->getLongitude());
1047 wppos.setElevationM(0);
1049 if (curr->getOn_ground()){
1051 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 3000),
1052 elevation_m, NULL, 0)){
1053 wppos.setElevationM(elevation_m);
1056 //cout << curr->name << " setting measured elev " << elevation_m << endl;
1059 wppos.setElevationM(curr->getAltitude());
1060 //cout << curr->name << " setting FP elev " << elevation_m << endl;
1063 curr->setAltitude(wppos.getElevationM());
1067 void FGAIShip::setXTrackError() {
1069 double course = getCourse(prev->getLatitude(), prev->getLongitude(),
1070 curr->getLatitude(), curr->getLongitude());
1071 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1072 curr->getLatitude(), curr->getLongitude());
1073 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1074 double factor = -0.0045 * speed + 1;
1075 double limit = _lead_angle_limit * factor;
1078 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1082 _lead_angle *= _lead_angle_gain * factor;
1083 _xtrack_error = xtrack_error_nm * 6076.1155;
1085 SG_CLAMP_RANGE(_lead_angle, -limit, limit);