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