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