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