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