]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AICarrier.cxx
6fba2eaabd57157dced579daf672cdce5f280a20
[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 <string>
25 #include <vector>
26
27 #include <simgear/math/SGMath.hxx>
28 #include <simgear/math/point3d.hxx>
29 #include <simgear/math/sg_geodesy.hxx>
30 #include <math.h>
31 #include <Main/util.hxx>
32 #include <Main/viewer.hxx>
33
34 #include "AICarrier.hxx"
35
36 /** Value of earth radius (meters) */
37 #define RADIUS_M   SG_EQUATORIAL_RADIUS_M
38
39
40
41 FGAICarrier::FGAICarrier() : FGAIShip(otCarrier) {
42 }
43
44 FGAICarrier::~FGAICarrier() {
45 }
46
47 void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) {
48   if (!scFileNode)
49     return;
50
51   FGAIShip::readFromScenario(scFileNode);
52
53   setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
54   setSign(scFileNode->getStringValue("pennant-number"));
55   setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
56   setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
57   setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID", "029Y"));
58   setMaxLat(scFileNode->getDoubleValue("max-lat", 0));
59   setMinLat(scFileNode->getDoubleValue("min-lat", 0));
60   setMaxLong(scFileNode->getDoubleValue("max-long", 0));
61   setMinLong(scFileNode->getDoubleValue("min-long", 0));
62
63   SGPropertyNode* flols = scFileNode->getChild("flols-pos");
64   if (flols) {
65     // Transform to the right coordinate frame, configuration is done in
66     // the usual x-back, y-right, z-up coordinates, computations
67     // in the simulation usual body x-forward, y-right, z-down coordinates
68     flols_off(0) = - flols->getDoubleValue("x-offset-m", 0);
69     flols_off(1) = flols->getDoubleValue("y-offset-m", 0);
70     flols_off(2) = - flols->getDoubleValue("z-offset-m", 0);
71   } else
72     flols_off = SGVec3d::zeros();
73
74   std::vector<SGPropertyNode_ptr> props = scFileNode->getChildren("wire");
75   std::vector<SGPropertyNode_ptr>::const_iterator it;
76   for (it = props.begin(); it != props.end(); ++it) {
77     std::string s = (*it)->getStringValue();
78     if (!s.empty())
79       wire_objects.push_back(s);
80   }
81   
82   props = scFileNode->getChildren("catapult");
83   for (it = props.begin(); it != props.end(); ++it) {
84     std::string s = (*it)->getStringValue();
85     if (!s.empty())
86       catapult_objects.push_back(s);
87   }
88
89   props = scFileNode->getChildren("solid");
90   for (it = props.begin(); it != props.end(); ++it) {
91     std::string s = (*it)->getStringValue();
92     if (!s.empty())
93       solid_objects.push_back(s);
94   }
95
96   props = scFileNode->getChildren("parking-pos");
97   for (it = props.begin(); it != props.end(); ++it) {
98     string name = (*it)->getStringValue("name", "unnamed");
99     // Transform to the right coordinate frame, configuration is done in
100     // the usual x-back, y-right, z-up coordinates, computations
101     // in the simulation usual body x-forward, y-right, z-down coordinates
102     double offset_x = -(*it)->getDoubleValue("x-offset-m", 0);
103     double offset_y = (*it)->getDoubleValue("y-offset-m", 0);
104     double offset_z = -(*it)->getDoubleValue("z-offset-m", 0);
105     double hd = (*it)->getDoubleValue("heading-offset-deg", 0);
106     ParkPosition pp(name, SGVec3d(offset_x, offset_y, offset_z), hd);
107     ppositions.push_back(pp);
108   }
109 }
110
111 void FGAICarrier::setWind_from_east(double fps) {
112     wind_from_east = fps;
113 }
114
115 void FGAICarrier::setWind_from_north(double fps) {
116     wind_from_north = fps;
117 }
118
119 void FGAICarrier::setMaxLat(double deg) {
120     max_lat = fabs(deg);
121 }
122
123 void FGAICarrier::setMinLat(double deg) {
124     min_lat = fabs(deg);
125 }
126
127 void FGAICarrier::setMaxLong(double deg) {
128     max_long = fabs(deg);
129 }
130
131 void FGAICarrier::setMinLong(double deg) {
132     min_long = fabs(deg);
133 }
134
135 void FGAICarrier::setSign(const string& s) {
136     sign = s;
137 }
138
139 void FGAICarrier::setTACANChannelID(const string& id) {
140     TACAN_channel_id = id;
141 }
142
143 void FGAICarrier::getVelocityWrtEarth(sgdVec3& v, sgdVec3& omega, sgdVec3& pivot) {
144     sgdCopyVec3(v, vel_wrt_earth.sg() );
145     sgdCopyVec3(omega, rot_wrt_earth.sg() );
146     sgdCopyVec3(pivot, rot_pivot_wrt_earth.sg() );
147 }
148
149 void FGAICarrier::update(double dt) {
150     // For computation of rotation speeds we just use finite differences here.
151     // That is perfectly valid since this thing is not driven by accelerations
152     // but by just apply discrete changes at its velocity variables.
153     // Update the velocity information stored in those nodes.
154     // Transform that one to the horizontal local coordinate system.
155     SGQuatd ec2hl = SGQuatd::fromLonLatDeg(pos.lon(), pos.lat());
156     // The orientation of the carrier wrt the horizontal local frame
157     SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
158     // and postrotate the orientation of the AIModel wrt the horizontal
159     // local frame
160     SGQuatd ec2body = ec2hl*hl2body;
161     // The cartesian position of the carrier in the wgs84 world
162     SGVec3d cartPos = SGGeod::fromDegFt(pos.lon(), pos.lat(), pos.elev());
163     // Store for later use by the groundcache
164     rot_pivot_wrt_earth = cartPos;
165
166     // Compute the velocity in m/s in the earth centered coordinate system axis
167     double v_north = 0.51444444*speed*cos(hdg * SGD_DEGREES_TO_RADIANS);
168     double v_east  = 0.51444444*speed*sin(hdg * SGD_DEGREES_TO_RADIANS);
169     vel_wrt_earth = ec2hl.backTransform(SGVec3d(v_north, v_east, 0));
170
171     // Now update the position and heading. This will compute new hdg and
172     // roll values required for the rotation speed computation.
173     FGAIShip::update(dt);
174
175
176     //automatic turn into wind with a target wind of 25 kts otd
177     if(turn_to_launch_hdg){
178         TurnToLaunch();
179     } else if(OutsideBox() || returning) {// check that the carrier is inside the operating box
180         ReturnToBox();
181     } else {
182         TurnToBase();
183     }
184
185     // Only change these values if we are able to compute them safely
186     if (dt < DBL_MIN)
187       rot_wrt_earth = SGVec3d::zeros();
188     else {
189       // Now here is the finite difference ...
190
191       // Transform that one to the horizontal local coordinate system.
192       SGQuatd ec2hlNew = SGQuatd::fromLonLatDeg(pos.lon(), pos.lat());
193       // compute the new orientation
194       SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
195       // The rotation difference
196       SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
197       SGVec3d dOrAngleAxis;
198       dOr.getAngleAxis(dOrAngleAxis);
199       // divided by the time difference provides a rotation speed vector
200       dOrAngleAxis /= dt;
201
202       // now rotate the rotation speed vector back into the
203       // earth centered frames coordinates
204       dOrAngleAxis = ec2body.backTransform(dOrAngleAxis);
205 //       dOrAngleAxis = hl2body.backTransform(dOrAngleAxis);
206 //       dOrAngleAxis(1) = 0;
207 //       dOrAngleAxis = ec2hl.backTransform(dOrAngleAxis);
208       rot_wrt_earth = dOrAngleAxis;
209     }
210
211     UpdateWind(dt);
212     UpdateElevator(dt, transition_time);
213
214     // For the flols reuse some computations done above ...
215
216     // The position of the eyepoint - at least near that ...
217     SGVec3d eyePos(globals->get_current_view()->get_absolute_view_pos());
218     // Add the position offset of the AIModel to gain the earth
219     // centered position
220     SGVec3d eyeWrtCarrier = eyePos - cartPos;
221     // rotate the eyepoint wrt carrier vector into the carriers frame
222     eyeWrtCarrier = ec2body.transform(eyeWrtCarrier);
223     // the eyepoints vector wrt the flols position
224     SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off;
225     
226     // the distance from the eyepoint to the flols
227     dist = norm(eyeWrtFlols);
228     
229     // now the angle, positive angles are upwards
230     if (fabs(dist) < SGLimits<float>::min()) {
231       angle = 0;
232     } else {
233       double sAngle = -eyeWrtFlols(2)/dist;
234       sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
235       angle = SGMiscd::rad2deg(asin(sAngle));
236     }
237     
238     // set the value of source
239     if ( angle <= 4.35 && angle > 4.01 )
240       source = 1;
241     else if ( angle <= 4.01 && angle > 3.670 )
242       source = 2;
243     else if ( angle <= 3.670 && angle > 3.330 )
244       source = 3;
245     else if ( angle <= 3.330 && angle > 2.990 )
246       source = 4;
247     else if ( angle <= 2.990 && angle > 2.650 )
248       source = 5;
249     else if ( angle <= 2.650 )
250       source = 6;
251     else
252       source = 0;
253 } //end update
254
255 bool FGAICarrier::init() {
256     if (!FGAIShip::init())
257         return false;
258
259     // process the 3d model here
260     // mark some objects solid, mark the wires ...
261
262     // The model should be used for altitude computations.
263     // To avoid that every detail in a carrier 3D model will end into
264     // the aircraft local cache, only set the HOT traversal bit on
265     // selected objects.
266     ssgEntity *sel = aip.getSceneGraph();
267     // Clear the HOT traversal flag
268     mark_nohot(sel);
269     // Selectively set that flag again for wires/cats/solid objects.
270     // Attach a pointer to this carrier class to those objects.
271     mark_wires(sel, wire_objects);
272     mark_cat(sel, catapult_objects);
273     mark_solid(sel, solid_objects);
274
275     _longitude_node = fgGetNode("/position/longitude-deg", true);
276     _latitude_node = fgGetNode("/position/latitude-deg", true);
277     _altitude_node = fgGetNode("/position/altitude-ft", true);
278     // _elevator_node = fgGetNode("/controls/elevators", true);
279
280     _surface_wind_from_deg_node =
281             fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
282     _surface_wind_speed_node =
283             fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
284
285
286     turn_to_launch_hdg = false;
287     returning = false;
288
289     initialpos = pos;
290     base_course = hdg;
291     base_speed = speed;
292
293     step = 0;
294     pos_norm = 0;
295     elevators = false;
296     transition_time = 150;
297     time_constant = 0.005;
298
299     return true;
300 }
301
302 void FGAICarrier::bind() {
303     FGAIShip::bind();
304
305     props->untie("velocities/true-airspeed-kt");
306
307     props->tie("controls/flols/source-lights",
308                 SGRawValuePointer<int>(&source));
309     props->tie("controls/flols/distance-m",
310                 SGRawValuePointer<double>(&dist));
311     props->tie("controls/flols/angle-degs",
312                 SGRawValuePointer<double>(&angle));
313     props->tie("controls/turn-to-launch-hdg",
314                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
315     props->tie("controls/in-to-wind",
316                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
317     props->tie("controls/base-course-deg",
318                 SGRawValuePointer<double>(&base_course));
319     props->tie("controls/base-speed-kts",
320                 SGRawValuePointer<double>(&base_speed));
321     props->tie("controls/start-pos-lat-deg",
322                 SGRawValuePointer<double>(&initialpos[1]));
323     props->tie("controls/start-pos-long-deg",
324                 SGRawValuePointer<double>(&initialpos[0]));
325     props->tie("velocities/speed-kts",
326                 SGRawValuePointer<double>(&speed));
327     props->tie("environment/surface-wind-speed-true-kts",
328                 SGRawValuePointer<double>(&wind_speed_kts));
329     props->tie("environment/surface-wind-from-true-degs",
330                 SGRawValuePointer<double>(&wind_from_deg));
331     props->tie("environment/rel-wind-from-degs",
332                 SGRawValuePointer<double>(&rel_wind_from_deg));
333     props->tie("environment/rel-wind-from-carrier-hdg-degs",
334                 SGRawValuePointer<double>(&rel_wind));
335     props->tie("environment/rel-wind-speed-kts",
336                 SGRawValuePointer<double>(&rel_wind_speed_kts));
337     props->tie("controls/flols/wave-off-lights",
338                 SGRawValuePointer<bool>(&wave_off_lights));
339     props->tie("controls/elevators",
340                 SGRawValuePointer<bool>(&elevators));
341     props->tie("surface-positions/elevators-pos-norm",
342                 SGRawValuePointer<double>(&pos_norm));
343     props->tie("controls/elevators-trans-time-s",
344                 SGRawValuePointer<double>(&transition_time));
345     props->tie("controls/elevators-time-constant",
346                 SGRawValuePointer<double>(&time_constant));
347
348     props->setBoolValue("controls/flols/cut-lights", false);
349     props->setBoolValue("controls/flols/wave-off-lights", false);
350     props->setBoolValue("controls/flols/cond-datum-lights", true);
351     props->setBoolValue("controls/crew", false);
352     props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
353     props->setStringValue("sign", sign.c_str());
354 }
355
356
357 void FGAICarrier::unbind() {
358     FGAIShip::unbind();
359
360     props->untie("velocities/true-airspeed-kt");
361     props->untie("controls/flols/source-lights");
362     props->untie("controls/flols/distance-m");
363     props->untie("controls/flols/angle-degs");
364     props->untie("controls/turn-to-launch-hdg");
365     props->untie("velocities/speed-kts");
366     props->untie("environment/wind-speed-true-kts");
367     props->untie("environment/wind-from-true-degs");
368     props->untie("environment/rel-wind-from-degs");
369     props->untie("environment/rel-wind-speed-kts");
370     props->untie("controls/flols/wave-off-lights");
371     props->untie("controls/elevators");
372     props->untie("surface-positions/elevators-pos-norm");
373     props->untie("controls/elevators-trans-time-secs");
374     props->untie("controls/elevators-time-constant");
375 }
376
377
378 bool FGAICarrier::getParkPosition(const string& id, SGGeod& geodPos,
379                                   double& hdng, SGVec3d& uvw)
380 {
381
382     // FIXME: does not yet cover rotation speeds.
383     list<ParkPosition>::iterator it = ppositions.begin();
384     while (it != ppositions.end()) {
385         // Take either the specified one or the first one ...
386         if ((*it).name == id || id.empty()) {
387             ParkPosition ppos = *it;
388             SGVec3d cartPos = getCartPosAt(ppos.offset);
389             geodPos = cartPos;
390             hdng = hdg + ppos.heading_deg;
391             double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
392             double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
393             double speed_fps = speed*1.6878099;
394             uvw = SGVec3d(chdng*speed_fps, shdng*speed_fps, 0);
395             return true;
396         }
397         ++it;
398     }
399
400     return false;
401 }
402
403
404 void FGAICarrier::mark_nohot(ssgEntity* e) {
405     if (e->isAKindOf(ssgTypeBranch())) {
406         ssgBranch* br = (ssgBranch*)e;
407         ssgEntity* kid;
408         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
409             mark_nohot(kid);
410
411         br->clrTraversalMaskBits(SSGTRAV_HOT);
412
413     } else if (e->isAKindOf(ssgTypeLeaf())) {
414
415         e->clrTraversalMaskBits(SSGTRAV_HOT);
416     }
417 }
418
419
420 bool FGAICarrier::mark_wires(ssgEntity* e, const list<string>& wire_objects, bool mark) {
421     bool found = false;
422     if (e->isAKindOf(ssgTypeBranch())) {
423         ssgBranch* br = (ssgBranch*)e;
424         ssgEntity* kid;
425
426         list<string>::const_iterator it;
427         for (it = wire_objects.begin(); it != wire_objects.end(); ++it)
428             mark = mark || (e->getName() && (*it) == e->getName());
429
430         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
431             found = mark_wires(kid, wire_objects, mark) || found;
432
433         if (found)
434             br->setTraversalMaskBits(SSGTRAV_HOT);
435
436     } else if (e->isAKindOf(ssgTypeLeaf())) {
437         list<string>::const_iterator it;
438         for (it = wire_objects.begin(); it != wire_objects.end(); ++it) {
439             if (mark || (e->getName() && (*it) == e->getName())) {
440                 e->setTraversalMaskBits(SSGTRAV_HOT);
441                 ssgBase* ud = e->getUserData();
442                 if (ud) {
443                     FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
444                     if (ch) {
445                         SG_LOG(SG_GENERAL, SG_WARN,
446                                 "AICarrier: Carrier hardware gets marked twice!\n"
447                                 "           You have probably a whole branch marked as"
448                                 " a wire which also includes other carrier hardware.");
449                     } else {
450                         SG_LOG(SG_GENERAL, SG_ALERT,
451                                 "AICarrier: Found user data attached to a leaf node which "
452                                 "should be marked as a wire!\n    ****Skipping!****");
453                     }
454                 } else {
455                     e->setUserData( FGAICarrierHardware::newWire( this ) );
456                     ssgLeaf *l = (ssgLeaf*)e;
457                     if ( l->getNumLines() != 1 ) {
458                         SG_LOG(SG_GENERAL, SG_ALERT,
459                                 "AICarrier: Found wires not modeled with exactly one line!");
460                     }
461                     found = true;
462                 }
463             }
464         }
465     }
466     return found;
467 }
468
469
470 bool FGAICarrier::mark_solid(ssgEntity* e, const list<string>& solid_objects, bool mark) {
471     bool found = false;
472     if (e->isAKindOf(ssgTypeBranch())) {
473         ssgBranch* br = (ssgBranch*)e;
474         ssgEntity* kid;
475
476         list<string>::const_iterator it;
477         for (it = solid_objects.begin(); it != solid_objects.end(); ++it)
478             mark = mark || (e->getName() && (*it) == e->getName());
479
480         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
481             found = mark_solid(kid, solid_objects, mark) || found;
482
483         if (found)
484             br->setTraversalMaskBits(SSGTRAV_HOT);
485
486     } else if (e->isAKindOf(ssgTypeLeaf())) {
487         list<string>::const_iterator it;
488         for (it = solid_objects.begin(); it != solid_objects.end(); ++it) {
489             if (mark || (e->getName() && (*it) == e->getName())) {
490                 e->setTraversalMaskBits(SSGTRAV_HOT);
491                 ssgBase* ud = e->getUserData();
492
493                 if (ud) {
494                     FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
495                     if (ch) {
496                         SG_LOG(SG_GENERAL, SG_WARN,
497                                 "AICarrier: Carrier hardware gets marked twice!\n"
498                                 "           You have probably a whole branch marked solid"
499                                 " which also includes other carrier hardware.");
500                     } else {
501                         SG_LOG(SG_GENERAL, SG_ALERT,
502                                 "AICarrier: Found user data attached to a leaf node which "
503                                 "should be marked solid!\n    ****Skipping!****");
504                     }
505                 } else {
506                     e->setUserData( FGAICarrierHardware::newSolid( this ) );
507                     found = true;
508                 }
509             }
510         }
511     }
512     return found;
513 }
514
515
516 bool FGAICarrier::mark_cat(ssgEntity* e, const list<string>& cat_objects, bool mark) {
517     bool found = false;
518     if (e->isAKindOf(ssgTypeBranch())) {
519         ssgBranch* br = (ssgBranch*)e;
520         ssgEntity* kid;
521
522         list<string>::const_iterator it;
523         for (it = cat_objects.begin(); it != cat_objects.end(); ++it)
524             mark = mark || (e->getName() && (*it) == e->getName());
525
526         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
527             found = mark_cat(kid, cat_objects, mark) || found;
528
529         if (found)
530             br->setTraversalMaskBits(SSGTRAV_HOT);
531
532     } else if (e->isAKindOf(ssgTypeLeaf())) {
533         list<string>::const_iterator it;
534         for (it = cat_objects.begin(); it != cat_objects.end(); ++it) {
535             if (mark || (e->getName() && (*it) == e->getName())) {
536                 e->setTraversalMaskBits(SSGTRAV_HOT);
537                 ssgBase* ud = e->getUserData();
538                 if (ud) {
539                     FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
540                     if (ch) {
541                         SG_LOG(SG_GENERAL, SG_WARN,
542                                 "AICarrier: Carrier hardware gets marked twice!\n"
543                                 "You have probably a whole branch marked as"
544                                 "a catapult which also includes other carrier hardware.");
545                     } else {
546                         SG_LOG(SG_GENERAL, SG_ALERT,
547                                 "AICarrier: Found user data attached to a leaf node which "
548                                 "should be marked as a catapult!\n    ****Skipping!****");
549                     }
550                 } else {
551                     e->setUserData( FGAICarrierHardware::newCatapult( this ) );
552                     ssgLeaf *l = (ssgLeaf*)e;
553                     if ( l->getNumLines() != 1 ) {
554                         SG_LOG(SG_GENERAL, SG_ALERT,
555                                 "AICarrier: Found a cat not modeled with exactly "
556                                 "one line!");
557                     } else {
558                         // Now some special code to make sure the cat points in the right
559                         // direction. The 0 index must be the backward end, the 1 index
560                         // the forward end.
561                         // Forward is positive x-direction in our 3D model, also the model
562                         // as such is flattened when it is loaded, so we do not need to
563                         // care for transforms ...
564                         short v[2];
565                         l->getLine(0, v, v+1 );
566                         sgVec3 ends[2];
567                         for (int k=0; k<2; ++k)
568                             sgCopyVec3( ends[k], l->getVertex( v[k] ) );
569
570                         // When the 1 end is behind the 0 end, swap the coordinates.
571                         if (ends[0][0] < ends[1][0]) {
572                             sgCopyVec3( l->getVertex( v[0] ), ends[1] );
573                             sgCopyVec3( l->getVertex( v[1] ), ends[0] );
574                         }
575                         found = true;
576                     }
577                 }
578             }
579         }
580     }
581     return found;
582 }
583
584 // find relative wind
585 void FGAICarrier::UpdateWind( double dt) {
586
587     double recip;
588
589     //calculate the reciprocal hdg
590
591     if (hdg >= 180)
592         recip = hdg - 180;
593     else
594         recip = hdg + 180;
595
596     //cout <<" heading: " << hdg << "recip: " << recip << endl;
597
598     //get the surface wind speed and direction
599     wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
600     wind_speed_kts  = _surface_wind_speed_node->getDoubleValue();
601
602     //calculate the surface wind speed north and east in kts
603     double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
604     double wind_speed_from_east_kts  = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
605
606     //calculate the carrier speed north and east in kts
607     double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
608     double speed_east_kts  = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
609
610     //calculate the relative wind speed north and east in kts
611     double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
612     double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
613
614     //combine relative speeds north and east to get relative windspeed in kts
615     rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts)
616     + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
617
618     //calculate the relative wind direction
619     rel_wind_from_deg = atan(rel_wind_speed_from_east_kts/rel_wind_speed_from_north_kts)
620                             * SG_RADIANS_TO_DEGREES;
621
622     // rationalise the output
623     if (rel_wind_speed_from_north_kts <= 0) {
624         rel_wind_from_deg = 180 + rel_wind_from_deg;
625     } else {
626         if(rel_wind_speed_from_east_kts <= 0)
627             rel_wind_from_deg = 360 + rel_wind_from_deg;
628     }
629
630     //calculate rel wind
631     rel_wind = rel_wind_from_deg - hdg;
632     if (rel_wind > 180)
633         rel_wind -= 360;
634
635     //switch the wave-off lights
636     if (InToWind())
637        wave_off_lights = false;
638     else
639        wave_off_lights = true;
640
641     // cout << "rel wind: " << rel_wind << endl;
642
643 }// end update wind
644
645
646 void FGAICarrier::TurnToLaunch(){
647
648     //calculate tgt speed
649     double tgt_speed = 25 - wind_speed_kts;
650     if (tgt_speed < 10)
651         tgt_speed = 10;
652
653     //turn the carrier
654     FGAIShip::TurnTo(wind_from_deg);
655     FGAIShip::AccelTo(tgt_speed);
656
657 }
658
659
660 void FGAICarrier::TurnToBase(){
661
662     //turn the carrier
663     FGAIShip::TurnTo(base_course);
664     FGAIShip::AccelTo(base_speed);
665
666 }
667
668
669 void FGAICarrier::ReturnToBox(){
670     double course, distance, az2;
671
672     //get the carrier position
673     carrierpos = pos;
674
675     //cout << "lat: " << carrierpos[1] << " lon: " << carrierpos[0] << endl;
676
677     //calculate the bearing and range of the initial position from the carrier
678     geo_inverse_wgs_84(carrierpos[2],
679                        carrierpos[1],
680                        carrierpos[0],
681                        initialpos[1],
682                        initialpos[0],
683                        &course, &az2, &distance);
684
685     distance *= SG_METER_TO_NM;
686
687     //cout << "return course: " << course << " distance: " << distance << endl;
688     //turn the carrier
689     FGAIShip::TurnTo(course);
690     FGAIShip::AccelTo(base_speed);
691
692     if (distance >= 1)
693         returning = true;
694     else
695         returning = false;
696
697 } //  end turn to base
698
699
700 bool FGAICarrier::OutsideBox() { //returns true if the carrier is outside operating box
701
702     if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
703         SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: No Operating Box defined" );
704         return false;
705     }
706
707     if (initialpos[1] >= 0) { //northern hemisphere
708         if (pos[1] >= initialpos[1] + max_lat)
709             return true;
710
711         if (pos[1] <= initialpos[1] - min_lat)
712             return true;
713
714     } else {                  //southern hemisphere
715         if (pos[1] <= initialpos[1] - max_lat)
716             return true;
717
718         if (pos[1] >= initialpos[1] + min_lat)
719             return true;
720     }
721
722     if (initialpos[0] >=0) { //eastern hemisphere
723         if (pos[0] >= initialpos[0] + max_long)
724             return true;
725
726         if (pos[0] <= initialpos[0] - min_long)
727             return true;
728
729     } else {                 //western hemisphere
730         if (pos[0] <= initialpos[0] - max_long)
731             return true;
732
733         if (pos[0] >= initialpos[0] + min_long)
734             return true;
735     }
736
737     SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: Inside Operating Box" );
738     return false;
739
740 } // end OutsideBox
741
742
743 // return the distance to the horizon, given the altitude and the radius of the earth
744 float FGAICarrier::Horizon(float h) {
745     return RADIUS_M * acos(RADIUS_M / (RADIUS_M + h));
746 }
747
748
749 bool FGAICarrier::InToWind() {
750     if ( fabs(rel_wind) < 5 )
751         return true;
752
753     return false;
754 }
755
756
757 void FGAICarrier::UpdateElevator(double dt, double transition_time) {
758
759     if ((elevators && pos_norm >= 1 ) || (!elevators && pos_norm <= 0 ))
760         return;
761
762     // move the elevators
763     if ( elevators ) {
764         step += dt/transition_time;
765         if ( step > 1 )
766             step = 1;
767
768     } else {
769         step -= dt/transition_time;
770         if ( step < 0 )
771             step = 0;
772     }
773     // assume a linear relationship
774     raw_pos_norm = step;
775     if (raw_pos_norm >= 1) {
776         raw_pos_norm = 1;
777     } else if (raw_pos_norm <= 0) {
778         raw_pos_norm = 0;
779     }
780
781     //low pass filter
782     pos_norm = (raw_pos_norm * time_constant) + (pos_norm * (1 - time_constant));
783     return;
784
785 } // end UpdateElevator
786
787
788 int FGAICarrierHardware::unique_id = 1;
789