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