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