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