]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Simplify canvas OpenVG initialization and fix sometimes rendering too lazy
[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 #include <iostream>
31
32 #include <osg/Camera>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
35
36 // Class references
37 #include <simgear/canvas/VGInitOperation.hxx>
38 #include <simgear/scene/model/modellib.hxx>
39 #include <simgear/scene/material/matlib.hxx>
40 #include <simgear/props/AtomicChangeListener.hxx>
41 #include <simgear/props/props.hxx>
42 #include <simgear/timing/sg_time.hxx>
43 #include <simgear/io/raw_socket.hxx>
44 #include <simgear/scene/tsync/terrasync.hxx>
45 #include <simgear/math/SGMath.hxx>
46 #include <simgear/math/sg_random.h>
47
48 #include <Model/panelnode.hxx>
49 #include <Scenery/scenery.hxx>
50 #include <Scenery/tilemgr.hxx>
51 #include <Sound/soundmanager.hxx>
52 #include <Time/TimeManager.hxx>
53 #include <GUI/gui.h>
54 #include <Viewer/splash.hxx>
55 #include <Viewer/renderer.hxx>
56 #include <Viewer/WindowSystemAdapter.hxx>
57 #include <Navaids/NavDataCache.hxx>
58
59 #include "fg_commands.hxx"
60 #include "fg_io.hxx"
61 #include "main.hxx"
62 #include "util.hxx"
63 #include "fg_init.hxx"
64 #include "fg_os.hxx"
65 #include "fg_props.hxx"
66 #include "positioninit.hxx"
67 #include "subsystemFactory.hxx"
68
69 using namespace flightgear;
70
71 using std::cerr;
72 using std::vector;
73
74 // The atexit() function handler should know when the graphical subsystem
75 // is initialized.
76 extern int _bootstrap_OSInit;
77
78 // What should we do when we have nothing else to do?  Let's get ready
79 // for the next move and update the display?
80 static void fgMainLoop( void )
81 {
82     static SGPropertyNode_ptr frame_signal
83         = fgGetNode("/sim/signals/frame", true);
84
85     frame_signal->fireValueChanged();
86
87     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
88     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
89
90     // compute simulated time (allowing for pause, warp, etc) and
91     // real elapsed time
92     double sim_dt, real_dt;
93     static TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
94     timeMgr->computeTimeDeltas(sim_dt, real_dt);
95
96     // update all subsystems
97     globals->get_subsystem_mgr()->update(sim_dt);
98
99     simgear::AtomicChangeListener::fireChangeListeners();
100
101     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
102 }
103
104
105 // This is the top level master main function that is registered as
106 // our idle function
107
108 // The first few passes take care of initialization things (a couple
109 // per pass) and once everything has been initialized fgMainLoop from
110 // then on.
111
112 static void fgIdleFunction ( void ) {
113     // Specify our current idle function state.  This is used to run all
114     // our initializations out of the idle callback so that we can get a
115     // splash screen up and running right away.
116     static int idle_state = 0;
117   
118     if ( idle_state == 0 ) {
119         if (guiInit())
120         {
121             idle_state+=2;
122             fgSplashProgress("loading-aircraft-list");
123         }
124
125     } else if ( idle_state == 2 ) {
126         idle_state++;
127         fgSplashProgress("loading-nav-dat");
128
129     } else if ( idle_state == 3 ) {
130         
131         bool done = fgInitNav();
132         if (done) {
133           ++idle_state;
134           fgSplashProgress("init-scenery");
135         } else {
136           fgSplashProgress("loading-nav-dat");
137         }
138       
139     } else if ( idle_state == 4 ) {
140         idle_state+=2;
141         // based on the requested presets, calculate the true starting
142         // lon, lat
143         flightgear::initPosition();
144         flightgear::initTowerLocationListener();
145
146         TimeManager* t = new TimeManager;
147         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
148         t->init(); // need to init now, not during initSubsystems
149         
150         // Do some quick general initializations
151         if( !fgInitGeneral()) {
152             SG_LOG( SG_GENERAL, SG_ALERT,
153                 "General initialization failed ..." );
154             exit(-1);
155         }
156
157         ////////////////////////////////////////////////////////////////////
158         // Initialize the property-based built-in commands
159         ////////////////////////////////////////////////////////////////////
160         fgInitCommands();
161
162         flightgear::registerSubsystemCommands(globals->get_commands());
163
164         ////////////////////////////////////////////////////////////////////
165         // Initialize the material manager
166         ////////////////////////////////////////////////////////////////////
167         globals->set_matlib( new SGMaterialLib );
168         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
169         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
170
171         ////////////////////////////////////////////////////////////////////
172         // Initialize the TG scenery subsystem.
173         ////////////////////////////////////////////////////////////////////
174         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
175         globals->add_subsystem("terrasync", terra_sync);
176         globals->set_scenery( new FGScenery );
177         globals->get_scenery()->init();
178         globals->get_scenery()->bind();
179         globals->set_tile_mgr( new FGTileMgr );
180
181         fgSplashProgress("loading-aircraft");
182
183     } else if ( idle_state == 6 ) {
184         idle_state++;
185         fgSplashProgress("creating-subsystems");
186
187     } else if ( idle_state == 7 ) {
188         idle_state++;
189         SGTimeStamp st;
190         st.stamp();
191         fgCreateSubsystems();
192         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
193         fgSplashProgress("binding-subsystems");
194       
195     } else if ( idle_state == 8 ) {
196         idle_state++;
197         SGTimeStamp st;
198         st.stamp();
199         globals->get_subsystem_mgr()->bind();
200         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
201
202         fgSplashProgress("init-subsystems");
203     } else if ( idle_state == 9 ) {
204         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
205         if ( status == SGSubsystem::INIT_DONE) {
206           ++idle_state;
207           fgSplashProgress("finishing-subsystems");
208         } else {
209           fgSplashProgress("init-subsystems");
210         }
211       
212     } else if ( idle_state == 10 ) {
213         idle_state = 900;
214         fgPostInitSubsystems();
215       
216               // Torsten Dreyer:
217         // ugly hack for automatic runway selection on startup based on
218         // metar data. Makes startup.nas obsolete and guarantees the same
219         // runway selection as for AI traffic. However, this code belongs to
220         // somewhere(?) else - if I only new where...
221         if( true == fgGetBool( "/environment/metar/valid" ) ) {
222             SG_LOG(SG_ENVIRONMENT, SG_INFO,
223                 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
224             // the realwx_ctrl fetches metar in the foreground on init,
225             // If it was able to fetch a metar or one was given on the commandline,
226             // the valid flag is set here, otherwise it is false
227             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
228             string apt = fgGetString( "/sim/startup/options/airport" );
229             string rwy = fgGetString( "/sim/startup/options/runway" );
230             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
231             string parkpos = fgGetString( "/sim/presets/parkpos" );
232             bool onground = fgGetBool( "/sim/presets/onground", false );
233             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
234             // the other logic is taken from former startup.nas
235             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
236                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
237                 flightgear::setPosFromAirportIDandHdg( apt, hdg );
238             }
239         } else {
240             SG_LOG(SG_ENVIRONMENT, SG_INFO,
241                 "No METAR available to pick active runway" );
242         }
243
244         fgSplashProgress("init-graphics");
245
246     } else if ( idle_state == 900 ) {
247         idle_state = 1000;
248         
249         // setup OpenGL view parameters
250         globals->get_renderer()->setupView();
251
252         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
253                                          fgGetInt("/sim/startup/ysize") );
254         WindowSystemAdapter::getWSA()->windows[0]->gc->add(
255           new simgear::canvas::VGInitOperation()
256         );
257
258         int session = fgGetInt("/sim/session",0);
259         session++;
260         fgSetInt("/sim/session",session);
261     }
262
263     if ( idle_state == 1000 ) {
264         // We've finished all our initialization steps, from now on we
265         // run the main loop.
266         fgSetBool("sim/sceneryloaded", false);
267         fgRegisterIdleHandler( fgMainLoop );
268     }
269 }
270
271 static void upper_case_property(const char *name)
272 {
273     using namespace simgear;
274     SGPropertyNode *p = fgGetNode(name, false);
275     if (!p) {
276         p = fgGetNode(name, true);
277         p->setStringValue("");
278     } else {
279         props::Type t = p->getType();
280         if (t == props::NONE || t == props::UNSPECIFIED)
281             p->setStringValue("");
282         else
283             assert(t == props::STRING);
284     }
285     p->addChangeListener(new FGMakeUpperCase);
286 }
287
288
289 // Main top level initialization
290 int fgMainInit( int argc, char **argv ) {
291
292     // set default log levels
293     sglog().setLogLevels( SG_ALL, SG_ALERT );
294
295     string version;
296 #ifdef FLIGHTGEAR_VERSION
297     version = FLIGHTGEAR_VERSION;
298 #else
299     version = "unknown version";
300 #endif
301     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
302             << version );
303     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
304
305     // Allocate global data structures.  This needs to happen before
306     // we parse command line options
307
308     globals = new FGGlobals;
309
310     // seed the random number generator
311     sg_srandom_time();
312
313     string_list *col = new string_list;
314     globals->set_channel_options_list( col );
315
316     fgValidatePath("", false);  // initialize static variables
317     upper_case_property("/sim/presets/airport-id");
318     upper_case_property("/sim/presets/runway");
319     upper_case_property("/sim/tower/airport-id");
320     upper_case_property("/autopilot/route-manager/input");
321
322     // Load the configuration parameters.  (Command line options
323     // override config file options.  Config file options override
324     // defaults.)
325     if ( !fgInitConfig(argc, argv) ) {
326       SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
327       exit(-1);
328     }
329
330     // Initialize the Window/Graphics environment.
331     fgOSInit(&argc, argv);
332     _bootstrap_OSInit++;
333
334     fgRegisterIdleHandler( &fgIdleFunction );
335
336     // Initialize sockets (WinSock needs this)
337     simgear::Socket::initSockets();
338
339     // Clouds3D requires an alpha channel
340     fgOSOpenWindow(true /* request stencil buffer */);
341
342     // Initialize the splash screen right away
343     fntInit();
344     fgSplashInit();
345
346     // pass control off to the master event handler
347     int result = fgOSMainLoop();
348     
349     // clean up here; ensure we null globals to avoid
350     // confusing the atexit() handler
351     delete globals;
352     globals = NULL;
353     
354     // delete the NavCache here. This will cause the destruction of many cached
355     // objects (eg, airports, navaids, runways).
356     delete flightgear::NavDataCache::instance();
357   
358     return result;
359 }