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