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);
74 //SG_LOG(SG_GENERAL, SG_ALERT, "AICarrierVisitor::apply() solidObject" );
76 node.setUserData(mUserData.get());
80 mFoundHot = oldFoundHot || mFoundHot;
83 node.setNodeMask(node.getNodeMask() | SG_NODEMASK_TERRAIN_BIT);
85 node.setNodeMask(node.getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
87 mUserData = oldUserData;
91 std::list<std::string> mWireObjects;
92 std::list<std::string> mCatapultObjects;
93 std::list<std::string> mSolidObjects;
95 FGAICarrier* mCarrier;
96 osg::ref_ptr<osg::Referenced> mUserData;
99 FGAICarrier::FGAICarrier() : FGAIShip(otCarrier) {
102 FGAICarrier::~FGAICarrier() {
105 void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) {
109 FGAIShip::readFromScenario(scFileNode);
111 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
112 setSign(scFileNode->getStringValue("pennant-number"));
113 setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
114 setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
115 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID", "029Y"));
116 setMaxLat(scFileNode->getDoubleValue("max-lat", 0));
117 setMinLat(scFileNode->getDoubleValue("min-lat", 0));
118 setMaxLong(scFileNode->getDoubleValue("max-long", 0));
119 setMinLong(scFileNode->getDoubleValue("min-long", 0));
121 SGPropertyNode* flols = scFileNode->getChild("flols-pos");
123 // Transform to the right coordinate frame, configuration is done in
124 // the usual x-back, y-right, z-up coordinates, computations
125 // in the simulation usual body x-forward, y-right, z-down coordinates
126 flols_off(0) = - flols->getDoubleValue("x-offset-m", 0);
127 flols_off(1) = flols->getDoubleValue("y-offset-m", 0);
128 flols_off(2) = - flols->getDoubleValue("z-offset-m", 0);
130 flols_off = SGVec3d::zeros();
132 std::vector<SGPropertyNode_ptr> props = scFileNode->getChildren("wire");
133 std::vector<SGPropertyNode_ptr>::const_iterator it;
134 for (it = props.begin(); it != props.end(); ++it) {
135 std::string s = (*it)->getStringValue();
137 wire_objects.push_back(s);
140 props = scFileNode->getChildren("catapult");
141 for (it = props.begin(); it != props.end(); ++it) {
142 std::string s = (*it)->getStringValue();
144 catapult_objects.push_back(s);
147 props = scFileNode->getChildren("solid");
148 for (it = props.begin(); it != props.end(); ++it) {
149 std::string s = (*it)->getStringValue();
151 solid_objects.push_back(s);
154 props = scFileNode->getChildren("parking-pos");
155 for (it = props.begin(); it != props.end(); ++it) {
156 string name = (*it)->getStringValue("name", "unnamed");
157 // Transform to the right coordinate frame, configuration is done in
158 // the usual x-back, y-right, z-up coordinates, computations
159 // in the simulation usual body x-forward, y-right, z-down coordinates
160 double offset_x = -(*it)->getDoubleValue("x-offset-m", 0);
161 double offset_y = (*it)->getDoubleValue("y-offset-m", 0);
162 double offset_z = -(*it)->getDoubleValue("z-offset-m", 0);
163 double hd = (*it)->getDoubleValue("heading-offset-deg", 0);
164 ParkPosition pp(name, SGVec3d(offset_x, offset_y, offset_z), hd);
165 ppositions.push_back(pp);
169 void FGAICarrier::setWind_from_east(double fps) {
170 wind_from_east = fps;
173 void FGAICarrier::setWind_from_north(double fps) {
174 wind_from_north = fps;
177 void FGAICarrier::setMaxLat(double deg) {
181 void FGAICarrier::setMinLat(double deg) {
185 void FGAICarrier::setMaxLong(double deg) {
186 max_long = fabs(deg);
189 void FGAICarrier::setMinLong(double deg) {
190 min_long = fabs(deg);
193 void FGAICarrier::setSign(const string& s) {
197 void FGAICarrier::setTACANChannelID(const string& id) {
198 TACAN_channel_id = id;
201 void FGAICarrier::getVelocityWrtEarth(SGVec3d& v, SGVec3d& omega, SGVec3d& pivot) {
203 omega = rot_wrt_earth;
204 pivot = rot_pivot_wrt_earth;
207 void FGAICarrier::update(double dt) {
208 // For computation of rotation speeds we just use finite differences here.
209 // That is perfectly valid since this thing is not driven by accelerations
210 // but by just apply discrete changes at its velocity variables.
211 // Update the velocity information stored in those nodes.
212 // Transform that one to the horizontal local coordinate system.
213 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
214 // The orientation of the carrier wrt the horizontal local frame
215 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
216 // and postrotate the orientation of the AIModel wrt the horizontal
218 SGQuatd ec2body = ec2hl*hl2body;
219 // The cartesian position of the carrier in the wgs84 world
220 SGVec3d cartPos = SGVec3d::fromGeod(pos);
221 // Store for later use by the groundcache
222 rot_pivot_wrt_earth = cartPos;
224 // Compute the velocity in m/s in the earth centered coordinate system axis
225 double v_north = 0.51444444*speed*cos(hdg * SGD_DEGREES_TO_RADIANS);
226 double v_east = 0.51444444*speed*sin(hdg * SGD_DEGREES_TO_RADIANS);
227 vel_wrt_earth = ec2hl.backTransform(SGVec3d(v_north, v_east, 0));
229 // Now update the position and heading. This will compute new hdg and
230 // roll values required for the rotation speed computation.
231 FGAIShip::update(dt);
234 //automatic turn into wind with a target wind of 25 kts otd
235 if(turn_to_launch_hdg){
237 } else if(OutsideBox() || returning) {// check that the carrier is inside the operating box
243 // Only change these values if we are able to compute them safely
245 rot_wrt_earth = SGVec3d::zeros();
247 // Now here is the finite difference ...
249 // Transform that one to the horizontal local coordinate system.
250 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
251 // compute the new orientation
252 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
253 // The rotation difference
254 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
255 SGVec3d dOrAngleAxis;
256 dOr.getAngleAxis(dOrAngleAxis);
257 // divided by the time difference provides a rotation speed vector
260 // now rotate the rotation speed vector back into the
261 // earth centered frames coordinates
262 dOrAngleAxis = ec2body.backTransform(dOrAngleAxis);
263 // dOrAngleAxis = hl2body.backTransform(dOrAngleAxis);
264 // dOrAngleAxis(1) = 0;
265 // dOrAngleAxis = ec2hl.backTransform(dOrAngleAxis);
266 rot_wrt_earth = dOrAngleAxis;
270 UpdateElevator(dt, transition_time);
271 UpdateJBD(dt, jbd_transition_time);
272 // For the flols reuse some computations done above ...
274 // The position of the eyepoint - at least near that ...
275 SGVec3d eyePos(globals->get_current_view()->get_view_pos());
276 // Add the position offset of the AIModel to gain the earth
278 SGVec3d eyeWrtCarrier = eyePos - cartPos;
279 // rotate the eyepoint wrt carrier vector into the carriers frame
280 eyeWrtCarrier = ec2body.transform(eyeWrtCarrier);
281 // the eyepoints vector wrt the flols position
282 SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off;
284 // the distance from the eyepoint to the flols
285 dist = norm(eyeWrtFlols);
287 // now the angle, positive angles are upwards
288 if (fabs(dist) < SGLimits<float>::min()) {
291 double sAngle = -eyeWrtFlols(2)/dist;
292 sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
293 angle = SGMiscd::rad2deg(asin(sAngle));
296 // set the value of source
297 if ( angle <= 4.35 && angle > 4.01 )
299 else if ( angle <= 4.01 && angle > 3.670 )
301 else if ( angle <= 3.670 && angle > 3.330 )
303 else if ( angle <= 3.330 && angle > 2.990 )
305 else if ( angle <= 2.990 && angle > 2.650 )
307 else if ( angle <= 2.650 )
313 bool FGAICarrier::init(bool search_in_AI_path) {
314 if (!FGAIShip::init(search_in_AI_path))
317 _longitude_node = fgGetNode("/position/longitude-deg", true);
318 _latitude_node = fgGetNode("/position/latitude-deg", true);
319 _altitude_node = fgGetNode("/position/altitude-ft", true);
321 _launchbar_state_node = fgGetNode("/gear/launchbar/state", true);
323 _surface_wind_from_deg_node =
324 fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
325 _surface_wind_speed_node =
326 fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
329 turn_to_launch_hdg = false;
338 transition_time = 150;
339 time_constant = 0.005;
340 jbd_pos_norm = raw_jbd_pos_norm = 0;
342 jbd_transition_time = 3;
343 jbd_time_constant = 0.1;
347 void FGAICarrier::initModel(osg::Node *node)
349 SG_LOG(SG_GENERAL, SG_ALERT, "AICarrier::initModel()" );
350 FGAIShip::initModel(node);
351 // process the 3d model here
352 // mark some objects solid, mark the wires ...
354 // The model should be used for altitude computations.
355 // To avoid that every detail in a carrier 3D model will end into
356 // the aircraft local cache, only set the HOT traversal bit on
359 // Clear the HOT traversal flag
360 // Selectively set that flag again for wires/cats/solid objects.
361 // Attach a pointer to this carrier class to those objects.
362 SG_LOG(SG_GENERAL, SG_ALERT, "AICarrier::initModel() visit" );
363 FGCarrierVisitor carrierVisitor(this, wire_objects, catapult_objects, solid_objects);
364 model->accept(carrierVisitor);
365 // model->setNodeMask(node->getNodeMask() & SG_NODEMASK_TERRAIN_BIT | model->getNodeMask());
368 void FGAICarrier::bind() {
371 props->untie("velocities/true-airspeed-kt");
373 props->tie("controls/flols/source-lights",
374 SGRawValuePointer<int>(&source));
375 props->tie("controls/flols/distance-m",
376 SGRawValuePointer<double>(&dist));
377 props->tie("controls/flols/angle-degs",
378 SGRawValuePointer<double>(&angle));
379 props->tie("controls/turn-to-launch-hdg",
380 SGRawValuePointer<bool>(&turn_to_launch_hdg));
381 props->tie("controls/in-to-wind",
382 SGRawValuePointer<bool>(&turn_to_launch_hdg));
383 props->tie("controls/base-course-deg",
384 SGRawValuePointer<double>(&base_course));
385 props->tie("controls/base-speed-kts",
386 SGRawValuePointer<double>(&base_speed));
387 props->tie("controls/start-pos-lat-deg",
388 SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLatitudeDeg));
389 props->tie("controls/start-pos-long-deg",
390 SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLongitudeDeg));
391 props->tie("velocities/speed-kts",
392 SGRawValuePointer<double>(&speed));
393 props->tie("environment/surface-wind-speed-true-kts",
394 SGRawValuePointer<double>(&wind_speed_kts));
395 props->tie("environment/surface-wind-from-true-degs",
396 SGRawValuePointer<double>(&wind_from_deg));
397 props->tie("environment/rel-wind-from-degs",
398 SGRawValuePointer<double>(&rel_wind_from_deg));
399 props->tie("environment/rel-wind-from-carrier-hdg-degs",
400 SGRawValuePointer<double>(&rel_wind));
401 props->tie("environment/rel-wind-speed-kts",
402 SGRawValuePointer<double>(&rel_wind_speed_kts));
403 props->tie("controls/flols/wave-off-lights",
404 SGRawValuePointer<bool>(&wave_off_lights));
405 props->tie("controls/elevators",
406 SGRawValuePointer<bool>(&elevators));
407 props->tie("surface-positions/elevators-pos-norm",
408 SGRawValuePointer<double>(&pos_norm));
409 props->tie("controls/elevators-trans-time-s",
410 SGRawValuePointer<double>(&transition_time));
411 props->tie("controls/elevators-time-constant",
412 SGRawValuePointer<double>(&time_constant));
413 props->tie("controls/jbd",
414 SGRawValuePointer<bool>(&jbd));
415 props->tie("surface-positions/jbd-pos-norm",
416 SGRawValuePointer<double>(&jbd_pos_norm));
417 props->tie("controls/jbd-trans-time-s",
418 SGRawValuePointer<double>(&jbd_transition_time));
419 props->tie("controls/jbd-time-constant",
420 SGRawValuePointer<double>(&jbd_time_constant));
422 props->setBoolValue("controls/flols/cut-lights", false);
423 props->setBoolValue("controls/flols/wave-off-lights", false);
424 props->setBoolValue("controls/flols/cond-datum-lights", true);
425 props->setBoolValue("controls/crew", false);
426 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
427 props->setStringValue("sign", sign.c_str());
431 void FGAICarrier::unbind() {
434 props->untie("velocities/true-airspeed-kt");
435 props->untie("controls/flols/source-lights");
436 props->untie("controls/flols/distance-m");
437 props->untie("controls/flols/angle-degs");
438 props->untie("controls/turn-to-launch-hdg");
439 props->untie("velocities/speed-kts");
440 props->untie("environment/wind-speed-true-kts");
441 props->untie("environment/wind-from-true-degs");
442 props->untie("environment/rel-wind-from-degs");
443 props->untie("environment/rel-wind-speed-kts");
444 props->untie("controls/flols/wave-off-lights");
445 props->untie("controls/elevators");
446 props->untie("surface-positions/elevators-pos-norm");
447 props->untie("controls/elevators-trans-time-secs");
448 props->untie("controls/elevators-time-constant");
449 props->untie("controls/jbd");
450 props->untie("surface-positions/jbd-pos-norm");
451 props->untie("controls/jbd-trans-time-s");
452 props->untie("controls/jbd-time-constant");
457 bool FGAICarrier::getParkPosition(const string& id, SGGeod& geodPos,
458 double& hdng, SGVec3d& uvw)
461 // FIXME: does not yet cover rotation speeds.
462 list<ParkPosition>::iterator it = ppositions.begin();
463 while (it != ppositions.end()) {
464 // Take either the specified one or the first one ...
465 if ((*it).name == id || id.empty()) {
466 ParkPosition ppos = *it;
467 SGVec3d cartPos = getCartPosAt(ppos.offset);
468 geodPos = SGGeod::fromCart(cartPos);
469 hdng = hdg + ppos.heading_deg;
470 double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
471 double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
472 double speed_fps = speed*1.6878099;
473 uvw = SGVec3d(chdng*speed_fps, shdng*speed_fps, 0);
482 // find relative wind
483 void FGAICarrier::UpdateWind( double dt) {
487 //calculate the reciprocal hdg
494 //cout <<" heading: " << hdg << "recip: " << recip << endl;
496 //get the surface wind speed and direction
497 wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
498 wind_speed_kts = _surface_wind_speed_node->getDoubleValue();
500 //calculate the surface wind speed north and east in kts
501 double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
502 double wind_speed_from_east_kts = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
504 //calculate the carrier speed north and east in kts
505 double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
506 double speed_east_kts = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
508 //calculate the relative wind speed north and east in kts
509 double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
510 double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
512 //combine relative speeds north and east to get relative windspeed in kts
513 rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts)
514 + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
516 //calculate the relative wind direction
517 rel_wind_from_deg = atan(rel_wind_speed_from_east_kts/rel_wind_speed_from_north_kts)
518 * SG_RADIANS_TO_DEGREES;
520 // rationalise the output
521 if (rel_wind_speed_from_north_kts <= 0) {
522 rel_wind_from_deg = 180 + rel_wind_from_deg;
524 if(rel_wind_speed_from_east_kts <= 0)
525 rel_wind_from_deg = 360 + rel_wind_from_deg;
529 rel_wind = rel_wind_from_deg - hdg;
533 //switch the wave-off lights
535 wave_off_lights = false;
537 wave_off_lights = true;
539 // cout << "rel wind: " << rel_wind << endl;
544 void FGAICarrier::TurnToLaunch(){
546 //calculate tgt speed
547 double tgt_speed = 25 - wind_speed_kts;
552 FGAIShip::TurnTo(wind_from_deg);
553 FGAIShip::AccelTo(tgt_speed);
558 void FGAICarrier::TurnToBase(){
561 FGAIShip::TurnTo(base_course);
562 FGAIShip::AccelTo(base_speed);
567 void FGAICarrier::ReturnToBox(){
568 double course, distance, az2;
570 //calculate the bearing and range of the initial position from the carrier
571 geo_inverse_wgs_84(pos, mOpBoxPos, &course, &az2, &distance);
573 distance *= SG_METER_TO_NM;
575 //cout << "return course: " << course << " distance: " << distance << endl;
577 FGAIShip::TurnTo(course);
578 FGAIShip::AccelTo(base_speed);
585 } // end turn to base
588 bool FGAICarrier::OutsideBox() { //returns true if the carrier is outside operating box
590 if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
591 SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: No Operating Box defined" );
595 if (mOpBoxPos.getLatitudeDeg() >= 0) { //northern hemisphere
596 if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + max_lat)
599 if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - min_lat)
602 } else { //southern hemisphere
603 if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - max_lat)
606 if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + min_lat)
610 if (mOpBoxPos.getLongitudeDeg() >=0) { //eastern hemisphere
611 if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + max_long)
614 if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - min_long)
617 } else { //western hemisphere
618 if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - max_long)
621 if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + min_long)
625 SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: Inside Operating Box" );
631 bool FGAICarrier::InToWind() {
632 if ( fabs(rel_wind) < 5 )
639 void FGAICarrier::UpdateElevator(double dt, double transition_time) {
643 if ((elevators && pos_norm >= 1 ) || (!elevators && pos_norm <= 0 ))
646 // move the elevators
648 step = dt/transition_time;
652 step = -dt/transition_time;
656 // assume a linear relationship
657 raw_pos_norm += step;
660 pos_norm = (raw_pos_norm * time_constant) + (pos_norm * (1 - time_constant));
662 //sanitise the output
663 if (raw_pos_norm >= 1) {
665 } else if (raw_pos_norm <= 0) {
670 } // end UpdateElevator
672 void FGAICarrier::UpdateJBD(double dt, double jbd_transition_time) {
674 string launchbar_state = _launchbar_state_node->getStringValue();
677 if (launchbar_state == "Engaged"){
683 if (( jbd && jbd_pos_norm >= 1 ) || ( !jbd && jbd_pos_norm <= 0 )){
689 step = dt/jbd_transition_time;
693 step = -dt/jbd_transition_time;
698 // assume a linear relationship
699 raw_jbd_pos_norm += step;
702 jbd_pos_norm = (raw_jbd_pos_norm * jbd_time_constant) + (jbd_pos_norm * (1 - jbd_time_constant));
704 //sanitise the output
705 if (jbd_pos_norm >= 1) {
707 } else if (jbd_pos_norm <= 0) {
716 int FGAICarrierHardware::unique_id = 1;