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) :
69 _roll_constant(0.001),
71 _roll_factor(-0.0083335)
77 FGAIShip::~FGAIShip() {
80 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
85 FGAIBase::readFromScenario(scFileNode);
87 setRudder(scFileNode->getFloatValue("rudder", 0.0));
88 setName(scFileNode->getStringValue("name", "Titanic"));
89 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
90 std::string flightplan = scFileNode->getStringValue("flightplan");
91 setRepeat(scFileNode->getBoolValue("repeat", false));
92 setStartTime(scFileNode->getStringValue("time", ""));
93 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
94 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
95 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
96 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
97 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
98 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
100 if (!flightplan.empty()) {
101 SG_LOG(SG_GENERAL, SG_ALERT, "getting flightplan: " << _name );
103 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
109 bool FGAIShip::init(bool search_in_AI_path) {
110 prev = 0; // the one behind you
111 curr = 0; // the one ahead
112 next = 0; // the next plus 1
114 props->setStringValue("name", _name.c_str());
115 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
116 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
117 props->setStringValue("waypoint/name-next", _next_name.c_str());
118 props->setStringValue("submodels/path", _path.c_str());
119 props->setStringValue("waypoint/start-time", _start_time.c_str());
120 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
126 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
129 _fp_init = initFlightPlan();
131 return FGAIBase::init(search_in_AI_path);
134 void FGAIShip::bind() {
137 props->tie("surface-positions/rudder-pos-deg",
138 SGRawValuePointer<float>(&_rudder));
139 props->tie("controls/heading-lock",
140 SGRawValuePointer<bool>(&_hdg_lock));
141 props->tie("controls/tgt-speed-kts",
142 SGRawValuePointer<double>(&tgt_speed));
143 props->tie("controls/tgt-heading-degs",
144 SGRawValuePointer<double>(&tgt_heading));
145 props->tie("controls/constants/rudder",
146 SGRawValuePointer<double>(&_rudder_constant));
147 props->tie("controls/constants/roll-factor",
148 SGRawValuePointer<double>(&_roll_factor));
149 props->tie("controls/constants/roll",
150 SGRawValuePointer<double>(&_roll_constant));
151 props->tie("controls/constants/rudder",
152 SGRawValuePointer<double>(&_rudder_constant));
153 props->tie("controls/constants/speed",
154 SGRawValuePointer<double>(&_speed_constant));
155 props->tie("waypoint/range-nm",
156 SGRawValuePointer<double>(&_wp_range));
157 props->tie("waypoint/brg-deg",
158 SGRawValuePointer<double>(&_course));
159 props->tie("waypoint/rangerate-nm-sec",
160 SGRawValuePointer<double>(&_range_rate));
161 props->tie("waypoint/new",
162 SGRawValuePointer<bool>(&_new_waypoint));
163 props->tie("waypoint/missed",
164 SGRawValuePointer<bool>(&_missed));
165 props->tie("waypoint/missed-count-sec",
166 SGRawValuePointer<double>(&_missed_count));
167 props->tie("waypoint/missed-range-nm",
168 SGRawValuePointer<double>(&_missed_range));
169 props->tie("waypoint/missed-time-sec",
170 SGRawValuePointer<double>(&_missed_time_sec));
171 props->tie("waypoint/wait-count-sec",
172 SGRawValuePointer<double>(&_wait_count));
173 props->tie("waypoint/xtrack-error-ft",
174 SGRawValuePointer<double>(&_xtrack_error));
175 props->tie("waypoint/waiting",
176 SGRawValuePointer<bool>(&_waiting));
177 props->tie("waypoint/lead-angle-deg",
178 SGRawValuePointer<double>(&_lead_angle));
179 props->tie("waypoint/tunnel",
180 SGRawValuePointer<bool>(&_tunnel));
181 props->tie("waypoint/alt-curr-m",
182 SGRawValuePointer<double>(&_curr_alt));
183 props->tie("waypoint/alt-prev-m",
184 SGRawValuePointer<double>(&_prev_alt));
185 props->tie("submodels/serviceable",
186 SGRawValuePointer<bool>(&_serviceable));
187 props->tie("controls/turn-radius-ft",
188 SGRawValuePointer<double>(&turn_radius_ft));
189 props->tie("controls/turn-radius-corrected-ft",
190 SGRawValuePointer<double>(&_rd_turn_radius_ft));
191 props->tie("controls/constants/lead-angle/gain",
192 SGRawValuePointer<double>(&_lead_angle_gain));
193 props->tie("controls/constants/lead-angle/limit-deg",
194 SGRawValuePointer<double>(&_lead_angle_limit));
195 props->tie("controls/constants/lead-angle/proportion",
196 SGRawValuePointer<double>(&_proportion));
197 props->tie("controls/fixed-turn-radius-ft",
198 SGRawValuePointer<double>(&_fixed_turn_radius));
201 void FGAIShip::unbind() {
203 props->untie("surface-positions/rudder-pos-deg");
204 props->untie("controls/heading-lock");
205 props->untie("controls/tgt-speed-kts");
206 props->untie("controls/tgt-heading-degs");
207 props->untie("controls/constants/roll");
208 props->untie("controls/constants/rudder");
209 props->untie("controls/constants/roll-factor");
210 props->untie("controls/constants/speed");
211 props->untie("waypoint/range-nm");
212 props->untie("waypoint/range-brg-deg");
213 props->untie("waypoint/rangerate-nm-sec");
214 props->untie("waypoint/new");
215 props->untie("waypoint/missed");
216 props->untie("waypoint/missed-count-sec");
217 props->untie("waypoint/missed-time-sec");
218 props->untie("waypoint/missed-range");
219 props->untie("waypoint/wait-count-sec");
220 props->untie("waypoint/lead-angle-deg");
221 props->untie("waypoint/xtrack-error-ft");
222 props->untie("waypoint/waiting");
223 props->untie("waypoint/tunnel");
224 props->untie("waypoint/alt-curr-m");
225 props->untie("waypoint/alt-prev-m");
226 props->untie("submodels/serviceable");
227 props->untie("controls/turn-radius-ft");
228 props->untie("controls/turn-radius-corrected-ft");
229 props->untie("controls/constants/lead-angle/gain");
230 props->untie("controls/constants/lead-angle/limit-deg");
231 props->untie("controls/constants/lead-angle/proportion");
232 props->untie("controls/fixed-turn-radius-ft");
233 props->untie("controls/constants/speed");
236 void FGAIShip::update(double dt) {
237 //SG_LOG(SG_GENERAL, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
238 // For computation of rotation speeds we just use finite differences here.
239 // That is perfectly valid since this thing is not driven by accelerations
240 // but by just apply discrete changes at its velocity variables.
241 // Update the velocity information stored in those nodes.
242 // Transform that one to the horizontal local coordinate system.
243 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
244 // The orientation of the carrier wrt the horizontal local frame
245 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
246 // and postrotate the orientation of the AIModel wrt the horizontal
248 SGQuatd ec2body = ec2hl*hl2body;
249 // The cartesian position of the carrier in the wgs84 world
250 SGVec3d cartPos = SGVec3d::fromGeod(pos);
252 // The simulation time this transform is meant for
253 aip.setReferenceTime(globals->get_sim_time_sec());
255 // Compute the velocity in m/s in the body frame
256 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
258 FGAIBase::update(dt);
264 // Only change these values if we are able to compute them safely
265 if (SGLimits<double>::min() < dt) {
266 // Now here is the finite difference ...
268 // Transform that one to the horizontal local coordinate system.
269 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
270 // compute the new orientation
271 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
272 // The rotation difference
273 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
274 SGVec3d dOrAngleAxis;
275 dOr.getAngleAxis(dOrAngleAxis);
276 // divided by the time difference provides a rotation speed vector
279 aip.setBodyAngularVelocity(dOrAngleAxis);
283 void FGAIShip::Run(double dt) {
285 ProcessFlightPlan(dt);
287 string type = getTypeString();
294 double speed_diff = tgt_speed - speed;
296 if (fabs(speed_diff) > 0.1) {
298 if (speed_diff > 0.0)
299 speed += _speed_constant * dt;
301 if (speed_diff < 0.0)
302 speed -= _speed_constant * dt;
306 // do not allow unreasonable speeds
310 // convert speed to degrees per second
311 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
312 * speed * 1.686 / ft_per_deg_lat;
313 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
314 * speed * 1.686 / ft_per_deg_lon;
317 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
318 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
319 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
320 pos.setElevationFt(tgt_altitude_ft);
323 // adjust heading based on current _rudder angle
324 if (turn_radius_ft <= 0)
325 turn_radius_ft = 0; // don't allow nonsense values
334 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
336 _sp_turn_radius_ft = _fixed_turn_radius;
338 // adjust turn radius for speed. The equation is very approximate.
339 // we need to allow for negative speeds
341 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
343 _sp_turn_radius_ft = turn_radius_ft;
347 if (_rudder <= -0.25 || _rudder >= 0.25) {
348 // adjust turn radius for _rudder angle. The equation is even more approximate.
353 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
355 // calculate the angle, alpha, subtended by the arc traversed in time dt
356 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
357 //cout << _name << " alpha " << alpha << endl;
358 // make sure that alpha is applied in the right direction
359 hdg += alpha * sign(_rudder);
361 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
363 //adjust roll for rudder angle and speed. Another bit of voodoo
364 raw_roll = _roll_factor * speed * _rudder;
366 // _rudder angle is 0
374 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
376 // adjust target _rudder angle if heading lock engaged
377 double rudder_diff = 0.0;
379 double rudder_sense = 0.0;
380 double diff = fabs(hdg - tgt_heading);
381 //cout << "_rudder diff" << diff << endl;
383 diff = fabs(diff - 360);
385 double sum = hdg + diff;
390 if (fabs(sum - tgt_heading)< 1.0)
396 rudder_sense = -rudder_sense;
399 _tgt_rudder = diff * rudder_sense;
401 _tgt_rudder = 45 * rudder_sense;
403 rudder_diff = _tgt_rudder - _rudder;
406 // set the _rudder limit by speed
410 rudder_limit = (-0.825 * speed) + 35;
417 if (fabs(rudder_diff)> 0.1) { // apply dead zone
419 if (rudder_diff > 0.0) {
420 _rudder += _rudder_constant * dt;
422 if (_rudder > rudder_limit) // apply the _rudder limit
423 _rudder = rudder_limit;
425 } else if (rudder_diff < 0.0) {
426 _rudder -= _rudder_constant * dt;
428 if (_rudder < -rudder_limit)
429 _rudder = -rudder_limit;
433 // do calculations for radar
434 UpdateRadar(manager);
438 void FGAIShip::AccelTo(double speed) {
442 void FGAIShip::PitchTo(double angle) {
446 void FGAIShip::RollTo(double angle) {
450 void FGAIShip::YawTo(double angle) {
453 void FGAIShip::ClimbTo(double altitude) {
454 tgt_altitude_ft = altitude;
455 _setAltitude(altitude);
458 void FGAIShip::TurnTo(double heading) {
459 //double relbrg_corr = _relbrg;
461 //if ( relbrg_corr > 5)
463 //else if( relbrg_corr < -5)
466 tgt_heading = heading - _lead_angle + _tow_angle;
467 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
471 double FGAIShip::sign(double x) {
478 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
482 void FGAIShip::setName(const string& n) {
486 void FGAIShip::setStartTime(const string& st) {
490 void FGAIShip::setUntilTime(const string& ut) {
492 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
495 void FGAIShip::setCurrName(const string& c) {
497 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
500 void FGAIShip::setNextName(const string& n) {
502 props->setStringValue("waypoint/name-next", _next_name.c_str());
505 void FGAIShip::setPrevName(const string& p) {
507 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
510 void FGAIShip::setRepeat(bool r) {
514 void FGAIShip::setMissed(bool m) {
516 props->setBoolValue("waypoint/missed", _missed);
519 void FGAIShip::setRudder(float r) {
523 void FGAIShip::setRoll(double rl) {
527 void FGAIShip::setLeadAngleGain(double g) {
528 _lead_angle_gain = g;
531 void FGAIShip::setLeadAngleLimit(double l) {
532 _lead_angle_limit = l;
535 void FGAIShip::setLeadAngleProp(double p) {
539 void FGAIShip::setRudderConstant(double rc) {
540 _rudder_constant = rc;
543 void FGAIShip::setSpeedConstant(double sc) {
544 _speed_constant = sc;
547 void FGAIShip::setFixedTurnRadius(double ftr) {
548 _fixed_turn_radius = ftr;
551 void FGAIShip::setWPNames() {
554 setPrevName(prev->name);
559 setCurrName(curr->name);
562 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: current wp name error" );
566 setNextName(next->name);
570 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
571 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
572 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
576 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
578 double course, distance, az2;
580 //calculate the bearing and range of the second pos from the first
581 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
582 distance *= SG_METER_TO_NM;
586 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
588 double course, distance, recip;
590 //calculate the bearing and range of the second pos from the first
591 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
592 if (tgt_speed >= 0) {
594 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: course " << course);
597 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: recip " << recip);
601 void FGAIShip::ProcessFlightPlan(double dt) {
603 double time_sec = getDaySeconds();
607 ///////////////////////////////////////////////////////////////////////////
608 // Check Execution time (currently once every 1 sec)
609 // Add a bit of randomization to prevent the execution of all flight plans
610 // in synchrony, which can add significant periodic framerate flutter.
611 ///////////////////////////////////////////////////////////////////////////
613 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
614 if (_dt_count < _next_run && _start_sec < time_sec)
617 _next_run = 1.0 + (0.5 * sg_random());
619 double until_time_sec = 0;
622 // check to see if we've reached the point for our next turn
623 // if the range to the waypoint is less than the calculated turn
624 // radius we can start the turn to the next leg
625 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
626 _range_rate = (_wp_range - _old_range) / _dt_count;
627 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
628 // we need to try to identify a _missed waypoint
630 // calculate the time needed to turn through an arc of 90 degrees,
631 // and allow a time error
633 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
635 _missed_time_sec = 10;
637 _missed_range = 4 * sp_turn_radius_nm;
639 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
640 //if ((_range_rate > 0) && !_new_waypoint){
641 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
642 _missed_count += _dt_count;
645 if (_missed_count >= 120)
647 else if (_missed_count >= _missed_time_sec)
652 _old_range = _wp_range;
655 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
657 if (_next_name == "TUNNEL"){
660 //SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " TUNNEL ");
662 fp->IncrementWaypoint(false);
663 next = fp->getNextWaypoint();
665 if (next->name == "WAITUNTIL" || next->name == "WAIT"
666 || next->name == "END" || next->name == "TUNNEL")
670 fp->IncrementWaypoint(false);
671 curr = fp->getCurrentWaypoint();
672 next = fp->getNextWaypoint();
674 }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
677 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: "<< _name << "Flightplan restarting ");
680 curr = fp->getCurrentWaypoint();
681 next = fp->getNextWaypoint();
683 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
684 _old_range = _wp_range;
686 _new_waypoint = true;
689 AccelTo(prev->speed);
691 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
697 } else if (_next_name == "WAIT") {
699 if (_wait_count < next->time_sec) {
700 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
703 _wait_count += _dt_count;
708 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
709 << " wait done: getting new waypoints ");
712 fp->IncrementWaypoint(false);
713 next = fp->getNextWaypoint();
715 if (next->name == "WAITUNTIL" || next->name == "WAIT"
716 || next->name == "END" || next->name == "TUNNEL")
720 fp->IncrementWaypoint(false);
721 curr = fp->getCurrentWaypoint();
722 next = fp->getNextWaypoint();
725 } else if (_next_name == "WAITUNTIL") {
726 time_sec = getDaySeconds();
727 until_time_sec = processTimeString(next->time);
728 _until_time = next->time;
729 setUntilTime(next->time);
730 if (until_time_sec > time_sec) {
731 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " "
732 << curr->name << " waiting until: "
733 << _until_time << " " << until_time_sec << " now " << time_sec );
739 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
740 << _name << " wait until done: getting new waypoints ");
742 fp->IncrementWaypoint(false);
744 while (next->name == "WAITUNTIL") {
745 fp->IncrementWaypoint(false);
746 next = fp->getNextWaypoint();
749 if (next->name == "WAIT")
753 fp->IncrementWaypoint(false);
754 curr = fp->getCurrentWaypoint();
755 next = fp->getNextWaypoint();
760 //now reorganise the waypoints, so that next becomes current and so on
761 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
762 fp->IncrementWaypoint(false);
763 prev = fp->getPreviousWaypoint(); //first waypoint
764 curr = fp->getCurrentWaypoint(); //second waypoint
765 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
769 _new_waypoint = true;
773 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
774 _old_range = _wp_range;
776 object_type type = getType();
779 AccelTo(prev->speed);
781 _curr_alt = curr->altitude;
782 _prev_alt = prev->altitude;
785 _new_waypoint = false;
788 // now revise the required course for the next way point
789 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
794 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
797 } // end Processing FlightPlan
799 bool FGAIShip::initFlightPlan() {
801 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
807 fp->IncrementWaypoint(false);
809 prev = fp->getPreviousWaypoint(); //first waypoint
810 curr = fp->getCurrentWaypoint(); //second waypoint
811 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
813 while (curr->name == "WAIT" || curr->name == "WAITUNTIL") { // don't wait when initialising
814 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
815 fp->IncrementWaypoint(false);
816 curr = fp->getCurrentWaypoint();
817 next = fp->getNextWaypoint();
820 if (!_start_time.empty()){
821 _start_sec = processTimeString(_start_time);
822 double day_sec = getDaySeconds();
824 if (_start_sec < day_sec){
825 //cout << "flight plan has already started " << _start_time << endl;
826 init = advanceFlightPlan(_start_sec, day_sec);
828 } else if (_start_sec > day_sec && _repeat) {
829 //cout << "flight plan has not started, " << _start_time;
830 //cout << "offsetting start time by -24 hrs" << endl;
832 init = advanceFlightPlan(_start_sec, day_sec);
836 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
839 fp->IncrementWaypoint(false);
840 prev = fp->getPreviousWaypoint();
841 curr = fp->getCurrentWaypoint();
842 next = fp->getNextWaypoint();
847 setLatitude(prev->latitude);
848 setLongitude(prev->longitude);
849 setSpeed(prev->speed);
853 setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
854 _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
855 _old_range = _wp_range;
860 _new_waypoint = true;
862 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " done initialising waypoints ");
871 } // end of initialization
874 double FGAIShip::processTimeString(const string& theTime) {
880 // first split theTime string into
881 // hour, minute, second and convert to int;
882 Hour = atoi(theTime.substr(0,2).c_str());
883 Minute = atoi(theTime.substr(3,5).c_str());
884 Second = atoi(theTime.substr(6,8).c_str());
886 // offset by a day-sec to allow for starting a day earlier
887 double time_seconds = Hour * 3600
894 double FGAIShip::getDaySeconds () {
896 struct tm *t = globals->get_time_params()->getGmt();
898 double day_seconds = t->tm_hour * 3600
905 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
907 double elapsed_sec = start_sec;
908 double distance_nm = 0;
910 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
912 while ( elapsed_sec < day_sec ) {
914 if (next->name == "END" || fp->getNextWaypoint() == 0) {
917 //cout << _name << ": " << "restarting flightplan" << endl;
919 curr = fp->getCurrentWaypoint();
920 next = fp->getNextWaypoint();
922 //cout << _name << ": " << "ending flightplan" << endl;
927 } else if (next->name == "WAIT") {
928 //cout << _name << ": begin WAIT: " << prev->name << " ";
929 //cout << curr->name << " " << next->name << endl;
931 elapsed_sec += next->time_sec;
933 if ( elapsed_sec >= day_sec)
936 fp->IncrementWaypoint(false);
937 next = fp->getNextWaypoint();
939 if (next->name != "WAITUNTIL" && next->name != "WAIT"
940 && next->name != "END") {
942 fp->IncrementWaypoint(false);
943 curr = fp->getCurrentWaypoint();
944 next = fp->getNextWaypoint();
947 } else if (next->name == "WAITUNTIL") {
948 double until_sec = processTimeString(next->time);
950 if (until_sec > _start_sec && start_sec < 0)
953 if (elapsed_sec < until_sec)
954 elapsed_sec = until_sec;
956 if (elapsed_sec >= day_sec )
959 fp->IncrementWaypoint(false);
960 next = fp->getNextWaypoint();
962 if (next->name != "WAITUNTIL" && next->name != "WAIT") {
964 fp->IncrementWaypoint(false);
965 curr = fp->getCurrentWaypoint();
966 next = fp->getNextWaypoint();
969 //cout << _name << ": end WAITUNTIL: ";
970 //cout << prev->name << " " << curr->name << " " << next->name << endl;
973 distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
974 elapsed_sec += distance_nm * 60 * 60 / prev->speed;
976 if (elapsed_sec >= day_sec)
979 fp->IncrementWaypoint(false);
980 prev = fp->getPreviousWaypoint();
981 curr = fp->getCurrentWaypoint();
982 next = fp->getNextWaypoint();
987 // the required position lies between the previous and current waypoints
988 // so we will calculate the distance back up the track from the current waypoint
989 // then calculate the lat and lon.
991 //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
992 // << " " << day_sec << endl;
994 double time_diff = elapsed_sec - day_sec;
995 double lat, lon, recip;
997 //cout << " time diff " << time_diff << endl;
999 if (next->name == "WAIT" ){
1001 lat = curr->latitude;
1002 lon = curr->longitude;
1003 _wait_count= time_diff;
1005 } else if (next->name == "WAITUNTIL") {
1007 lat = curr->latitude;
1008 lon = curr->longitude;
1011 setSpeed(prev->speed);
1012 distance_nm = speed * time_diff / (60 * 60);
1013 double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
1015 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1016 // << " lat " << curr->latitude << " lon " << curr->longitude
1017 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1019 lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
1020 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1021 lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
1022 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1023 recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
1024 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1033 void FGAIShip::setWPPos() {
1035 if (curr->name == "END" || curr->name == "WAIT"
1036 || curr->name == "WAITUNTIL" || curr->name == "TUNNEL"){
1037 //cout << curr->name << " returning" << endl;
1041 double elevation_m = 0;
1042 wppos.setLatitudeDeg(curr->latitude);
1043 wppos.setLongitudeDeg(curr->longitude);
1044 wppos.setElevationM(0);
1046 if (curr->on_ground){
1048 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 10000),
1049 elevation_m, &_material)){
1050 wppos.setElevationM(elevation_m);
1053 //cout << curr->name << " setting measured elev " << elevation_m << endl;
1056 wppos.setElevationM(curr->altitude);
1057 //cout << curr->name << " setting FP elev " << elevation_m << endl;
1060 curr->altitude = wppos.getElevationM();
1064 void FGAIShip::setXTrackError() {
1066 double course = getCourse(prev->latitude, prev->longitude,
1067 curr->latitude, curr->longitude);
1068 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1069 curr->latitude, curr->longitude);
1070 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1073 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1077 _lead_angle *= _lead_angle_gain;
1078 _xtrack_error = xtrack_error_nm * 6076.1155;
1080 SG_CLAMP_RANGE(_lead_angle, -_lead_angle_limit, _lead_angle_limit);