]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
Bertrand Coconnier:
[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 <string>
30
31 #include <osg/ref_ptr>
32 #include <osg/Node>
33 #include <osgDB/FileUtils>
34
35 #include <simgear/math/SGMath.hxx>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/scene/model/modellib.hxx>
38 #include <simgear/scene/util/SGNodeMasks.hxx>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/props/props.hxx>
41
42 #include <Main/globals.hxx>
43 #include <Scenery/scenery.hxx>
44 #include <Scripting/NasalSys.hxx>
45
46 #include "AIBase.hxx"
47 #include "AIManager.hxx"
48
49 const char *default_model = "Models/Geometry/glider.ac";
50 const double FGAIBase::e = 2.71828183;
51 const double FGAIBase::lbs_to_slugs = 0.031080950172;   //conversion factor
52
53 using namespace simgear;
54
55 FGAIBase::FGAIBase(object_type ot) :
56     props( NULL ),
57     model_removed( fgGetNode("/ai/models/model-removed", true) ),
58     manager( NULL ),
59     fp( NULL ),
60
61     _impact_lat(0),
62     _impact_lon(0),
63     _impact_elev(0),
64     _impact_hdg(0),
65     _impact_pitch(0),
66     _impact_roll(0),
67     _impact_speed(0),
68
69     _refID( _newAIModelID() ),
70     _otype(ot),
71     _initialized(false)
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",
109             fgGetString("/sim/multiplay/default-model", default_model)));
110
111     setHeading(scFileNode->getDoubleValue("heading", 0.0));
112     setSpeed(scFileNode->getDoubleValue("speed", 0.0));
113     setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
114     setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
115     setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
116     setBank(scFileNode->getDoubleValue("roll", 0.0));
117
118     SGPropertyNode* submodels = scFileNode->getChild("submodels");
119
120     if (submodels) {
121         setServiceable(submodels->getBoolValue("serviceable", false));
122         setSMPath(submodels->getStringValue("path", ""));
123     }
124
125 }
126
127 void FGAIBase::update(double dt) {
128
129     if (_otype == otStatic)
130         return;
131
132     if (_otype == otBallistic)
133         CalculateMach();
134
135     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
136     ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
137 }
138
139 void FGAIBase::Transform() {
140
141     if (!invisible) {
142         aip.setVisible(true);
143         aip.setPosition(pos);
144
145         if (no_roll)
146             aip.setOrientation(0.0, pitch, hdg);
147         else
148             aip.setOrientation(roll, pitch, hdg);
149
150         aip.update();
151     } else {
152         aip.setVisible(false);
153         aip.update();
154     }
155
156 }
157
158 bool FGAIBase::init(bool search_in_AI_path) {
159     osg::ref_ptr<osgDB::ReaderWriter::Options> opt=
160         new osgDB::ReaderWriter::Options(*osgDB::Registry::instance()->getOptions());
161
162     if(search_in_AI_path)
163     {
164         SGPath ai_path(globals->get_fg_root());
165         ai_path.append("AI");
166         opt->getDatabasePathList().push_front(ai_path.str());
167     }
168
169     string f = osgDB::findDataFile(model_path, opt.get());
170
171     if(f.empty())
172         f = fgGetString("/sim/multiplay/default-model", default_model);
173
174     model = load3DModel(f, props);
175
176     if (model.valid() && _initialized == false) {
177         aip.init( model.get() );
178         aip.setVisible(true);
179         invisible = false;
180         globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
181         _initialized = true;
182
183     } else if (!model_path.empty()) {
184         SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
185     }
186
187     setDie(false);
188     return true;
189 }
190
191 void FGAIBase::initModel(osg::Node *node)
192 {
193     if (model.valid()) {
194
195         fgSetString("/ai/models/model-added", props->getPath());
196
197     } else if (!model_path.empty()) {
198         SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
199     }
200
201     props->setStringValue("submodels/path", _path.c_str());
202     setDie(false);
203 }
204
205
206 osg::Node* FGAIBase::load3DModel(const string &path, SGPropertyNode *prop_root)
207 {
208   model = SGModelLib::loadPagedModel(path, prop_root, new FGNasalModelData(prop_root));
209   initModel(model.get());
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     props->setBoolValue("/sim/controls/radar/", true);
321
322 }
323
324 double FGAIBase::UpdateRadar(FGAIManager* manager) {
325     bool control = fgGetBool("/sim/controls/radar", true);
326
327     if(!control) return 0;
328
329     double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
330     bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
331     radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
332     radar_range_ft2 *= radar_range_ft2;
333
334     double user_latitude  = manager->get_user_latitude();
335     double user_longitude = manager->get_user_longitude();
336     double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
337     double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
338     double range_ft2 = lat_range*lat_range + lon_range*lon_range;
339
340     //
341     // Test whether the target is within radar range.
342     //
343     in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
344
345     if ( in_range || force_on ) {
346         props->setBoolValue("radar/in-range", true);
347
348         // copy values from the AIManager
349         double user_altitude  = manager->get_user_altitude();
350         double user_heading   = manager->get_user_heading();
351         double user_pitch     = manager->get_user_pitch();
352         //double user_yaw       = manager->get_user_yaw();
353         //double user_speed     = manager->get_user_speed();
354
355         // calculate range to target in feet and nautical miles
356         double range_ft = sqrt( range_ft2 );
357         range = range_ft / 6076.11549;
358
359         // calculate bearing to target
360         if (pos.getLatitudeDeg() >= user_latitude) {
361             bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
362             if (pos.getLongitudeDeg() >= user_longitude) {
363                 bearing = 90.0 - bearing;
364             } else {
365                 bearing = 270.0 + bearing;
366             }
367         } else {
368             bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
369             if (pos.getLongitudeDeg() >= user_longitude) {
370                 bearing = 180.0 - bearing;
371             } else {
372                 bearing = 180.0 + bearing;
373             }
374         }
375
376         // This is an alternate way to compute bearing and distance which
377         // agrees with the original scheme within about 0.1 degrees.
378         //
379         // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
380         //                user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
381         // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
382         // double gc_bearing, gc_range;
383         // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
384         // gc_range *= SG_METER_TO_NM;
385         // gc_bearing *= SGD_RADIANS_TO_DEGREES;
386         // printf("orig b = %.3f %.2f  gc b= %.3f, %.2f\n",
387         //        bearing, range, gc_bearing, gc_range);
388
389         // calculate look left/right to target, without yaw correction
390         horiz_offset = bearing - user_heading;
391         if (horiz_offset > 180.0) horiz_offset -= 360.0;
392         if (horiz_offset < -180.0) horiz_offset += 360.0;
393
394         // calculate elevation to target
395         elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
396
397         // calculate look up/down to target
398         vert_offset = elevation - user_pitch;
399
400         /* this calculation needs to be fixed, but it isn't important anyway
401         // calculate range rate
402         double recip_bearing = bearing + 180.0;
403         if (recip_bearing > 360.0) recip_bearing -= 360.0;
404         double my_horiz_offset = recip_bearing - hdg;
405         if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
406         if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
407         rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
408         +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
409         */
410
411         // now correct look left/right for yaw
412         // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
413
414         // calculate values for radar display
415         y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
416         x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
417         rotation = hdg - user_heading;
418         if (rotation < 0.0) rotation += 360.0;
419         ht_diff = altitude_ft - user_altitude;
420
421     }
422
423     return range_ft2;
424 }
425
426 /*
427 * Getters and Setters
428 */
429
430 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
431     // Transform that one to the horizontal local coordinate system.
432     SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
433
434     // and postrotate the orientation of the AIModel wrt the horizontal
435     // local frame
436     hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
437
438     // The offset converted to the usual body fixed coordinate system
439     // rotated to the earth fiexed coordinates axis
440     SGVec3d off = hlTrans.backTransform(_off);
441
442     // Add the position offset of the AIModel to gain the earth centered position
443     SGVec3d cartPos = SGVec3d::fromGeod(pos);
444
445     return cartPos + off;
446 }
447
448 SGVec3d FGAIBase::getCartPos() const {
449     SGVec3d cartPos = SGVec3d::fromGeod(pos);
450     return cartPos;
451 }
452
453 bool FGAIBase::getGroundElevationM(const SGGeod& pos, double& elev,
454                                    const SGMaterial** material) const {
455     return globals->get_scenery()->get_elevation_m(pos, elev, material,
456                                                    model.get());
457 }
458
459 double FGAIBase::_getCartPosX() const {
460     SGVec3d cartPos = getCartPos();
461     return cartPos.x();
462 }
463
464 double FGAIBase::_getCartPosY() const {
465     SGVec3d cartPos = getCartPos();
466     return cartPos.y();
467 }
468
469 double FGAIBase::_getCartPosZ() const {
470     SGVec3d cartPos = getCartPos();
471     return cartPos.z();
472 }
473
474 void FGAIBase::_setLongitude( double longitude ) {
475     pos.setLongitudeDeg(longitude);
476 }
477
478 void FGAIBase::_setLatitude ( double latitude )  {
479     pos.setLatitudeDeg(latitude);
480 }
481
482 void FGAIBase::_setUserPos(){
483     userpos.setLatitudeDeg(manager->get_user_latitude());
484     userpos.setLongitudeDeg(manager->get_user_longitude());
485     userpos.setElevationM(manager->get_user_altitude() * SG_FEET_TO_METER);
486 }
487
488 void FGAIBase::_setSubID( int s ) {
489     _subID = s;
490 }
491
492 double FGAIBase::_getLongitude() const {
493     return pos.getLongitudeDeg();
494 }
495
496 double FGAIBase::_getLatitude() const {
497     return pos.getLatitudeDeg();
498 }
499
500 double FGAIBase::_getElevationFt () const {
501     return pos.getElevationFt();
502 }
503
504 double FGAIBase::_getRdot() const {
505     return rdot;
506 }
507
508 double FGAIBase::_getVS_fps() const {
509     return vs*60.0;
510 }
511
512 double FGAIBase::_get_speed_east_fps() const {
513     return speed_east_deg_sec * ft_per_deg_lon;
514 }
515
516 double FGAIBase::_get_speed_north_fps() const {
517     return speed_north_deg_sec * ft_per_deg_lat;
518 }
519
520 void FGAIBase::_setVS_fps( double _vs ) {
521     vs = _vs/60.0;
522 }
523
524 double FGAIBase::_getAltitude() const {
525     return altitude_ft;
526 }
527
528 bool FGAIBase::_getServiceable() const {
529     return serviceable;
530 }
531
532 SGPropertyNode* FGAIBase::_getProps() const {
533     return props;
534 }
535
536 void FGAIBase::_setAltitude( double _alt ) {
537     setAltitude( _alt );
538 }
539
540 bool FGAIBase::_isNight() {
541     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
542 }
543
544 bool FGAIBase::_getCollisionData() {
545     return _collision_reported;
546 }
547
548 bool FGAIBase::_getImpactData() {
549     return _impact_reported;
550 }
551
552 double FGAIBase::_getImpactLat() const {
553     return _impact_lat;
554 }
555
556 double FGAIBase::_getImpactLon() const {
557     return _impact_lon;
558 }
559
560 double FGAIBase::_getImpactElevFt() const {
561     return _impact_elev * SG_METER_TO_FEET;
562 }
563
564 double FGAIBase::_getImpactPitch() const {
565     return _impact_pitch;
566 }
567
568 double FGAIBase::_getImpactRoll() const {
569     return _impact_roll;
570 }
571
572 double FGAIBase::_getImpactHdg() const {
573     return _impact_hdg;
574 }
575
576 double FGAIBase::_getImpactSpeed() const {
577     return _impact_speed;
578 }
579
580 int FGAIBase::getID() const {
581     return  _refID;
582 }
583
584 int FGAIBase::_getSubID() const {
585     return  _subID;
586 }
587
588 double FGAIBase::_getSpeed() const {
589     return speed;
590 }
591
592 double FGAIBase::_getRoll() const {
593     return roll;
594 }
595
596 double FGAIBase::_getPitch() const {
597     return pitch;
598 }
599
600 double FGAIBase::_getHeading() const {
601     return hdg;
602 }
603
604 double  FGAIBase::_getXOffset() const {
605     return _x_offset;
606 }
607
608 double  FGAIBase::_getYOffset() const {
609     return _y_offset;
610 }
611
612 double  FGAIBase::_getZOffset() const {
613     return _z_offset;
614 }
615
616 const char* FGAIBase::_getPath() const {
617     return model_path.c_str();
618 }
619
620 const char* FGAIBase::_getSMPath() const {
621     return _path.c_str();
622 }
623
624 const char* FGAIBase::_getName() const {
625     return _name.c_str();
626 }
627
628 const char* FGAIBase::_getCallsign() const {
629     return _callsign.c_str();
630 }
631
632 const char* FGAIBase::_getSubmodel() const {
633     return _submodel.c_str();
634 }
635
636 void FGAIBase::CalculateMach() {
637     // Calculate rho at altitude, using standard atmosphere
638     // For the temperature T and the pressure p,
639     double altitude = altitude_ft;
640
641     if (altitude < 36152) {             // curve fits for the troposphere
642         T = 59 - 0.00356 * altitude;
643         p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
644     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
645         T = -70;
646         p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
647     } else {                                    //  upper stratosphere
648         T = -205.05 + (0.00164 * altitude);
649         p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
650     }
651
652     rho = p / (1718 * (T + 459.7));
653
654     // calculate the speed of sound at altitude
655     // a = sqrt ( g * R * (T + 459.7))
656     // where:
657     // a = speed of sound [ft/s]
658     // g = specific heat ratio, which is usually equal to 1.4
659     // R = specific gas constant, which equals 1716 ft-lb/slug/R
660     a = sqrt ( 1.4 * 1716 * (T + 459.7));
661
662     // calculate Mach number
663     Mach = speed/a;
664
665     // cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
666 }
667
668 int FGAIBase::_newAIModelID() {
669     static int id = 0;
670
671     if (!++id)
672         id++;   // id = 0 is not allowed.
673
674     return id;
675 }
676