1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 #include <simgear/compiler.h>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
37 #include <simgear/canvas/VGInitOperation.hxx>
38 #include <simgear/scene/model/modellib.hxx>
39 #include <simgear/scene/material/matlib.hxx>
40 #include <simgear/props/AtomicChangeListener.hxx>
41 #include <simgear/props/props.hxx>
42 #include <simgear/timing/sg_time.hxx>
43 #include <simgear/io/raw_socket.hxx>
44 #include <simgear/scene/tsync/terrasync.hxx>
45 #include <simgear/math/SGMath.hxx>
46 #include <simgear/math/sg_random.h>
48 #include <Model/panelnode.hxx>
49 #include <Scenery/scenery.hxx>
50 #include <Scenery/tilemgr.hxx>
51 #include <Sound/soundmanager.hxx>
52 #include <Time/TimeManager.hxx>
54 #include <Viewer/splash.hxx>
55 #include <Viewer/renderer.hxx>
56 #include <Viewer/WindowSystemAdapter.hxx>
57 #include <Navaids/NavDataCache.hxx>
59 #include "fg_commands.hxx"
63 #include "fg_init.hxx"
65 #include "fg_props.hxx"
66 #include "positioninit.hxx"
67 #include "subsystemFactory.hxx"
68 #include "options.hxx"
70 using namespace flightgear;
75 // The atexit() function handler should know when the graphical subsystem
77 extern int _bootstrap_OSInit;
79 static SGPropertyNode_ptr frame_signal;
80 static TimeManager* timeMgr;
82 // What should we do when we have nothing else to do? Let's get ready
83 // for the next move and update the display?
84 static void fgMainLoop( void )
86 frame_signal->fireValueChanged();
88 // compute simulated time (allowing for pause, warp, etc) and
90 double sim_dt, real_dt;
91 timeMgr->computeTimeDeltas(sim_dt, real_dt);
93 // update all subsystems
94 globals->get_subsystem_mgr()->update(sim_dt);
96 simgear::AtomicChangeListener::fireChangeListeners();
100 static void registerMainLoop()
102 // stash current frame signal property
103 frame_signal = fgGetNode("/sim/signals/frame", true);
104 timeMgr = (TimeManager*) globals->get_subsystem("time");
105 fgRegisterIdleHandler( fgMainLoop );
108 // This is the top level master main function that is registered as
111 // The first few passes take care of initialization things (a couple
112 // per pass) and once everything has been initialized fgMainLoop from
115 static void fgIdleFunction ( void ) {
116 // Specify our current idle function state. This is used to run all
117 // our initializations out of the idle callback so that we can get a
118 // splash screen up and running right away.
119 static int idle_state = 0;
121 if ( idle_state == 0 ) {
125 fgSplashProgress("loading-aircraft-list");
128 } else if ( idle_state == 2 ) {
130 // start TerraSync up now, so it can be synchronizing shared models
131 // and airports data in parallel with a nav-cache rebuild.
132 SGPath tsyncCache(globals->get_fg_home());
133 tsyncCache.append("terrasync-cache.xml");
135 // wipe the cache file if requested
136 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
137 SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
139 if (tsyncCache.exists()) {
144 fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
146 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
147 terra_sync->setRoot(globals->get_props());
148 globals->add_subsystem("terrasync", terra_sync);
155 // add the terrasync root as a data path so data can be retrieved from it
156 std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
157 globals->append_data_path(terraSyncDir);
160 fgSplashProgress("loading-nav-dat");
162 } else if ( idle_state == 3 ) {
164 bool done = fgInitNav();
167 fgSplashProgress("init-scenery");
169 fgSplashProgress("loading-nav-dat");
172 } else if ( idle_state == 4 ) {
174 // based on the requested presets, calculate the true starting
176 flightgear::initPosition();
177 flightgear::initTowerLocationListener();
179 TimeManager* t = new TimeManager;
180 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
181 t->init(); // need to init now, not during initSubsystems
183 // Do some quick general initializations
184 if( !fgInitGeneral()) {
185 throw sg_exception("General initialization failed");
188 ////////////////////////////////////////////////////////////////////
189 // Initialize the property-based built-in commands
190 ////////////////////////////////////////////////////////////////////
193 flightgear::registerSubsystemCommands(globals->get_commands());
195 ////////////////////////////////////////////////////////////////////
196 // Initialize the material manager
197 ////////////////////////////////////////////////////////////////////
198 globals->set_matlib( new SGMaterialLib );
199 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
200 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
202 ////////////////////////////////////////////////////////////////////
203 // Initialize the TG scenery subsystem.
204 ////////////////////////////////////////////////////////////////////
206 globals->set_scenery( new FGScenery );
207 globals->get_scenery()->init();
208 globals->get_scenery()->bind();
209 globals->set_tile_mgr( new FGTileMgr );
211 fgSplashProgress("loading-aircraft");
213 } else if ( idle_state == 6 ) {
215 fgSplashProgress("creating-subsystems");
217 } else if ( idle_state == 7 ) {
221 fgCreateSubsystems();
222 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
223 fgSplashProgress("binding-subsystems");
225 } else if ( idle_state == 8 ) {
229 globals->get_subsystem_mgr()->bind();
230 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
232 fgSplashProgress("init-subsystems");
233 } else if ( idle_state == 9 ) {
234 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
235 if ( status == SGSubsystem::INIT_DONE) {
237 fgSplashProgress("finishing-subsystems");
239 fgSplashProgress("init-subsystems");
242 } else if ( idle_state == 10 ) {
244 fgPostInitSubsystems();
245 fgSplashProgress("finalize-position");
246 } else if ( idle_state == 900 ) {
249 // setup OpenGL view parameters
250 globals->get_renderer()->setupView();
252 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
253 fgGetInt("/sim/startup/ysize") );
254 WindowSystemAdapter::getWSA()->windows[0]->gc->add(
255 new simgear::canvas::VGInitOperation()
258 int session = fgGetInt("/sim/session",0);
260 fgSetInt("/sim/session",session);
263 if ( idle_state == 1000 ) {
264 // We've finished all our initialization steps, from now on we
265 // run the main loop.
266 fgSetBool("sim/sceneryloaded", false);
271 static void upper_case_property(const char *name)
273 using namespace simgear;
274 SGPropertyNode *p = fgGetNode(name, false);
276 p = fgGetNode(name, true);
277 p->setStringValue("");
279 props::Type t = p->getType();
280 if (t == props::NONE || t == props::UNSPECIFIED)
281 p->setStringValue("");
283 assert(t == props::STRING);
285 p->addChangeListener(new FGMakeUpperCase);
288 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
289 // for the details of this.
290 static void ATIScreenSizeHack()
292 osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
293 hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
294 int prettyMuchAnyInt = 1;
295 hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
296 globals->get_renderer()->addCamera(hackCam, false);
299 // Propose NVIDIA Optimus to use high-end GPU
300 #if defined(SG_WINDOWS)
302 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
306 static void logToFile()
308 SGPath logPath = globals->get_fg_home();
309 logPath.append("fgfs.log");
310 if (logPath.exists()) {
311 SGPath prevLogPath = globals->get_fg_home();
312 prevLogPath.append("fgfs_0.log");
313 logPath.rename(prevLogPath);
314 // bit strange, we need to restore the correct value of logPath now
315 logPath = globals->get_fg_home();
316 logPath.append("fgfs.log");
318 sglog().logToFile(logPath, SG_ALL, SG_INFO);
321 // Main top level initialization
322 int fgMainInit( int argc, char **argv ) {
324 // set default log levels
325 sglog().setLogLevels( SG_ALL, SG_ALERT );
327 globals = new FGGlobals;
330 // now home is initialised, we can log to a file inside it
334 #ifdef FLIGHTGEAR_VERSION
335 version = FLIGHTGEAR_VERSION;
337 version = "unknown version";
339 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
341 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
343 // Allocate global data structures. This needs to happen before
344 // we parse command line options
348 // seed the random number generator
351 string_list *col = new string_list;
352 globals->set_channel_options_list( col );
354 fgValidatePath("", false); // initialize static variables
355 upper_case_property("/sim/presets/airport-id");
356 upper_case_property("/sim/presets/runway");
357 upper_case_property("/sim/tower/airport-id");
358 upper_case_property("/autopilot/route-manager/input");
360 // Load the configuration parameters. (Command line options
361 // override config file options. Config file options override
363 int configResult = fgInitConfig(argc, argv);
364 if (configResult == flightgear::FG_OPTIONS_ERROR) {
366 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
370 // Initialize the Window/Graphics environment.
371 fgOSInit(&argc, argv);
374 fgRegisterIdleHandler( &fgIdleFunction );
376 // Initialize sockets (WinSock needs this)
377 simgear::Socket::initSockets();
379 // Clouds3D requires an alpha channel
380 fgOSOpenWindow(true /* request stencil buffer */);
382 // Initialize the splash screen right away
386 if (fgGetBool("/sim/ati-viewport-hack", true)) {
387 SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
393 // pass control off to the master event handler
394 int result = fgOSMainLoop();
395 frame_signal.clear();
398 // clean up here; ensure we null globals to avoid
399 // confusing the atexit() handler
403 // delete the NavCache here. This will cause the destruction of many cached
404 // objects (eg, airports, navaids, runways).
405 delete flightgear::NavDataCache::instance();