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