]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
Merge branch 'next' into attenuation
[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 <string.h>
28
29 #include <simgear/compiler.h>
30
31 #include <string>
32
33 #include <osg/ref_ptr>
34 #include <osg/Node>
35 #include <osgDB/FileUtils>
36
37 #include <simgear/math/SGMath.hxx>
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/scene/model/modellib.hxx>
40 #include <simgear/scene/util/SGNodeMasks.hxx>
41 #include <simgear/sound/soundmgr_openal.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 #include <Sound/fg_fx.hxx>
49
50 #include "AIBase.hxx"
51 #include "AIManager.hxx"
52
53 const char *default_model = "Models/Geometry/glider.ac";
54 const double FGAIBase::e = 2.71828183;
55 const double FGAIBase::lbs_to_slugs = 0.031080950172;   //conversion factor
56
57 using namespace simgear;
58
59 FGAIBase::FGAIBase(object_type ot, bool enableHot) :
60     _max_speed(300),
61     _name(""),
62     _parent(""),
63     props( NULL ),
64     model_removed( fgGetNode("/ai/models/model-removed", true) ),
65     manager( NULL ),
66     _installed(false),
67     fp( NULL ),
68     _impact_lat(0),
69     _impact_lon(0),
70     _impact_elev(0),
71     _impact_hdg(0),
72     _impact_pitch(0),
73     _impact_roll(0),
74     _impact_speed(0),
75     _refID( _newAIModelID() ),
76     _otype(ot),
77     _initialized(false),
78     _aimodel(0),
79     _fxpath(""),
80     _fx(0)
81
82 {
83     tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
84     tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs = pitch = 0.0;
85     bearing = elevation = range = rdot = 0.0;
86     x_shift = y_shift = rotation = 0.0;
87     in_range = false;
88     invisible = false;
89     no_roll = true;
90     life = 900;
91     delete_me = false;
92     _impact_reported = false;
93     _collision_reported = false;
94     _expiry_reported = false;
95
96     _subID = 0;
97
98     _x_offset = 0;
99     _y_offset = 0;
100     _z_offset = 0;
101
102     _pitch_offset = 0;
103     _roll_offset = 0;
104     _yaw_offset = 0;
105
106     userpos = SGGeod::fromDeg(0, 0);
107
108     pos = SGGeod::fromDeg(0, 0);
109     speed = 0;
110     altitude_ft = 0;
111     speed_north_deg_sec = 0;
112     speed_east_deg_sec = 0;
113     turn_radius_ft = 0;
114
115     ft_per_deg_lon = 0;
116     ft_per_deg_lat = 0;
117
118     horiz_offset = 0;
119     vert_offset = 0;
120     ht_diff = 0;
121
122     serviceable = false;
123
124     fp = 0;
125
126     rho = 1;
127     T = 280;
128     p = 1e5;
129     a = 340;
130     Mach = 0;
131
132     // explicitly disable HOT for (most) AI models
133     if (!enableHot)
134         aip.getSceneGraph()->setNodeMask(~SG_NODEMASK_TERRAIN_BIT);
135 }
136
137 FGAIBase::~FGAIBase() {
138     // Unregister that one at the scenery manager
139     removeModel();
140
141     if (props) {
142         SGPropertyNode* parent = props->getParent();
143
144         if (parent)
145             model_removed->setStringValue(props->getPath());
146     }
147
148     if (_fx && _refID != 0 && _refID !=  1) {
149         SGSoundMgr *smgr = globals->get_soundmgr();
150         stringstream name; 
151         name <<  "aifx:";
152         name << _refID;
153         smgr->remove(name.str());
154     }
155
156     if (fp)
157         delete fp;
158     fp = 0;
159 }
160
161 /** Cleanly remove the model
162  * and let the scenery database pager do the clean-up work.
163  */
164 void
165 FGAIBase::removeModel()
166 {
167     if (!_model.valid())
168         return;
169
170     FGScenery* pSceneryManager = globals->get_scenery();
171     if (pSceneryManager)
172     {
173         osg::ref_ptr<osg::Object> temp = _model.get();
174         pSceneryManager->get_scene_graph()->removeChild(aip.getSceneGraph());
175         // withdraw from SGModelPlacement and drop own reference (unref)
176         aip.init( 0 );
177         _model = 0;
178         // pass it on to the pager, to be be deleted in the pager thread
179         pSceneryManager->getPagerSingleton()->queueDeleteRequest(temp);
180     }
181     else
182     {
183         SG_LOG(SG_AI, SG_ALERT, "AIBase: Could not unload model. Missing scenery manager!");
184     }
185 }
186
187 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
188 {
189     if (!scFileNode)
190         return;
191
192     setPath(scFileNode->getStringValue("model",
193             fgGetString("/sim/multiplay/default-model", default_model)));
194
195     setHeading(scFileNode->getDoubleValue("heading", 0.0));
196     setSpeed(scFileNode->getDoubleValue("speed", 0.0));
197     setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
198     setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
199     setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
200     setBank(scFileNode->getDoubleValue("roll", 0.0));
201
202     SGPropertyNode* submodels = scFileNode->getChild("submodels");
203
204     if (submodels) {
205         setServiceable(submodels->getBoolValue("serviceable", false));
206         setSMPath(submodels->getStringValue("path", ""));
207     }
208
209 }
210
211 void FGAIBase::update(double dt) {
212
213     if (_otype == otStatic)
214         return;
215
216     if (_otype == otBallistic)
217         CalculateMach();
218
219     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
220     ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
221
222     if ( _fx )
223     {
224         // update model's audio sample values
225         _fx->set_position_geod( pos );
226
227         SGQuatd orient = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
228         _fx->set_orientation( orient );
229
230         SGVec3d velocity;
231         velocity = SGVec3d( speed_north_deg_sec, speed_east_deg_sec,
232                             pitch*speed );
233         _fx->set_velocity( velocity );
234     }
235     else if ((_aimodel)&&(fgGetBool("/sim/sound/aimodels/enabled",false)))
236     {
237         string fxpath = _aimodel->get_sound_path();
238         if (fxpath != "")
239         {
240             _fxpath = fxpath;
241             props->setStringValue("sim/sound/path", _fxpath.c_str());
242
243             // initialize the sound configuration
244             SGSoundMgr *smgr = globals->get_soundmgr();
245             stringstream name;
246             name <<  "aifx:";
247             name << _refID;
248             _fx = new FGFX(smgr, name.str(), props);
249             _fx->init();
250         }
251     }
252 }
253
254 /** update LOD properties of the model */
255 void FGAIBase::updateLOD()
256 {
257     double maxRangeDetail = fgGetDouble("/sim/rendering/static-lod/ai-detailed", 10000.0);
258     double maxRangeBare   = fgGetDouble("/sim/rendering/static-lod/ai-bare", 20000.0);
259     if (_model.valid())
260     {
261         if( maxRangeDetail == 0.0 )
262         {
263             // disable LOD
264             _model->setRange(0, 0.0,     FLT_MAX);
265             _model->setRange(1, FLT_MAX, FLT_MAX);
266         }
267         else
268         {
269             _model->setRange(0, 0.0, maxRangeDetail);
270             _model->setRange(1, maxRangeDetail,maxRangeBare);
271         }
272     }
273 }
274
275 void FGAIBase::Transform() {
276
277     if (!invisible) {
278         aip.setVisible(true);
279         aip.setPosition(pos);
280
281         if (no_roll)
282             aip.setOrientation(0.0, pitch, hdg);
283         else
284             aip.setOrientation(roll, pitch, hdg);
285
286         aip.update();
287     } else {
288         aip.setVisible(false);
289         aip.update();
290     }
291
292 }
293
294 bool FGAIBase::init(bool search_in_AI_path)
295 {
296     if (_model.valid())
297     {
298         SG_LOG(SG_AI, SG_ALERT, "AIBase: Cannot initialize a model multiple times! " << model_path);
299         return false;
300     }
301
302     string f;
303     if(search_in_AI_path)
304     {
305     // setup a modified Options structure, with only the $fg-root/AI defined;
306     // we'll check that first, then give the normal search logic a chance.
307     // this ensures that models in AI/ are preferred to normal models, where
308     // both exist.
309         osg::ref_ptr<osgDB::ReaderWriter::Options> 
310           opt(osg::clone(osgDB::Registry::instance()->getOptions(), osg::CopyOp::SHALLOW_COPY));
311
312         SGPath ai_path(globals->get_fg_root(), "AI");
313         opt->setDatabasePath(ai_path.str());
314         
315         f = osgDB::findDataFile(model_path, opt.get());
316     }
317
318     if (f.empty()) {
319       f = simgear::SGModelLib::findDataFile(model_path);
320     }
321     
322     if(f.empty())
323         f = fgGetString("/sim/multiplay/default-model", default_model);
324     else
325         _installed = true;
326
327     _aimodel = new FGAIModelData(props);
328     osg::Node * mdl = SGModelLib::loadDeferredModel(f, props, _aimodel);
329
330     _model = new osg::LOD;
331     _model->setName("AI-model range animation node");
332
333     _model->addChild( mdl, 0, FLT_MAX );
334     _model->setCenterMode(osg::LOD::USE_BOUNDING_SPHERE_CENTER);
335     _model->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
336 //    We really need low-resolution versions of AI/MP aircraft.
337 //    Or at least dummy "stubs" with some default silhouette.
338 //        _model->addChild( SGModelLib::loadPagedModel(fgGetString("/sim/multiplay/default-model", default_model),
339 //                                                    props, new FGNasalModelData(props)), FLT_MAX, FLT_MAX);
340     updateLOD();
341
342     initModel(mdl);
343     if (_model.valid() && _initialized == false) {
344         aip.init( _model.get() );
345         aip.setVisible(true);
346         invisible = false;
347         globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
348
349         // Get the sound-path tag from the configuration file and store it
350         // in the property tree.
351         _initialized = true;
352
353     } else if (!model_path.empty()) {
354         SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
355         // not properly installed...
356         _installed = false;
357     }
358
359     setDie(false);
360     return true;
361 }
362
363 void FGAIBase::initModel(osg::Node *node)
364 {
365     if (_model.valid()) { 
366
367         if( _path != ""){
368             props->setStringValue("submodels/path", _path.c_str());
369             SG_LOG(SG_AI, SG_DEBUG, "AIBase: submodels/path " << _path);
370         }
371
372         if( _parent!= ""){
373             props->setStringValue("parent-name", _parent.c_str());
374         }
375
376         fgSetString("/ai/models/model-added", props->getPath().c_str());
377     } else if (!model_path.empty()) {
378         SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
379     }
380
381     setDie(false);
382 }
383
384
385 bool FGAIBase::isa( object_type otype ) {
386     return otype == _otype;
387 }
388
389
390 void FGAIBase::bind() {
391     props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
392         &FGAIBase::getID));
393     props->tie("velocities/true-airspeed-kt",  SGRawValuePointer<double>(&speed));
394     props->tie("velocities/vertical-speed-fps",
395         SGRawValueMethods<FGAIBase,double>(*this,
396         &FGAIBase::_getVS_fps,
397         &FGAIBase::_setVS_fps));
398
399     props->tie("position/altitude-ft",
400         SGRawValueMethods<FGAIBase,double>(*this,
401         &FGAIBase::_getAltitude,
402         &FGAIBase::_setAltitude));
403     props->tie("position/latitude-deg",
404         SGRawValueMethods<FGAIBase,double>(*this,
405         &FGAIBase::_getLatitude,
406         &FGAIBase::_setLatitude));
407     props->tie("position/longitude-deg",
408         SGRawValueMethods<FGAIBase,double>(*this,
409         &FGAIBase::_getLongitude,
410         &FGAIBase::_setLongitude));
411
412     props->tie("position/global-x",
413         SGRawValueMethods<FGAIBase,double>(*this,
414         &FGAIBase::_getCartPosX,
415         0));
416     props->tie("position/global-y",
417         SGRawValueMethods<FGAIBase,double>(*this,
418         &FGAIBase::_getCartPosY,
419         0));
420     props->tie("position/global-z",
421         SGRawValueMethods<FGAIBase,double>(*this,
422         &FGAIBase::_getCartPosZ,
423         0));
424     props->tie("callsign",
425         SGRawValueMethods<FGAIBase,const char*>(*this,
426         &FGAIBase::_getCallsign,
427         0));
428
429     props->tie("orientation/pitch-deg",   SGRawValuePointer<double>(&pitch));
430     props->tie("orientation/roll-deg",    SGRawValuePointer<double>(&roll));
431     props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
432
433     props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
434     props->tie("radar/bearing-deg",   SGRawValuePointer<double>(&bearing));
435     props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
436     props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
437     props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
438     props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
439     props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
440     props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
441     props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
442     props->tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
443     props->tie("subID", SGRawValuePointer<int>(&_subID));
444     props->tie("controls/lighting/nav-lights",
445         SGRawValueFunctions<bool>(_isNight));
446     props->setBoolValue("controls/lighting/beacon", true);
447     props->setBoolValue("controls/lighting/strobe", true);
448     props->setBoolValue("controls/glide-path", true);
449
450     props->setStringValue("controls/flight/lateral-mode", "roll");
451     props->setDoubleValue("controls/flight/target-hdg", hdg);
452     props->setDoubleValue("controls/flight/target-roll", roll);
453
454     props->setStringValue("controls/flight/longitude-mode", "alt");
455     props->setDoubleValue("controls/flight/target-alt", altitude_ft);
456     props->setDoubleValue("controls/flight/target-pitch", pitch);
457
458     props->setDoubleValue("controls/flight/target-spd", speed);
459
460     props->setBoolValue("sim/sound/avionics/enabled", false);
461     props->setDoubleValue("sim/sound/avionics/volume", 0.0);
462     props->setBoolValue("sim/sound/avionics/external-view", false);
463     props->setBoolValue("sim/current-view/internal", false);
464
465 }
466
467 void FGAIBase::unbind() {
468     props->untie("id");
469     props->untie("velocities/true-airspeed-kt");
470     props->untie("velocities/vertical-speed-fps");
471
472     props->untie("position/altitude-ft");
473     props->untie("position/latitude-deg");
474     props->untie("position/longitude-deg");
475     props->untie("position/global-x");
476     props->untie("position/global-y");
477     props->untie("position/global-z");
478     props->untie("callsign");
479
480     props->untie("orientation/pitch-deg");
481     props->untie("orientation/roll-deg");
482     props->untie("orientation/true-heading-deg");
483
484     props->untie("radar/in-range");
485     props->untie("radar/bearing-deg");
486     props->untie("radar/elevation-deg");
487     props->untie("radar/range-nm");
488     props->untie("radar/h-offset");
489     props->untie("radar/v-offset");
490     props->untie("radar/x-shift");
491     props->untie("radar/y-shift");
492     props->untie("radar/rotation");
493     props->untie("radar/ht-diff-ft");
494
495     props->untie("controls/lighting/nav-lights");
496
497     props->setBoolValue("/sim/controls/radar/", true);
498
499     // drop reference to sound effects now
500     _fx = 0;
501 }
502
503 double FGAIBase::UpdateRadar(FGAIManager* manager) {
504     bool control = fgGetBool("/sim/controls/radar", true);
505
506     if(!control) return 0;
507
508     double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
509     bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
510     radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
511     radar_range_ft2 *= radar_range_ft2;
512
513     double user_latitude  = manager->get_user_latitude();
514     double user_longitude = manager->get_user_longitude();
515     double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
516     double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
517     double range_ft2 = lat_range*lat_range + lon_range*lon_range;
518
519     //
520     // Test whether the target is within radar range.
521     //
522     in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
523
524     if ( in_range || force_on ) {
525         props->setBoolValue("radar/in-range", true);
526
527         // copy values from the AIManager
528         double user_altitude  = manager->get_user_altitude();
529         double user_heading   = manager->get_user_heading();
530         double user_pitch     = manager->get_user_pitch();
531         //double user_yaw       = manager->get_user_yaw();
532         //double user_speed     = manager->get_user_speed();
533
534         // calculate range to target in feet and nautical miles
535         double range_ft = sqrt( range_ft2 );
536         range = range_ft / 6076.11549;
537
538         // calculate bearing to target
539         if (pos.getLatitudeDeg() >= user_latitude) {
540             bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
541             if (pos.getLongitudeDeg() >= user_longitude) {
542                 bearing = 90.0 - bearing;
543             } else {
544                 bearing = 270.0 + bearing;
545             }
546         } else {
547             bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
548             if (pos.getLongitudeDeg() >= user_longitude) {
549                 bearing = 180.0 - bearing;
550             } else {
551                 bearing = 180.0 + bearing;
552             }
553         }
554
555         // This is an alternate way to compute bearing and distance which
556         // agrees with the original scheme within about 0.1 degrees.
557         //
558         // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
559         //                user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
560         // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
561         // double gc_bearing, gc_range;
562         // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
563         // gc_range *= SG_METER_TO_NM;
564         // gc_bearing *= SGD_RADIANS_TO_DEGREES;
565         // printf("orig b = %.3f %.2f  gc b= %.3f, %.2f\n",
566         //        bearing, range, gc_bearing, gc_range);
567
568         // calculate look left/right to target, without yaw correction
569         horiz_offset = bearing - user_heading;
570         if (horiz_offset > 180.0) horiz_offset -= 360.0;
571         if (horiz_offset < -180.0) horiz_offset += 360.0;
572
573         // calculate elevation to target
574         elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
575
576         // calculate look up/down to target
577         vert_offset = elevation - user_pitch;
578
579         /* this calculation needs to be fixed, but it isn't important anyway
580         // calculate range rate
581         double recip_bearing = bearing + 180.0;
582         if (recip_bearing > 360.0) recip_bearing -= 360.0;
583         double my_horiz_offset = recip_bearing - hdg;
584         if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
585         if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
586         rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
587         +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
588         */
589
590         // now correct look left/right for yaw
591         // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
592
593         // calculate values for radar display
594         y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
595         x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
596         rotation = hdg - user_heading;
597         if (rotation < 0.0) rotation += 360.0;
598         ht_diff = altitude_ft - user_altitude;
599
600     }
601
602     return range_ft2;
603 }
604
605 /*
606 * Getters and Setters
607 */
608
609 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
610     // Transform that one to the horizontal local coordinate system.
611     SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
612
613     // and postrotate the orientation of the AIModel wrt the horizontal
614     // local frame
615     hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
616
617     // The offset converted to the usual body fixed coordinate system
618     // rotated to the earth fixed coordinates axis
619     SGVec3d off = hlTrans.backTransform(_off);
620
621     // Add the position offset of the AIModel to gain the earth centered position
622     SGVec3d cartPos = SGVec3d::fromGeod(pos);
623
624     return cartPos + off;
625 }
626
627 SGVec3d FGAIBase::getCartPos() const {
628     SGVec3d cartPos = SGVec3d::fromGeod(pos);
629     return cartPos;
630 }
631
632 bool FGAIBase::getGroundElevationM(const SGGeod& pos, double& elev,
633                                    const SGMaterial** material) const {
634     return globals->get_scenery()->get_elevation_m(pos, elev, material,
635                                                    _model.get());
636 }
637
638 double FGAIBase::_getCartPosX() const {
639     SGVec3d cartPos = getCartPos();
640     return cartPos.x();
641 }
642
643 double FGAIBase::_getCartPosY() const {
644     SGVec3d cartPos = getCartPos();
645     return cartPos.y();
646 }
647
648 double FGAIBase::_getCartPosZ() const {
649     SGVec3d cartPos = getCartPos();
650     return cartPos.z();
651 }
652
653 void FGAIBase::_setLongitude( double longitude ) {
654     pos.setLongitudeDeg(longitude);
655 }
656
657 void FGAIBase::_setLatitude ( double latitude )  {
658     pos.setLatitudeDeg(latitude);
659 }
660
661 void FGAIBase::_setUserPos(){
662     userpos.setLatitudeDeg(manager->get_user_latitude());
663     userpos.setLongitudeDeg(manager->get_user_longitude());
664     userpos.setElevationM(manager->get_user_altitude() * SG_FEET_TO_METER);
665 }
666
667 void FGAIBase::_setSubID( int s ) {
668     _subID = s;
669 }
670
671 bool FGAIBase::setParentNode() {
672
673     if (_parent == ""){
674        SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name
675             << " parent not set ");
676        return false;
677     }
678
679     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
680
681     for (int i = ai->nChildren() - 1; i >= -1; i--) {
682         SGPropertyNode_ptr model;
683
684         if (i < 0) { // last iteration: selected model
685             model = _selected_ac;
686         } else {
687             model = ai->getChild(i);
688             string path = ai->getPath();
689             const string name = model->getStringValue("name");
690
691             if (!model->nChildren()){
692                 continue;
693             }
694             if (name == _parent) {
695                 _selected_ac = model;  // save selected model for last iteration
696                 break;
697             }
698
699         }
700         if (!model)
701             continue;
702
703     }// end for loop
704
705     if (_selected_ac != 0){
706         const string name = _selected_ac->getStringValue("name");
707         return true;
708     } else {
709         SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name
710             << " parent not found: dying ");
711         setDie(true);
712         return false;
713     }
714
715 }
716
717 double FGAIBase::_getLongitude() const {
718     return pos.getLongitudeDeg();
719 }
720
721 double FGAIBase::_getLatitude() const {
722     return pos.getLatitudeDeg();
723 }
724
725 double FGAIBase::_getElevationFt() const {
726     return pos.getElevationFt();
727 }
728
729 double FGAIBase::_getRdot() const {
730     return rdot;
731 }
732
733 double FGAIBase::_getVS_fps() const {
734     return vs/60.0;
735 }
736
737 double FGAIBase::_get_speed_east_fps() const {
738     return speed_east_deg_sec * ft_per_deg_lon;
739 }
740
741 double FGAIBase::_get_speed_north_fps() const {
742     return speed_north_deg_sec * ft_per_deg_lat;
743 }
744
745 void FGAIBase::_setVS_fps( double _vs ) {
746     vs = _vs*60.0;
747 }
748
749 double FGAIBase::_getAltitude() const {
750     return altitude_ft;
751 }
752
753 double FGAIBase::_getAltitudeAGL(SGGeod inpos, double start){
754     getGroundElevationM(SGGeod::fromGeodM(inpos, start),
755         _elevation_m, &_material);
756     return inpos.getElevationFt() - _elevation_m * SG_METER_TO_FEET;
757 }
758
759 bool FGAIBase::_getServiceable() const {
760     return serviceable;
761 }
762
763 SGPropertyNode* FGAIBase::_getProps() const {
764     return props;
765 }
766
767 void FGAIBase::_setAltitude( double _alt ) {
768     setAltitude( _alt );
769 }
770
771 bool FGAIBase::_isNight() {
772     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
773 }
774
775 bool FGAIBase::_getCollisionData() {
776     return _collision_reported;
777 }
778
779 bool FGAIBase::_getExpiryData() {
780     return _expiry_reported;
781 }
782
783 bool FGAIBase::_getImpactData() {
784     return _impact_reported;
785 }
786
787 double FGAIBase::_getImpactLat() const {
788     return _impact_lat;
789 }
790
791 double FGAIBase::_getImpactLon() const {
792     return _impact_lon;
793 }
794
795 double FGAIBase::_getImpactElevFt() const {
796     return _impact_elev * SG_METER_TO_FEET;
797 }
798
799 double FGAIBase::_getImpactPitch() const {
800     return _impact_pitch;
801 }
802
803 double FGAIBase::_getImpactRoll() const {
804     return _impact_roll;
805 }
806
807 double FGAIBase::_getImpactHdg() const {
808     return _impact_hdg;
809 }
810
811 double FGAIBase::_getImpactSpeed() const {
812     return _impact_speed;
813 }
814
815 int FGAIBase::getID() const {
816     return  _refID;
817 }
818
819 int FGAIBase::_getSubID() const {
820     return  _subID;
821 }
822
823 double FGAIBase::_getSpeed() const {
824     return speed;
825 }
826
827 double FGAIBase::_getRoll() const {
828     return roll;
829 }
830
831 double FGAIBase::_getPitch() const {
832     return pitch;
833 }
834
835 double FGAIBase::_getHeading() const {
836     return hdg;
837 }
838
839 double  FGAIBase::_getXOffset() const {
840     return _x_offset;
841 }
842
843 double  FGAIBase::_getYOffset() const {
844     return _y_offset;
845 }
846
847 double  FGAIBase::_getZOffset() const {
848     return _z_offset;
849 }
850
851 const char* FGAIBase::_getPath() const {
852     return model_path.c_str();
853 }
854
855 const char* FGAIBase::_getSMPath() const {
856     return _path.c_str();
857 }
858
859 const char* FGAIBase::_getName() const {
860     return _name.c_str();
861 }
862
863 const char* FGAIBase::_getCallsign() const {
864     return _callsign.c_str();
865 }
866
867 const char* FGAIBase::_getSubmodel() const {
868     return _submodel.c_str();
869 }
870
871 void FGAIBase::CalculateMach() {
872     // Calculate rho at altitude, using standard atmosphere
873     // For the temperature T and the pressure p,
874     double altitude = altitude_ft;
875
876     if (altitude < 36152) {             // curve fits for the troposphere
877         T = 59 - 0.00356 * altitude;
878         p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
879     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
880         T = -70;
881         p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
882     } else {                                    //  upper stratosphere
883         T = -205.05 + (0.00164 * altitude);
884         p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
885     }
886
887     rho = p / (1718 * (T + 459.7));
888
889     // calculate the speed of sound at altitude
890     // a = sqrt ( g * R * (T + 459.7))
891     // where:
892     // a = speed of sound [ft/s]
893     // g = specific heat ratio, which is usually equal to 1.4
894     // R = specific gas constant, which equals 1716 ft-lb/slug/R
895     a = sqrt ( 1.4 * 1716 * (T + 459.7));
896
897     // calculate Mach number
898     Mach = speed/a;
899
900     // cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
901 }
902
903 int FGAIBase::_newAIModelID() {
904     static int id = 0;
905
906     if (!++id)
907         id++;   // id = 0 is not allowed.
908
909     return id;
910 }
911
912
913 FGAIModelData::FGAIModelData(SGPropertyNode *root)
914   : _nasal( new FGNasalModelData(root) ),
915     _path("")
916 {
917 }
918
919 FGAIModelData::~FGAIModelData()
920 {
921     delete _nasal;
922 }
923
924 void FGAIModelData::modelLoaded(const string& path, SGPropertyNode *prop, osg::Node *n)
925 {
926     const char* fxpath = prop->getStringValue("sound/path");
927     if (fxpath) {
928         string sound_path = string(fxpath);
929         if (sound_path != "") {
930             _path = "/AI/"+sound_path;
931         }
932     }
933     _nasal->modelLoaded(path, prop, n);
934 }