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