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