]> git.mxchange.org Git - flightgear.git/blobdiff - src/AIModel/AIBase.cxx
NavDisplay: fix update lag when switching range or centre.
[flightgear.git] / src / AIModel / AIBase.cxx
index 8a8e1c8f31eec673924c9ee49a5d19d910f2c8d9..a9d64e341683d619fa4cc78132faf1cb9c0720c3 100644 (file)
@@ -24,6 +24,8 @@
 #  include <config.h>
 #endif
 
+#include <string.h>
+
 #include <simgear/compiler.h>
 
 #include <string>
 #include <simgear/misc/sg_path.hxx>
 #include <simgear/scene/model/modellib.hxx>
 #include <simgear/scene/util/SGNodeMasks.hxx>
+#include <simgear/sound/soundmgr_openal.hxx>
 #include <simgear/debug/logstream.hxx>
 #include <simgear/props/props.hxx>
 
 #include <Main/globals.hxx>
 #include <Scenery/scenery.hxx>
 #include <Scripting/NasalSys.hxx>
+#include <Sound/fg_fx.hxx>
 
 #include "AIBase.hxx"
 #include "AIManager.hxx"
@@ -70,7 +74,9 @@ FGAIBase::FGAIBase(object_type ot, bool enableHot) :
     _impact_speed(0),
     _refID( _newAIModelID() ),
     _otype(ot),
-    _initialized(false)
+    _initialized(false),
+    _modeldata(0),
+    _fx(0)
 
 {
     tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
@@ -129,9 +135,7 @@ FGAIBase::FGAIBase(object_type ot, bool enableHot) :
 
 FGAIBase::~FGAIBase() {
     // Unregister that one at the scenery manager
-    if (globals->get_scenery()) {
-        globals->get_scenery()->get_scene_graph()->removeChild(aip.getSceneGraph());
-    }
+    removeModel();
 
     if (props) {
         SGPropertyNode* parent = props->getParent();
@@ -139,10 +143,46 @@ FGAIBase::~FGAIBase() {
         if (parent)
             model_removed->setStringValue(props->getPath());
     }
-    delete fp;
+
+    if (_fx && _refID != 0 && _refID !=  1) {
+        SGSoundMgr *smgr = globals->get_soundmgr();
+        stringstream name; 
+        name <<  "aifx:";
+        name << _refID;
+        smgr->remove(name.str());
+    }
+
+    if (fp)
+        delete fp;
     fp = 0;
 }
 
+/** Cleanly remove the model
+ * and let the scenery database pager do the clean-up work.
+ */
+void
+FGAIBase::removeModel()
+{
+    if (!_model.valid())
+        return;
+
+    FGScenery* pSceneryManager = globals->get_scenery();
+    if (pSceneryManager)
+    {
+        osg::ref_ptr<osg::Object> temp = _model.get();
+        pSceneryManager->get_scene_graph()->removeChild(aip.getSceneGraph());
+        // withdraw from SGModelPlacement and drop own reference (unref)
+        aip.init( 0 );
+        _model = 0;
+        // pass it on to the pager, to be be deleted in the pager thread
+        pSceneryManager->getPagerSingleton()->queueDeleteRequest(temp);
+    }
+    else
+    {
+        SG_LOG(SG_AI, SG_ALERT, "AIBase: Could not unload model. Missing scenery manager!");
+    }
+}
+
 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
 {
     if (!scFileNode)
@@ -177,6 +217,65 @@ void FGAIBase::update(double dt) {
 
     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
     ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
+
+    if ( _fx )
+    {
+        // update model's audio sample values
+        _fx->set_position_geod( pos );
+
+        SGQuatd orient = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
+        _fx->set_orientation( orient );
+
+        SGVec3d velocity;
+        velocity = SGVec3d( speed_north_deg_sec, speed_east_deg_sec,
+                            pitch*speed );
+        _fx->set_velocity( velocity );
+    }
+    else if ((_modeldata)&&(_modeldata->needInitilization()))
+    {
+        // process deferred nasal initialization,
+        // which must be done in main thread
+        _modeldata->init();
+
+        // sound initialization
+        if (fgGetBool("/sim/sound/aimodels/enabled",false))
+        {
+            string fxpath = _modeldata->get_sound_path();
+            if (fxpath != "")
+            {
+                props->setStringValue("sim/sound/path", fxpath.c_str());
+
+                // initialize the sound configuration
+                SGSoundMgr *smgr = globals->get_soundmgr();
+                stringstream name;
+                name <<  "aifx:";
+                name << _refID;
+                _fx = new FGFX(smgr, name.str(), props);
+                _fx->init();
+            }
+        }
+    }
+}
+
+/** update LOD properties of the model */
+void FGAIBase::updateLOD()
+{
+    double maxRangeDetail = fgGetDouble("/sim/rendering/static-lod/ai-detailed", 10000.0);
+    double maxRangeBare   = fgGetDouble("/sim/rendering/static-lod/ai-bare", 20000.0);
+    if (_model.valid())
+    {
+        if( maxRangeDetail == 0.0 )
+        {
+            // disable LOD
+            _model->setRange(0, 0.0,     FLT_MAX);
+            _model->setRange(1, FLT_MAX, FLT_MAX);
+        }
+        else
+        {
+            _model->setRange(0, 0.0, maxRangeDetail);
+            _model->setRange(1, maxRangeDetail,maxRangeBare);
+        }
+    }
 }
 
 void FGAIBase::Transform() {
@@ -198,8 +297,14 @@ void FGAIBase::Transform() {
 
 }
 
-bool FGAIBase::init(bool search_in_AI_path) {
-    
+bool FGAIBase::init(bool search_in_AI_path)
+{
+    if (_model.valid())
+    {
+        SG_LOG(SG_AI, SG_ALERT, "AIBase: Cannot initialize a model multiple times! " << model_path);
+        return false;
+    }
+
     string f;
     if(search_in_AI_path)
     {
@@ -225,31 +330,34 @@ bool FGAIBase::init(bool search_in_AI_path) {
     else
         _installed = true;
 
-    osg::Node * mdl = SGModelLib::loadPagedModel(f, props, new FGNasalModelData(props));
-    model = mdl;
+    _modeldata = new FGAIModelData(props);
+    osg::Node * mdl = SGModelLib::loadDeferredModel(f, props, _modeldata);
 
-    double aiModelMaxRange = fgGetDouble("/sim/rendering/static-lod/ai", 0.0);
-    if( aiModelMaxRange > 0.0 ) {
-        osg::LOD * lod = new osg::LOD;
-        lod->setName("AI-model range animation node");
+    _model = new osg::LOD;
+    _model->setName("AI-model range animation node");
 
-        lod->addChild( mdl, 0, aiModelMaxRange );
-        lod->setCenterMode(osg::LOD::USE_BOUNDING_SPHERE_CENTER);
-        lod->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
-
-        model = lod;
-    }
+    _model->addChild( mdl, 0, FLT_MAX );
+    _model->setCenterMode(osg::LOD::USE_BOUNDING_SPHERE_CENTER);
+    _model->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
+//    We really need low-resolution versions of AI/MP aircraft.
+//    Or at least dummy "stubs" with some default silhouette.
+//        _model->addChild( SGModelLib::loadPagedModel(fgGetString("/sim/multiplay/default-model", default_model),
+//                                                    props, new FGNasalModelData(props)), FLT_MAX, FLT_MAX);
+    updateLOD();
 
     initModel(mdl);
-    if (model.valid() && _initialized == false) {
-        aip.init( model.get() );
+    if (_model.valid() && _initialized == false) {
+        aip.init( _model.get() );
         aip.setVisible(true);
         invisible = false;
         globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
+
+        // Get the sound-path tag from the configuration file and store it
+        // in the property tree.
         _initialized = true;
 
     } else if (!model_path.empty()) {
-        SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
+        SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
         // not properly installed...
         _installed = false;
     }
@@ -260,11 +368,11 @@ bool FGAIBase::init(bool search_in_AI_path) {
 
 void FGAIBase::initModel(osg::Node *node)
 {
-    if (model.valid()) { 
+    if (_model.valid()) { 
 
         if( _path != ""){
             props->setStringValue("submodels/path", _path.c_str());
-            SG_LOG(SG_INPUT, SG_DEBUG, "AIBase: submodels/path " << _path);
+            SG_LOG(SG_AI, SG_DEBUG, "AIBase: submodels/path " << _path);
         }
 
         if( _parent!= ""){
@@ -273,7 +381,7 @@ void FGAIBase::initModel(osg::Node *node)
 
         fgSetString("/ai/models/model-added", props->getPath().c_str());
     } else if (!model_path.empty()) {
-        SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
+        SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
     }
 
     setDie(false);
@@ -353,7 +461,12 @@ void FGAIBase::bind() {
     props->setDoubleValue("controls/flight/target-alt", altitude_ft);
     props->setDoubleValue("controls/flight/target-pitch", pitch);
 
-   props->setDoubleValue("controls/flight/target-spd", speed);
+    props->setDoubleValue("controls/flight/target-spd", speed);
+
+    props->setBoolValue("sim/sound/avionics/enabled", false);
+    props->setDoubleValue("sim/sound/avionics/volume", 0.0);
+    props->setBoolValue("sim/sound/avionics/external-view", false);
+    props->setBoolValue("sim/current-view/internal", false);
 
 }
 
@@ -389,6 +502,8 @@ void FGAIBase::unbind() {
 
     props->setBoolValue("/sim/controls/radar/", true);
 
+    // drop reference to sound effects now
+    _fx = 0;
 }
 
 double FGAIBase::UpdateRadar(FGAIManager* manager) {
@@ -523,7 +638,7 @@ SGVec3d FGAIBase::getCartPos() const {
 bool FGAIBase::getGroundElevationM(const SGGeod& pos, double& elev,
                                    const SGMaterial** material) const {
     return globals->get_scenery()->get_elevation_m(pos, elev, material,
-                                                   model.get());
+                                                   _model.get());
 }
 
 double FGAIBase::_getCartPosX() const {
@@ -562,7 +677,7 @@ void FGAIBase::_setSubID( int s ) {
 bool FGAIBase::setParentNode() {
 
     if (_parent == ""){
-       SG_LOG(SG_GENERAL, SG_ALERT, "AIBase: " << _name
+       SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name
             << " parent not set ");
        return false;
     }
@@ -597,7 +712,7 @@ bool FGAIBase::setParentNode() {
         const string name = _selected_ac->getStringValue("name");
         return true;
     } else {
-        SG_LOG(SG_GENERAL, SG_ALERT, "AIBase: " << _name
+        SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name
             << " parent not found: dying ");
         setDie(true);
         return false;
@@ -800,3 +915,36 @@ int FGAIBase::_newAIModelID() {
     return id;
 }
 
+
+FGAIModelData::FGAIModelData(SGPropertyNode *root)
+  : _nasal( new FGNasalModelData(root) ),
+    _ready(false),
+    _initialized(false)
+{
+}
+
+FGAIModelData::~FGAIModelData()
+{
+    delete _nasal;
+}
+
+void FGAIModelData::modelLoaded(const string& path, SGPropertyNode *prop, osg::Node *n)
+{
+    // WARNING: All this is called in a separate OSG thread! Only use thread-safe stuff
+    // here that is fine to be run concurrently with stuff in the main loop!
+    if (_ready)
+        return;
+    _fxpath = _prop->getStringValue("sound/path");
+    _prop = prop;
+    _path = path;
+    _ready = true;
+}
+
+// do Nasal initialization (must be called in the main loop)
+void FGAIModelData::init()
+{
+    // call FGNasalSys to create context and run hooks (not-thread safe!)
+    _nasal->modelLoaded(_path, _prop, 0);
+    _prop = 0;
+    _initialized = true;
+}