# include <process.h> // _getpid()
# include <Windows.h>
# define isatty _isatty
+#else
+// for open() and options
+# include <sys/types.h>
+# include <sys/stat.h>
+# include <fcntl.h>
#endif
#include <string>
+
#include <boost/algorithm/string/compare.hpp>
#include <boost/algorithm/string/predicate.hpp>
+#include <osgViewer/Viewer>
+
+#include <simgear/canvas/Canvas.hxx>
#include <simgear/constants.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/structure/exception.hxx>
#include <simgear/misc/sgstream.hxx>
#include <simgear/misc/strutils.hxx>
#include <simgear/props/props_io.hxx>
+#include <simgear/scene/tsync/terrasync.hxx>
+#include <simgear/scene/model/modellib.hxx>
#include <simgear/scene/material/matlib.hxx>
+#include <simgear/scene/material/Effect.hxx>
#include <simgear/scene/model/particles.hxx>
#include <simgear/scene/tsync/terrasync.hxx>
#include <Canvas/canvas_mgr.hxx>
#include <Canvas/gui_mgr.hxx>
+#include <Canvas/FGCanvasSystemAdapter.hxx>
#include <GUI/new_gui.hxx>
#include <GUI/MessageBox.hxx>
#include <Input/input.hxx>
#include <Sound/soundmanager.hxx>
#include <Systems/system_mgr.hxx>
#include <Time/light.hxx>
+#include <Time/TimeManager.hxx>
+
#include <Traffic/TrafficMgr.hxx>
#include <MultiPlayer/multiplaymgr.hxx>
#include <FDM/fdm_shell.hxx>
#include <Environment/environment_mgr.hxx>
#include <Viewer/renderer.hxx>
#include <Viewer/viewmgr.hxx>
+#include <Viewer/FGEventHandler.hxx>
#include <Navaids/NavDataCache.hxx>
#include <Instrumentation/HUD/HUD.hxx>
#include <Cockpit/cockpitDisplayManager.hxx>
#include <Network/HTTPClient.hxx>
#include <Network/fgcom.hxx>
+#include <Viewer/CameraGroup.hxx>
+
#include "fg_init.hxx"
#include "fg_io.hxx"
#include "fg_commands.hxx"
#include "main.hxx"
#include "positioninit.hxx"
#include "util.hxx"
+#include "AircraftDirVisitorBase.hxx"
+
+#if defined(SG_MAC)
+#include <GUI/CocoaHelpers.h> // for Mac impl of platformDefaultDataPath()
+#endif
+
+//#define NEW_RESET 1
using std::string;
using std::endl;
using std::cout;
using namespace boost::algorithm;
+extern osg::ref_ptr<osgViewer::Viewer> viewer;
// Return the current base package version
string fgBasePackageVersion() {
return version;
}
-
-template <class T>
-bool fgFindAircraftInDir(const SGPath& dirPath, T* obj, bool (T::*pred)(const SGPath& p))
-{
- if (!dirPath.exists()) {
- SG_LOG(SG_GENERAL, SG_WARN, "fgFindAircraftInDir: no such path:" << dirPath.str());
- return false;
- }
-
- bool recurse = true;
- simgear::Dir dir(dirPath);
- simgear::PathList setFiles(dir.children(simgear::Dir::TYPE_FILE, "-set.xml"));
- simgear::PathList::iterator p;
- for (p = setFiles.begin(); p != setFiles.end(); ++p) {
- // check file name ends with -set.xml
-
- // if we found a -set.xml at this level, don't recurse any deeper
- recurse = false;
-
- bool done = (obj->*pred)(*p);
- if (done) {
- return true;
- }
- } // of -set.xml iteration
-
- if (!recurse) {
- return false;
- }
-
- simgear::PathList subdirs(dir.children(simgear::Dir::TYPE_DIR | simgear::Dir::NO_DOT_OR_DOTDOT));
- for (p = subdirs.begin(); p != subdirs.end(); ++p) {
- if (p->file() == "CVS") {
- continue;
- }
-
- if (fgFindAircraftInDir(*p, obj, pred)) {
- return true;
- }
- } // of subdirs iteration
-
- return false;
-}
-
-template <class T>
-void fgFindAircraft(T* obj, bool (T::*pred)(const SGPath& p))
-{
- const string_list& paths(globals->get_aircraft_paths());
- string_list::const_iterator it = paths.begin();
- for (; it != paths.end(); ++it) {
- bool done = fgFindAircraftInDir(SGPath(*it), obj, pred);
- if (done) {
- return;
- }
- } // of aircraft paths iteration
-
- // if we reach this point, search the default location (always last)
- SGPath rootAircraft(globals->get_fg_root());
- rootAircraft.append("Aircraft");
- fgFindAircraftInDir(rootAircraft, obj, pred);
-}
-
-class FindAndCacheAircraft
+class FindAndCacheAircraft : public AircraftDirVistorBase
{
public:
FindAndCacheAircraft(SGPropertyNode* autoSave)
n->setAttribute(SGPropertyNode::USERARCHIVE, true);
_cache->removeChildren("aircraft");
- fgFindAircraft(this, &FindAndCacheAircraft::checkAircraft);
+ visitAircraftPaths();
}
if (_foundPath.str().empty()) {
return false;
}
- bool checkAircraft(const SGPath& p)
+ virtual VisitResult visit(const SGPath& p)
{
// create cache node
int i = 0;
if ( boost::equals(fileName, _searchAircraft.c_str(), is_iequal()) ) {
_foundPath = p;
- return true;
+ return VISIT_DONE;
}
- return false;
+ return VISIT_CONTINUE;
}
std::string _searchAircraft;
return config;
}
-#elif __APPLE__
-#include <CoreServices/CoreServices.h>
-
-static SGPath platformDefaultDataPath()
-{
- FSRef ref;
- OSErr err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, false, &ref);
- if (err) {
- return SGPath();
- }
+#elif defined(SG_MAC)
- unsigned char path[1024];
- if (FSRefMakePath(&ref, path, 1024) != noErr) {
- return SGPath();
- }
+// platformDefaultDataPath defined in GUI/CocoaHelpers.h
- SGPath appData;
- appData.set((const char*) path);
- appData.append("FlightGear");
- return appData;
-}
#else
static SGPath platformDefaultDataPath()
{
#else
// POSIX, do open+unlink trick to the file is deleted on exit, even if we
// crash or exit(-1)
- size_t len = snprintf(buf, 16, "%d", getpid());
+ ssize_t len = snprintf(buf, 16, "%d", getpid());
int fd = ::open(pidPath.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
if (fd >= 0) {
- ::write(fd, buf, len);
- ::unlink(pidPath.c_str()); // delete file when app quits
- result = true;
+ result = ::write(fd, buf, len) == len;
+ if( ::unlink(pidPath.c_str()) != 0 ) // delete file when app quits
+ result = false;
}
-
- fgSetBool("/sim/fghome-readonly", false);
#endif
+
+ fgSetBool("/sim/fghome-readonly", false);
+
if (!result) {
flightgear::fatalMessageBox("File permissions problem",
"Can't write to user-data storage folder, check file permissions and FG_HOME.",
}
// Read in configuration (file and command line)
-int fgInitConfig ( int argc, char **argv )
+int fgInitConfig ( int argc, char **argv, bool reinit )
{
SGPath dataPath = globals->get_fg_home();
home->setStringValue(dataPath.c_str());
home->setAttribute(SGPropertyNode::WRITE, false);
+ fgSetDefaults();
flightgear::Options* options = flightgear::Options::sharedInstance();
- options->init(argc, argv, dataPath);
- bool loadDefaults = flightgear::Options::sharedInstance()->shouldLoadDefaultConfig();
+ if (!reinit) {
+ options->init(argc, argv, dataPath);
+ }
+
+ bool loadDefaults = options->shouldLoadDefaultConfig();
if (loadDefaults) {
// Read global preferences from $FG_ROOT/preferences.xml
SG_LOG(SG_INPUT, SG_INFO, "Reading global preferences");
} else {
SG_LOG(SG_GENERAL, SG_INFO, "not reading default configuration files");
}// of no-default-config selected
-
- // Scan user config files and command line for a specified aircraft.
- options->initAircraft();
+
+ return flightgear::FG_OPTIONS_OK;
+}
+int fgInitAircraft(bool reinit)
+{
+ // Scan user config files and command line for a specified aircraft.
+ if (!reinit) {
+ flightgear::Options::sharedInstance()->initAircraft();
+ }
+
FindAndCacheAircraft f(globals->get_props());
if (!f.loadAircraft()) {
- return flightgear::FG_OPTIONS_ERROR;
+ return flightgear::FG_OPTIONS_ERROR;
}
-
- // parse options after loading aircraft to ensure any user
- // overrides of defaults are honored.
- return options->processOptions();
+
+ return flightgear::FG_OPTIONS_OK;
}
-
-
/**
* Initialize vor/ndb/ils/fix list management and query systems (as
* well as simple airport db list)
// initialization routines. If you are adding a subsystem to flight
// gear, its initialization call should located in this routine.
// Returns non-zero if a problem encountered.
-void fgCreateSubsystems() {
+void fgCreateSubsystems(bool duringReset) {
SG_LOG( SG_GENERAL, SG_INFO, "Creating Subsystems");
SG_LOG( SG_GENERAL, SG_INFO, "========== ==========");
mpath.append( fgGetString("/sim/rendering/materials-file") );
if ( ! globals->get_matlib()->load(globals->get_fg_root(), mpath.str(),
globals->get_props()) ) {
- throw sg_io_exception("Error loading materials file", mpath);
+ throw sg_io_exception("Error loading materials file", mpath);
}
-
+
globals->add_subsystem( "http", new FGHTTPClient );
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// Initialize the canvas 2d drawing subsystem.
////////////////////////////////////////////////////////////////////
+ simgear::canvas::Canvas::setSystemAdapter(
+ simgear::canvas::SystemAdapterPtr(new canvas::FGCanvasSystemAdapter)
+ );
globals->add_subsystem("Canvas", new CanvasMgr, SGSubsystemMgr::DISPLAY);
globals->add_subsystem("CanvasGUI", new GUIMgr, SGSubsystemMgr::DISPLAY);
// Initialize the lighting subsystem.
////////////////////////////////////////////////////////////////////
- globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
-
// ordering here is important : Nasal (via events), then models, then views
- globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
+ if (!duringReset) {
+ globals->add_subsystem("lighting", new FGLight, SGSubsystemMgr::DISPLAY);
+ globals->add_subsystem("events", globals->get_event_mgr(), SGSubsystemMgr::DISPLAY);
+ }
globals->add_subsystem("aircraft-model", new FGAircraftModel, SGSubsystemMgr::DISPLAY);
globals->add_subsystem("model-manager", new FGModelMgr, SGSubsystemMgr::DISPLAY);
// Reset: this is what the 'reset' command (and hence, GUI) is attached to
void fgReInitSubsystems()
{
+#ifdef NEW_RESET
+ fgResetIdleState();
+ return;
+#endif
+
SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
SG_LOG( SG_GENERAL, SG_INFO, "fgReInitSubsystems()");
fgSetBool("/sim/sceneryloaded",false);
}
-
-///////////////////////////////////////////////////////////////////////////////
-// helper object to implement the --show-aircraft command.
-// resides here so we can share the fgFindAircraftInDir template above,
-// and hence ensure this command lists exectly the same aircraft as the normal
-// loading path.
-class ShowAircraft
+void fgStartNewReset()
{
-public:
- ShowAircraft()
- {
- _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
- }
-
-
- void show(const SGPath& path)
- {
- fgFindAircraftInDir(path, this, &ShowAircraft::processAircraft);
-
- simgear::requestConsole(); // ensure console is shown on Windows
-
- std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
- cout << "Available aircraft:" << endl;
- for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
- cout << _aircraft[i] << endl;
- }
- }
-
-private:
- bool processAircraft(const SGPath& path)
- {
- SGPropertyNode root;
- try {
- readProperties(path.str(), &root);
- } catch (sg_exception& ) {
- return false;
- }
-
- int maturity = 0;
- string descStr(" ");
- descStr += path.file();
- // trim common suffix from file names
- int nPos = descStr.rfind("-set.xml");
- if (nPos == (int)(descStr.size() - 8)) {
- descStr.resize(nPos);
- }
+ SGPropertyNode_ptr preserved(new SGPropertyNode);
- SGPropertyNode *node = root.getNode("sim");
- if (node) {
- SGPropertyNode* desc = node->getNode("description");
- // if a status tag is found, read it in
- if (node->hasValue("status")) {
- maturity = getNumMaturity(node->getStringValue("status"));
- }
-
- if (desc) {
- if (descStr.size() <= 27+3) {
- descStr.append(29+3-descStr.size(), ' ');
- } else {
- descStr += '\n';
- descStr.append( 32, ' ');
+ if (!copyPropertiesWithAttribute(globals->get_props(), preserved, SGPropertyNode::PRESERVE))
+ SG_LOG(SG_GENERAL, SG_ALERT, "Error saving preserved state");
+
+ fgSetBool("/sim/signals/reinit", true);
+ fgSetBool("/sim/freeze/master", true);
+
+ SGSubsystemMgr* subsystemManger = globals->get_subsystem_mgr();
+ subsystemManger->shutdown();
+ subsystemManger->unbind();
+
+ // remove most subsystems, with a few exceptions.
+ for (int g=0; g<SGSubsystemMgr::MAX_GROUPS; ++g) {
+ SGSubsystemGroup* grp = subsystemManger->get_group(static_cast<SGSubsystemMgr::GroupType>(g));
+ const string_list& names(grp->member_names());
+ string_list::const_iterator it;
+ for (it = names.begin(); it != names.end(); ++it) {
+ if ((*it == "time") || (*it == "terrasync") || (*it == "events")
+ || (*it == "lighting"))
+ {
+ continue;
+ }
+
+ try {
+ subsystemManger->remove(it->c_str());
+ } catch (std::exception& e) {
+ SG_LOG(SG_GENERAL, SG_INFO, "caught std::exception shutting down:" << *it);
+ } catch (...) {
+ SG_LOG(SG_GENERAL, SG_INFO, "caught generic exception shutting down:" << *it);
+ }
+
+ // don't delete here, dropping the ref should be sufficient
}
- descStr += desc->getStringValue();
- }
- } // of have 'sim' node
+ } // of top-level groups iteration
- if (maturity < _minStatus) {
- return false;
- }
-
- _aircraft.push_back(descStr);
- return false;
- }
-
-
- int getNumMaturity(const char * str)
- {
- // changes should also be reflected in $FG_ROOT/data/options.xml &
- // $FG_ROOT/data/Translations/string-default.xml
- const char* levels[] = {"alpha","beta","early-production","production"};
-
- if (!strcmp(str, "all")) {
- return 0;
+ // order is important here since tile-manager shutdown needs to
+ // access the scenery object
+ globals->set_tile_mgr(NULL);
+ globals->set_scenery(NULL);
+ flightgear::CameraGroup::setDefault(NULL);
+
+ FGRenderer* render = globals->get_renderer();
+ // don't cancel the pager until after shutdown, since AIModels (and
+ // potentially others) can queue delete requests on the pager.
+ render->getViewer()->getDatabasePager()->cancel();
+ render->getViewer()->getDatabasePager()->clear();
+
+ osgDB::Registry::instance()->clearObjectCache();
+
+ // preserve the event handler; re-creating it would entail fixing the
+ // idle handler
+ osg::ref_ptr<flightgear::FGEventHandler> eventHandler = render->getEventHandler();
+
+ globals->set_renderer(NULL);
+ globals->set_matlib(NULL);
+ globals->set_chatter_queue(NULL);
+
+ simgear::clearEffectCache();
+ simgear::SGModelLib::resetPropertyRoot();
+
+ simgear::GlobalParticleCallback::setSwitch(NULL);
+
+ globals->resetPropertyRoot();
+ fgInitConfig(0, NULL, true);
+ fgInitGeneral(); // all of this?
+
+ if ( copyProperties(preserved, globals->get_props()) ) {
+ SG_LOG( SG_GENERAL, SG_INFO, "Preserved state restored successfully" );
+ } else {
+ SG_LOG( SG_GENERAL, SG_INFO,
+ "Some errors restoring preserved state (read-only props?)" );
}
- for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
- if (strcmp(str,levels[i])==0)
- return i;
+ fgGetNode("/sim")->removeChild("aircraft-dir");
+ fgInitAircraft(true);
+ flightgear::Options::sharedInstance()->processOptions();
+
+ render = new FGRenderer;
+ render->setEventHandler(eventHandler);
+ globals->set_renderer(render);
+ render->init();
+ render->setViewer(viewer.get());
+ viewer->getDatabasePager()->setUpThreads(1, 1);
+ render->splashinit();
+
+ flightgear::CameraGroup::buildDefaultGroup(viewer.get());
- return 0;
- }
+ fgOSResetProperties();
- // recommended in Meyers, Effective STL when internationalization and embedded
- // NULLs aren't an issue. Much faster than the STL or Boost lex versions.
- struct ciLessLibC : public std::binary_function<string, string, bool>
- {
- bool operator()(const std::string &lhs, const std::string &rhs) const
- {
- return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
- }
- };
-
- int _minStatus;
- string_list _aircraft;
-};
+
+// init some things manually
+// which do not follow the regular init pattern
+
+ globals->get_event_mgr()->init();
+ globals->get_event_mgr()->setRealtimeProperty(fgGetNode("/sim/time/delta-realtime-sec", true));
+
+ globals->set_matlib( new SGMaterialLib );
+
+// terra-sync needs the property tree root, pass it back in
+ simgear::SGTerraSync* terra_sync = static_cast<simgear::SGTerraSync*>(subsystemManger->get_subsystem("terrasync"));
+ terra_sync->setRoot(globals->get_props());
-void fgShowAircraft(const SGPath &path)
-{
- ShowAircraft s;
- s.show(path);
-
-#ifdef _MSC_VER
- cout << "Hit a key to continue..." << endl;
- std::cin.get();
-#endif
+ fgSetBool("/sim/signals/reinit", false);
+ fgSetBool("/sim/freeze/master", false);
+ fgSetBool("/sim/sceneryloaded",false);
}
-