]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Use a helper thread to rebuild the navcache.
[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 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #include <iostream>
36
37 #include <osg/Camera>
38 #include <osg/GraphicsContext>
39 #include <osgDB/Registry>
40
41 // Class references
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44 #include <simgear/props/AtomicChangeListener.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/timing/sg_time.hxx>
47 #include <simgear/io/raw_socket.hxx>
48 #include <simgear/scene/tsync/terrasync.hxx>
49 #include <simgear/math/SGMath.hxx>
50 #include <simgear/math/sg_random.h>
51
52 #include <Model/panelnode.hxx>
53 #include <Scenery/scenery.hxx>
54 #include <Scenery/tilemgr.hxx>
55 #include <Sound/soundmanager.hxx>
56 #include <Time/TimeManager.hxx>
57 #include <GUI/gui.h>
58 #include <Viewer/CameraGroup.hxx>
59 #include <Viewer/WindowSystemAdapter.hxx>
60 #include <Viewer/splash.hxx>
61 #include <Viewer/renderer.hxx>
62 #include <Navaids/NavDataCache.hxx>
63
64 #include "fg_commands.hxx"
65 #include "fg_io.hxx"
66 #include "main.hxx"
67 #include "util.hxx"
68 #include "fg_init.hxx"
69 #include "fg_os.hxx"
70 #include "fg_props.hxx"
71 #include "positioninit.hxx"
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 // 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     static SGPropertyNode_ptr frame_signal
87         = fgGetNode("/sim/signals/frame", true);
88
89     frame_signal->fireValueChanged();
90
91     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
92     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
93
94     // compute simulated time (allowing for pause, warp, etc) and
95     // real elapsed time
96     double sim_dt, real_dt;
97     static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
98     timeMgr->computeTimeDeltas(sim_dt, real_dt);
99
100     // update all subsystems
101     globals->get_subsystem_mgr()->update(sim_dt);
102
103     simgear::AtomicChangeListener::fireChangeListeners();
104
105     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
106 }
107
108 // Operation for querying OpenGL parameters. This must be done in a
109 // valid OpenGL context, potentially in another thread.
110 namespace
111 {
112 struct GeneralInitOperation : public GraphicsContextOperation
113 {
114     GeneralInitOperation()
115         : GraphicsContextOperation(std::string("General init"))
116     {
117     }
118     void run(osg::GraphicsContext* gc)
119     {
120         SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
121         
122         simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
123         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
124         
125         simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
126         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
127         
128         simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
129         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
130
131         simRendering->setStringValue("gl-shading-language-version", (char*) glGetString(GL_SHADING_LANGUAGE_VERSION));
132         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_SHADING_LANGUAGE_VERSION));
133
134         GLint tmp;
135         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
136         simRendering->setIntValue("max-texture-size", tmp);
137
138         glGetIntegerv( GL_DEPTH_BITS, &tmp );
139         simRendering->setIntValue("depth-buffer-bits", tmp);
140     }
141 };
142
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 void fgIdleFunction ( void ) {
153     // Specify our current idle function state.  This is used to run all
154     // our initializations out of the idle callback so that we can get a
155     // splash screen up and running right away.
156     static int idle_state = 0;
157   
158     static osg::ref_ptr<GeneralInitOperation> genOp;
159     if ( idle_state == 0 ) {
160         idle_state++;
161         // Pick some window on which to do queries.
162         // XXX Perhaps all this graphics initialization code should be
163         // moved to renderer.cxx?
164         genOp = new GeneralInitOperation;
165         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
166         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
167         osg::GraphicsContext* gc = 0;
168         if (guiCamera)
169             gc = guiCamera->getGraphicsContext();
170         if (gc) {
171             gc->add(genOp.get());
172         } else {
173             wsa->windows[0]->gc->add(genOp.get());
174         }
175         guiStartInit(gc);
176     } else if ( idle_state == 1 ) {
177         if (genOp.valid()) {
178             if (!genOp->isFinished())
179                 return;
180             genOp = 0;
181         }
182         if (!guiFinishInit())
183             return;
184         idle_state++;
185         fgSplashProgress("loading-aircraft-list");
186
187     } else if ( idle_state == 2 ) {
188         idle_state++;
189         fgSplashProgress("loading-nav-data");
190
191     } else if ( idle_state == 3 ) {
192         
193         bool done = fgInitNav();
194         if (done) {
195           ++idle_state;
196           fgSplashProgress("init-scenery");
197         } else {
198           fgSplashProgress("loading-nav-data");
199         }
200       
201     } else if ( idle_state == 4 ) {
202         idle_state+=2;
203         // based on the requested presets, calculate the true starting
204         // lon, lat
205         flightgear::initPosition();
206         flightgear::initTowerLocationListener();
207
208         TimeManager* t = new TimeManager;
209         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
210         t->init(); // need to init now, not during initSubsystems
211         
212         // Do some quick general initializations
213         if( !fgInitGeneral()) {
214             SG_LOG( SG_GENERAL, SG_ALERT,
215                 "General initialization failed ..." );
216             exit(-1);
217         }
218
219         ////////////////////////////////////////////////////////////////////
220         // Initialize the property-based built-in commands
221         ////////////////////////////////////////////////////////////////////
222         fgInitCommands();
223
224         ////////////////////////////////////////////////////////////////////
225         // Initialize the material manager
226         ////////////////////////////////////////////////////////////////////
227         globals->set_matlib( new SGMaterialLib );
228         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
229         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
230
231         ////////////////////////////////////////////////////////////////////
232         // Initialize the TG scenery subsystem.
233         ////////////////////////////////////////////////////////////////////
234         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
235         globals->add_subsystem("terrasync", terra_sync);
236         globals->set_scenery( new FGScenery );
237         globals->get_scenery()->init();
238         globals->get_scenery()->bind();
239         globals->set_tile_mgr( new FGTileMgr );
240
241         fgSplashProgress("loading-aircraft");
242
243     } else if ( idle_state == 6 ) {
244         idle_state++;
245         fgSplashProgress("creating-subsystems");
246
247     } else if ( idle_state == 7 ) {
248         idle_state++;
249         SGTimeStamp st;
250         st.stamp();
251         fgCreateSubsystems();
252         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
253         fgSplashProgress("binding-subsystems");
254       
255     } else if ( idle_state == 8 ) {
256         idle_state++;
257         SGTimeStamp st;
258         st.stamp();
259         globals->get_subsystem_mgr()->bind();
260         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
261
262         fgSplashProgress("init-subsystems");
263     } else if ( idle_state == 9 ) {
264         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
265         if ( status == SGSubsystem::INIT_DONE) {
266           ++idle_state;
267           fgSplashProgress("finishing-subsystems");
268         } else {
269           fgSplashProgress("init-subsystems");
270         }
271       
272     } else if ( idle_state == 10 ) {
273         idle_state = 900;
274         fgPostInitSubsystems();
275       
276               // Torsten Dreyer:
277         // ugly hack for automatic runway selection on startup based on
278         // metar data. Makes startup.nas obsolete and guarantees the same
279         // runway selection as for AI traffic. However, this code belongs to
280         // somewhere(?) else - if I only new where...
281         if( true == fgGetBool( "/environment/metar/valid" ) ) {
282             SG_LOG(SG_ENVIRONMENT, SG_INFO,
283                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
284             // the realwx_ctrl fetches metar in the foreground on init,
285             // If it was able to fetch a metar or one was given on the commandline,
286             // the valid flag is set here, otherwise it is false
287             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
288             string apt = fgGetString( "/sim/startup/options/airport" );
289             string rwy = fgGetString( "/sim/startup/options/runway" );
290             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
291             string parkpos = fgGetString( "/sim/presets/parkpos" );
292             bool onground = fgGetBool( "/sim/presets/onground", false );
293             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
294             // the other logic is taken from former startup.nas
295             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
296                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
297                 flightgear::setPosFromAirportIDandHdg( apt, hdg );
298             }
299         } else {
300             SG_LOG(SG_ENVIRONMENT, SG_INFO,
301                 "No METAR available to pick active runway" );
302         }
303
304         fgSplashProgress("init-graphics");
305
306     } else if ( idle_state == 900 ) {
307         idle_state = 1000;
308         
309         // setup OpenGL view parameters
310         globals->get_renderer()->setupView();
311
312         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
313                                          fgGetInt("/sim/startup/ysize") );
314
315         int session = fgGetInt("/sim/session",0);
316         session++;
317         fgSetInt("/sim/session",session);
318     }
319
320     if ( idle_state == 1000 ) {
321         // We've finished all our initialization steps, from now on we
322         // run the main loop.
323         fgSetBool("sim/sceneryloaded", false);
324         fgRegisterIdleHandler( fgMainLoop );
325     }
326 }
327
328 static void upper_case_property(const char *name)
329 {
330     using namespace simgear;
331     SGPropertyNode *p = fgGetNode(name, false);
332     if (!p) {
333         p = fgGetNode(name, true);
334         p->setStringValue("");
335     } else {
336         props::Type t = p->getType();
337         if (t == props::NONE || t == props::UNSPECIFIED)
338             p->setStringValue("");
339         else
340             assert(t == props::STRING);
341     }
342     p->addChangeListener(new FGMakeUpperCase);
343 }
344
345
346 // Main top level initialization
347 int fgMainInit( int argc, char **argv ) {
348
349     // set default log levels
350     sglog().setLogLevels( SG_ALL, SG_ALERT );
351
352     string version;
353 #ifdef FLIGHTGEAR_VERSION
354     version = FLIGHTGEAR_VERSION;
355 #else
356     version = "unknown version";
357 #endif
358     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
359             << version );
360     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
361
362     // Allocate global data structures.  This needs to happen before
363     // we parse command line options
364
365     globals = new FGGlobals;
366
367     // seed the random number generator
368     sg_srandom_time();
369
370     string_list *col = new string_list;
371     globals->set_channel_options_list( col );
372
373     fgValidatePath("", false);  // initialize static variables
374     upper_case_property("/sim/presets/airport-id");
375     upper_case_property("/sim/presets/runway");
376     upper_case_property("/sim/tower/airport-id");
377     upper_case_property("/autopilot/route-manager/input");
378
379     // Load the configuration parameters.  (Command line options
380     // override config file options.  Config file options override
381     // defaults.)
382     if ( !fgInitConfig(argc, argv) ) {
383       SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
384       exit(-1);
385     }
386
387     // Initialize the Window/Graphics environment.
388     fgOSInit(&argc, argv);
389     _bootstrap_OSInit++;
390
391     fgRegisterIdleHandler( &fgIdleFunction );
392
393     // Initialize sockets (WinSock needs this)
394     simgear::Socket::initSockets();
395
396     // Clouds3D requires an alpha channel
397     fgOSOpenWindow(true /* request stencil buffer */);
398
399     // Initialize the splash screen right away
400     fntInit();
401     fgSplashInit();
402
403     // pass control off to the master event handler
404     int result = fgOSMainLoop();
405     
406     // clean up here; ensure we null globals to avoid
407     // confusing the atexit() handler
408     delete globals;
409     globals = NULL;
410     
411     // delete the NavCache here. This will cause the destruction of many cached
412     // objects (eg, airports, navaids, runways).
413     delete flightgear::NavDataCache::instance();
414   
415     return result;
416 }