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