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