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.
26 # define finite _finite
27 #elif defined(__sun) || defined(sgi)
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>
44 FGAIShip::FGAIShip(object_type ot) :
58 FGAIShip::~FGAIShip() {
61 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
66 FGAIBase::readFromScenario(scFileNode);
68 setRudder(scFileNode->getFloatValue("rudder", 0.0));
69 setName(scFileNode->getStringValue("name", "Titanic"));
70 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
71 std::string flightplan = scFileNode->getStringValue("flightplan");
72 setRepeat(scFileNode->getBoolValue("repeat", false));
73 setStartTime(scFileNode->getStringValue("time", ""));
74 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
75 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
76 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
77 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
78 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
79 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
81 if (!flightplan.empty()) {
82 SG_LOG(SG_GENERAL, SG_ALERT, "getting flightplan: " << _name );
84 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
90 bool FGAIShip::init(bool search_in_AI_path) {
91 prev = 0; // the one behind you
92 curr = 0; // the one ahead
93 next = 0; // the next plus 1
97 props->setStringValue("name", _name.c_str());
98 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
99 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
100 props->setStringValue("waypoint/name-next", _next_name.c_str());
101 props->setStringValue("submodels/path", _path.c_str());
102 props->setStringValue("waypoint/start-time", _start_time.c_str());
103 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
109 _roll_constant = 0.001;
110 _hdg_constant = 0.01;
111 _roll_factor = -0.0083335;
113 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
118 _new_waypoint = true;
122 _missed_time_sec = 30;
127 _wp_range = _old_range = 0;
131 _fp_init = initFlightPlan();
133 return FGAIBase::init(search_in_AI_path);
136 void FGAIShip::bind() {
139 props->tie("surface-positions/rudder-pos-deg",
140 SGRawValuePointer<float>(&_rudder));
141 props->tie("controls/heading-lock",
142 SGRawValuePointer<bool>(&_hdg_lock));
143 props->tie("controls/tgt-speed-kts",
144 SGRawValuePointer<double>(&tgt_speed));
145 props->tie("controls/tgt-heading-degs",
146 SGRawValuePointer<double>(&tgt_heading));
147 props->tie("controls/constants/rudder",
148 SGRawValuePointer<double>(&_rudder_constant));
149 props->tie("controls/constants/roll-factor",
150 SGRawValuePointer<double>(&_roll_factor));
151 props->tie("controls/constants/roll",
152 SGRawValuePointer<double>(&_roll_constant));
153 props->tie("controls/constants/rudder",
154 SGRawValuePointer<double>(&_rudder_constant));
155 props->tie("controls/constants/speed",
156 SGRawValuePointer<double>(&_speed_constant));
157 props->tie("waypoint/range-nm",
158 SGRawValuePointer<double>(&_wp_range));
159 props->tie("waypoint/brg-deg",
160 SGRawValuePointer<double>(&_course));
161 props->tie("waypoint/rangerate-nm-sec",
162 SGRawValuePointer<double>(&_range_rate));
163 props->tie("waypoint/new",
164 SGRawValuePointer<bool>(&_new_waypoint));
165 props->tie("waypoint/missed",
166 SGRawValuePointer<bool>(&_missed));
167 props->tie("waypoint/missed-count-sec",
168 SGRawValuePointer<double>(&_missed_count));
169 props->tie("waypoint/missed-range-nm",
170 SGRawValuePointer<double>(&_missed_range));
171 props->tie("waypoint/missed-time-sec",
172 SGRawValuePointer<double>(&_missed_time_sec));
173 props->tie("waypoint/wait-count-sec",
174 SGRawValuePointer<double>(&_wait_count));
175 props->tie("waypoint/xtrack-error-ft",
176 SGRawValuePointer<double>(&_xtrack_error));
177 props->tie("waypoint/waiting",
178 SGRawValuePointer<bool>(&_waiting));
179 props->tie("waypoint/lead-angle-deg",
180 SGRawValuePointer<double>(&_lead_angle));
181 props->tie("submodels/serviceable",
182 SGRawValuePointer<bool>(&_serviceable));
183 props->tie("controls/turn-radius-ft",
184 SGRawValuePointer<double>(&turn_radius_ft));
185 props->tie("controls/turn-radius-corrected-ft",
186 SGRawValuePointer<double>(&_rd_turn_radius_ft));
187 props->tie("controls/constants/lead-angle/gain",
188 SGRawValuePointer<double>(&_lead_angle_gain));
189 props->tie("controls/constants/lead-angle/limit-deg",
190 SGRawValuePointer<double>(&_lead_angle_limit));
191 props->tie("controls/constants/lead-angle/proportion",
192 SGRawValuePointer<double>(&_proportion));
193 props->tie("controls/fixed-turn-radius-ft",
194 SGRawValuePointer<double>(&_fixed_turn_radius));
197 void FGAIShip::unbind() {
199 props->untie("surface-positions/rudder-pos-deg");
200 props->untie("controls/heading-lock");
201 props->untie("controls/tgt-speed-kts");
202 props->untie("controls/tgt-heading-degs");
203 props->untie("controls/constants/roll");
204 props->untie("controls/constants/rudder");
205 props->untie("controls/constants/roll-factor");
206 props->untie("controls/constants/speed");
207 props->untie("waypoint/range-nm");
208 props->untie("waypoint/range-brg-deg");
209 props->untie("waypoint/rangerate-nm-sec");
210 props->untie("waypoint/new");
211 props->untie("waypoint/missed");
212 props->untie("waypoint/missed-count-sec");
213 props->untie("waypoint/missed-time-sec");
214 props->untie("waypoint/missed-range");
215 props->untie("waypoint/wait-count-sec");
216 props->untie("waypoint/lead-angle-deg");
217 props->untie("waypoint/xtrack-error-ft");
218 props->untie("waypoint/waiting");
219 props->untie("submodels/serviceable");
220 props->untie("controls/turn-radius-ft");
221 props->untie("controls/turn-radius-corrected-ft");
222 props->untie("controls/constants/lead-angle/gain");
223 props->untie("controls/constants/lead-angle/limit-deg");
224 props->untie("controls/constants/lead-angle/proportion");
225 props->untie("controls/fixed-turn-radius-ft");
226 props->untie("controls/constants/speed");
229 void FGAIShip::update(double dt) {
230 //SG_LOG(SG_GENERAL, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
231 // For computation of rotation speeds we just use finite differences here.
232 // That is perfectly valid since this thing is not driven by accelerations
233 // but by just apply discrete changes at its velocity variables.
234 // Update the velocity information stored in those nodes.
235 // Transform that one to the horizontal local coordinate system.
236 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
237 // The orientation of the carrier wrt the horizontal local frame
238 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
239 // and postrotate the orientation of the AIModel wrt the horizontal
241 SGQuatd ec2body = ec2hl*hl2body;
242 // The cartesian position of the carrier in the wgs84 world
243 SGVec3d cartPos = SGVec3d::fromGeod(pos);
245 // The simulation time this transform is meant for
246 aip.setReferenceTime(globals->get_sim_time_sec());
248 // Compute the velocity in m/s in the body frame
249 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
251 FGAIBase::update(dt);
257 // Only change these values if we are able to compute them safely
258 if (SGLimits<double>::min() < dt) {
259 // Now here is the finite difference ...
261 // Transform that one to the horizontal local coordinate system.
262 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
263 // compute the new orientation
264 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
265 // The rotation difference
266 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
267 SGVec3d dOrAngleAxis;
268 dOr.getAngleAxis(dOrAngleAxis);
269 // divided by the time difference provides a rotation speed vector
272 aip.setBodyAngularVelocity(dOrAngleAxis);
276 void FGAIShip::Run(double dt) {
278 ProcessFlightPlan(dt);
280 string type = getTypeString();
287 double speed_diff = tgt_speed - speed;
289 if (fabs(speed_diff) > 0.1) {
291 if (speed_diff > 0.0)
292 speed += _speed_constant * dt;
294 if (speed_diff < 0.0)
295 speed -= _speed_constant * dt;
299 // do not allow unreasonable speeds
303 // convert speed to degrees per second
304 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
305 * speed * 1.686 / ft_per_deg_lat;
306 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
307 * speed * 1.686 / ft_per_deg_lon;
310 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
311 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
312 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
313 pos.setElevationFt(tgt_altitude_ft);
316 // adjust heading based on current _rudder angle
317 if (turn_radius_ft <= 0)
318 turn_radius_ft = 0; // don't allow nonsense values
327 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
329 _sp_turn_radius_ft = _fixed_turn_radius;
331 // adjust turn radius for speed. The equation is very approximate.
332 // we need to allow for negative speeds
334 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
336 _sp_turn_radius_ft = turn_radius_ft;
340 if (_rudder <= -0.25 || _rudder >= 0.25) {
341 // adjust turn radius for _rudder angle. The equation is even more approximate.
346 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
348 // calculate the angle, alpha, subtended by the arc traversed in time dt
349 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
350 //cout << _name << " alpha " << alpha << endl;
351 // make sure that alpha is applied in the right direction
352 hdg += alpha * sign(_rudder);
354 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
356 //adjust roll for rudder angle and speed. Another bit of voodoo
357 raw_roll = _roll_factor * speed * _rudder;
359 // _rudder angle is 0
367 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
369 // adjust target _rudder angle if heading lock engaged
370 double rudder_diff = 0.0;
372 double rudder_sense = 0.0;
373 double diff = fabs(hdg - tgt_heading);
374 //cout << "_rudder diff" << diff << endl;
376 diff = fabs(diff - 360);
378 double sum = hdg + diff;
383 if (fabs(sum - tgt_heading)< 1.0)
389 rudder_sense = -rudder_sense;
392 _tgt_rudder = diff * rudder_sense;
394 _tgt_rudder = 45 * rudder_sense;
396 rudder_diff = _tgt_rudder - _rudder;
399 // set the _rudder limit by speed
403 rudder_limit = (-0.825 * speed) + 35;
410 if (fabs(rudder_diff)> 0.1) { // apply dead zone
412 if (rudder_diff > 0.0) {
413 _rudder += _rudder_constant * dt;
415 if (_rudder > rudder_limit) // apply the _rudder limit
416 _rudder = rudder_limit;
418 } else if (rudder_diff < 0.0) {
419 _rudder -= _rudder_constant * dt;
421 if (_rudder < -rudder_limit)
422 _rudder = -rudder_limit;
426 // do calculations for radar
427 UpdateRadar(manager);
431 void FGAIShip::AccelTo(double speed) {
435 void FGAIShip::PitchTo(double angle) {
439 void FGAIShip::RollTo(double angle) {
443 void FGAIShip::YawTo(double angle) {
446 void FGAIShip::ClimbTo(double altitude) {
447 tgt_altitude_ft = altitude;
448 _setAltitude(altitude);
451 void FGAIShip::TurnTo(double heading) {
452 //double relbrg_corr = _relbrg;
454 //if ( relbrg_corr > 5)
456 //else if( relbrg_corr < -5)
459 tgt_heading = heading - _lead_angle + _tow_angle;
460 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
464 double FGAIShip::sign(double x) {
471 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
475 void FGAIShip::setName(const string& n) {
479 void FGAIShip::setStartTime(const string& st) {
483 void FGAIShip::setUntilTime(const string& ut) {
485 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
488 void FGAIShip::setCurrName(const string& c) {
490 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
493 void FGAIShip::setNextName(const string& n) {
495 props->setStringValue("waypoint/name-next", _next_name.c_str());
498 void FGAIShip::setPrevName(const string& p) {
500 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
503 void FGAIShip::setRepeat(bool r) {
507 void FGAIShip::setMissed(bool m) {
509 props->setBoolValue("waypoint/missed", _missed);
512 void FGAIShip::setRudder(float r) {
516 void FGAIShip::setRoll(double rl) {
520 void FGAIShip::setLeadAngleGain(double g) {
521 _lead_angle_gain = g;
524 void FGAIShip::setLeadAngleLimit(double l) {
525 _lead_angle_limit = l;
528 void FGAIShip::setLeadAngleProp(double p) {
532 void FGAIShip::setRudderConstant(double rc) {
533 _rudder_constant = rc;
536 void FGAIShip::setSpeedConstant(double sc) {
537 _speed_constant = sc;
540 void FGAIShip::setFixedTurnRadius(double ftr) {
541 _fixed_turn_radius = ftr;
544 void FGAIShip::setWPNames() {
547 setPrevName(prev->name);
552 setCurrName(curr->name);
555 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: current wp name error" );
559 setNextName(next->name);
563 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
564 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
565 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
569 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
571 double course, distance, az2;
573 //calculate the bearing and range of the second pos from the first
574 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
575 distance *= SG_METER_TO_NM;
579 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
581 double course, distance, recip;
583 //calculate the bearing and range of the second pos from the first
584 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
585 if (tgt_speed >= 0) {
587 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: course " << course);
590 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: recip " << recip);
594 void FGAIShip::ProcessFlightPlan(double dt) {
596 double time_sec = getDaySeconds();
597 double until_time_sec = 0;
602 ///////////////////////////////////////////////////////////////////////////
603 // Check Execution time (currently once every 1 sec)
604 // Add a bit of randomization to prevent the execution of all flight plans
605 // in synchrony, which can add significant periodic framerate flutter.
606 ///////////////////////////////////////////////////////////////////////////
608 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
609 if (_dt_count < _next_run && _start_sec < time_sec)
612 _next_run = 1.0 + (0.5 * sg_random());
614 // check to see if we've reached the point for our next turn
615 // if the range to the waypoint is less than the calculated turn
616 // radius we can start the turn to the next leg
617 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
618 _range_rate = (_wp_range - _old_range) / _dt_count;
619 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
620 // we need to try to identify a _missed waypoint
622 // calculate the time needed to turn through an arc of 90 degrees,
623 // and allow a time error
625 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
627 _missed_time_sec = 10;
629 _missed_range = 4 * sp_turn_radius_nm;
631 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
632 //if ((_range_rate > 0) && !_new_waypoint){
633 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
634 _missed_count += _dt_count;
637 if (_missed_count >= 120)
639 else if (_missed_count >= _missed_time_sec)
644 _old_range = _wp_range;
647 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
649 if (_next_name == "END" || fp->getNextWaypoint() == 0) {
652 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: "<< _name << "Flightplan restarting ");
655 curr = fp->getCurrentWaypoint();
656 next = fp->getNextWaypoint();
658 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
659 _old_range = _wp_range;
661 _new_waypoint = true;
664 AccelTo(prev->speed);
666 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
672 } else if (_next_name == "WAIT") {
674 if (_wait_count < next->time_sec) {
675 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
678 _wait_count += _dt_count;
683 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
684 << " wait done: getting new waypoints ");
687 fp->IncrementWaypoint(false);
688 next = fp->getNextWaypoint();
690 if (next->name == "WAITUNTIL" || next->name == "WAIT"
691 || next->name == "END")
695 fp->IncrementWaypoint(false);
696 curr = fp->getCurrentWaypoint();
697 next = fp->getNextWaypoint();
700 } else if (_next_name == "WAITUNTIL") {
701 time_sec = getDaySeconds();
702 until_time_sec = processTimeString(next->time);
703 _until_time = next->time;
704 setUntilTime(next->time);
705 if (until_time_sec > time_sec) {
706 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " "
707 << curr->name << " waiting until: "
708 << _until_time << " " << until_time_sec << " now " << time_sec );
714 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
715 << _name << " wait until done: getting new waypoints ");
717 fp->IncrementWaypoint(false);
719 while (next->name == "WAITUNTIL") {
720 fp->IncrementWaypoint(false);
721 next = fp->getNextWaypoint();
724 if (next->name == "WAIT")
728 fp->IncrementWaypoint(false);
729 curr = fp->getCurrentWaypoint();
730 next = fp->getNextWaypoint();
735 //now reorganise the waypoints, so that next becomes current and so on
736 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
737 fp->IncrementWaypoint(false);
738 prev = fp->getPreviousWaypoint(); //first waypoint
739 curr = fp->getCurrentWaypoint(); //second waypoint
740 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
744 _new_waypoint = true;
748 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
749 _old_range = _wp_range;
751 AccelTo(prev->speed);
754 _new_waypoint = false;
757 // now revise the required course for the next way point
758 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
763 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
766 } // end Processing FlightPlan
768 bool FGAIShip::initFlightPlan() {
770 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
777 fp->IncrementWaypoint(false);
779 prev = fp->getPreviousWaypoint(); //first waypoint
780 curr = fp->getCurrentWaypoint(); //second waypoint
781 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
783 while (curr->name == "WAIT" || curr->name == "WAITUNTIL") { // don't wait when initialising
784 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
785 fp->IncrementWaypoint(false);
786 curr = fp->getCurrentWaypoint();
787 next = fp->getNextWaypoint();
790 if (!_start_time.empty()){
791 _start_sec = processTimeString(_start_time);
792 double day_sec = getDaySeconds();
794 if (_start_sec < day_sec){
795 //cout << "flight plan has already started " << _start_time << endl;
796 init = advanceFlightPlan(_start_sec, day_sec);
798 } else if (_start_sec > day_sec && _repeat) {
799 //cout << "flight plan has not started, " << _start_time;
800 //cout << "offsetting start time by -24 hrs" << endl;
802 init = advanceFlightPlan(_start_sec, day_sec);
806 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
809 fp->IncrementWaypoint(false);
810 prev = fp->getPreviousWaypoint();
811 curr = fp->getCurrentWaypoint();
812 next = fp->getNextWaypoint();
817 setLatitude(prev->latitude);
818 setLongitude(prev->longitude);
819 setSpeed(prev->speed);
823 setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
824 _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
825 _old_range = _wp_range;
830 _new_waypoint = true;
832 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " done initialising waypoints ");
841 } // end of initialization
844 double FGAIShip::processTimeString(const string& theTime) {
850 // first split theTime string into
851 // hour, minute, second and convert to int;
852 Hour = atoi(theTime.substr(0,2).c_str());
853 Minute = atoi(theTime.substr(3,5).c_str());
854 Second = atoi(theTime.substr(6,8).c_str());
856 // offset by a day-sec to allow for starting a day earlier
857 double time_seconds = Hour * 3600
864 double FGAIShip::getDaySeconds () {
866 struct tm *t = globals->get_time_params()->getGmt();
868 double day_seconds = t->tm_hour * 3600
875 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
877 double elapsed_sec = start_sec;
878 double distance_nm = 0;
880 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
882 while ( elapsed_sec < day_sec ) {
884 if (next->name == "END" || fp->getNextWaypoint() == 0) {
887 //cout << _name << ": " << "restarting flightplan" << endl;
889 curr = fp->getCurrentWaypoint();
890 next = fp->getNextWaypoint();
892 //cout << _name << ": " << "ending flightplan" << endl;
897 } else if (next->name == "WAIT") {
898 //cout << _name << ": begin WAIT: " << prev->name << " ";
899 //cout << curr->name << " " << next->name << endl;
901 elapsed_sec += next->time_sec;
903 if ( elapsed_sec >= day_sec)
906 fp->IncrementWaypoint(false);
907 next = fp->getNextWaypoint();
909 if (next->name != "WAITUNTIL" && next->name != "WAIT"
910 && next->name != "END") {
912 fp->IncrementWaypoint(false);
913 curr = fp->getCurrentWaypoint();
914 next = fp->getNextWaypoint();
917 } else if (next->name == "WAITUNTIL") {
918 double until_sec = processTimeString(next->time);
920 if (until_sec > _start_sec && start_sec < 0)
923 if (elapsed_sec < until_sec)
924 elapsed_sec = until_sec;
926 if (elapsed_sec >= day_sec )
929 fp->IncrementWaypoint(false);
930 next = fp->getNextWaypoint();
932 if (next->name != "WAITUNTIL" && next->name != "WAIT") {
934 fp->IncrementWaypoint(false);
935 curr = fp->getCurrentWaypoint();
936 next = fp->getNextWaypoint();
939 //cout << _name << ": end WAITUNTIL: ";
940 //cout << prev->name << " " << curr->name << " " << next->name << endl;
943 distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
944 elapsed_sec += distance_nm * 60 * 60 / prev->speed;
946 if (elapsed_sec >= day_sec)
949 fp->IncrementWaypoint(false);
950 prev = fp->getPreviousWaypoint();
951 curr = fp->getCurrentWaypoint();
952 next = fp->getNextWaypoint();
957 // the required position lies between the previous and current waypoints
958 // so we will calculate the distance back up the track from the current waypoint
959 // then calculate the lat and lon.
961 /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
962 << " " << day_sec << endl;*/
964 double time_diff = elapsed_sec - day_sec;
965 double lat, lon, recip;
967 //cout << " time diff " << time_diff << endl;
969 if (next->name == "WAIT" ){
971 lat = curr->latitude;
972 lon = curr->longitude;
973 _wait_count= time_diff;
975 } else if (next->name == "WAITUNTIL") {
977 lat = curr->latitude;
978 lon = curr->longitude;
981 setSpeed(prev->speed);
982 distance_nm = speed * time_diff / (60 * 60);
983 double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
985 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
986 // << " lat " << curr->latitude << " lon " << curr->longitude
987 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
989 lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
990 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
991 lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
992 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
993 recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
994 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1003 void FGAIShip::setWPPos() {
1005 if (curr->name == "END" || curr->name == "WAIT" || curr->name == "WAITUNTIL"){
1006 cout<< curr->name << endl;
1010 double elevation_m = 0;
1011 wppos.setLatitudeDeg(curr->latitude);
1012 wppos.setLongitudeDeg(curr->longitude);
1013 wppos.setElevationFt(0);
1015 if (curr->on_ground){
1017 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 10000),
1018 elevation_m, &_material)){
1019 wppos.setElevationM(elevation_m);
1023 wppos.setElevationFt(curr->altitude);
1028 void FGAIShip::setXTrackError() {
1030 double course = getCourse(prev->latitude, prev->longitude,
1031 curr->latitude, curr->longitude);
1032 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1033 curr->latitude, curr->longitude);
1034 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1036 //if (_wp_range > _sp_turn_radius_ft / (2 * 6076.1155)){
1038 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1042 _lead_angle *= _lead_angle_gain;
1043 _xtrack_error = xtrack_error_nm * 6076.1155;
1045 if (_lead_angle<= -_lead_angle_limit)
1046 _lead_angle = -_lead_angle_limit;
1047 else if (_lead_angle >= _lead_angle_limit)
1048 _lead_angle = _lead_angle_limit;