]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Make FGTaxiNode and FGParking inherit FGPositioned.
[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 <Aircraft/controls.hxx>
53 #include <Model/panelnode.hxx>
54 #include <Scenery/scenery.hxx>
55 #include <Scenery/tilemgr.hxx>
56 #include <Sound/soundmanager.hxx>
57 #include <Time/TimeManager.hxx>
58 #include <GUI/gui.h>
59 #include <Viewer/CameraGroup.hxx>
60 #include <Viewer/WindowSystemAdapter.hxx>
61 #include <Viewer/splash.hxx>
62 #include <Viewer/renderer.hxx>
63 #include <Navaids/NavDataCache.hxx>
64
65 #include "fg_commands.hxx"
66 #include "fg_io.hxx"
67 #include "main.hxx"
68 #include "util.hxx"
69 #include "fg_init.hxx"
70 #include "fg_os.hxx"
71 #include "fg_props.hxx"
72 #include "positioninit.hxx"
73
74 using namespace flightgear;
75
76 using std::cerr;
77 using std::vector;
78
79 // The atexit() function handler should know when the graphical subsystem
80 // is initialized.
81 extern int _bootstrap_OSInit;
82
83 // What should we do when we have nothing else to do?  Let's get ready
84 // for the next move and update the display?
85 static void fgMainLoop( void )
86 {
87     static SGPropertyNode_ptr frame_signal
88         = fgGetNode("/sim/signals/frame", true);
89
90     frame_signal->fireValueChanged();
91
92     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
93     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
94
95     // compute simulated time (allowing for pause, warp, etc) and
96     // real elapsed time
97     double sim_dt, real_dt;
98     static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
99     timeMgr->computeTimeDeltas(sim_dt, real_dt);
100
101     // update all subsystems
102     globals->get_subsystem_mgr()->update(sim_dt);
103
104     simgear::AtomicChangeListener::fireChangeListeners();
105
106     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
107 }
108
109 // Operation for querying OpenGL parameters. This must be done in a
110 // valid OpenGL context, potentially in another thread.
111 namespace
112 {
113 struct GeneralInitOperation : public GraphicsContextOperation
114 {
115     GeneralInitOperation()
116         : GraphicsContextOperation(std::string("General init"))
117     {
118     }
119     void run(osg::GraphicsContext* gc)
120     {
121         SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
122         
123         simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
124         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
125         
126         simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
127         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
128         
129         simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
130         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
131
132         simRendering->setStringValue("gl-shading-language-version", (char*) glGetString(GL_SHADING_LANGUAGE_VERSION));
133         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_SHADING_LANGUAGE_VERSION));
134
135         GLint tmp;
136         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
137         simRendering->setIntValue("max-texture-size", tmp);
138
139         glGetIntegerv( GL_DEPTH_BITS, &tmp );
140         simRendering->setIntValue("depth-buffer-bits", tmp);
141     }
142 };
143
144 }
145
146 // This is the top level master main function that is registered as
147 // our idle function
148
149 // The first few passes take care of initialization things (a couple
150 // per pass) and once everything has been initialized fgMainLoop from
151 // then on.
152
153 static void fgIdleFunction ( void ) {
154     // Specify our current idle function state.  This is used to run all
155     // our initializations out of the idle callback so that we can get a
156     // splash screen up and running right away.
157     static int idle_state = 0;
158   
159     static osg::ref_ptr<GeneralInitOperation> genOp;
160     if ( idle_state == 0 ) {
161         idle_state++;
162         // Pick some window on which to do queries.
163         // XXX Perhaps all this graphics initialization code should be
164         // moved to renderer.cxx?
165         genOp = new GeneralInitOperation;
166         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
167         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
168         osg::GraphicsContext* gc = 0;
169         if (guiCamera)
170             gc = guiCamera->getGraphicsContext();
171         if (gc) {
172             gc->add(genOp.get());
173         } else {
174             wsa->windows[0]->gc->add(genOp.get());
175         }
176         guiStartInit(gc);
177     } else if ( idle_state == 1 ) {
178         if (genOp.valid()) {
179             if (!genOp->isFinished())
180                 return;
181             genOp = 0;
182         }
183         if (!guiFinishInit())
184             return;
185         idle_state++;
186         fgSplashProgress("loading-aircraft-list");
187
188     } else if ( idle_state == 2 ) {
189         idle_state++;
190         fgSplashProgress("loading-nav-data");
191
192     } else if ( idle_state == 3 ) {
193         idle_state++;
194         fgInitNav();
195
196         fgSplashProgress("init-scenery");
197
198     } else if ( idle_state == 4 ) {
199         idle_state+=2;
200         // based on the requested presets, calculate the true starting
201         // lon, lat
202         flightgear::initPosition();
203         flightgear::initTowerLocationListener();
204
205         TimeManager* t = new TimeManager;
206         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
207         t->init(); // need to init now, not during initSubsystems
208         
209         // Do some quick general initializations
210         if( !fgInitGeneral()) {
211             SG_LOG( SG_GENERAL, SG_ALERT,
212                 "General initialization failed ..." );
213             exit(-1);
214         }
215
216         ////////////////////////////////////////////////////////////////////
217         // Initialize the property-based built-in commands
218         ////////////////////////////////////////////////////////////////////
219         fgInitCommands();
220
221         ////////////////////////////////////////////////////////////////////
222         // Initialize the material manager
223         ////////////////////////////////////////////////////////////////////
224         globals->set_matlib( new SGMaterialLib );
225         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
226         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
227
228         ////////////////////////////////////////////////////////////////////
229         // Initialize the TG scenery subsystem.
230         ////////////////////////////////////////////////////////////////////
231         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
232         globals->add_subsystem("terrasync", terra_sync);
233         globals->set_scenery( new FGScenery );
234         globals->get_scenery()->init();
235         globals->get_scenery()->bind();
236         globals->set_tile_mgr( new FGTileMgr );
237
238         fgSplashProgress("loading-aircraft");
239
240     } else if ( idle_state == 6 ) {
241         idle_state++;
242         fgSplashProgress("creating-subsystems");
243
244     } else if ( idle_state == 7 ) {
245         idle_state++;
246         SGTimeStamp st;
247         st.stamp();
248         fgCreateSubsystems();
249         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
250         fgSplashProgress("binding-subsystems");
251       
252     } else if ( idle_state == 8 ) {
253         idle_state++;
254         SGTimeStamp st;
255         st.stamp();
256         globals->get_subsystem_mgr()->bind();
257         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
258
259         fgSplashProgress("init-subsystems");
260     } else if ( idle_state == 9 ) {
261         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
262         if ( status == SGSubsystem::INIT_DONE) {
263           ++idle_state;
264           fgSplashProgress("finishing-subsystems");
265         } else {
266           fgSplashProgress("init-subsystems");
267         }
268       
269     } else if ( idle_state == 10 ) {
270         idle_state = 900;
271         fgPostInitSubsystems();
272       
273               // Torsten Dreyer:
274         // ugly hack for automatic runway selection on startup based on
275         // metar data. Makes startup.nas obsolete and guarantees the same
276         // runway selection as for AI traffic. However, this code belongs to
277         // somewhere(?) else - if I only new where...
278         if( true == fgGetBool( "/environment/metar/valid" ) ) {
279             SG_LOG(SG_ENVIRONMENT, SG_INFO,
280                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
281             // the realwx_ctrl fetches metar in the foreground on init,
282             // If it was able to fetch a metar or one was given on the commandline,
283             // the valid flag is set here, otherwise it is false
284             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
285             string apt = fgGetString( "/sim/startup/options/airport" );
286             string rwy = fgGetString( "/sim/startup/options/runway" );
287             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
288             string parkpos = fgGetString( "/sim/presets/parkpos" );
289             bool onground = fgGetBool( "/sim/presets/onground", false );
290             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
291             // the other logic is taken from former startup.nas
292             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
293                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
294                 flightgear::setPosFromAirportIDandHdg( apt, hdg );
295             }
296         } else {
297             SG_LOG(SG_ENVIRONMENT, SG_INFO,
298                 "No METAR available to pick active runway" );
299         }
300
301         fgSplashProgress("init-graphics");
302
303     } else if ( idle_state == 900 ) {
304         idle_state = 1000;
305         
306         // setup OpenGL view parameters
307         globals->get_renderer()->setupView();
308
309         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
310                                          fgGetInt("/sim/startup/ysize") );
311
312         int session = fgGetInt("/sim/session",0);
313         session++;
314         fgSetInt("/sim/session",session);
315     }
316
317     if ( idle_state == 1000 ) {
318         // We've finished all our initialization steps, from now on we
319         // run the main loop.
320         fgSetBool("sim/sceneryloaded", false);
321         fgRegisterIdleHandler( fgMainLoop );
322     }
323 }
324
325 static void upper_case_property(const char *name)
326 {
327     using namespace simgear;
328     SGPropertyNode *p = fgGetNode(name, false);
329     if (!p) {
330         p = fgGetNode(name, true);
331         p->setStringValue("");
332     } else {
333         props::Type t = p->getType();
334         if (t == props::NONE || t == props::UNSPECIFIED)
335             p->setStringValue("");
336         else
337             assert(t == props::STRING);
338     }
339     p->addChangeListener(new FGMakeUpperCase);
340 }
341
342
343 // Main top level initialization
344 int fgMainInit( int argc, char **argv ) {
345
346     // set default log levels
347     sglog().setLogLevels( SG_ALL, SG_ALERT );
348
349     string version;
350 #ifdef FLIGHTGEAR_VERSION
351     version = FLIGHTGEAR_VERSION;
352 #else
353     version = "unknown version";
354 #endif
355     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
356             << version );
357     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
358
359     // Allocate global data structures.  This needs to happen before
360     // we parse command line options
361
362     globals = new FGGlobals;
363
364     // seed the random number generator
365     sg_srandom_time();
366
367     FGControls *controls = new FGControls;
368     globals->set_controls( controls );
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 }