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