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