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