]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIShip.cxx
30e889aba6b3119e3889813134217ad4d8b722e3
[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     }
338 }//end function
339
340 void FGAIShip::AccelTo(double speed) {
341     tgt_speed = speed;
342 }
343
344 void FGAIShip::PitchTo(double angle) {
345     tgt_pitch = angle;
346 }
347
348 void FGAIShip::RollTo(double angle) {
349     tgt_roll = angle;
350 }
351
352 void FGAIShip::YawTo(double angle) {
353 }
354
355 void FGAIShip::ClimbTo(double altitude) {
356 }
357
358
359 void FGAIShip::TurnTo(double heading) {
360     tgt_heading = heading;
361     _hdg_lock = true;
362 }
363
364 double FGAIShip::sign(double x) {
365     if (x < 0.0)
366         return -1.0;
367     else
368         return 1.0;
369 }
370
371 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
372     fp = f;
373 }
374
375 void FGAIShip::setName(const string& n) {
376     _name = n;
377 }
378
379 void FGAIShip::setStartTime(const string& st) {
380     _start_time = st;
381 }
382
383 void FGAIShip::setUntilTime(const string& ut) {
384     _until_time = ut;
385     props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
386 }
387
388 void FGAIShip::setCurrName(const string& c) {
389     _curr_name = c;
390     props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
391 }
392
393 void FGAIShip::setNextName(const string& n) {
394     _next_name = n;
395     props->setStringValue("position/waypoint-name-next", _next_name.c_str());
396 }
397
398 void FGAIShip::setPrevName(const string& p) {
399     _prev_name = p;
400     props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
401 }
402
403 void FGAIShip::setRepeat(bool r) {
404     _repeat = r;
405 }
406
407 void FGAIShip::setMissed(bool m) {
408     _missed = m;
409     props->setBoolValue("position/waypoint-missed", _missed);
410 }
411
412 void FGAIShip::setRudder(float r) {
413     _rudder = r;
414 }
415
416 void FGAIShip::setRoll(double rl) {
417     roll = rl;
418 }
419
420 void FGAIShip::setWPNames() {
421
422     if (prev != 0)
423         setPrevName(prev->name);
424     else
425         setPrevName("");
426
427     setCurrName(curr->name);
428
429     if (next != 0)
430         setNextName(next->name);
431     else
432         setNextName("");
433
434     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
435     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
436     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
437
438 }
439
440 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
441
442     double course, distance, az2;
443
444     //calculate the bearing and range of the second pos from the first
445     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
446     distance *= SG_METER_TO_NM;
447     return distance;
448 }
449
450 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
451
452     double course, distance, recip;
453
454     //calculate the bearing and range of the second pos from the first
455     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
456     if (tgt_speed >= 0) {
457         return course;
458     } else {
459         return recip;
460     }
461 }
462
463 void FGAIShip::ProcessFlightPlan(double dt) {
464
465     double time_sec = getDaySeconds();
466     double until_time_sec = 0;
467
468     _missed = false;
469     _dt_count += dt;
470
471     ///////////////////////////////////////////////////////////////////////////
472     // Check Execution time (currently once every 1 sec)
473     // Add a bit of randomization to prevent the execution of all flight plans
474     // in synchrony, which can add significant periodic framerate flutter.
475     ///////////////////////////////////////////////////////////////////////////
476
477     //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
478     if (_dt_count < _next_run && _start_sec < time_sec)
479         return;
480
481     _next_run = 1.0 + (0.5 * sg_random());
482
483     // check to see if we've reached the point for our next turn
484     // if the range to the waypoint is less than the calculated turn
485     // radius we can start the turn to the next leg
486     _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
487     _range_rate = (_wp_range - _old_range) / _dt_count;
488     double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
489
490     // we need to try to identify a _missed waypoint
491
492     // calculate the time needed to turn through an arc of 90 degrees, and allow an error of 30 secs
493     if (speed != 0)
494         _missed_time_sec = 30 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
495     else
496         _missed_time_sec = 30;
497
498     if ((_range_rate > 0) && (_wp_range < 3 * sp_turn_radius_nm) && !_new_waypoint)
499         _missed_count += _dt_count;
500
501     if (_missed_count >= _missed_time_sec) {
502         setMissed(true);
503     } else {
504         setMissed(false);
505     }
506
507     _old_range = _wp_range;
508     setWPNames();
509
510     if ((_wp_range < sp_turn_radius_nm) || _missed || _waiting && !_new_waypoint) {
511
512         if (_next_name == "END") {
513
514             if (_repeat) {
515                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan restarting ");
516                 fp->restart();
517                 prev = curr;
518                 curr = fp->getCurrentWaypoint();
519                 next = fp->getNextWaypoint();
520                 setWPNames();
521                 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
522                 _old_range = _wp_range;
523                 _range_rate = 0;
524                 _new_waypoint = true;
525                 _missed_count = 0;
526                 AccelTo(prev->speed);
527             } else {
528                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan dieing ");
529                 setDie(true);
530                 _dt_count = 0;
531                 return;
532             }
533
534         } else if (_next_name == "WAIT") {
535
536             if (_wait_count < next->time_sec) {
537                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
538                 setSpeed(0);
539                 _waiting = true;
540                 _wait_count += _dt_count;
541                 _dt_count = 0;
542                 return;
543             } else {
544                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
545                     << " wait done: getting new waypoints ");
546                 _waiting = false;
547                 _wait_count = 0;
548                 fp->IncrementWaypoint(false);
549                 next = fp->getNextWaypoint();
550
551                 if (next->name == "WAITUNTIL" || next->name == "WAIT"
552                         || next->name == "END")
553                     return;
554
555                 prev = curr;
556                 fp->IncrementWaypoint(false);
557                 curr = fp->getCurrentWaypoint();
558                 next = fp->getNextWaypoint();
559             }
560
561         } else if (_next_name == "WAITUNTIL") {
562             time_sec = getDaySeconds();
563             until_time_sec = processTimeString(next->time);
564             _until_time = next->time;
565             setUntilTime(next->time);
566             if (until_time_sec > time_sec) {
567                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting until: "
568                     << _until_time << " " << until_time_sec << " now " << time_sec );
569                 setSpeed(0);
570                 _waiting = true;
571                 return;
572             } else {
573                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
574                     << _name << " wait until done: getting new waypoints ");
575                 setUntilTime("");
576                 fp->IncrementWaypoint(false);
577
578                 while (next->name == "WAITUNTIL") {
579                     fp->IncrementWaypoint(false);
580                     next = fp->getNextWaypoint();
581                 }
582
583                 if (next->name == "WAIT")
584                     return;
585
586                 prev = curr;
587                 fp->IncrementWaypoint(false);
588                 curr = fp->getCurrentWaypoint();
589                 next = fp->getNextWaypoint();
590                 _waiting = false;
591             }
592
593         } else {
594             //now reorganise the waypoints, so that next becomes current and so on
595             SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
596             fp->IncrementWaypoint(false);
597             prev = fp->getPreviousWaypoint(); //first waypoint
598             curr = fp->getCurrentWaypoint();  //second waypoint
599             next = fp->getNextWaypoint();     //third waypoint (might not exist!)
600         }
601
602         setWPNames();
603         _new_waypoint = true;
604         _missed_count = 0;
605         _range_rate = 0;
606         _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
607         _old_range = _wp_range;
608         AccelTo(prev->speed);
609     } else {
610         _new_waypoint = false;
611     }
612
613     //   now revise the required course for the next way point
614     double course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
615
616     if (finite(course))
617         TurnTo(course);
618     else
619         SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Bearing or Range is not a finite number");
620
621      _dt_count = 0;
622 } // end Processing FlightPlan
623
624 bool FGAIShip::initFlightPlan() {
625
626     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " initializing waypoints ");
627
628     bool init = false;
629
630     _start_sec = 0;
631
632     fp->restart();
633     fp->IncrementWaypoint(false);
634
635     prev = fp->getPreviousWaypoint(); //first waypoint
636     curr = fp->getCurrentWaypoint();  //second waypoint
637     next = fp->getNextWaypoint();     //third waypoint (might not exist!)
638
639     while (curr->name == "WAIT" || curr->name == "WAITUNTIL") {  // don't wait when initialising
640         SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
641         fp->IncrementWaypoint(false);
642         curr = fp->getCurrentWaypoint();
643         next = fp->getNextWaypoint();
644     }
645
646     if (!_start_time.empty()){
647         _start_sec = processTimeString(_start_time);
648         double day_sec = getDaySeconds();
649
650         if (_start_sec < day_sec){
651             //cout << "flight plan has already started " << _start_time << endl;
652             init = advanceFlightPlan(_start_sec, day_sec);
653
654         } else if (_start_sec > day_sec && _repeat) {
655             //cout << "flight plan has not started, " << _start_time;
656             //cout << "offsetting start time by -24 hrs" << endl;
657             _start_sec -= _day;
658             init = advanceFlightPlan(_start_sec, day_sec);
659         }
660
661         if (init)
662             _start_sec = 0; // set to zero for an immediate start of the Flight Plan
663         else {
664             fp->restart();
665             fp->IncrementWaypoint(false);
666             prev = fp->getPreviousWaypoint();
667             curr = fp->getCurrentWaypoint();
668             next = fp->getNextWaypoint();
669             return false;
670         }
671
672     } else {
673     setLatitude(prev->latitude);
674     setLongitude(prev->longitude);
675     setSpeed(prev->speed);
676     }
677
678     setWPNames();
679     setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
680     _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
681     _old_range = _wp_range;
682     _range_rate = 0;
683     _hdg_lock = true;
684     _missed = false;
685     _missed_count = 0;
686     _new_waypoint = true;
687
688     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " done initialising waypoints ");
689     if (prev)
690         init = true;
691
692     if (init)
693         return true;
694     else
695         return false;
696
697 } // end of initialization
698
699
700 double FGAIShip::processTimeString(const string& theTime) {
701
702     int Hour;
703     int Minute;
704     int Second;
705
706     // first split theTime string into
707     //  hour, minute, second and convert to int;
708     Hour   = atoi(theTime.substr(0,2).c_str());
709     Minute = atoi(theTime.substr(3,5).c_str());
710     Second = atoi(theTime.substr(6,8).c_str());
711
712     // offset by a day-sec to allow for starting a day earlier
713     double time_seconds = Hour * 3600
714         + Minute * 60
715         + Second;
716
717     return time_seconds;
718 }
719
720 double FGAIShip::getDaySeconds () {
721     // Date and time
722     struct tm *t = globals->get_time_params()->getGmt();
723
724     double day_seconds = t->tm_hour * 3600
725         + t->tm_min * 60
726         + t->tm_sec;
727
728     return day_seconds;
729 }
730
731 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
732
733     double elapsed_sec = start_sec;
734     double distance_nm = 0;
735
736     //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
737
738     while ( elapsed_sec < day_sec ) {
739
740         if (next->name == "END") {
741
742             if (_repeat ) {
743                 //cout << _name << ": " << "restarting flightplan" << endl;
744                 fp->restart();
745                 curr = fp->getCurrentWaypoint();
746                 next = fp->getNextWaypoint();
747             } else {
748                 //cout << _name << ": " << "ending flightplan" << endl;
749                 setDie(true);
750                 return false;
751             }
752
753         } else if (next->name == "WAIT") {
754             //cout << _name << ": begin WAIT: " << prev->name << " ";
755             //cout << curr->name << " " << next->name << endl;
756
757             elapsed_sec += next->time_sec;
758
759             if ( elapsed_sec >= day_sec)
760                 continue;
761
762             fp->IncrementWaypoint(false);
763             next = fp->getNextWaypoint();
764
765             if (next->name != "WAITUNTIL" && next->name != "WAIT"
766                     && next->name != "END") {
767                 prev = curr;
768                 fp->IncrementWaypoint(false);
769                 curr = fp->getCurrentWaypoint();
770                 next = fp->getNextWaypoint();
771             }
772
773         } else if (next->name == "WAITUNTIL") {
774             double until_sec = processTimeString(next->time);
775
776             if (until_sec > _start_sec && start_sec < 0)
777                 until_sec -= _day;
778
779             if (elapsed_sec < until_sec)
780                 elapsed_sec = until_sec;
781
782             if (elapsed_sec >= day_sec )
783                 break;
784
785             fp->IncrementWaypoint(false);
786             next = fp->getNextWaypoint();
787
788             if (next->name != "WAITUNTIL" && next->name != "WAIT") {
789                 prev = curr;
790                 fp->IncrementWaypoint(false);
791                 curr = fp->getCurrentWaypoint();
792                 next = fp->getNextWaypoint();
793             }
794
795             //cout << _name << ": end WAITUNTIL: ";
796             //cout << prev->name << " " << curr->name << " " << next->name <<  endl;
797
798         } else {
799             distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
800             elapsed_sec += distance_nm * 60 * 60 / prev->speed;
801
802             if (elapsed_sec >= day_sec)
803                 continue;
804
805             fp->IncrementWaypoint(false);
806             prev = fp->getPreviousWaypoint();
807             curr = fp->getCurrentWaypoint();
808             next = fp->getNextWaypoint();
809         }
810
811     }   // end while
812
813     // the required position lies between the previous and current waypoints
814     // so we will calculate the distance back up the track from the current waypoint
815     // then calculate the lat and lon.
816     /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
817         << " " << day_sec << endl;*/
818
819     double time_diff = elapsed_sec - day_sec;
820     double lat, lon, recip;
821
822     //cout << " time diff " << time_diff << endl;
823
824     if (next->name == "WAIT" ){
825         setSpeed(0);
826         lat = curr->latitude;
827         lon = curr->longitude;
828         _wait_count= time_diff;
829         _waiting = true;
830     } else if (next->name == "WAITUNTIL") {
831         setSpeed(0);
832         lat = curr->latitude;
833         lon = curr->longitude;
834         _waiting = true;
835     } else {
836         setSpeed(prev->speed);
837         distance_nm = speed * time_diff / (60 * 60);
838         double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
839
840         //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
841         //    << " lat "  << curr->latitude << " lon " << curr->longitude
842         //    << " distance m " << distance_nm * SG_NM_TO_METER << endl;
843
844         lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
845             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
846         lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
847             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
848         recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
849             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
850     }
851
852     //cout << "Pos " << lat << ", " << lon << " recip " << recip << endl;
853
854     setLatitude(lat);
855     setLongitude(lon);
856     return true;
857 }