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