]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
4c8a24eaa16e112b41fc167e5913b67413361975
[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    bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
310    double radar_range_nm = fgGetDouble("/instrumentation/radar/range");
311    double radar_range_ft2 = radar_range_nm;
312    radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
313    radar_range_ft2 *= radar_range_ft2;
314
315    double user_latitude  = manager->get_user_latitude();
316    double user_longitude = manager->get_user_longitude();
317    double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
318    double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
319    double range_ft2 = lat_range*lat_range + lon_range*lon_range;
320
321    //
322    // Test whether the target is within radar range.
323    //
324    in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
325
326    if ( in_range || force_on ) {
327      props->setBoolValue("radar/in-range", true);
328
329      // copy values from the AIManager
330      double user_altitude  = manager->get_user_altitude();
331      double user_heading   = manager->get_user_heading();
332      double user_pitch     = manager->get_user_pitch();
333      //double user_yaw       = manager->get_user_yaw();
334      //double user_speed     = manager->get_user_speed();
335
336      // calculate range to target in feet and nautical miles
337      double range_ft = sqrt( range_ft2 );
338      range = range_ft / 6076.11549;
339
340      // calculate bearing to target
341      if (pos.getLatitudeDeg() >= user_latitude) {
342         bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
343         if (pos.getLongitudeDeg() >= user_longitude) {
344            bearing = 90.0 - bearing;
345         } else {
346            bearing = 270.0 + bearing;
347         }
348      } else {
349         bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
350         if (pos.getLongitudeDeg() >= user_longitude) {
351            bearing = 180.0 - bearing;
352         } else {
353            bearing = 180.0 + bearing;
354         }
355      }
356
357      // This is an alternate way to compute bearing and distance which
358      // agrees with the original scheme within about 0.1 degrees.
359      //
360      // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
361      //                user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
362      // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
363      // double gc_bearing, gc_range;
364      // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
365      // gc_range *= SG_METER_TO_NM;
366      // gc_bearing *= SGD_RADIANS_TO_DEGREES;
367      // printf("orig b = %.3f %.2f  gc b= %.3f, %.2f\n",
368      //        bearing, range, gc_bearing, gc_range);
369
370      // calculate look left/right to target, without yaw correction
371      horiz_offset = bearing - user_heading;
372      if (horiz_offset > 180.0) horiz_offset -= 360.0;
373      if (horiz_offset < -180.0) horiz_offset += 360.0;
374
375      // calculate elevation to target
376      elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
377
378      // calculate look up/down to target
379      vert_offset = elevation - user_pitch;
380
381      /* this calculation needs to be fixed, but it isn't important anyway
382      // calculate range rate
383      double recip_bearing = bearing + 180.0;
384      if (recip_bearing > 360.0) recip_bearing -= 360.0;
385      double my_horiz_offset = recip_bearing - hdg;
386      if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
387      if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
388      rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
389              +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
390 */
391
392      // now correct look left/right for yaw
393      // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
394
395      // calculate values for radar display
396      y_shift = (range * cos( horiz_offset * SG_DEGREES_TO_RADIANS)) / radar_range_nm;
397      x_shift = (range * sin( horiz_offset * SG_DEGREES_TO_RADIANS)) / radar_range_nm;
398      rotation = hdg - user_heading;
399      if (rotation < 0.0) rotation += 360.0;
400      ht_diff = altitude_ft - user_altitude;
401
402    }
403
404    return range_ft2;
405 }
406
407 /*
408 * Getters and Setters
409 */
410   
411 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
412     // Transform that one to the horizontal local coordinate system.
413   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
414
415   // and postrotate the orientation of the AIModel wrt the horizontal
416   // local frame
417   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
418
419   // The offset converted to the usual body fixed coordinate system
420   // rotated to the earth fiexed coordinates axis
421   SGVec3d off = hlTrans.backTransform(_off);
422
423   // Add the position offset of the AIModel to gain the earth centered position
424   SGVec3d cartPos = SGVec3d::fromGeod(pos);
425
426   return cartPos + off;
427 }
428
429 SGVec3d FGAIBase::getCartPos() const {
430   // Transform that one to the horizontal local coordinate system.
431   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
432
433   // and postrotate the orientation of the AIModel wrt the horizontal
434   // local frame
435   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
436
437   SGVec3d cartPos = SGVec3d::fromGeod(pos);
438
439   return cartPos;
440 }
441
442 double FGAIBase::_getCartPosX() const {
443     SGVec3d cartPos = getCartPos();
444     return cartPos.x();
445 }
446
447 double FGAIBase::_getCartPosY() const {
448     SGVec3d cartPos = getCartPos();
449     return cartPos.y();
450 }
451
452 double FGAIBase::_getCartPosZ() const {
453     SGVec3d cartPos = getCartPos();
454     return cartPos.z();
455 }
456
457 void FGAIBase::_setLongitude( double longitude ) {
458     pos.setLongitudeDeg(longitude);
459 }
460
461 void FGAIBase::_setLatitude ( double latitude )  {
462     pos.setLatitudeDeg(latitude);
463 }
464
465 double FGAIBase::_getLongitude() const {
466     return pos.getLongitudeDeg();
467 }
468
469 double FGAIBase::_getLatitude () const {
470     return pos.getLatitudeDeg();
471 }
472
473 double FGAIBase::_getRdot() const {
474     return rdot;
475 }
476
477 double FGAIBase::_getVS_fps() const {
478     return vs*60.0;
479 }
480
481 double FGAIBase::_get_speed_east_fps() const {
482     return speed_east_deg_sec * ft_per_deg_lon;
483 }
484
485 double FGAIBase::_get_speed_north_fps() const {
486     return speed_north_deg_sec * ft_per_deg_lat;
487 }
488
489 void FGAIBase::_setVS_fps( double _vs ) {
490     vs = _vs/60.0;
491 }
492
493 double FGAIBase::_getAltitude() const {
494     return altitude_ft;
495 }
496
497 bool FGAIBase::_getServiceable() const {
498     return serviceable;
499 }
500
501 SGPropertyNode* FGAIBase::_getProps() const {
502     return props;
503 }
504
505 void FGAIBase::_setAltitude( double _alt ) {
506     setAltitude( _alt );
507 }
508
509 bool FGAIBase::_isNight() {
510     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
511 }
512
513 int FGAIBase::getID() const {
514     return  _refID;
515 }
516
517 double FGAIBase::_getSpeed() const {
518     return speed;
519 }
520
521 double FGAIBase::_getRoll() const {
522     return roll;
523 }
524
525 double FGAIBase::_getPitch() const {
526     return pitch;
527 }
528
529 double FGAIBase::_getHeading() const {
530     return hdg;
531 }
532
533 const char* FGAIBase::_getPath() {
534     return _path.c_str();
535 }
536
537 void FGAIBase::CalculateMach() {
538     // Calculate rho at altitude, using standard atmosphere
539     // For the temperature T and the pressure p,
540     double altitude = altitude_ft;
541
542     if (altitude < 36152) {             // curve fits for the troposphere
543       T = 59 - 0.00356 * altitude;
544       p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
545     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
546       T = -70;
547       p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
548     } else {                                    //  upper stratosphere
549       T = -205.05 + (0.00164 * altitude);
550       p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
551     }
552
553     rho = p / (1718 * (T + 459.7));
554
555     // calculate the speed of sound at altitude
556     // a = sqrt ( g * R * (T + 459.7))
557     // where:
558     // a = speed of sound [ft/s]
559     // g = specific heat ratio, which is usually equal to 1.4
560     // R = specific gas constant, which equals 1716 ft-lb/slug/°R
561     a = sqrt ( 1.4 * 1716 * (T + 459.7));
562
563     // calculate Mach number
564     Mach = speed/a;
565
566 //    cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
567 }
568
569 int FGAIBase::_newAIModelID() {
570     static int id = 0;
571
572    if (!++id)
573       id++;     // id = 0 is not allowed.
574
575    return id;
576 }
577