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