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