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