]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Sink position-init code into its own file.
[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
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
83 static void fgLoadInitialScenery()
84 {
85     static SGPropertyNode_ptr scenery_loaded
86         = fgGetNode("sim/sceneryloaded", true);
87     static SGPropertyNode_ptr scenery_override
88         = fgGetNode("/sim/sceneryloaded-override", true);
89
90     if (!scenery_loaded->getBoolValue())
91     {
92         if (scenery_override->getBoolValue() ||
93             (globals->get_tile_mgr()->isSceneryLoaded()
94              && fgGetBool("sim/fdm-initialized"))) {
95             fgSetBool("sim/sceneryloaded",true);
96             fgSplashProgress("");
97         }
98         else
99         {
100             fgSplashProgress("loading scenery");
101             // be nice to loader threads while waiting for initial scenery, reduce to 2fps
102             SGTimeStamp::sleepForMSec(500);
103         }
104     }
105 }
106
107 // What should we do when we have nothing else to do?  Let's get ready
108 // for the next move and update the display?
109 static void fgMainLoop( void )
110 {
111     static SGPropertyNode_ptr frame_signal
112         = fgGetNode("/sim/signals/frame", true);
113
114     frame_signal->fireValueChanged();
115
116     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
117     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
118
119     // compute simulated time (allowing for pause, warp, etc) and
120     // real elapsed time
121     double sim_dt, real_dt;
122     static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
123     timeMgr->computeTimeDeltas(sim_dt, real_dt);
124
125     // update all subsystems
126     globals->get_subsystem_mgr()->update(sim_dt);
127
128     // END Tile Manager updates
129     fgLoadInitialScenery();
130
131     simgear::AtomicChangeListener::fireChangeListeners();
132
133     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
134 }
135
136 // Operation for querying OpenGL parameters. This must be done in a
137 // valid OpenGL context, potentially in another thread.
138 namespace
139 {
140 struct GeneralInitOperation : public GraphicsContextOperation
141 {
142     GeneralInitOperation()
143         : GraphicsContextOperation(std::string("General init"))
144     {
145     }
146     void run(osg::GraphicsContext* gc)
147     {
148         SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
149         
150         simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
151         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
152         
153         simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
154         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
155         
156         simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
157         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
158
159         simRendering->setStringValue("gl-shading-language-version", (char*) glGetString(GL_SHADING_LANGUAGE_VERSION));
160         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_SHADING_LANGUAGE_VERSION));
161
162         GLint tmp;
163         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
164         simRendering->setIntValue("max-texture-size", tmp);
165
166         glGetIntegerv( GL_DEPTH_BITS, &tmp );
167         simRendering->setIntValue("depth-buffer-bits", tmp);
168     }
169 };
170
171 }
172
173 // This is the top level master main function that is registered as
174 // our idle function
175
176 // The first few passes take care of initialization things (a couple
177 // per pass) and once everything has been initialized fgMainLoop from
178 // then on.
179
180 static void fgIdleFunction ( void ) {
181     // Specify our current idle function state.  This is used to run all
182     // our initializations out of the idle callback so that we can get a
183     // splash screen up and running right away.
184     static int idle_state = 0;
185     static int spin_count = 0;
186   
187     static osg::ref_ptr<GeneralInitOperation> genOp;
188     if ( idle_state == 0 ) {
189         idle_state++;
190         // Pick some window on which to do queries.
191         // XXX Perhaps all this graphics initialization code should be
192         // moved to renderer.cxx?
193         genOp = new GeneralInitOperation;
194         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
195         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
196         osg::GraphicsContext* gc = 0;
197         if (guiCamera)
198             gc = guiCamera->getGraphicsContext();
199         if (gc) {
200             gc->add(genOp.get());
201         } else {
202             wsa->windows[0]->gc->add(genOp.get());
203         }
204         guiStartInit(gc);
205     } else if ( idle_state == 1 ) {
206         if (genOp.valid()) {
207             if (!genOp->isFinished())
208                 return;
209             genOp = 0;
210         }
211         if (!guiFinishInit())
212             return;
213         idle_state++;
214         fgSplashProgress("loading aircraft list");
215
216     } else if ( idle_state == 2 ) {
217         idle_state++;
218         fgSplashProgress("loading navigation data");
219
220     } else if ( idle_state == 3 ) {
221         idle_state++;
222         fgInitNav();
223
224         fgSplashProgress("initializing scenery system");
225
226     } else if ( idle_state == 4 ) {
227         idle_state+=2;
228         // based on the requested presets, calculate the true starting
229         // lon, lat
230         flightgear::initPosition();
231         flightgear::initTowerLocationListener();
232
233         TimeManager* t = new TimeManager;
234         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
235         t->init(); // need to init now, not during initSubsystems
236         
237         // Do some quick general initializations
238         if( !fgInitGeneral()) {
239             SG_LOG( SG_GENERAL, SG_ALERT,
240                 "General initialization failed ..." );
241             exit(-1);
242         }
243
244         ////////////////////////////////////////////////////////////////////
245         // Initialize the property-based built-in commands
246         ////////////////////////////////////////////////////////////////////
247         fgInitCommands();
248
249         ////////////////////////////////////////////////////////////////////
250         // Initialize the material manager
251         ////////////////////////////////////////////////////////////////////
252         globals->set_matlib( new SGMaterialLib );
253         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
254         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
255
256         ////////////////////////////////////////////////////////////////////
257         // Initialize the TG scenery subsystem.
258         ////////////////////////////////////////////////////////////////////
259         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
260         globals->add_subsystem("terrasync", terra_sync);
261         globals->set_scenery( new FGScenery );
262         globals->get_scenery()->init();
263         globals->get_scenery()->bind();
264         globals->set_tile_mgr( new FGTileMgr );
265
266         fgSplashProgress("loading aircraft");
267
268     } else if ( idle_state == 6 ) {
269         idle_state++;
270         fgSplashProgress("creating subsystems");
271
272     } else if ( idle_state == 7 ) {
273         idle_state++;
274         SGTimeStamp st;
275         st.stamp();
276         fgCreateSubsystems();
277         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
278         fgSplashProgress("binding subsystems");
279       
280     } else if ( idle_state == 8 ) {
281         idle_state++;
282         SGTimeStamp st;
283         st.stamp();
284         globals->get_subsystem_mgr()->bind();
285         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
286
287         fgSplashProgress("initing subsystems");
288     } else if ( idle_state == 9 ) {
289         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
290         if ( status == SGSubsystem::INIT_DONE) {
291           ++idle_state;
292           fgSplashProgress("finishing subsystem init");
293         } else {
294           const char* spinChars = "-\\|/";
295           string msg = string("initing subsystems ") + spinChars[spin_count++ % 4];
296           fgSplashProgress(msg.c_str());
297         }
298       
299     } else if ( idle_state == 10 ) {
300         idle_state = 900;
301         fgPostInitSubsystems();
302       
303               // Torsten Dreyer:
304         // ugly hack for automatic runway selection on startup based on
305         // metar data. Makes startup.nas obsolete and guarantees the same
306         // runway selection as for AI traffic. However, this code belongs to
307         // somewhere(?) else - if I only new where...
308         if( true == fgGetBool( "/environment/metar/valid" ) ) {
309             SG_LOG(SG_ENVIRONMENT, SG_INFO,
310                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
311             // the realwx_ctrl fetches metar in the foreground on init,
312             // If it was able to fetch a metar or one was given on the commandline,
313             // the valid flag is set here, otherwise it is false
314             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
315             string apt = fgGetString( "/sim/startup/options/airport" );
316             string rwy = fgGetString( "/sim/startup/options/runway" );
317             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
318             string parkpos = fgGetString( "/sim/presets/parkpos" );
319             bool onground = fgGetBool( "/sim/presets/onground", false );
320             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
321             // the other logic is taken from former startup.nas
322             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
323                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
324                 flightgear::setPosFromAirportIDandHdg( apt, hdg );
325             }
326         } else {
327             SG_LOG(SG_ENVIRONMENT, SG_INFO,
328                 "No METAR available to pick active runway" );
329         }
330
331         fgSplashProgress("initializing graphics engine");
332
333     } else if ( idle_state == 900 ) {
334         idle_state = 1000;
335         
336         // setup OpenGL view parameters
337         globals->get_renderer()->setupView();
338
339         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
340                                          fgGetInt("/sim/startup/ysize") );
341
342         int session = fgGetInt("/sim/session",0);
343         session++;
344         fgSetInt("/sim/session",session);
345     }
346
347     if ( idle_state == 1000 ) {
348         // We've finished all our initialization steps, from now on we
349         // run the main loop.
350         fgSetBool("sim/sceneryloaded", false);
351         fgRegisterIdleHandler( fgMainLoop );
352     }
353 }
354
355 static void upper_case_property(const char *name)
356 {
357     using namespace simgear;
358     SGPropertyNode *p = fgGetNode(name, false);
359     if (!p) {
360         p = fgGetNode(name, true);
361         p->setStringValue("");
362     } else {
363         props::Type t = p->getType();
364         if (t == props::NONE || t == props::UNSPECIFIED)
365             p->setStringValue("");
366         else
367             assert(t == props::STRING);
368     }
369     p->addChangeListener(new FGMakeUpperCase);
370 }
371
372
373 // Main top level initialization
374 int fgMainInit( int argc, char **argv ) {
375
376     // set default log levels
377     sglog().setLogLevels( SG_ALL, SG_ALERT );
378
379     string version;
380 #ifdef FLIGHTGEAR_VERSION
381     version = FLIGHTGEAR_VERSION;
382 #else
383     version = "unknown version";
384 #endif
385     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
386             << version );
387     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
388
389     // Allocate global data structures.  This needs to happen before
390     // we parse command line options
391
392     globals = new FGGlobals;
393
394     // seed the random number generator
395     sg_srandom_time();
396
397     FGControls *controls = new FGControls;
398     globals->set_controls( controls );
399
400     string_list *col = new string_list;
401     globals->set_channel_options_list( col );
402
403     fgValidatePath("", false);  // initialize static variables
404     upper_case_property("/sim/presets/airport-id");
405     upper_case_property("/sim/presets/runway");
406     upper_case_property("/sim/tower/airport-id");
407     upper_case_property("/autopilot/route-manager/input");
408
409     // Load the configuration parameters.  (Command line options
410     // override config file options.  Config file options override
411     // defaults.)
412     if ( !fgInitConfig(argc, argv) ) {
413       SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
414       exit(-1);
415     }
416
417     // Initialize the Window/Graphics environment.
418     fgOSInit(&argc, argv);
419     _bootstrap_OSInit++;
420
421     fgRegisterIdleHandler( &fgIdleFunction );
422
423     // Initialize sockets (WinSock needs this)
424     simgear::Socket::initSockets();
425
426     // Clouds3D requires an alpha channel
427     fgOSOpenWindow(true /* request stencil buffer */);
428
429     // Initialize the splash screen right away
430     fntInit();
431     fgSplashInit();
432
433     // pass control off to the master event handler
434     int result = fgOSMainLoop();
435     
436     // clean up here; ensure we null globals to avoid
437     // confusing the atexit() handler
438     delete globals;
439     globals = NULL;
440     
441     return result;
442 }