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