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