]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AICarrier.cxx
Add a small bit of nan/fpe protection. It's possible that this routine
[flightgear.git] / src / AIModel / AICarrier.cxx
1 // FGAICarrier - FGAIShip-derived class creates an AI aircraft carrier
2 //
3 // Written by David Culp, started October 2004.
4 // - davidculp2@comcast.net
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 <algorithm>
25 #include <string>
26 #include <vector>
27
28 #include <simgear/sg_inlines.h>
29 #include <simgear/math/SGMath.hxx>
30 #include <simgear/math/sg_geodesy.hxx>
31
32 #include <math.h>
33 #include <Main/util.hxx>
34 #include <Main/viewer.hxx>
35
36 #include "AICarrier.hxx"
37
38 FGAICarrier::FGAICarrier() : FGAIShip(otCarrier) {
39 }
40
41 FGAICarrier::~FGAICarrier() {
42 }
43
44 void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) {
45   if (!scFileNode)
46     return;
47
48   FGAIShip::readFromScenario(scFileNode);
49
50   setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
51   setSign(scFileNode->getStringValue("pennant-number"));
52   setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
53   setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
54   setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID", "029Y"));
55   setMaxLat(scFileNode->getDoubleValue("max-lat", 0));
56   setMinLat(scFileNode->getDoubleValue("min-lat", 0));
57   setMaxLong(scFileNode->getDoubleValue("max-long", 0));
58   setMinLong(scFileNode->getDoubleValue("min-long", 0));
59   setMPControl(scFileNode->getBoolValue("mp-control", false));
60   setAIControl(scFileNode->getBoolValue("ai-control", false));
61   setCallSign(scFileNode->getStringValue("callsign", ""));
62
63
64   SGPropertyNode* flols = scFileNode->getChild("flols-pos");
65   if (flols) {
66     // Transform to the right coordinate frame, configuration is done in
67     // the usual x-back, y-right, z-up coordinates, computations
68     // in the simulation usual body x-forward, y-right, z-down coordinates
69     flols_off(0) = - flols->getDoubleValue("x-offset-m", 0);
70     flols_off(1) = flols->getDoubleValue("y-offset-m", 0);
71     flols_off(2) = - flols->getDoubleValue("z-offset-m", 0);
72   } else
73     flols_off = SGVec3d::zeros();
74
75   std::vector<SGPropertyNode_ptr> props = scFileNode->getChildren("parking-pos");
76   std::vector<SGPropertyNode_ptr>::const_iterator it;
77   for (it = props.begin(); it != props.end(); ++it) {
78     string name = (*it)->getStringValue("name", "unnamed");
79     // Transform to the right coordinate frame, configuration is done in
80     // the usual x-back, y-right, z-up coordinates, computations
81     // in the simulation usual body x-forward, y-right, z-down coordinates
82     double offset_x = -(*it)->getDoubleValue("x-offset-m", 0);
83     double offset_y = (*it)->getDoubleValue("y-offset-m", 0);
84     double offset_z = -(*it)->getDoubleValue("z-offset-m", 0);
85     double hd = (*it)->getDoubleValue("heading-offset-deg", 0);
86     ParkPosition pp(name, SGVec3d(offset_x, offset_y, offset_z), hd);
87     ppositions.push_back(pp);
88   }
89 }
90
91 void FGAICarrier::setWind_from_east(double fps) {
92     wind_from_east = fps;
93 }
94
95 void FGAICarrier::setWind_from_north(double fps) {
96     wind_from_north = fps;
97 }
98
99 void FGAICarrier::setMaxLat(double deg) {
100     max_lat = fabs(deg);
101 }
102
103 void FGAICarrier::setMinLat(double deg) {
104     min_lat = fabs(deg);
105 }
106
107 void FGAICarrier::setMaxLong(double deg) {
108     max_long = fabs(deg);
109 }
110
111 void FGAICarrier::setMinLong(double deg) {
112     min_long = fabs(deg);
113 }
114
115 void FGAICarrier::setSign(const string& s) {
116     sign = s;
117 }
118
119 void FGAICarrier::setTACANChannelID(const string& id) {
120     TACAN_channel_id = id;
121 }
122
123 void FGAICarrier::setMPControl(bool c) {
124     MPControl = c;
125 }
126
127 void FGAICarrier::setAIControl(bool c) {
128     AIControl = c;
129 }
130
131 void FGAICarrier::update(double dt) {
132     // Now update the position and heading. This will compute new hdg and
133     // roll values required for the rotation speed computation.
134     FGAIShip::update(dt);
135
136     //automatic turn into wind with a target wind of 25 kts otd
137     //SG_LOG(SG_GENERAL, SG_ALERT, "AICarrier: MPControl " << MPControl << " AIControl " << AIControl);
138     if (!MPControl && AIControl){
139
140         if(turn_to_launch_hdg){
141             TurnToLaunch();
142         } else if(turn_to_recovery_hdg ){
143             TurnToRecover();
144         } else if(OutsideBox() || returning ) {// check that the carrier is inside
145             ReturnToBox();                     // the operating box,
146         } else {
147             TurnToBase();
148         }
149
150     } else {
151         FGAIShip::TurnTo(tgt_heading);
152         FGAIShip::AccelTo(tgt_speed);
153     }
154
155     UpdateWind(dt);
156     UpdateElevator(dt, transition_time);
157     UpdateJBD(dt, jbd_transition_time);
158
159     // Transform that one to the horizontal local coordinate system.
160     SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
161     // The orientation of the carrier wrt the horizontal local frame
162     SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
163     // and postrotate the orientation of the AIModel wrt the horizontal
164     // local frame
165     SGQuatd ec2body = ec2hl*hl2body;
166     // The cartesian position of the carrier in the wgs84 world
167     SGVec3d cartPos = SGVec3d::fromGeod(pos);
168
169     // The position of the eyepoint - at least near that ...
170     SGVec3d eyePos(globals->get_current_view()->get_view_pos());
171     // Add the position offset of the AIModel to gain the earth
172     // centered position
173     SGVec3d eyeWrtCarrier = eyePos - cartPos;
174     // rotate the eyepoint wrt carrier vector into the carriers frame
175     eyeWrtCarrier = ec2body.transform(eyeWrtCarrier);
176     // the eyepoints vector wrt the flols position
177     SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off;
178
179     // the distance from the eyepoint to the flols
180     dist = norm(eyeWrtFlols);
181
182     // now the angle, positive angles are upwards
183     if (fabs(dist) < SGLimits<float>::min()) {
184       angle = 0;
185     } else {
186       double sAngle = -eyeWrtFlols(2)/dist;
187       sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
188       angle = SGMiscd::rad2deg(asin(sAngle));
189     }
190
191     // set the value of source
192     if ( angle <= 4.35 && angle > 4.01 )
193       source = 1;
194     else if ( angle <= 4.01 && angle > 3.670 )
195       source = 2;
196     else if ( angle <= 3.670 && angle > 3.330 )
197       source = 3;
198     else if ( angle <= 3.330 && angle > 2.990 )
199       source = 4;
200     else if ( angle <= 2.990 && angle > 2.650 )
201       source = 5;
202     else if ( angle <= 2.650 )
203       source = 6;
204     else
205       source = 0;
206 } //end update
207
208 bool FGAICarrier::init(bool search_in_AI_path) {
209     if (!FGAIShip::init(search_in_AI_path))
210         return false;
211
212     _longitude_node = fgGetNode("/position/longitude-deg", true);
213     _latitude_node = fgGetNode("/position/latitude-deg", true);
214     _altitude_node = fgGetNode("/position/altitude-ft", true);
215
216     _launchbar_state_node = fgGetNode("/gear/launchbar/state", true);
217
218     _surface_wind_from_deg_node =
219             fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
220     _surface_wind_speed_node =
221             fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
222
223
224     turn_to_launch_hdg = false;
225     turn_to_recovery_hdg = false;
226     turn_to_base_course = true;
227     returning = false;
228     in_to_wind = false;
229
230     mOpBoxPos = pos;
231     base_course = hdg;
232     base_speed = speed;
233
234     pos_norm = raw_pos_norm = 0;
235     elevators = false;
236     transition_time = 150;
237     time_constant = 0.005;
238     jbd_pos_norm = raw_jbd_pos_norm = 0;
239     jbd = false ;
240     jbd_transition_time = 3;
241     jbd_time_constant = 0.1;
242     return true;
243 }
244
245 void FGAICarrier::bind() {
246     FGAIShip::bind();
247
248     props->untie("velocities/true-airspeed-kt");
249
250     props->tie("controls/flols/source-lights",
251                 SGRawValuePointer<int>(&source));
252     props->tie("controls/flols/distance-m",
253                 SGRawValuePointer<double>(&dist));
254     props->tie("controls/flols/angle-degs",
255                 SGRawValuePointer<double>(&angle));
256     props->tie("controls/turn-to-launch-hdg",
257                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
258     props->tie("controls/in-to-wind",
259                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
260     props->tie("controls/base-course-deg",
261                 SGRawValuePointer<double>(&base_course));
262     props->tie("controls/base-speed-kts",
263                 SGRawValuePointer<double>(&base_speed));
264     props->tie("controls/start-pos-lat-deg",
265                SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLatitudeDeg));
266     props->tie("controls/start-pos-long-deg",
267                SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLongitudeDeg));
268     props->tie("controls/mp-control",
269                 SGRawValuePointer<bool>(&MPControl));
270     props->tie("controls/ai-control",
271                 SGRawValuePointer<bool>(&AIControl));
272     props->tie("environment/surface-wind-speed-true-kts",
273                 SGRawValuePointer<double>(&wind_speed_kts));
274     props->tie("environment/surface-wind-from-true-degs",
275                 SGRawValuePointer<double>(&wind_from_deg));
276     props->tie("environment/rel-wind-from-degs",
277                 SGRawValuePointer<double>(&rel_wind_from_deg));
278     props->tie("environment/rel-wind-from-carrier-hdg-degs",
279                 SGRawValuePointer<double>(&rel_wind));
280     props->tie("environment/rel-wind-speed-kts",
281                 SGRawValuePointer<double>(&rel_wind_speed_kts));
282     props->tie("environment/in-to-wind",
283         SGRawValuePointer<bool>(&in_to_wind));
284     //props->tie("controls/flols/wave-off-lights",
285     //            SGRawValuePointer<bool>(&wave_off_lights));
286     props->tie("controls/elevators",
287                 SGRawValuePointer<bool>(&elevators));
288     props->tie("surface-positions/elevators-pos-norm",
289                 SGRawValuePointer<double>(&pos_norm));
290     props->tie("controls/constants/elevators/trans-time-s",
291                 SGRawValuePointer<double>(&transition_time));
292     props->tie("controls/constants/elevators/time-constant",
293                 SGRawValuePointer<double>(&time_constant));
294     props->tie("controls/jbd",
295         SGRawValuePointer<bool>(&jbd));
296     props->tie("surface-positions/jbd-pos-norm",
297         SGRawValuePointer<double>(&jbd_pos_norm));
298     props->tie("controls/constants/jbd/trans-time-s",
299         SGRawValuePointer<double>(&jbd_transition_time));
300     props->tie("controls/constants/jbd/time-constant",
301         SGRawValuePointer<double>(&jbd_time_constant));
302     props->tie("controls/turn-to-recovery-hdg",
303         SGRawValuePointer<bool>(&turn_to_recovery_hdg));
304     props->tie("controls/turn-to-base-course",
305         SGRawValuePointer<bool>(&turn_to_base_course));
306
307
308     props->setBoolValue("controls/flols/cut-lights", false);
309     props->setBoolValue("controls/flols/wave-off-lights", false);
310     props->setBoolValue("controls/flols/cond-datum-lights", true);
311     props->setBoolValue("controls/crew", false);
312     props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
313     props->setStringValue("sign", sign.c_str());
314     props->setBoolValue("controls/lighting/deck-lights", false);
315     props->setDoubleValue("controls/lighting/flood-lights-red-norm", 0);
316 }
317
318
319 void FGAICarrier::unbind() {
320     FGAIShip::unbind();
321
322     props->untie("velocities/true-airspeed-kt");
323     props->untie("controls/flols/source-lights");
324     props->untie("controls/flols/distance-m");
325     props->untie("controls/flols/angle-degs");
326     props->untie("controls/turn-to-launch-hdg");
327     props->untie("environment/wind-speed-true-kts");
328     props->untie("environment/wind-from-true-degs");
329     props->untie("environment/rel-wind-from-degs");
330     props->untie("environment/rel-wind-speed-kts");
331     props->untie("environment/in-to-wind");
332     //props->untie("controls/flols/wave-off-lights");
333     props->untie("controls/elevators");
334     props->untie("surface-positions/elevators-pos-norm");
335     props->untie("controls/constants/elevators/trans-time-secs");
336     props->untie("controls/constants/elevators/time-constant");
337     props->untie("controls/jbd");
338     props->untie("surface-positions/jbd/pos-norm");
339     props->untie("controls/constants/jbd/trans-time-s");
340     props->untie("controls/jbd-time-constant");
341     props->untie("controls/mp-control");
342     props->untie("controls/ai-control");
343     props->untie("controls/turn-to-recovery-hdg");
344     props->untie("controls/turn-to-base-course");
345 }
346
347
348 bool FGAICarrier::getParkPosition(const string& id, SGGeod& geodPos,
349                                   double& hdng, SGVec3d& uvw)
350 {
351
352     // FIXME: does not yet cover rotation speeds.
353     list<ParkPosition>::iterator it = ppositions.begin();
354     while (it != ppositions.end()) {
355         // Take either the specified one or the first one ...
356         if ((*it).name == id || id.empty()) {
357             ParkPosition ppos = *it;
358             SGVec3d cartPos = getCartPosAt(ppos.offset);
359             geodPos = SGGeod::fromCart(cartPos);
360             hdng = hdg + ppos.heading_deg;
361             double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
362             double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
363             double speed_fps = speed*1.6878099;
364             uvw = SGVec3d(chdng*speed_fps, shdng*speed_fps, 0);
365             return true;
366         }
367         ++it;
368     }
369
370     return false;
371 }
372
373 // find relative wind
374 void FGAICarrier::UpdateWind( double dt) {
375
376     //get the surface wind speed and direction
377     wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
378     wind_speed_kts  = _surface_wind_speed_node->getDoubleValue();
379
380     //calculate the surface wind speed north and east in kts
381     double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
382     double wind_speed_from_east_kts  = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
383
384     //calculate the carrier speed north and east in kts
385     double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
386     double speed_east_kts  = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
387
388     //calculate the relative wind speed north and east in kts
389     double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
390     double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
391
392     //combine relative speeds north and east to get relative windspeed in kts
393     rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts)
394     + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
395
396     //calculate the relative wind direction
397     rel_wind_from_deg = atan2(rel_wind_speed_from_east_kts, rel_wind_speed_from_north_kts)
398                             * SG_RADIANS_TO_DEGREES;
399
400     //calculate rel wind
401     rel_wind = rel_wind_from_deg - hdg;
402     SG_NORMALIZE_RANGE(rel_wind, -180.0, 180.0);
403
404     //set in to wind property
405     InToWind();
406
407     //switch the wave-off lights
408     //if (InToWind())
409     //   wave_off_lights = false;
410     //else
411     //   wave_off_lights = true;
412
413     // cout << "rel wind: " << rel_wind << endl;
414
415 }// end update wind
416
417
418 void FGAICarrier::TurnToLaunch(){
419
420     // calculate tgt heading
421     if (wind_speed_kts < 3){
422         tgt_heading = base_course;
423     } else {
424         tgt_heading = wind_from_deg;
425     }
426
427     //calculate tgt speed
428     double tgt_speed = 25 - wind_speed_kts;
429     if (tgt_speed < 10)
430         tgt_speed = 10;
431
432     //turn the carrier
433     FGAIShip::TurnTo(tgt_heading);
434     FGAIShip::AccelTo(tgt_speed);
435
436 }
437
438 void FGAICarrier::TurnToRecover(){
439
440     //these are the rules for adjusting heading to provide a relative wind
441     //down the angled flightdeck
442
443     if (wind_speed_kts < 3){
444         tgt_heading = base_course + 60;
445     } else if (rel_wind < -9 && rel_wind >= -180){
446         tgt_heading = wind_from_deg;
447     } else if (rel_wind > -7 && rel_wind < 45){
448         tgt_heading = wind_from_deg + 60;
449     } else if (rel_wind >=45 && rel_wind < 180){
450         tgt_heading = wind_from_deg + 45;
451     } else
452         tgt_heading = hdg;
453
454     SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
455
456     //calculate tgt speed
457     double tgt_speed = 26 - wind_speed_kts;
458     if (tgt_speed < 10)
459         tgt_speed = 10;
460
461     //turn the carrier
462     FGAIShip::TurnTo(tgt_heading);
463     FGAIShip::AccelTo(tgt_speed);
464
465 }
466 void FGAICarrier::TurnToBase(){
467
468     //turn the carrier
469     FGAIShip::TurnTo(base_course);
470     FGAIShip::AccelTo(base_speed);
471
472 }
473
474
475 void FGAICarrier::ReturnToBox(){
476     double course, distance, az2;
477
478     //calculate the bearing and range of the initial position from the carrier
479     geo_inverse_wgs_84(pos, mOpBoxPos, &course, &az2, &distance);
480
481     distance *= SG_METER_TO_NM;
482
483     //cout << "return course: " << course << " distance: " << distance << endl;
484     //turn the carrier
485     FGAIShip::TurnTo(course);
486     FGAIShip::AccelTo(base_speed);
487
488     if (distance >= 1)
489         returning = true;
490     else
491         returning = false;
492
493 } //  end turn to base
494
495
496 bool FGAICarrier::OutsideBox() { //returns true if the carrier is outside operating box
497
498     if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
499         SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: No Operating Box defined" );
500         return false;
501     }
502
503     if (mOpBoxPos.getLatitudeDeg() >= 0) { //northern hemisphere
504         if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + max_lat)
505             return true;
506
507         if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - min_lat)
508             return true;
509
510     } else {                  //southern hemisphere
511         if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - max_lat)
512             return true;
513
514         if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + min_lat)
515             return true;
516     }
517
518     if (mOpBoxPos.getLongitudeDeg() >=0) { //eastern hemisphere
519         if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + max_long)
520             return true;
521
522         if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - min_long)
523             return true;
524
525     } else {                 //western hemisphere
526         if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - max_long)
527             return true;
528
529         if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + min_long)
530             return true;
531     }
532
533     SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: Inside Operating Box" );
534     return false;
535
536 } // end OutsideBox
537
538
539 bool FGAICarrier::InToWind() {
540     in_to_wind = false;
541
542     if ( fabs(rel_wind) < 10 ){
543         in_to_wind = true;
544         return true;
545     }
546     return false;
547 }
548
549
550 void FGAICarrier::UpdateElevator(double dt, double transition_time) {
551
552     double step = 0;
553
554     if ((elevators && pos_norm >= 1 ) || (!elevators && pos_norm <= 0 ))
555         return;
556
557     // move the elevators
558     if ( elevators ) {
559         step = dt/transition_time;
560         if ( step > 1 )
561             step = 1;
562     } else {
563         step = -dt/transition_time;
564         if ( step < -1 )
565             step = -1;
566     }
567     // assume a linear relationship
568     raw_pos_norm += step;
569
570     //low pass filter
571     pos_norm = (raw_pos_norm * time_constant) + (pos_norm * (1 - time_constant));
572
573     //sanitise the output
574     if (raw_pos_norm >= 1) {
575         raw_pos_norm = 1;
576     } else if (raw_pos_norm <= 0) {
577         raw_pos_norm = 0;
578     }
579     return;
580
581 } // end UpdateElevator
582
583 void FGAICarrier::UpdateJBD(double dt, double jbd_transition_time) {
584
585     string launchbar_state = _launchbar_state_node->getStringValue();
586     double step = 0;
587
588     if (launchbar_state == "Engaged"){
589         jbd = true;
590     } else {
591         jbd = false;
592     }
593
594     if (( jbd && jbd_pos_norm >= 1 ) || ( !jbd && jbd_pos_norm <= 0 )){
595         return;
596     }
597
598     // move the jbds
599     if ( jbd ) {
600         step = dt/jbd_transition_time;
601         if ( step > 1 )
602             step = 1;
603     } else {
604         step = -dt/jbd_transition_time;
605         if ( step < -1 )
606             step = -1;
607     }
608
609     // assume a linear relationship
610     raw_jbd_pos_norm += step;
611
612     //low pass filter
613     jbd_pos_norm = (raw_jbd_pos_norm * jbd_time_constant) + (jbd_pos_norm * (1 - jbd_time_constant));
614
615     //sanitise the output
616     if (jbd_pos_norm >= 1) {
617         jbd_pos_norm = 1;
618     } else if (jbd_pos_norm <= 0) {
619         jbd_pos_norm = 0;
620     }
621
622     return;
623
624 } // end UpdateJBD