]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Make Traffic-via-terrasync conditional
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <iostream>
31
32 #include <osg/Camera>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
35
36 // Class references
37 #include <simgear/canvas/VGInitOperation.hxx>
38 #include <simgear/scene/model/modellib.hxx>
39 #include <simgear/scene/material/matlib.hxx>
40 #include <simgear/scene/material/Effect.hxx>
41 #include <simgear/props/AtomicChangeListener.hxx>
42 #include <simgear/props/props.hxx>
43 #include <simgear/timing/sg_time.hxx>
44 #include <simgear/io/raw_socket.hxx>
45 #include <simgear/scene/tsync/terrasync.hxx>
46 #include <simgear/math/SGMath.hxx>
47 #include <simgear/math/sg_random.h>
48
49 #include <Model/panelnode.hxx>
50 #include <Scenery/scenery.hxx>
51 #include <Scenery/tilemgr.hxx>
52 #include <Sound/soundmanager.hxx>
53 #include <Time/TimeManager.hxx>
54 #include <GUI/gui.h>
55 #include <Viewer/splash.hxx>
56 #include <Viewer/renderer.hxx>
57 #include <Viewer/WindowSystemAdapter.hxx>
58 #include <Navaids/NavDataCache.hxx>
59
60 #include "fg_commands.hxx"
61 #include "fg_io.hxx"
62 #include "main.hxx"
63 #include "util.hxx"
64 #include "fg_init.hxx"
65 #include "fg_os.hxx"
66 #include "fg_props.hxx"
67 #include "positioninit.hxx"
68 #include "screensaver_control.hxx"
69 #include "subsystemFactory.hxx"
70 #include "options.hxx"
71
72
73 using namespace flightgear;
74
75 using std::cerr;
76 using std::vector;
77
78 // The atexit() function handler should know when the graphical subsystem
79 // is initialized.
80 extern int _bootstrap_OSInit;
81
82 static SGPropertyNode_ptr frame_signal;
83 static TimeManager* timeMgr;
84
85 // What should we do when we have nothing else to do?  Let's get ready
86 // for the next move and update the display?
87 static void fgMainLoop( void )
88 {
89     frame_signal->fireValueChanged();
90
91     // compute simulated time (allowing for pause, warp, etc) and
92     // real elapsed time
93     double sim_dt, real_dt;
94     timeMgr->computeTimeDeltas(sim_dt, real_dt);
95
96     // update all subsystems
97     globals->get_subsystem_mgr()->update(sim_dt);
98
99     simgear::AtomicChangeListener::fireChangeListeners();
100 }
101
102 static void initTerrasync()
103 {
104     // add the terrasync root as a data path so data can be retrieved from it
105     // (even if we are in read-only mode)
106     std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
107     globals->append_data_path(terraSyncDir);
108     
109     if (fgGetBool("/sim/fghome-readonly", false)) {
110         return;
111     }
112     
113     // start TerraSync up now, so it can be synchronizing shared models
114     // and airports data in parallel with a nav-cache rebuild.
115     SGPath tsyncCache(globals->get_fg_home());
116     tsyncCache.append("terrasync-cache.xml");
117     
118     // wipe the cache file if requested
119     if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
120         SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
121                tsyncCache);
122         if (tsyncCache.exists()) {
123             tsyncCache.remove();
124         }
125     }
126     
127     fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
128     
129     simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
130     terra_sync->setRoot(globals->get_props());
131     globals->add_subsystem("terrasync", terra_sync);
132     
133     terra_sync->bind();
134     terra_sync->init();
135 }
136
137 static void registerMainLoop()
138 {
139     // stash current frame signal property
140     frame_signal = fgGetNode("/sim/signals/frame", true);
141     timeMgr = (TimeManager*) globals->get_subsystem("time");
142     fgRegisterIdleHandler( fgMainLoop );
143 }
144
145 // This is the top level master main function that is registered as
146 // our idle function
147
148 // The first few passes take care of initialization things (a couple
149 // per pass) and once everything has been initialized fgMainLoop from
150 // then on.
151
152 static int idle_state = 0;
153
154 static void fgIdleFunction ( void ) {
155     // Specify our current idle function state.  This is used to run all
156     // our initializations out of the idle callback so that we can get a
157     // splash screen up and running right away.
158     
159     if ( idle_state == 0 ) {
160         if (guiInit())
161         {
162             idle_state+=2;
163             fgSplashProgress("loading-aircraft-list");
164         }
165
166     } else if ( idle_state == 2 ) {
167         initTerrasync();
168         idle_state++;
169         fgSplashProgress("loading-nav-dat");
170
171     } else if ( idle_state == 3 ) {
172         
173         bool done = fgInitNav();
174         if (done) {
175           ++idle_state;
176           fgSplashProgress("init-scenery");
177         } else {
178           fgSplashProgress("loading-nav-dat");
179         }
180       
181     } else if ( idle_state == 4 ) {
182         idle_state++;
183
184         TimeManager* t = new TimeManager;
185         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
186         
187         // Do some quick general initializations
188         if( !fgInitGeneral()) {
189             throw sg_exception("General initialization failed");
190         }
191
192         ////////////////////////////////////////////////////////////////////
193         // Initialize the property-based built-in commands
194         ////////////////////////////////////////////////////////////////////
195         fgInitCommands();
196
197         flightgear::registerSubsystemCommands(globals->get_commands());
198
199         ////////////////////////////////////////////////////////////////////
200         // Initialize the material manager
201         ////////////////////////////////////////////////////////////////////
202         globals->set_matlib( new SGMaterialLib );
203         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
204  
205     } else if (( idle_state == 5 ) || (idle_state == 2005)) {
206         idle_state+=2;
207         flightgear::initPosition();
208         flightgear::initTowerLocationListener();
209         
210         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
211         
212         TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
213         timeManager->init();
214         
215         ////////////////////////////////////////////////////////////////////
216         // Initialize the TG scenery subsystem.
217         ////////////////////////////////////////////////////////////////////
218         
219         globals->set_scenery( new FGScenery );
220         globals->get_scenery()->init();
221         globals->get_scenery()->bind();
222         globals->set_tile_mgr( new FGTileMgr );
223         
224         fgSplashProgress("creating-subsystems");
225     } else if (( idle_state == 7 ) || (idle_state == 2007)) {
226         bool isReset = (idle_state == 2007);
227         idle_state = 8; // from the next state on, reset & startup are identical
228         SGTimeStamp st;
229         st.stamp();
230         fgCreateSubsystems(isReset);
231         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
232         fgSplashProgress("binding-subsystems");
233       
234     } else if ( idle_state == 8 ) {
235         idle_state++;
236         SGTimeStamp st;
237         st.stamp();
238         globals->get_subsystem_mgr()->bind();
239         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
240
241         fgSplashProgress("init-subsystems");
242     } else if ( idle_state == 9 ) {
243         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
244         if ( status == SGSubsystem::INIT_DONE) {
245           ++idle_state;
246           fgSplashProgress("finishing-subsystems");
247         } else {
248           fgSplashProgress("init-subsystems");
249         }
250       
251     } else if ( idle_state == 10 ) {
252         idle_state = 900;
253         fgPostInitSubsystems();
254         fgSplashProgress("finalize-position");
255     } else if ( idle_state == 900 ) {
256         idle_state = 1000;
257         
258         // setup OpenGL view parameters
259         globals->get_renderer()->setupView();
260
261         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
262                                          fgGetInt("/sim/startup/ysize") );
263         WindowSystemAdapter::getWSA()->windows[0]->gc->add(
264           new simgear::canvas::VGInitOperation()
265         );
266
267         int session = fgGetInt("/sim/session",0);
268         session++;
269         fgSetInt("/sim/session",session);
270     }
271
272     if ( idle_state == 1000 ) {
273         // We've finished all our initialization steps, from now on we
274         // run the main loop.
275         fgSetBool("sim/sceneryloaded", false);
276         registerMainLoop();
277     }
278     
279     if ( idle_state == 2000 ) {
280         fgStartNewReset();
281         idle_state = 2005;
282     }
283 }
284
285 void fgResetIdleState()
286 {
287     idle_state = 2000;
288     fgRegisterIdleHandler( &fgIdleFunction );
289 }
290
291
292 static void upper_case_property(const char *name)
293 {
294     using namespace simgear;
295     SGPropertyNode *p = fgGetNode(name, false);
296     if (!p) {
297         p = fgGetNode(name, true);
298         p->setStringValue("");
299     } else {
300         props::Type t = p->getType();
301         if (t == props::NONE || t == props::UNSPECIFIED)
302             p->setStringValue("");
303         else
304             assert(t == props::STRING);
305     }
306     SGPropertyChangeListener* muc = new FGMakeUpperCase;
307     globals->addListenerToCleanup(muc);
308     p->addChangeListener(muc);
309 }
310
311 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
312 // for the details of this.
313 static void ATIScreenSizeHack()
314 {
315     osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
316     hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
317     int prettyMuchAnyInt = 1;
318     hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
319     globals->get_renderer()->addCamera(hackCam, false);
320 }
321
322 // Propose NVIDIA Optimus to use high-end GPU
323 #if defined(SG_WINDOWS)
324 extern "C" {
325     _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
326 }
327 #endif
328
329 static void logToFile()
330 {
331     SGPath logPath = globals->get_fg_home();
332     logPath.append("fgfs.log");
333     if (logPath.exists()) {
334         SGPath prevLogPath = globals->get_fg_home();
335         prevLogPath.append("fgfs_0.log");
336         logPath.rename(prevLogPath);
337         // bit strange, we need to restore the correct value of logPath now
338         logPath = globals->get_fg_home();
339         logPath.append("fgfs.log");
340     }
341     sglog().logToFile(logPath, SG_ALL, SG_INFO);
342 }
343
344 // Main top level initialization
345 int fgMainInit( int argc, char **argv ) {
346
347     // set default log levels
348     sglog().setLogLevels( SG_ALL, SG_ALERT );
349
350     globals = new FGGlobals;
351     if (!fgInitHome()) {
352         return EXIT_FAILURE;
353     }
354     
355     if (!fgGetBool("/sim/fghome-readonly")) {
356         // now home is initialised, we can log to a file inside it
357         logToFile();
358     }
359     
360     std::string version;
361 #ifdef FLIGHTGEAR_VERSION
362     version = FLIGHTGEAR_VERSION;
363 #else
364     version = "unknown version";
365 #endif
366     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
367             << version );
368     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
369
370     // Allocate global data structures.  This needs to happen before
371     // we parse command line options
372
373     
374     
375     // seed the random number generator
376     sg_srandom_time();
377
378     string_list *col = new string_list;
379     globals->set_channel_options_list( col );
380
381     fgValidatePath("", false);  // initialize static variables
382     upper_case_property("/sim/presets/airport-id");
383     upper_case_property("/sim/presets/runway");
384     upper_case_property("/sim/tower/airport-id");
385     upper_case_property("/autopilot/route-manager/input");
386
387     // Load the configuration parameters.  (Command line options
388     // override config file options.  Config file options override
389     // defaults.)
390     int configResult = fgInitConfig(argc, argv, false);
391     if (configResult == flightgear::FG_OPTIONS_ERROR) {
392         return EXIT_FAILURE;
393     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
394         return EXIT_SUCCESS;
395     }
396     
397     configResult = fgInitAircraft(false);
398     if (configResult == flightgear::FG_OPTIONS_ERROR) {
399         return EXIT_FAILURE;
400     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
401         return EXIT_SUCCESS;
402     }
403     
404     configResult = flightgear::Options::sharedInstance()->processOptions();
405     if (configResult == flightgear::FG_OPTIONS_ERROR) {
406         return EXIT_FAILURE;
407     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
408         return EXIT_SUCCESS;
409     }
410     
411     // Initialize the Window/Graphics environment.
412     fgOSInit(&argc, argv);
413     _bootstrap_OSInit++;
414
415     fgRegisterIdleHandler( &fgIdleFunction );
416
417     // Initialize sockets (WinSock needs this)
418     simgear::Socket::initSockets();
419
420     // Clouds3D requires an alpha channel
421     fgOSOpenWindow(true /* request stencil buffer */);
422     fgOSResetProperties();
423     
424     // Initialize the splash screen right away
425     fntInit();
426     fgSplashInit();
427
428     if (fgGetBool("/sim/ati-viewport-hack", true)) {
429         SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
430         ATIScreenSizeHack();
431     }
432     
433     fgOutputSettings();
434     
435     //try to disable the screensaver
436     fgOSDisableScreensaver();
437     
438     // pass control off to the master event handler
439     int result = fgOSMainLoop();
440     frame_signal.clear();
441     fgOSCloseWindow();
442     
443     simgear::clearEffectCache();
444     
445     // clean up here; ensure we null globals to avoid
446     // confusing the atexit() handler
447     delete globals;
448     globals = NULL;
449     
450     // delete the NavCache here. This will cause the destruction of many cached
451     // objects (eg, airports, navaids, runways).
452     delete flightgear::NavDataCache::instance();
453   
454     return result;
455 }