1 // FGAICarrier - FGAIShip-derived class creates an AI aircraft carrier
3 // Written by David Culp, started October 2004.
4 // - davidculp2@comcast.net
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.
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.
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.
28 #include <osg/NodeVisitor>
30 #include <simgear/math/SGMath.hxx>
31 #include <simgear/math/sg_geodesy.hxx>
32 #include <simgear/scene/util/SGNodeMasks.hxx>
35 #include <Main/util.hxx>
36 #include <Main/viewer.hxx>
38 #include "AICarrier.hxx"
40 class FGCarrierVisitor : public osg::NodeVisitor {
42 FGCarrierVisitor(FGAICarrier* carrier,
43 const std::list<std::string>& wireObjects,
44 const std::list<std::string>& catapultObjects,
45 const std::list<std::string>& solidObjects) :
46 osg::NodeVisitor(osg::NodeVisitor::NODE_VISITOR,
47 osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
48 mWireObjects(wireObjects),
49 mCatapultObjects(catapultObjects),
50 mSolidObjects(solidObjects),
54 virtual void apply(osg::Node& node)
56 osg::ref_ptr<osg::Referenced> oldUserData = mUserData;
57 bool oldFoundHot = mFoundHot;
60 if (std::find(mWireObjects.begin(), mWireObjects.end(), node.getName())
61 != mWireObjects.end()) {
63 mUserData = FGAICarrierHardware::newWire(mCarrier);
65 if (std::find(mCatapultObjects.begin(), mCatapultObjects.end(), node.getName())
66 != mCatapultObjects.end()) {
68 mUserData = FGAICarrierHardware::newCatapult(mCarrier);
70 if (std::find(mSolidObjects.begin(), mSolidObjects.end(), node.getName())
71 != mSolidObjects.end()) {
73 mUserData = FGAICarrierHardware::newSolid(mCarrier);
75 node.setUserData(mUserData.get());
79 mFoundHot = oldFoundHot || mFoundHot;
82 node.setNodeMask(node.getNodeMask() | SG_NODEMASK_TERRAIN_BIT);
84 node.setNodeMask(node.getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
86 mUserData = oldUserData;
90 std::list<std::string> mWireObjects;
91 std::list<std::string> mCatapultObjects;
92 std::list<std::string> mSolidObjects;
94 FGAICarrier* mCarrier;
95 osg::ref_ptr<osg::Referenced> mUserData;
98 FGAICarrier::FGAICarrier() : FGAIShip(otCarrier) {
101 FGAICarrier::~FGAICarrier() {
104 void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) {
108 FGAIShip::readFromScenario(scFileNode);
110 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
111 setSign(scFileNode->getStringValue("pennant-number"));
112 setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
113 setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
114 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID", "029Y"));
115 setMaxLat(scFileNode->getDoubleValue("max-lat", 0));
116 setMinLat(scFileNode->getDoubleValue("min-lat", 0));
117 setMaxLong(scFileNode->getDoubleValue("max-long", 0));
118 setMinLong(scFileNode->getDoubleValue("min-long", 0));
120 SGPropertyNode* flols = scFileNode->getChild("flols-pos");
122 // Transform to the right coordinate frame, configuration is done in
123 // the usual x-back, y-right, z-up coordinates, computations
124 // in the simulation usual body x-forward, y-right, z-down coordinates
125 flols_off(0) = - flols->getDoubleValue("x-offset-m", 0);
126 flols_off(1) = flols->getDoubleValue("y-offset-m", 0);
127 flols_off(2) = - flols->getDoubleValue("z-offset-m", 0);
129 flols_off = SGVec3d::zeros();
131 std::vector<SGPropertyNode_ptr> props = scFileNode->getChildren("wire");
132 std::vector<SGPropertyNode_ptr>::const_iterator it;
133 for (it = props.begin(); it != props.end(); ++it) {
134 std::string s = (*it)->getStringValue();
136 wire_objects.push_back(s);
139 props = scFileNode->getChildren("catapult");
140 for (it = props.begin(); it != props.end(); ++it) {
141 std::string s = (*it)->getStringValue();
143 catapult_objects.push_back(s);
146 props = scFileNode->getChildren("solid");
147 for (it = props.begin(); it != props.end(); ++it) {
148 std::string s = (*it)->getStringValue();
150 solid_objects.push_back(s);
153 props = scFileNode->getChildren("parking-pos");
154 for (it = props.begin(); it != props.end(); ++it) {
155 string name = (*it)->getStringValue("name", "unnamed");
156 // Transform to the right coordinate frame, configuration is done in
157 // the usual x-back, y-right, z-up coordinates, computations
158 // in the simulation usual body x-forward, y-right, z-down coordinates
159 double offset_x = -(*it)->getDoubleValue("x-offset-m", 0);
160 double offset_y = (*it)->getDoubleValue("y-offset-m", 0);
161 double offset_z = -(*it)->getDoubleValue("z-offset-m", 0);
162 double hd = (*it)->getDoubleValue("heading-offset-deg", 0);
163 ParkPosition pp(name, SGVec3d(offset_x, offset_y, offset_z), hd);
164 ppositions.push_back(pp);
168 void FGAICarrier::setWind_from_east(double fps) {
169 wind_from_east = fps;
172 void FGAICarrier::setWind_from_north(double fps) {
173 wind_from_north = fps;
176 void FGAICarrier::setMaxLat(double deg) {
180 void FGAICarrier::setMinLat(double deg) {
184 void FGAICarrier::setMaxLong(double deg) {
185 max_long = fabs(deg);
188 void FGAICarrier::setMinLong(double deg) {
189 min_long = fabs(deg);
192 void FGAICarrier::setSign(const string& s) {
196 void FGAICarrier::setTACANChannelID(const string& id) {
197 TACAN_channel_id = id;
200 void FGAICarrier::getVelocityWrtEarth(SGVec3d& v, SGVec3d& omega, SGVec3d& pivot) {
202 omega = rot_wrt_earth;
203 pivot = rot_pivot_wrt_earth;
206 void FGAICarrier::update(double dt) {
207 // For computation of rotation speeds we just use finite differences here.
208 // That is perfectly valid since this thing is not driven by accelerations
209 // but by just apply discrete changes at its velocity variables.
210 // Update the velocity information stored in those nodes.
211 // Transform that one to the horizontal local coordinate system.
212 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
213 // The orientation of the carrier wrt the horizontal local frame
214 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
215 // and postrotate the orientation of the AIModel wrt the horizontal
217 SGQuatd ec2body = ec2hl*hl2body;
218 // The cartesian position of the carrier in the wgs84 world
219 SGVec3d cartPos = SGVec3d::fromGeod(pos);
220 // Store for later use by the groundcache
221 rot_pivot_wrt_earth = cartPos;
223 // Compute the velocity in m/s in the earth centered coordinate system axis
224 double v_north = 0.51444444*speed*cos(hdg * SGD_DEGREES_TO_RADIANS);
225 double v_east = 0.51444444*speed*sin(hdg * SGD_DEGREES_TO_RADIANS);
226 vel_wrt_earth = ec2hl.backTransform(SGVec3d(v_north, v_east, 0));
228 // Now update the position and heading. This will compute new hdg and
229 // roll values required for the rotation speed computation.
230 FGAIShip::update(dt);
233 //automatic turn into wind with a target wind of 25 kts otd
234 if(turn_to_launch_hdg){
236 } else if(OutsideBox() || returning) {// check that the carrier is inside the operating box
242 // Only change these values if we are able to compute them safely
244 rot_wrt_earth = SGVec3d::zeros();
246 // Now here is the finite difference ...
248 // Transform that one to the horizontal local coordinate system.
249 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
250 // compute the new orientation
251 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
252 // The rotation difference
253 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
254 SGVec3d dOrAngleAxis;
255 dOr.getAngleAxis(dOrAngleAxis);
256 // divided by the time difference provides a rotation speed vector
259 // now rotate the rotation speed vector back into the
260 // earth centered frames coordinates
261 dOrAngleAxis = ec2body.backTransform(dOrAngleAxis);
262 // dOrAngleAxis = hl2body.backTransform(dOrAngleAxis);
263 // dOrAngleAxis(1) = 0;
264 // dOrAngleAxis = ec2hl.backTransform(dOrAngleAxis);
265 rot_wrt_earth = dOrAngleAxis;
269 UpdateElevator(dt, transition_time);
270 UpdateJBD(dt, jbd_transition_time);
271 // For the flols reuse some computations done above ...
273 // The position of the eyepoint - at least near that ...
274 SGVec3d eyePos(globals->get_current_view()->get_view_pos());
275 // Add the position offset of the AIModel to gain the earth
277 SGVec3d eyeWrtCarrier = eyePos - cartPos;
278 // rotate the eyepoint wrt carrier vector into the carriers frame
279 eyeWrtCarrier = ec2body.transform(eyeWrtCarrier);
280 // the eyepoints vector wrt the flols position
281 SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off;
283 // the distance from the eyepoint to the flols
284 dist = norm(eyeWrtFlols);
286 // now the angle, positive angles are upwards
287 if (fabs(dist) < SGLimits<float>::min()) {
290 double sAngle = -eyeWrtFlols(2)/dist;
291 sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
292 angle = SGMiscd::rad2deg(asin(sAngle));
295 // set the value of source
296 if ( angle <= 4.35 && angle > 4.01 )
298 else if ( angle <= 4.01 && angle > 3.670 )
300 else if ( angle <= 3.670 && angle > 3.330 )
302 else if ( angle <= 3.330 && angle > 2.990 )
304 else if ( angle <= 2.990 && angle > 2.650 )
306 else if ( angle <= 2.650 )
312 bool FGAICarrier::init(bool search_in_AI_path) {
313 if (!FGAIShip::init(search_in_AI_path))
316 // process the 3d model here
317 // mark some objects solid, mark the wires ...
319 // The model should be used for altitude computations.
320 // To avoid that every detail in a carrier 3D model will end into
321 // the aircraft local cache, only set the HOT traversal bit on
323 osg::Node* sel = aip.getSceneGraph();
324 // Clear the HOT traversal flag
325 // Selectively set that flag again for wires/cats/solid objects.
326 // Attach a pointer to this carrier class to those objects.
327 FGCarrierVisitor carrierVisitor(this, wire_objects, catapult_objects, solid_objects);
328 sel->accept(carrierVisitor);
330 _longitude_node = fgGetNode("/position/longitude-deg", true);
331 _latitude_node = fgGetNode("/position/latitude-deg", true);
332 _altitude_node = fgGetNode("/position/altitude-ft", true);
334 _launchbar_state_node = fgGetNode("/gear/launchbar/state", true);
336 _surface_wind_from_deg_node =
337 fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
338 _surface_wind_speed_node =
339 fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
342 turn_to_launch_hdg = false;
351 transition_time = 150;
352 time_constant = 0.005;
353 jbd_pos_norm = raw_jbd_pos_norm = 0;
355 jbd_transition_time = 3;
356 jbd_time_constant = 0.1;
360 void FGAICarrier::bind() {
363 props->untie("velocities/true-airspeed-kt");
365 props->tie("controls/flols/source-lights",
366 SGRawValuePointer<int>(&source));
367 props->tie("controls/flols/distance-m",
368 SGRawValuePointer<double>(&dist));
369 props->tie("controls/flols/angle-degs",
370 SGRawValuePointer<double>(&angle));
371 props->tie("controls/turn-to-launch-hdg",
372 SGRawValuePointer<bool>(&turn_to_launch_hdg));
373 props->tie("controls/in-to-wind",
374 SGRawValuePointer<bool>(&turn_to_launch_hdg));
375 props->tie("controls/base-course-deg",
376 SGRawValuePointer<double>(&base_course));
377 props->tie("controls/base-speed-kts",
378 SGRawValuePointer<double>(&base_speed));
379 props->tie("controls/start-pos-lat-deg",
380 SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLatitudeDeg));
381 props->tie("controls/start-pos-long-deg",
382 SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLongitudeDeg));
383 props->tie("velocities/speed-kts",
384 SGRawValuePointer<double>(&speed));
385 props->tie("environment/surface-wind-speed-true-kts",
386 SGRawValuePointer<double>(&wind_speed_kts));
387 props->tie("environment/surface-wind-from-true-degs",
388 SGRawValuePointer<double>(&wind_from_deg));
389 props->tie("environment/rel-wind-from-degs",
390 SGRawValuePointer<double>(&rel_wind_from_deg));
391 props->tie("environment/rel-wind-from-carrier-hdg-degs",
392 SGRawValuePointer<double>(&rel_wind));
393 props->tie("environment/rel-wind-speed-kts",
394 SGRawValuePointer<double>(&rel_wind_speed_kts));
395 props->tie("controls/flols/wave-off-lights",
396 SGRawValuePointer<bool>(&wave_off_lights));
397 props->tie("controls/elevators",
398 SGRawValuePointer<bool>(&elevators));
399 props->tie("surface-positions/elevators-pos-norm",
400 SGRawValuePointer<double>(&pos_norm));
401 props->tie("controls/elevators-trans-time-s",
402 SGRawValuePointer<double>(&transition_time));
403 props->tie("controls/elevators-time-constant",
404 SGRawValuePointer<double>(&time_constant));
405 props->tie("controls/jbd",
406 SGRawValuePointer<bool>(&jbd));
407 props->tie("surface-positions/jbd-pos-norm",
408 SGRawValuePointer<double>(&jbd_pos_norm));
409 props->tie("controls/jbd-trans-time-s",
410 SGRawValuePointer<double>(&jbd_transition_time));
411 props->tie("controls/jbd-time-constant",
412 SGRawValuePointer<double>(&jbd_time_constant));
414 props->setBoolValue("controls/flols/cut-lights", false);
415 props->setBoolValue("controls/flols/wave-off-lights", false);
416 props->setBoolValue("controls/flols/cond-datum-lights", true);
417 props->setBoolValue("controls/crew", false);
418 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
419 props->setStringValue("sign", sign.c_str());
423 void FGAICarrier::unbind() {
426 props->untie("velocities/true-airspeed-kt");
427 props->untie("controls/flols/source-lights");
428 props->untie("controls/flols/distance-m");
429 props->untie("controls/flols/angle-degs");
430 props->untie("controls/turn-to-launch-hdg");
431 props->untie("velocities/speed-kts");
432 props->untie("environment/wind-speed-true-kts");
433 props->untie("environment/wind-from-true-degs");
434 props->untie("environment/rel-wind-from-degs");
435 props->untie("environment/rel-wind-speed-kts");
436 props->untie("controls/flols/wave-off-lights");
437 props->untie("controls/elevators");
438 props->untie("surface-positions/elevators-pos-norm");
439 props->untie("controls/elevators-trans-time-secs");
440 props->untie("controls/elevators-time-constant");
441 props->untie("controls/jbd");
442 props->untie("surface-positions/jbd-pos-norm");
443 props->untie("controls/jbd-trans-time-s");
444 props->untie("controls/jbd-time-constant");
449 bool FGAICarrier::getParkPosition(const string& id, SGGeod& geodPos,
450 double& hdng, SGVec3d& uvw)
453 // FIXME: does not yet cover rotation speeds.
454 list<ParkPosition>::iterator it = ppositions.begin();
455 while (it != ppositions.end()) {
456 // Take either the specified one or the first one ...
457 if ((*it).name == id || id.empty()) {
458 ParkPosition ppos = *it;
459 SGVec3d cartPos = getCartPosAt(ppos.offset);
460 geodPos = SGGeod::fromCart(cartPos);
461 hdng = hdg + ppos.heading_deg;
462 double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
463 double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
464 double speed_fps = speed*1.6878099;
465 uvw = SGVec3d(chdng*speed_fps, shdng*speed_fps, 0);
474 // find relative wind
475 void FGAICarrier::UpdateWind( double dt) {
479 //calculate the reciprocal hdg
486 //cout <<" heading: " << hdg << "recip: " << recip << endl;
488 //get the surface wind speed and direction
489 wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
490 wind_speed_kts = _surface_wind_speed_node->getDoubleValue();
492 //calculate the surface wind speed north and east in kts
493 double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
494 double wind_speed_from_east_kts = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
496 //calculate the carrier speed north and east in kts
497 double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
498 double speed_east_kts = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
500 //calculate the relative wind speed north and east in kts
501 double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
502 double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
504 //combine relative speeds north and east to get relative windspeed in kts
505 rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts)
506 + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
508 //calculate the relative wind direction
509 rel_wind_from_deg = atan(rel_wind_speed_from_east_kts/rel_wind_speed_from_north_kts)
510 * SG_RADIANS_TO_DEGREES;
512 // rationalise the output
513 if (rel_wind_speed_from_north_kts <= 0) {
514 rel_wind_from_deg = 180 + rel_wind_from_deg;
516 if(rel_wind_speed_from_east_kts <= 0)
517 rel_wind_from_deg = 360 + rel_wind_from_deg;
521 rel_wind = rel_wind_from_deg - hdg;
525 //switch the wave-off lights
527 wave_off_lights = false;
529 wave_off_lights = true;
531 // cout << "rel wind: " << rel_wind << endl;
536 void FGAICarrier::TurnToLaunch(){
538 //calculate tgt speed
539 double tgt_speed = 25 - wind_speed_kts;
544 FGAIShip::TurnTo(wind_from_deg);
545 FGAIShip::AccelTo(tgt_speed);
550 void FGAICarrier::TurnToBase(){
553 FGAIShip::TurnTo(base_course);
554 FGAIShip::AccelTo(base_speed);
559 void FGAICarrier::ReturnToBox(){
560 double course, distance, az2;
562 //calculate the bearing and range of the initial position from the carrier
563 geo_inverse_wgs_84(pos, mOpBoxPos, &course, &az2, &distance);
565 distance *= SG_METER_TO_NM;
567 //cout << "return course: " << course << " distance: " << distance << endl;
569 FGAIShip::TurnTo(course);
570 FGAIShip::AccelTo(base_speed);
577 } // end turn to base
580 bool FGAICarrier::OutsideBox() { //returns true if the carrier is outside operating box
582 if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
583 SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: No Operating Box defined" );
587 if (mOpBoxPos.getLatitudeDeg() >= 0) { //northern hemisphere
588 if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + max_lat)
591 if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - min_lat)
594 } else { //southern hemisphere
595 if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - max_lat)
598 if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + min_lat)
602 if (mOpBoxPos.getLongitudeDeg() >=0) { //eastern hemisphere
603 if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + max_long)
606 if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - min_long)
609 } else { //western hemisphere
610 if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - max_long)
613 if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + min_long)
617 SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: Inside Operating Box" );
623 bool FGAICarrier::InToWind() {
624 if ( fabs(rel_wind) < 5 )
631 void FGAICarrier::UpdateElevator(double dt, double transition_time) {
635 if ((elevators && pos_norm >= 1 ) || (!elevators && pos_norm <= 0 ))
638 // move the elevators
640 step = dt/transition_time;
644 step = -dt/transition_time;
648 // assume a linear relationship
649 raw_pos_norm += step;
652 pos_norm = (raw_pos_norm * time_constant) + (pos_norm * (1 - time_constant));
654 //sanitise the output
655 if (raw_pos_norm >= 1) {
657 } else if (raw_pos_norm <= 0) {
662 } // end UpdateElevator
664 void FGAICarrier::UpdateJBD(double dt, double jbd_transition_time) {
666 string launchbar_state = _launchbar_state_node->getStringValue();
669 if (launchbar_state == "Engaged"){
675 if (( jbd && jbd_pos_norm >= 1 ) || ( !jbd && jbd_pos_norm <= 0 )){
681 step = dt/jbd_transition_time;
685 step = -dt/jbd_transition_time;
690 // assume a linear relationship
691 raw_jbd_pos_norm += step;
694 jbd_pos_norm = (raw_jbd_pos_norm * jbd_time_constant) + (jbd_pos_norm * (1 - jbd_time_constant));
696 //sanitise the output
697 if (jbd_pos_norm >= 1) {
699 } else if (jbd_pos_norm <= 0) {
708 int FGAICarrierHardware::unique_id = 1;