]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIShip.cxx
bd784444032aa296851e0e51d1a8ede08d92f7a4
[flightgear.git] / src / AIModel / AIShip.cxx
1 // FGAIShip - FGAIBase-derived class creates an AI ship
2 //
3 // Written by David Culp, started October 2003.
4 // with major amendments and additions by Vivian Meazza, 2004 - 2007
5 //
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.
10 //
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.
15 //
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.
19
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #ifdef _MSC_VER
25 #  include <float.h>
26 #  define finite _finite
27 #elif defined(__sun) || defined(sgi)
28 #  include <ieeefp.h>
29 #endif
30
31 #include <math.h>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/math/sg_random.h>
35
36 #include "AIShip.hxx"
37
38
39 FGAIShip::FGAIShip(object_type ot) :
40     FGAIBase(ot),
41     _dt_count(0),
42     _next_run(0)
43 {
44 }
45
46 FGAIShip::~FGAIShip() {
47 }
48
49 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
50
51     if (!scFileNode)
52         return;
53
54     FGAIBase::readFromScenario(scFileNode);
55
56     setRudder(scFileNode->getFloatValue("rudder", 0.0));
57     setName(scFileNode->getStringValue("name", "Titanic"));
58     setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
59     std::string flightplan = scFileNode->getStringValue("flightplan");
60     setRepeat(scFileNode->getBoolValue("repeat", false));
61     setStartTime(scFileNode->getStringValue("time", ""));
62
63     if (!flightplan.empty()) {
64         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
65         setFlightPlan(fp);
66     }
67
68 }
69
70 bool FGAIShip::init(bool search_in_AI_path) {
71     prev = 0; // the one behind you
72     curr = 0; // the one ahead
73     next = 0; // the next plus 1
74
75     _until_time = "";
76
77     props->setStringValue("name", _name.c_str());
78     props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
79     props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
80     props->setStringValue("position/waypoint-name-next", _next_name.c_str());
81     props->setStringValue("submodels/path", _path.c_str());
82     props->setStringValue("position/waypoint-start-time", _start_time.c_str());
83     props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
84
85     _hdg_lock = false;
86     _rudder = 0.0;
87     no_roll = false;
88
89     _rudder_constant = 0.5;
90     _roll_constant = 0.001;
91     _speed_constant = 0.05;
92     _hdg_constant = 0.01;
93     _roll_factor = -0.0083335;
94
95     _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
96
97     _fp_init = false;
98     _missed = false;
99     _waiting = false;
100     _new_waypoint = true;
101
102     _missed_count = 0;
103     _wait_count = 0;
104     _missed_time_sec = 30;
105
106     _day = 86400;
107
108
109     _wp_range = _old_range = 0;
110     _range_rate = 0;
111
112     if (fp)
113         _fp_init = initFlightPlan();
114
115     return FGAIBase::init(search_in_AI_path);
116 }
117
118
119 void FGAIShip::bind() {
120     FGAIBase::bind();
121
122     props->tie("surface-positions/rudder-pos-deg",
123         SGRawValuePointer<float>(&_rudder));
124     props->tie("controls/heading-lock",
125         SGRawValuePointer<bool>(&_hdg_lock));
126     props->tie("controls/tgt-speed-kts",
127         SGRawValuePointer<double>(&tgt_speed));
128     props->tie("controls/tgt-heading-degs",
129         SGRawValuePointer<double>(&tgt_heading));
130     props->tie("controls/constants/rudder",
131         SGRawValuePointer<double>(&_rudder_constant));
132     props->tie("controls/constants/roll-factor",
133         SGRawValuePointer<double>(&_roll_factor));
134     props->tie("controls/constants/roll",
135         SGRawValuePointer<double>(&_roll_constant));
136     props->tie("controls/constants/rudder",
137         SGRawValuePointer<double>(&_rudder_constant));
138     props->tie("controls/constants/speed",
139         SGRawValuePointer<double>(&_speed_constant));
140     props->tie("position/waypoint-range-nm",
141         SGRawValuePointer<double>(&_wp_range));
142     props->tie("position/waypoint-range-old-nm",
143         SGRawValuePointer<double>(&_old_range));
144     props->tie("position/waypoint-range-rate-nm-sec",
145         SGRawValuePointer<double>(&_range_rate));
146     props->tie("position/waypoint-new",
147         SGRawValuePointer<bool>(&_new_waypoint));
148     props->tie("position/waypoint-missed",
149         SGRawValuePointer<bool>(&_missed));
150     props->tie("position/waypoint-missed-count",
151         SGRawValuePointer<double>(&_missed_count));
152     props->tie("position/waypoint-missed-time-sec",
153         SGRawValuePointer<double>(&_missed_time_sec));
154     props->tie("position/waypoint-wait-count",
155         SGRawValuePointer<double>(&_wait_count));
156     props->tie("position/waypoint-waiting",
157         SGRawValuePointer<bool>(&_waiting));
158     props->tie("submodels/serviceable",
159         SGRawValuePointer<bool>(&_serviceable));
160 }
161
162 void FGAIShip::unbind() {
163     FGAIBase::unbind();
164     props->untie("surface-positions/rudder-pos-deg");
165     props->untie("controls/heading-lock");
166     props->untie("controls/tgt-speed-kts");
167     props->untie("controls/tgt-heading-degs");
168     props->untie("controls/constants/roll");
169     props->untie("controls/constants/rudder");
170     props->untie("controls/constants/roll-factor");
171     props->untie("controls/constants/speed");
172     props->untie("position/waypoint-range-nm");
173     props->untie("position/waypoint-range-old-nm");
174     props->untie("position/waypoint-range-rate-nm-sec");
175     props->untie("position/waypoint-new");
176     props->untie("position/waypoint-missed");
177     props->untie("position/waypoint-wait-count");
178     props->untie("position/waypoint-waiting");
179     props->untie("position/waypoint-missed-time-sec");
180     props->untie("submodels/serviceable");
181 }
182
183 void FGAIShip::update(double dt) {
184     FGAIBase::update(dt);
185     Run(dt);
186     Transform();
187 }
188
189 void FGAIShip::Run(double dt) {
190     //cout << _name << " init: " << _fp_init << endl;
191     if (_fp_init)
192         ProcessFlightPlan(dt);
193
194     //    double speed_north_deg_sec;
195     //    double speed_east_deg_sec;
196     double alpha;
197     double rudder_limit;
198     double raw_roll;
199
200     // adjust speed
201     double speed_diff = tgt_speed - speed;
202
203     if (fabs(speed_diff) > 0.1) {
204
205         if (speed_diff > 0.0)
206             speed += _speed_constant * dt;
207
208         if (speed_diff < 0.0)
209             speed -= _speed_constant * dt;
210
211     }
212
213     // do not allow unreasonable ship speeds
214     if (speed > 40)
215         speed = 40;
216
217     // convert speed to degrees per second
218     speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
219         * speed * 1.686 / ft_per_deg_lat;
220     speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
221         * speed * 1.686 / ft_per_deg_lon;
222
223     // set new position
224     pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
225     pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
226
227     // adjust heading based on current _rudder angle
228
229     //cout << "turn_radius_ft " << turn_radius_ft ;
230
231     if (turn_radius_ft <= 0)
232         turn_radius_ft = 0; // don't allow nonsense values
233
234     if (_rudder > 45)
235         _rudder = 45;
236
237     if (_rudder < -45)
238         _rudder = -45;
239
240     //we assume that at slow speed ships will manoeuvre using engines/bow thruster
241     if (fabs(speed)<=5)
242         _sp_turn_radius_ft = 500;
243     else
244         // adjust turn radius for speed. The equation is very approximate.
245         // we need to allow for negative speeds
246         _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
247
248     //cout << " speed turn radius " << _sp_turn_radius_ft ;
249
250     if (_rudder <= -0.25 || _rudder >= 0.25) {
251         // adjust turn radius for _rudder angle. The equation is even more approximate.
252         float a = 19;
253         float b = -0.2485;
254         float c = 0.543;
255
256         _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
257
258         //cout <<" _rudder turn radius " << _rd_turn_radius_ft << endl;
259
260         // calculate the angle, alpha, subtended by the arc traversed in time dt
261         alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
262
263         // make sure that alpha is applied in the right direction
264         hdg += alpha * sign(_rudder);
265
266         if (hdg > 360.0)
267             hdg -= 360.0;
268
269         if (hdg < 0.0)
270             hdg += 360.0;
271
272         //adjust roll for rudder angle and speed. Another bit of voodoo
273         raw_roll = _roll_factor * speed * _rudder;
274     } else {
275         // _rudder angle is 0
276         raw_roll = 0;
277     }
278
279     //low pass filter
280     if (speed < 0)
281         roll = -roll;
282
283     roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
284
285     // adjust target _rudder angle if heading lock engaged
286     if (_hdg_lock) {
287         double rudder_sense = 0.0;
288         double diff = fabs(hdg - tgt_heading);
289         //cout << "_rudder diff" << diff << endl;
290         if (diff > 180)
291             diff = fabs(diff - 360);
292
293         double sum = hdg + diff;
294
295         if (sum > 360.0)
296             sum -= 360.0;
297
298         if (fabs(sum - tgt_heading)< 1.0)
299             rudder_sense = 1.0;
300         else
301             rudder_sense = -1.0;
302
303         if (speed < 0)
304             rudder_sense = -rudder_sense;
305
306         if (diff < 15)
307             _tgt_rudder = diff * rudder_sense;
308         else
309             _tgt_rudder = 45 * rudder_sense;
310     }
311
312     // adjust _rudder angle
313     double rudder_diff = _tgt_rudder - _rudder;
314
315     // set the _rudder limit by speed
316     if (speed <= 40)
317         rudder_limit = (-0.825 * speed) + 35;
318     else
319         rudder_limit = 2;
320
321     if (fabs(rudder_diff)> 0.1) { // apply dead zone
322
323         if (rudder_diff > 0.0) {
324             _rudder += _rudder_constant * dt;
325
326             if (_rudder > rudder_limit) // apply the _rudder limit
327                 _rudder = rudder_limit;
328
329         } else if (rudder_diff < 0.0) {
330             _rudder -= _rudder_constant * dt;
331
332             if (_rudder < -rudder_limit)
333                 _rudder = -rudder_limit;
334
335         }
336
337         // do calculations for radar
338         UpdateRadar(manager);
339     }
340 }//end function
341
342 void FGAIShip::AccelTo(double speed) {
343     tgt_speed = speed;
344 }
345
346 void FGAIShip::PitchTo(double angle) {
347     tgt_pitch = angle;
348 }
349
350 void FGAIShip::RollTo(double angle) {
351     tgt_roll = angle;
352 }
353
354 void FGAIShip::YawTo(double angle) {
355 }
356
357 void FGAIShip::ClimbTo(double altitude) {
358 }
359
360
361 void FGAIShip::TurnTo(double heading) {
362     tgt_heading = heading;
363     _hdg_lock = true;
364 }
365
366 double FGAIShip::sign(double x) {
367     if (x < 0.0)
368         return -1.0;
369     else
370         return 1.0;
371 }
372
373 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
374     fp = f;
375 }
376
377 void FGAIShip::setName(const string& n) {
378     _name = n;
379 }
380
381 void FGAIShip::setStartTime(const string& st) {
382     _start_time = st;
383 }
384
385 void FGAIShip::setUntilTime(const string& ut) {
386     _until_time = ut;
387     props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
388 }
389
390 void FGAIShip::setCurrName(const string& c) {
391     _curr_name = c;
392     props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
393 }
394
395 void FGAIShip::setNextName(const string& n) {
396     _next_name = n;
397     props->setStringValue("position/waypoint-name-next", _next_name.c_str());
398 }
399
400 void FGAIShip::setPrevName(const string& p) {
401     _prev_name = p;
402     props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
403 }
404
405 void FGAIShip::setRepeat(bool r) {
406     _repeat = r;
407 }
408
409 void FGAIShip::setMissed(bool m) {
410     _missed = m;
411     props->setBoolValue("position/waypoint-missed", _missed);
412 }
413
414 void FGAIShip::setRudder(float r) {
415     _rudder = r;
416 }
417
418 void FGAIShip::setRoll(double rl) {
419     roll = rl;
420 }
421
422 void FGAIShip::setWPNames() {
423
424     if (prev != 0)
425         setPrevName(prev->name);
426     else
427         setPrevName("");
428
429     setCurrName(curr->name);
430
431     if (next != 0)
432         setNextName(next->name);
433     else
434         setNextName("");
435
436     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
437     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
438     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
439
440 }
441
442 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
443
444     double course, distance, az2;
445
446     //calculate the bearing and range of the second pos from the first
447     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
448     distance *= SG_METER_TO_NM;
449     return distance;
450 }
451
452 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
453
454     double course, distance, recip;
455
456     //calculate the bearing and range of the second pos from the first
457     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
458     if (tgt_speed >= 0) {
459         return course;
460     } else {
461         return recip;
462     }
463 }
464
465 void FGAIShip::ProcessFlightPlan(double dt) {
466
467     double time_sec = getDaySeconds();
468     double until_time_sec = 0;
469
470     _missed = false;
471     _dt_count += dt;
472
473     ///////////////////////////////////////////////////////////////////////////
474     // Check Execution time (currently once every 1 sec)
475     // Add a bit of randomization to prevent the execution of all flight plans
476     // in synchrony, which can add significant periodic framerate flutter.
477     ///////////////////////////////////////////////////////////////////////////
478
479     //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
480     if (_dt_count < _next_run && _start_sec < time_sec)
481         return;
482
483     _next_run = 1.0 + (0.5 * sg_random());
484
485     // check to see if we've reached the point for our next turn
486     // if the range to the waypoint is less than the calculated turn
487     // radius we can start the turn to the next leg
488     _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
489     _range_rate = (_wp_range - _old_range) / _dt_count;
490     double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
491
492     // we need to try to identify a _missed waypoint
493
494     // calculate the time needed to turn through an arc of 90 degrees, and allow an error of 30 secs
495     if (speed != 0)
496         _missed_time_sec = 30 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
497     else
498         _missed_time_sec = 30;
499
500     if ((_range_rate > 0) && (_wp_range < 3 * sp_turn_radius_nm) && !_new_waypoint)
501         _missed_count += _dt_count;
502
503     if (_missed_count >= _missed_time_sec) {
504         setMissed(true);
505     } else {
506         setMissed(false);
507     }
508
509     _old_range = _wp_range;
510     setWPNames();
511
512     if ((_wp_range < sp_turn_radius_nm) || _missed || _waiting && !_new_waypoint) {
513
514         if (_next_name == "END") {
515
516             if (_repeat) {
517                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan restarting ");
518                 fp->restart();
519                 prev = curr;
520                 curr = fp->getCurrentWaypoint();
521                 next = fp->getNextWaypoint();
522                 setWPNames();
523                 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
524                 _old_range = _wp_range;
525                 _range_rate = 0;
526                 _new_waypoint = true;
527                 _missed_count = 0;
528                 AccelTo(prev->speed);
529             } else {
530                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan dieing ");
531                 setDie(true);
532                 _dt_count = 0;
533                 return;
534             }
535
536         } else if (_next_name == "WAIT") {
537
538             if (_wait_count < next->time_sec) {
539                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
540                 setSpeed(0);
541                 _waiting = true;
542                 _wait_count += _dt_count;
543                 _dt_count = 0;
544                 return;
545             } else {
546                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
547                     << " wait done: getting new waypoints ");
548                 _waiting = false;
549                 _wait_count = 0;
550                 fp->IncrementWaypoint(false);
551                 next = fp->getNextWaypoint();
552
553                 if (next->name == "WAITUNTIL" || next->name == "WAIT"
554                         || next->name == "END")
555                     return;
556
557                 prev = curr;
558                 fp->IncrementWaypoint(false);
559                 curr = fp->getCurrentWaypoint();
560                 next = fp->getNextWaypoint();
561             }
562
563         } else if (_next_name == "WAITUNTIL") {
564             time_sec = getDaySeconds();
565             until_time_sec = processTimeString(next->time);
566             _until_time = next->time;
567             setUntilTime(next->time);
568             if (until_time_sec > time_sec) {
569                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting until: "
570                     << _until_time << " " << until_time_sec << " now " << time_sec );
571                 setSpeed(0);
572                 _waiting = true;
573                 return;
574             } else {
575                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
576                     << _name << " wait until done: getting new waypoints ");
577                 setUntilTime("");
578                 fp->IncrementWaypoint(false);
579
580                 while (next->name == "WAITUNTIL") {
581                     fp->IncrementWaypoint(false);
582                     next = fp->getNextWaypoint();
583                 }
584
585                 if (next->name == "WAIT")
586                     return;
587
588                 prev = curr;
589                 fp->IncrementWaypoint(false);
590                 curr = fp->getCurrentWaypoint();
591                 next = fp->getNextWaypoint();
592                 _waiting = false;
593             }
594
595         } else {
596             //now reorganise the waypoints, so that next becomes current and so on
597             SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
598             fp->IncrementWaypoint(false);
599             prev = fp->getPreviousWaypoint(); //first waypoint
600             curr = fp->getCurrentWaypoint();  //second waypoint
601             next = fp->getNextWaypoint();     //third waypoint (might not exist!)
602         }
603
604         setWPNames();
605         _new_waypoint = true;
606         _missed_count = 0;
607         _range_rate = 0;
608         _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
609         _old_range = _wp_range;
610         AccelTo(prev->speed);
611     } else {
612         _new_waypoint = false;
613     }
614
615     //   now revise the required course for the next way point
616     double course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
617
618     if (finite(course))
619         TurnTo(course);
620     else
621         SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Bearing or Range is not a finite number");
622
623      _dt_count = 0;
624 } // end Processing FlightPlan
625
626 bool FGAIShip::initFlightPlan() {
627
628     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " initializing waypoints ");
629
630     bool init = false;
631
632     _start_sec = 0;
633
634     fp->restart();
635     fp->IncrementWaypoint(false);
636
637     prev = fp->getPreviousWaypoint(); //first waypoint
638     curr = fp->getCurrentWaypoint();  //second waypoint
639     next = fp->getNextWaypoint();     //third waypoint (might not exist!)
640
641     while (curr->name == "WAIT" || curr->name == "WAITUNTIL") {  // don't wait when initialising
642         SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
643         fp->IncrementWaypoint(false);
644         curr = fp->getCurrentWaypoint();
645         next = fp->getNextWaypoint();
646     }
647
648     if (!_start_time.empty()){
649         _start_sec = processTimeString(_start_time);
650         double day_sec = getDaySeconds();
651
652         if (_start_sec < day_sec){
653             //cout << "flight plan has already started " << _start_time << endl;
654             init = advanceFlightPlan(_start_sec, day_sec);
655
656         } else if (_start_sec > day_sec && _repeat) {
657             //cout << "flight plan has not started, " << _start_time;
658             //cout << "offsetting start time by -24 hrs" << endl;
659             _start_sec -= _day;
660             init = advanceFlightPlan(_start_sec, day_sec);
661         }
662
663         if (init)
664             _start_sec = 0; // set to zero for an immediate start of the Flight Plan
665         else {
666             fp->restart();
667             fp->IncrementWaypoint(false);
668             prev = fp->getPreviousWaypoint();
669             curr = fp->getCurrentWaypoint();
670             next = fp->getNextWaypoint();
671             return false;
672         }
673
674     } else {
675     setLatitude(prev->latitude);
676     setLongitude(prev->longitude);
677     setSpeed(prev->speed);
678     }
679
680     setWPNames();
681     setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
682     _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
683     _old_range = _wp_range;
684     _range_rate = 0;
685     _hdg_lock = true;
686     _missed = false;
687     _missed_count = 0;
688     _new_waypoint = true;
689
690     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " done initialising waypoints ");
691     if (prev)
692         init = true;
693
694     if (init)
695         return true;
696     else
697         return false;
698
699 } // end of initialization
700
701
702 double FGAIShip::processTimeString(const string& theTime) {
703
704     int Hour;
705     int Minute;
706     int Second;
707
708     // first split theTime string into
709     //  hour, minute, second and convert to int;
710     Hour   = atoi(theTime.substr(0,2).c_str());
711     Minute = atoi(theTime.substr(3,5).c_str());
712     Second = atoi(theTime.substr(6,8).c_str());
713
714     // offset by a day-sec to allow for starting a day earlier
715     double time_seconds = Hour * 3600
716         + Minute * 60
717         + Second;
718
719     return time_seconds;
720 }
721
722 double FGAIShip::getDaySeconds () {
723     // Date and time
724     struct tm *t = globals->get_time_params()->getGmt();
725
726     double day_seconds = t->tm_hour * 3600
727         + t->tm_min * 60
728         + t->tm_sec;
729
730     return day_seconds;
731 }
732
733 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
734
735     double elapsed_sec = start_sec;
736     double distance_nm = 0;
737
738     //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
739
740     while ( elapsed_sec < day_sec ) {
741
742         if (next->name == "END") {
743
744             if (_repeat ) {
745                 //cout << _name << ": " << "restarting flightplan" << endl;
746                 fp->restart();
747                 curr = fp->getCurrentWaypoint();
748                 next = fp->getNextWaypoint();
749             } else {
750                 //cout << _name << ": " << "ending flightplan" << endl;
751                 setDie(true);
752                 return false;
753             }
754
755         } else if (next->name == "WAIT") {
756             //cout << _name << ": begin WAIT: " << prev->name << " ";
757             //cout << curr->name << " " << next->name << endl;
758
759             elapsed_sec += next->time_sec;
760
761             if ( elapsed_sec >= day_sec)
762                 continue;
763
764             fp->IncrementWaypoint(false);
765             next = fp->getNextWaypoint();
766
767             if (next->name != "WAITUNTIL" && next->name != "WAIT"
768                     && next->name != "END") {
769                 prev = curr;
770                 fp->IncrementWaypoint(false);
771                 curr = fp->getCurrentWaypoint();
772                 next = fp->getNextWaypoint();
773             }
774
775         } else if (next->name == "WAITUNTIL") {
776             double until_sec = processTimeString(next->time);
777
778             if (until_sec > _start_sec && start_sec < 0)
779                 until_sec -= _day;
780
781             if (elapsed_sec < until_sec)
782                 elapsed_sec = until_sec;
783
784             if (elapsed_sec >= day_sec )
785                 break;
786
787             fp->IncrementWaypoint(false);
788             next = fp->getNextWaypoint();
789
790             if (next->name != "WAITUNTIL" && next->name != "WAIT") {
791                 prev = curr;
792                 fp->IncrementWaypoint(false);
793                 curr = fp->getCurrentWaypoint();
794                 next = fp->getNextWaypoint();
795             }
796
797             //cout << _name << ": end WAITUNTIL: ";
798             //cout << prev->name << " " << curr->name << " " << next->name <<  endl;
799
800         } else {
801             distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
802             elapsed_sec += distance_nm * 60 * 60 / prev->speed;
803
804             if (elapsed_sec >= day_sec)
805                 continue;
806
807             fp->IncrementWaypoint(false);
808             prev = fp->getPreviousWaypoint();
809             curr = fp->getCurrentWaypoint();
810             next = fp->getNextWaypoint();
811         }
812
813     }   // end while
814
815     // the required position lies between the previous and current waypoints
816     // so we will calculate the distance back up the track from the current waypoint
817     // then calculate the lat and lon.
818     /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
819         << " " << day_sec << endl;*/
820
821     double time_diff = elapsed_sec - day_sec;
822     double lat, lon, recip;
823
824     //cout << " time diff " << time_diff << endl;
825
826     if (next->name == "WAIT" ){
827         setSpeed(0);
828         lat = curr->latitude;
829         lon = curr->longitude;
830         _wait_count= time_diff;
831         _waiting = true;
832     } else if (next->name == "WAITUNTIL") {
833         setSpeed(0);
834         lat = curr->latitude;
835         lon = curr->longitude;
836         _waiting = true;
837     } else {
838         setSpeed(prev->speed);
839         distance_nm = speed * time_diff / (60 * 60);
840         double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
841
842         //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
843         //    << " lat "  << curr->latitude << " lon " << curr->longitude
844         //    << " distance m " << distance_nm * SG_NM_TO_METER << endl;
845
846         lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
847             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
848         lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
849             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
850         recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
851             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
852     }
853
854     //cout << "Pos " << lat << ", " << lon << " recip " << recip << endl;
855
856     setLatitude(lat);
857     setLongitude(lon);
858     return true;
859 }