]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Make build information readonly and clean up debug output.
[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/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>
47
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>
53 #include <GUI/gui.h>
54 #include <Viewer/splash.hxx>
55 #include <Viewer/renderer.hxx>
56 #include <Viewer/WindowSystemAdapter.hxx>
57 #include <Navaids/NavDataCache.hxx>
58
59 #include "fg_commands.hxx"
60 #include "fg_io.hxx"
61 #include "main.hxx"
62 #include "util.hxx"
63 #include "fg_init.hxx"
64 #include "fg_os.hxx"
65 #include "fg_props.hxx"
66 #include "positioninit.hxx"
67 #include "subsystemFactory.hxx"
68 #include "options.hxx"
69
70 using namespace flightgear;
71
72 using std::cerr;
73 using std::vector;
74
75 // The atexit() function handler should know when the graphical subsystem
76 // is initialized.
77 extern int _bootstrap_OSInit;
78
79 static SGPropertyNode_ptr frame_signal;
80 static TimeManager* timeMgr;
81
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 )
85 {
86     frame_signal->fireValueChanged();
87
88     // compute simulated time (allowing for pause, warp, etc) and
89     // real elapsed time
90     double sim_dt, real_dt;
91     timeMgr->computeTimeDeltas(sim_dt, real_dt);
92
93     // update all subsystems
94     globals->get_subsystem_mgr()->update(sim_dt);
95
96     simgear::AtomicChangeListener::fireChangeListeners();
97 }
98
99
100 static void registerMainLoop()
101 {
102     // stash current frame signal property
103     frame_signal = fgGetNode("/sim/signals/frame", true);
104     timeMgr = (TimeManager*) globals->get_subsystem("time");
105     fgRegisterIdleHandler( fgMainLoop );
106 }
107
108 // This is the top level master main function that is registered as
109 // our idle function
110
111 // The first few passes take care of initialization things (a couple
112 // per pass) and once everything has been initialized fgMainLoop from
113 // then on.
114
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;
120   
121     if ( idle_state == 0 ) {
122         if (guiInit())
123         {
124             idle_state+=2;
125             fgSplashProgress("loading-aircraft-list");
126         }
127
128     } else if ( idle_state == 2 ) {
129         
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");
134         fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
135         
136         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
137         globals->add_subsystem("terrasync", terra_sync);
138         
139         
140         
141         terra_sync->bind();
142         terra_sync->init();
143         
144         // add the terrasync root as a data path so data can be retrieved from it
145         std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
146         globals->append_data_path(terraSyncDir);
147         
148         idle_state++;
149         fgSplashProgress("loading-nav-dat");
150
151     } else if ( idle_state == 3 ) {
152         
153         bool done = fgInitNav();
154         if (done) {
155           ++idle_state;
156           fgSplashProgress("init-scenery");
157         } else {
158           fgSplashProgress("loading-nav-dat");
159         }
160       
161     } else if ( idle_state == 4 ) {
162         idle_state+=2;
163         // based on the requested presets, calculate the true starting
164         // lon, lat
165         flightgear::initPosition();
166         flightgear::initTowerLocationListener();
167
168         TimeManager* t = new TimeManager;
169         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
170         t->init(); // need to init now, not during initSubsystems
171         
172         // Do some quick general initializations
173         if( !fgInitGeneral()) {
174             throw sg_exception("General initialization failed");
175         }
176
177         ////////////////////////////////////////////////////////////////////
178         // Initialize the property-based built-in commands
179         ////////////////////////////////////////////////////////////////////
180         fgInitCommands();
181
182         flightgear::registerSubsystemCommands(globals->get_commands());
183
184         ////////////////////////////////////////////////////////////////////
185         // Initialize the material manager
186         ////////////////////////////////////////////////////////////////////
187         globals->set_matlib( new SGMaterialLib );
188         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
189         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
190
191         ////////////////////////////////////////////////////////////////////
192         // Initialize the TG scenery subsystem.
193         ////////////////////////////////////////////////////////////////////
194
195         globals->set_scenery( new FGScenery );
196         globals->get_scenery()->init();
197         globals->get_scenery()->bind();
198         globals->set_tile_mgr( new FGTileMgr );
199
200         fgSplashProgress("loading-aircraft");
201
202     } else if ( idle_state == 6 ) {
203         idle_state++;
204         fgSplashProgress("creating-subsystems");
205
206     } else if ( idle_state == 7 ) {
207         idle_state++;
208         SGTimeStamp st;
209         st.stamp();
210         fgCreateSubsystems();
211         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
212         fgSplashProgress("binding-subsystems");
213       
214     } else if ( idle_state == 8 ) {
215         idle_state++;
216         SGTimeStamp st;
217         st.stamp();
218         globals->get_subsystem_mgr()->bind();
219         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
220
221         fgSplashProgress("init-subsystems");
222     } else if ( idle_state == 9 ) {
223         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
224         if ( status == SGSubsystem::INIT_DONE) {
225           ++idle_state;
226           fgSplashProgress("finishing-subsystems");
227         } else {
228           fgSplashProgress("init-subsystems");
229         }
230       
231     } else if ( idle_state == 10 ) {
232         idle_state = 900;
233         fgPostInitSubsystems();
234         fgSplashProgress("finalize-position");
235     } else if ( idle_state == 900 ) {
236         idle_state = 1000;
237         
238         // setup OpenGL view parameters
239         globals->get_renderer()->setupView();
240
241         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
242                                          fgGetInt("/sim/startup/ysize") );
243         WindowSystemAdapter::getWSA()->windows[0]->gc->add(
244           new simgear::canvas::VGInitOperation()
245         );
246
247         int session = fgGetInt("/sim/session",0);
248         session++;
249         fgSetInt("/sim/session",session);
250     }
251
252     if ( idle_state == 1000 ) {
253         // We've finished all our initialization steps, from now on we
254         // run the main loop.
255         fgSetBool("sim/sceneryloaded", false);
256         registerMainLoop();
257     }
258 }
259
260 static void upper_case_property(const char *name)
261 {
262     using namespace simgear;
263     SGPropertyNode *p = fgGetNode(name, false);
264     if (!p) {
265         p = fgGetNode(name, true);
266         p->setStringValue("");
267     } else {
268         props::Type t = p->getType();
269         if (t == props::NONE || t == props::UNSPECIFIED)
270             p->setStringValue("");
271         else
272             assert(t == props::STRING);
273     }
274     p->addChangeListener(new FGMakeUpperCase);
275 }
276
277 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
278 // for the details of this.
279 static void ATIScreenSizeHack()
280 {
281     osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
282     hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
283     int prettyMuchAnyInt = 1;
284     hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
285     globals->get_renderer()->addCamera(hackCam, false);
286 }
287
288 // Propose NVIDIA Optimus to use high-end GPU
289 #if defined(SG_WINDOWS)
290 extern "C" {
291     _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
292 }
293 #endif
294
295 static void logToFile()
296 {
297     SGPath logPath = globals->get_fg_home();
298     logPath.append("fgfs.log");
299     if (logPath.exists()) {
300         SGPath prevLogPath = globals->get_fg_home();
301         prevLogPath.append("fgfs_0.log");
302         logPath.rename(prevLogPath);
303         // bit strange, we need to restore the correct value of logPath now
304         logPath = globals->get_fg_home();
305         logPath.append("fgfs.log");
306     }
307     sglog().logToFile(logPath, SG_ALL, SG_INFO);
308 }
309
310 // Main top level initialization
311 int fgMainInit( int argc, char **argv ) {
312
313     // set default log levels
314     sglog().setLogLevels( SG_ALL, SG_ALERT );
315
316     globals = new FGGlobals;
317     fgInitHome();
318     
319     // now home is initialised, we can log to a file inside it
320     logToFile();
321     
322     std::string version;
323 #ifdef FLIGHTGEAR_VERSION
324     version = FLIGHTGEAR_VERSION;
325 #else
326     version = "unknown version";
327 #endif
328     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
329             << version );
330     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
331
332     // Allocate global data structures.  This needs to happen before
333     // we parse command line options
334
335     
336     
337     // seed the random number generator
338     sg_srandom_time();
339
340     string_list *col = new string_list;
341     globals->set_channel_options_list( col );
342
343     fgValidatePath("", false);  // initialize static variables
344     upper_case_property("/sim/presets/airport-id");
345     upper_case_property("/sim/presets/runway");
346     upper_case_property("/sim/tower/airport-id");
347     upper_case_property("/autopilot/route-manager/input");
348
349     // Load the configuration parameters.  (Command line options
350     // override config file options.  Config file options override
351     // defaults.)
352     int configResult = fgInitConfig(argc, argv);
353     if (configResult == flightgear::FG_OPTIONS_ERROR) {
354         return EXIT_FAILURE;
355     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
356         return EXIT_SUCCESS;
357     }
358     
359     // Initialize the Window/Graphics environment.
360     fgOSInit(&argc, argv);
361     _bootstrap_OSInit++;
362
363     fgRegisterIdleHandler( &fgIdleFunction );
364
365     // Initialize sockets (WinSock needs this)
366     simgear::Socket::initSockets();
367
368     // Clouds3D requires an alpha channel
369     fgOSOpenWindow(true /* request stencil buffer */);
370
371     // Initialize the splash screen right away
372     fntInit();
373     fgSplashInit();
374
375     if (fgGetBool("/sim/ati-viewport-hack", true)) {
376         SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
377         ATIScreenSizeHack();
378     }
379     
380     fgOutputSettings();
381     
382     // pass control off to the master event handler
383     int result = fgOSMainLoop();
384     
385     // clean up here; ensure we null globals to avoid
386     // confusing the atexit() handler
387     delete globals;
388     globals = NULL;
389     
390     // delete the NavCache here. This will cause the destruction of many cached
391     // objects (eg, airports, navaids, runways).
392     delete flightgear::NavDataCache::instance();
393   
394     return result;
395 }