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