]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
Maik: add ROTORELTARGET and ROTORENGINEMAXRELTORQUE input axes
[flightgear.git] / src / AIModel / AIBase.cxx
1 // FGAIBase - abstract base class for AI objects
2 // Written by David Culp, started Nov 2003, based on
3 // David Luff's FGAIEntity class.
4 // - davidculp2@comcast.net
5 //
6 // With additions by Mathias Froehlich & Vivian Meazza 2004 -2007
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <simgear/compiler.h>
28
29 #include STL_STRING
30
31 #include <osg/ref_ptr>
32 #include <osg/Node>
33
34 #include <simgear/math/point3d.hxx>
35 #include <simgear/math/polar3d.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/scene/model/location.hxx>
39 #include <simgear/scene/model/model.hxx>
40 #include <simgear/scene/util/SGNodeMasks.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
43
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <Scripting/NasalSys.hxx>
47
48
49 #include "AIBase.hxx"
50 #include "AIManager.hxx"
51
52
53 const double FGAIBase::e = 2.71828183;
54 const double FGAIBase::lbs_to_slugs = 0.031080950172;   //conversion factor
55
56
57 FGAIBase::FGAIBase(object_type ot) :
58     props( NULL ),
59     model_removed( fgGetNode("/ai/models/model-removed", true) ),
60     manager( NULL ),
61     fp( NULL ),
62     _refID( _newAIModelID() ),
63     _otype(ot)
64 {
65     tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
66     tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs = pitch = 0.0;
67     bearing = elevation = range = rdot = 0.0;
68     x_shift = y_shift = rotation = 0.0;
69     in_range = false;
70     invisible = true;
71     no_roll = true;
72     life = 900;
73     delete_me = false;
74 }
75
76 FGAIBase::~FGAIBase() {
77     // Unregister that one at the scenery manager
78     if (globals->get_scenery()) {
79         globals->get_scenery()->get_scene_graph()->removeChild(aip.getSceneGraph());
80     }
81
82     if (props) {
83         SGPropertyNode* parent = props->getParent();
84
85         if (parent)
86             model_removed->setStringValue(props->getPath());
87     }
88     delete fp;
89     fp = 0;
90 }
91
92 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
93 {
94     if (!scFileNode)
95         return;
96
97     setPath(scFileNode->getStringValue("model", "Models/Geometry/glider.ac"));
98
99     setHeading(scFileNode->getDoubleValue("heading", 0.0));
100     setSpeed(scFileNode->getDoubleValue("speed", 0.0));
101     setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
102     setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
103     setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
104     setBank(scFileNode->getDoubleValue("roll", 0.0));
105
106     SGPropertyNode* submodels = scFileNode->getChild("submodels");
107
108     if (submodels) {
109         setServiceable(submodels->getBoolValue("serviceable", false));
110         setSMPath(submodels->getStringValue("path", ""));
111     }
112
113 }
114
115 void FGAIBase::update(double dt) {
116
117     if (_otype == otStatic)
118         return;
119
120     if (_otype == otBallistic)
121         CalculateMach();
122
123     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
124     ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
125 }
126
127 void FGAIBase::Transform() {
128
129     if (!invisible) {
130       aip.setPosition(pos);
131
132         if (no_roll)
133          aip.setOrientation(0.0, pitch, hdg);
134         else
135          aip.setOrientation(roll, pitch, hdg);
136
137       aip.update();
138     }
139
140 }
141
142 bool FGAIBase::init(bool search_in_AI_path) {
143
144     if (!model_path.empty()) {
145
146      if ( (search_in_AI_path)
147           &&(model_path.substr(model_path.size() - 4, 4) == ".xml")) {
148        SGPath ai_path("AI");
149        ai_path.append(model_path);
150        try {
151          model = load3DModel( globals->get_fg_root(), ai_path.str(), props,
152                         globals->get_sim_time_sec() );
153        } catch (const sg_exception &e) {
154          model = NULL;
155        }
156      } else
157         model = NULL;
158
159      if (!model) {
160        try {
161          model = load3DModel( globals->get_fg_root(), model_path, props,
162                         globals->get_sim_time_sec() );
163        } catch (const sg_exception &e) {
164          model = NULL;
165        }
166      }
167
168    }
169
170    if (model.get()) {
171      aip.init( model.get() );
172      aip.setVisible(true);
173      invisible = false;
174      globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
175
176      fgSetString("/ai/models/model-added", props->getPath());
177    } else {
178
179         if (!model_path.empty())
180        SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
181
182    }
183
184     props->setStringValue("submodels/path", _path.c_str());
185    setDie(false);
186    return true;
187 }
188
189
190 osg::Node* FGAIBase::load3DModel(const string& fg_root,
191                       const string &path,
192                       SGPropertyNode *prop_root,
193                       double sim_time_sec)
194 {
195   model = sgLoad3DModel(fg_root, path, prop_root, sim_time_sec, 0,
196                         new FGNasalModelData(prop_root));
197   model->setNodeMask(model->getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
198   return model.get();
199 }
200
201 bool FGAIBase::isa( object_type otype ) {
202
203   if ( otype == _otype )
204     return true;
205   else
206     return false;
207 }
208
209
210 void FGAIBase::bind() {
211    props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
212                                          &FGAIBase::getID));
213    props->tie("velocities/true-airspeed-kt",  SGRawValuePointer<double>(&speed));
214    props->tie("velocities/vertical-speed-fps",
215                SGRawValueMethods<FGAIBase,double>(*this,
216                                          &FGAIBase::_getVS_fps,
217                                          &FGAIBase::_setVS_fps));
218
219    props->tie("position/altitude-ft",
220                SGRawValueMethods<FGAIBase,double>(*this,
221                                          &FGAIBase::_getAltitude,
222                                          &FGAIBase::_setAltitude));
223    props->tie("position/latitude-deg",
224                SGRawValueMethods<FGAIBase,double>(*this,
225                                          &FGAIBase::_getLatitude,
226                                          &FGAIBase::_setLatitude));
227    props->tie("position/longitude-deg",
228                SGRawValueMethods<FGAIBase,double>(*this,
229                                          &FGAIBase::_getLongitude,
230                                          &FGAIBase::_setLongitude));
231
232    props->tie("position/global-x",
233                SGRawValueMethods<FGAIBase,double>(*this,
234                                          &FGAIBase::_getCartPosX,
235                                          0));
236    props->tie("position/global-y",
237                SGRawValueMethods<FGAIBase,double>(*this,
238                                          &FGAIBase::_getCartPosY,
239                                          0));
240    props->tie("position/global-z",
241                SGRawValueMethods<FGAIBase,double>(*this,
242                                          &FGAIBase::_getCartPosZ,
243                                          0));
244
245    props->tie("orientation/pitch-deg",   SGRawValuePointer<double>(&pitch));
246    props->tie("orientation/roll-deg",    SGRawValuePointer<double>(&roll));
247    props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
248
249    props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
250    props->tie("radar/bearing-deg",   SGRawValuePointer<double>(&bearing));
251    props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
252    props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
253    props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
254    props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
255    props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
256    props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
257    props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
258    props->tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
259
260    props->tie("controls/lighting/nav-lights",
261                SGRawValueFunctions<bool>(_isNight));
262    props->setBoolValue("controls/lighting/beacon", true);
263    props->setBoolValue("controls/lighting/strobe", true);
264    props->setBoolValue("controls/glide-path", true);
265
266    props->setStringValue("controls/flight/lateral-mode", "roll");
267    props->setDoubleValue("controls/flight/target-hdg", hdg);
268    props->setDoubleValue("controls/flight/target-roll", roll);
269
270    props->setStringValue("controls/flight/longitude-mode", "alt");
271    props->setDoubleValue("controls/flight/target-alt", altitude_ft);
272    props->setDoubleValue("controls/flight/target-pitch", pitch);
273
274    props->setDoubleValue("controls/flight/target-spd", speed);
275
276 }
277
278 void FGAIBase::unbind() {
279     props->untie("id");
280     props->untie("velocities/true-airspeed-kt");
281     props->untie("velocities/vertical-speed-fps");
282
283     props->untie("position/altitude-ft");
284     props->untie("position/latitude-deg");
285     props->untie("position/longitude-deg");
286     props->untie("position/global-x");
287     props->untie("position/global-y");
288     props->untie("position/global-z");
289
290     props->untie("orientation/pitch-deg");
291     props->untie("orientation/roll-deg");
292     props->untie("orientation/true-heading-deg");
293
294     props->untie("radar/in-range");
295     props->untie("radar/bearing-deg");
296     props->untie("radar/elevation-deg");
297     props->untie("radar/range-nm");
298     props->untie("radar/h-offset");
299     props->untie("radar/v-offset");
300     props->untie("radar/x-shift");
301     props->untie("radar/y-shift");
302     props->untie("radar/rotation");
303     props->untie("radar/ht-diff-ft");
304
305     props->untie("controls/lighting/nav-lights");
306 }
307
308 double FGAIBase::UpdateRadar(FGAIManager* manager) {
309    double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
310    bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
311    radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
312    radar_range_ft2 *= radar_range_ft2;
313
314    double user_latitude  = manager->get_user_latitude();
315    double user_longitude = manager->get_user_longitude();
316    double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
317    double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
318    double range_ft2 = lat_range*lat_range + lon_range*lon_range;
319
320    //
321    // Test whether the target is within radar range.
322    //
323    in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
324
325    if ( in_range || force_on ) {
326      props->setBoolValue("radar/in-range", true);
327
328      // copy values from the AIManager
329      double user_altitude  = manager->get_user_altitude();
330      double user_heading   = manager->get_user_heading();
331      double user_pitch     = manager->get_user_pitch();
332      //double user_yaw       = manager->get_user_yaw();
333      //double user_speed     = manager->get_user_speed();
334
335      // calculate range to target in feet and nautical miles
336      double range_ft = sqrt( range_ft2 );
337      range = range_ft / 6076.11549;
338
339      // calculate bearing to target
340      if (pos.getLatitudeDeg() >= user_latitude) {
341         bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
342         if (pos.getLongitudeDeg() >= user_longitude) {
343            bearing = 90.0 - bearing;
344         } else {
345            bearing = 270.0 + bearing;
346         }
347      } else {
348         bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
349         if (pos.getLongitudeDeg() >= user_longitude) {
350            bearing = 180.0 - bearing;
351         } else {
352            bearing = 180.0 + bearing;
353         }
354      }
355
356      // This is an alternate way to compute bearing and distance which
357      // agrees with the original scheme within about 0.1 degrees.
358      //
359      // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
360      //                user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
361      // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
362      // double gc_bearing, gc_range;
363      // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
364      // gc_range *= SG_METER_TO_NM;
365      // gc_bearing *= SGD_RADIANS_TO_DEGREES;
366      // printf("orig b = %.3f %.2f  gc b= %.3f, %.2f\n",
367      //        bearing, range, gc_bearing, gc_range);
368
369      // calculate look left/right to target, without yaw correction
370      horiz_offset = bearing - user_heading;
371      if (horiz_offset > 180.0) horiz_offset -= 360.0;
372      if (horiz_offset < -180.0) horiz_offset += 360.0;
373
374      // calculate elevation to target
375      elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
376
377      // calculate look up/down to target
378      vert_offset = elevation - user_pitch;
379
380      /* this calculation needs to be fixed, but it isn't important anyway
381      // calculate range rate
382      double recip_bearing = bearing + 180.0;
383      if (recip_bearing > 360.0) recip_bearing -= 360.0;
384      double my_horiz_offset = recip_bearing - hdg;
385      if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
386      if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
387      rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
388              +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
389 */
390
391      // now correct look left/right for yaw
392      // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
393
394      // calculate values for radar display
395      y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
396      x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
397      rotation = hdg - user_heading;
398      if (rotation < 0.0) rotation += 360.0;
399      ht_diff = altitude_ft - user_altitude;
400
401    }
402
403    return range_ft2;
404 }
405
406 /*
407 * Getters and Setters
408 */
409   
410 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
411     // Transform that one to the horizontal local coordinate system.
412   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
413
414   // and postrotate the orientation of the AIModel wrt the horizontal
415   // local frame
416   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
417
418   // The offset converted to the usual body fixed coordinate system
419   // rotated to the earth fiexed coordinates axis
420   SGVec3d off = hlTrans.backTransform(_off);
421
422   // Add the position offset of the AIModel to gain the earth centered position
423   SGVec3d cartPos = SGVec3d::fromGeod(pos);
424
425   return cartPos + off;
426 }
427
428 SGVec3d FGAIBase::getCartPos() const {
429   // Transform that one to the horizontal local coordinate system.
430   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
431
432   // and postrotate the orientation of the AIModel wrt the horizontal
433   // local frame
434   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
435
436   SGVec3d cartPos = SGVec3d::fromGeod(pos);
437
438   return cartPos;
439 }
440
441 double FGAIBase::_getCartPosX() const {
442     SGVec3d cartPos = getCartPos();
443     return cartPos.x();
444 }
445
446 double FGAIBase::_getCartPosY() const {
447     SGVec3d cartPos = getCartPos();
448     return cartPos.y();
449 }
450
451 double FGAIBase::_getCartPosZ() const {
452     SGVec3d cartPos = getCartPos();
453     return cartPos.z();
454 }
455
456 void FGAIBase::_setLongitude( double longitude ) {
457     pos.setLongitudeDeg(longitude);
458 }
459
460 void FGAIBase::_setLatitude ( double latitude )  {
461     pos.setLatitudeDeg(latitude);
462 }
463
464 double FGAIBase::_getLongitude() const {
465     return pos.getLongitudeDeg();
466 }
467
468 double FGAIBase::_getLatitude () const {
469     return pos.getLatitudeDeg();
470 }
471
472 double FGAIBase::_getRdot() const {
473     return rdot;
474 }
475
476 double FGAIBase::_getVS_fps() const {
477     return vs*60.0;
478 }
479
480 double FGAIBase::_get_speed_east_fps() const {
481     return speed_east_deg_sec * ft_per_deg_lon;
482 }
483
484 double FGAIBase::_get_speed_north_fps() const {
485     return speed_north_deg_sec * ft_per_deg_lat;
486 }
487
488 void FGAIBase::_setVS_fps( double _vs ) {
489     vs = _vs/60.0;
490 }
491
492 double FGAIBase::_getAltitude() const {
493     return altitude_ft;
494 }
495
496 bool FGAIBase::_getServiceable() const {
497     return serviceable;
498 }
499
500 SGPropertyNode* FGAIBase::_getProps() const {
501     return props;
502 }
503
504 void FGAIBase::_setAltitude( double _alt ) {
505     setAltitude( _alt );
506 }
507
508 bool FGAIBase::_isNight() {
509     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
510 }
511
512 int FGAIBase::getID() const {
513     return  _refID;
514 }
515
516 double FGAIBase::_getSpeed() const {
517     return speed;
518 }
519
520 double FGAIBase::_getRoll() const {
521     return roll;
522 }
523
524 double FGAIBase::_getPitch() const {
525     return pitch;
526 }
527
528 double FGAIBase::_getHeading() const {
529     return hdg;
530 }
531
532 const char* FGAIBase::_getPath() {
533     return _path.c_str();
534 }
535
536 void FGAIBase::CalculateMach() {
537     // Calculate rho at altitude, using standard atmosphere
538     // For the temperature T and the pressure p,
539     double altitude = altitude_ft;
540
541     if (altitude < 36152) {             // curve fits for the troposphere
542       T = 59 - 0.00356 * altitude;
543       p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
544     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
545       T = -70;
546       p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
547     } else {                                    //  upper stratosphere
548       T = -205.05 + (0.00164 * altitude);
549       p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
550     }
551
552     rho = p / (1718 * (T + 459.7));
553
554     // calculate the speed of sound at altitude
555     // a = sqrt ( g * R * (T + 459.7))
556     // where:
557     // a = speed of sound [ft/s]
558     // g = specific heat ratio, which is usually equal to 1.4
559     // R = specific gas constant, which equals 1716 ft-lb/slug/°R
560     a = sqrt ( 1.4 * 1716 * (T + 459.7));
561
562     // calculate Mach number
563     Mach = speed/a;
564
565 //    cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
566 }
567
568 int FGAIBase::_newAIModelID() {
569     static int id = 0;
570
571    if (!++id)
572       id++;     // id = 0 is not allowed.
573
574    return id;
575 }
576