]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
3532bcb5ea4fdac6a5900238c49989b8f95eda87
[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/scene/model/animation.hxx>
45 #include <simgear/scene/sky/sky.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/props/AtomicChangeListener.hxx>
48 #include <simgear/props/props.hxx>
49 #include <simgear/timing/sg_time.hxx>
50 #include <simgear/timing/timestamp.hxx>
51 #include <simgear/magvar/magvar.hxx>
52 #include <simgear/math/sg_random.h>
53 #include <simgear/io/raw_socket.hxx>
54 #include <simgear/scene/tsync/terrasync.hxx>
55
56 #include <Time/light.hxx>
57 #include <Aircraft/replay.hxx>
58 #include <Aircraft/controls.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Model/acmodel.hxx>
61 #include <Scenery/scenery.hxx>
62 #include <Scenery/tilemgr.hxx>
63 #include <Sound/fg_fx.hxx>
64 #include <Sound/beacon.hxx>
65 #include <Sound/morse.hxx>
66 #include <Sound/fg_fx.hxx>
67 #include <ATCDCL/ATCmgr.hxx>
68 #include <Time/TimeManager.hxx>
69 #include <Environment/environment_mgr.hxx>
70 #include <GUI/gui.h>
71 #include <GUI/new_gui.hxx>
72 #include <MultiPlayer/multiplaymgr.hxx>
73
74 #include "CameraGroup.hxx"
75 #include "fg_commands.hxx"
76 #include "fg_io.hxx"
77 #include "renderer.hxx"
78 #include "splash.hxx"
79 #include "main.hxx"
80 #include "util.hxx"
81 #include "fg_init.hxx"
82 #include "fg_os.hxx"
83 #include "WindowSystemAdapter.hxx"
84 #include <Main/viewer.hxx>
85
86
87 using namespace flightgear;
88
89 using std::cerr;
90
91 // Specify our current idle function state.  This is used to run all
92 // our initializations out of the idle callback so that we can get a
93 // splash screen up and running right away.
94 int idle_state = 0;
95
96
97 void fgInitSoundManager();
98 void fgSetNewSoundDevice(const char *);
99
100 // The atexit() function handler should know when the graphical subsystem
101 // is initialized.
102 extern int _bootstrap_OSInit;
103
104 // What should we do when we have nothing else to do?  Let's get ready
105 // for the next move and update the display?
106 static void fgMainLoop( void )
107 {
108     static SGPropertyNode_ptr frame_signal
109         = fgGetNode("/sim/signals/frame", true);
110
111     static SGPropertyNode_ptr _statisticsFlag
112         = fgGetNode("/sim/timing-statistics/enabled", true);
113     static SGPropertyNode_ptr _statisticsInterval
114         = fgGetNode("/sim/timing-statistics/interval-s", true);
115     static SGPropertyNode_ptr _statiticsMinJitter
116         = fgGetNode("/sim/timing-statistics/min-jitter-ms", true);
117     static SGPropertyNode_ptr _statiticsMinTime
118         = fgGetNode("/sim/timing-statistics/min-time-ms", true);
119
120     frame_signal->fireValueChanged();
121     
122     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
123     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
124     
125     
126   // update "time"
127     double sim_dt, real_dt;
128     TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
129     // compute simulated time (allowing for pause, warp, etc) and
130     // real elapsed time
131     timeMgr->computeTimeDeltas(sim_dt, real_dt);
132
133     // update magvar model
134     globals->get_mag()->update( globals->get_aircraft_position(),
135                                 globals->get_time_params()->getJD() );
136
137     globals->get_subsystem_mgr()->update(sim_dt);
138
139     // Update the sound manager last so it can use the CPU while the GPU
140     // is processing the scenery (doubled the frame-rate for me) -EMH-
141 #ifdef ENABLE_AUDIO_SUPPORT
142     static bool smgr_init = true;
143     static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
144     if (smgr_init == true) {
145         if (sound_working->getBoolValue() == true) {
146             fgInitSoundManager();
147             smgr_init = false;
148         }
149     } else {
150         static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
151         static SGSoundMgr *smgr = globals->get_soundmgr();
152         static bool smgr_enabled = true;
153
154         if (sound_working->getBoolValue() == false) {   // request to reinit
155            smgr->reinit();
156            smgr->resume();
157            sound_working->setBoolValue(true);
158         }
159
160         if (smgr_enabled != sound_enabled->getBoolValue()) {
161             if (smgr_enabled == true) { // request to suspend
162                 smgr->suspend();
163                 smgr_enabled = false;
164             } else {
165                 smgr->resume();
166                 smgr_enabled = true;
167             }
168         }
169
170         if (smgr_enabled == true) {
171             static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
172             smgr->set_volume(volume->getFloatValue());
173             smgr->update(sim_dt);
174         }
175     }
176 #endif
177
178     // END Tile Manager updates
179     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
180     if (!scenery_loaded)
181     {
182         if (globals->get_tile_mgr()->isSceneryLoaded()
183              && fgGetBool("sim/fdm-initialized")) {
184             fgSetBool("sim/sceneryloaded",true);
185             fgSplashProgress("");
186             if (fgGetBool("/sim/sound/working")) {
187                 globals->get_soundmgr()->activate();
188             }
189             globals->get_props()->tie("/sim/sound/devices/name",
190                   SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
191         }
192         else
193         {
194             fgSplashProgress("loading scenery");
195             // be nice to loader threads while waiting for initial scenery, reduce to 2fps
196             SGTimeStamp::sleepForMSec(500);
197         }
198     }
199
200     // print timing statistics
201     static bool _lastStatisticsFlag = false;
202     if (_lastStatisticsFlag != _statisticsFlag->getBoolValue())
203     {
204         // flag has changed, update subsystem manager
205         _lastStatisticsFlag = _statisticsFlag->getBoolValue();
206         globals->get_subsystem_mgr()->collectDebugTiming(_lastStatisticsFlag);
207     }
208     if (_lastStatisticsFlag)
209     {
210         static double elapsed = 0;
211         elapsed += real_dt;
212         if (elapsed >= _statisticsInterval->getDoubleValue())
213         {
214             // print and reset timing statistics
215             globals->get_subsystem_mgr()->printTimingStatistics(_statiticsMinTime->getDoubleValue(),
216                                                                 _statiticsMinJitter->getDoubleValue());
217             elapsed = 0;
218         }
219     }
220
221     simgear::AtomicChangeListener::fireChangeListeners();
222
223     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
224 }
225
226 void fgInitSoundManager()
227 {
228     SGSoundMgr *smgr = globals->get_soundmgr();
229
230     smgr->bind();
231     smgr->init(fgGetString("/sim/sound/device-name", NULL));
232
233     vector <const char*>devices = smgr->get_available_devices();
234     for (unsigned int i=0; i<devices.size(); i++) {
235         SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
236         p->setStringValue(devices[i]);
237     }
238     devices.clear();
239 }
240
241 void fgSetNewSoundDevice(const char *device)
242 {
243     globals->get_soundmgr()->suspend();
244     globals->get_soundmgr()->stop();
245     globals->get_soundmgr()->init(device);
246     globals->get_soundmgr()->resume();
247 }
248
249 // Operation for querying OpenGL parameters. This must be done in a
250 // valid OpenGL context, potentially in another thread.
251 namespace
252 {
253 struct GeneralInitOperation : public GraphicsContextOperation
254 {
255     GeneralInitOperation()
256         : GraphicsContextOperation(std::string("General init"))
257     {
258     }
259     void run(osg::GraphicsContext* gc)
260     {
261         SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
262         
263         simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
264         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
265         
266         simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
267         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
268         
269         simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
270         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
271
272         GLint tmp;
273         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
274         simRendering->setIntValue("max-texture-size", tmp);
275
276         glGetIntegerv( GL_DEPTH_BITS, &tmp );
277         simRendering->setIntValue("depth-buffer-bits", tmp);
278     }
279 };
280
281
282 osg::Node* load_panel(SGPropertyNode *n)
283 {
284     osg::Geode* geode = new osg::Geode;
285     geode->addDrawable(new FGPanelNode(n));
286     return geode;
287 }
288
289 SGPath resolve_path(const std::string& s)
290 {
291   return globals->resolve_maybe_aircraft_path(s);
292 }
293
294 }
295
296 // This is the top level master main function that is registered as
297 // our idle function
298
299 // The first few passes take care of initialization things (a couple
300 // per pass) and once everything has been initialized fgMainLoop from
301 // then on.
302
303 static void fgIdleFunction ( void ) {
304     static osg::ref_ptr<GeneralInitOperation> genOp;
305     if ( idle_state == 0 ) {
306         idle_state++;
307         // Pick some window on which to do queries.
308         // XXX Perhaps all this graphics initialization code should be
309         // moved to renderer.cxx?
310         genOp = new GeneralInitOperation;
311         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
312         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
313         osg::GraphicsContext* gc = 0;
314         if (guiCamera)
315             gc = guiCamera->getGraphicsContext();
316         if (gc) {
317             gc->add(genOp.get());
318         } else {
319             wsa->windows[0]->gc->add(genOp.get());
320         }
321         guiStartInit(gc);
322     } else if ( idle_state == 1 ) {
323         if (genOp.valid()) {
324             if (!genOp->isFinished())
325                 return;
326             genOp = 0;
327         }
328         if (!guiFinishInit())
329             return;
330         idle_state++;
331         fgSplashProgress("loading aircraft list");
332
333     } else if ( idle_state == 2 ) {
334         idle_state++;
335         fgSplashProgress("loading navigation data");
336
337     } else if ( idle_state == 3 ) {
338         idle_state++;
339         fgInitNav();
340
341         fgSplashProgress("initializing scenery system");
342
343     } else if ( idle_state == 4 ) {
344         idle_state++;
345         // based on the requested presets, calculate the true starting
346         // lon, lat
347         fgInitPosition();
348         fgInitTowerLocationListener();
349
350         TimeManager* t = new TimeManager;
351         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
352         t->init(); // need to init now, not during initSubsystems
353         
354         // Do some quick general initializations
355         if( !fgInitGeneral()) {
356             SG_LOG( SG_GENERAL, SG_ALERT,
357                 "General initialization failed ..." );
358             exit(-1);
359         }
360
361         ////////////////////////////////////////////////////////////////////
362         // Initialize the property-based built-in commands
363         ////////////////////////////////////////////////////////////////////
364         fgInitCommands();
365
366         ////////////////////////////////////////////////////////////////////
367         // Initialize the material manager
368         ////////////////////////////////////////////////////////////////////
369         globals->set_matlib( new SGMaterialLib );
370         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
371         simgear::SGModelLib::setPanelFunc(load_panel);
372
373         ////////////////////////////////////////////////////////////////////
374         // Initialize the TG scenery subsystem.
375         ////////////////////////////////////////////////////////////////////
376         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
377         globals->add_subsystem("terrasync", terra_sync);
378         globals->set_scenery( new FGScenery );
379         globals->get_scenery()->init();
380         globals->get_scenery()->bind();
381         globals->set_tile_mgr( new FGTileMgr );
382
383         fgSplashProgress("loading aircraft");
384
385     } else if ( idle_state == 5 ) {
386         idle_state++;
387
388         fgSplashProgress("initializing sky elements");
389
390     } else if ( idle_state == 6 ) {
391         idle_state++;
392         
393         // Initialize MagVar model
394         SGMagVar *magvar = new SGMagVar();
395         globals->set_mag( magvar );
396         
397         
398         // kludge to initialize mag compass
399         // (should only be done for in-flight
400         // startup)
401         // update magvar model
402         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
403                                    * SGD_DEGREES_TO_RADIANS,
404                                    fgGetDouble("/position/latitude-deg")
405                                    * SGD_DEGREES_TO_RADIANS,
406                                    fgGetDouble("/position/altitude-ft")
407                                    * SG_FEET_TO_METER,
408                                    globals->get_time_params()->getJD() );
409         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
410         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
411         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
412
413         fgSplashProgress("initializing subsystems");
414
415     } else if ( idle_state == 7 ) {
416         idle_state++;
417         // Initialize audio support
418 #ifdef ENABLE_AUDIO_SUPPORT
419
420         // Start the intro music
421         if ( fgGetBool("/sim/startup/intro-music") ) {
422             SGPath mp3file( globals->get_fg_root() );
423             mp3file.append( "Sounds/intro.mp3" );
424
425             SG_LOG( SG_GENERAL, SG_INFO,
426                 "Starting intro music: " << mp3file.str() );
427
428 # if defined( __CYGWIN__ )
429             string command = "start /m `cygpath -w " + mp3file.str() + "`";
430 # elif defined( _WIN32 )
431             string command = "start /m " + mp3file.str();
432 # else
433             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
434 # endif
435
436             system ( command.c_str() );
437         }
438 #endif
439         // This is the top level init routine which calls all the
440         // other subsystem initialization routines.  If you are adding
441         // a subsystem to flightgear, its initialization call should be
442         // located in this routine.
443         if( !fgInitSubsystems()) {
444             SG_LOG( SG_GENERAL, SG_ALERT,
445                 "Subsystem initialization failed ..." );
446             exit(-1);
447         }
448
449         // Torsten Dreyer:
450         // ugly hack for automatic runway selection on startup based on
451         // metar data. Makes startup.nas obsolete and guarantees the same
452         // runway selection as for AI traffic. However, this code belongs to
453         // somewhere(?) else - if I only new where...
454         if( true == fgGetBool( "/environment/metar/valid" ) ) {
455             SG_LOG(SG_ENVIRONMENT, SG_INFO,
456                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
457             // the realwx_ctrl fetches metar in the foreground on init,
458             // If it was able to fetch a metar or one was given on the commandline,
459             // the valid flag is set here, otherwise it is false
460             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
461             string apt = fgGetString( "/sim/startup/options/airport" );
462             string rwy = fgGetString( "/sim/startup/options/runway" );
463             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
464             string parkpos = fgGetString( "/sim/presets/parkpos" );
465             bool onground = fgGetBool( "/sim/presets/onground", false );
466             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
467             // the other logic is taken from former startup.nas
468             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
469                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
470                 fgSetPosFromAirportIDandHdg( apt, hdg );
471             }
472         } else {
473             SG_LOG(SG_ENVIRONMENT, SG_INFO,
474                 "No METAR available to pick active runway" );
475         }
476
477         fgSplashProgress("initializing graphics engine");
478
479     } else if ( idle_state == 8 ) {
480         idle_state = 1000;
481         
482         // setup OpenGL view parameters
483         globals->get_renderer()->setupView();
484
485         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
486                                          fgGetInt("/sim/startup/ysize") );
487
488         int session = fgGetInt("/sim/session",0);
489         session++;
490         fgSetInt("/sim/session",session);
491     }
492
493     if ( idle_state == 1000 ) {
494         // We've finished all our initialization steps, from now on we
495         // run the main loop.
496         fgSetBool("sim/sceneryloaded", false);
497         fgRegisterIdleHandler( fgMainLoop );
498     }
499 }
500
501 static void upper_case_property(const char *name)
502 {
503     using namespace simgear;
504     SGPropertyNode *p = fgGetNode(name, false);
505     if (!p) {
506         p = fgGetNode(name, true);
507         p->setStringValue("");
508     } else {
509         props::Type t = p->getType();
510         if (t == props::NONE || t == props::UNSPECIFIED)
511             p->setStringValue("");
512         else
513             assert(t == props::STRING);
514     }
515     p->addChangeListener(new FGMakeUpperCase);
516 }
517
518
519 // Main top level initialization
520 int fgMainInit( int argc, char **argv ) {
521
522     // set default log levels
523     sglog().setLogLevels( SG_ALL, SG_ALERT );
524
525     string version;
526 #ifdef FLIGHTGEAR_VERSION
527     version = FLIGHTGEAR_VERSION;
528 #else
529     version = "unknown version";
530 #endif
531     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
532             << version );
533   SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
534
535     // Allocate global data structures.  This needs to happen before
536     // we parse command line options
537
538     globals = new FGGlobals;
539
540     // seed the random number generator
541     sg_srandom_time();
542
543     FGControls *controls = new FGControls;
544     globals->set_controls( controls );
545
546     string_list *col = new string_list;
547     globals->set_channel_options_list( col );
548
549     fgValidatePath("", false);  // initialize static variables
550     upper_case_property("/sim/presets/airport-id");
551     upper_case_property("/sim/presets/runway");
552     upper_case_property("/sim/tower/airport-id");
553     upper_case_property("/autopilot/route-manager/input");
554
555     // Load the configuration parameters.  (Command line options
556     // override config file options.  Config file options override
557     // defaults.)
558     if ( !fgInitConfig(argc, argv) ) {
559       SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
560       exit(-1);
561     }
562
563     // Initialize the Window/Graphics environment.
564     fgOSInit(&argc, argv);
565     _bootstrap_OSInit++;
566
567     fgRegisterIdleHandler( &fgIdleFunction );
568
569     // Initialize sockets (WinSock needs this)
570     simgear::Socket::initSockets();
571
572     // Clouds3D requires an alpha channel
573     fgOSOpenWindow(true /* request stencil buffer */);
574
575     // Initialize the splash screen right away
576     fntInit();
577     fgSplashInit();
578
579     // pass control off to the master event handler
580     int result = fgOSMainLoop();
581     
582     // clean up here; ensure we null globals to avoid
583     // confusing the atexit() handler
584     delete globals;
585     globals = NULL;
586     
587     return result;
588 }