]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Remove a stale reference.
[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., 675 Mass Ave, Cambridge, MA 02139, 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 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/netSocket.h>
45
46 #include <simgear/props/props.hxx>
47 #include <simgear/timing/sg_time.hxx>
48 #include <simgear/math/sg_random.h>
49
50 // Class references
51 #include <simgear/ephemeris/ephemeris.hxx>
52 #include <simgear/scene/model/modellib.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/animation.hxx>
55 #include <simgear/scene/sky/sky.hxx>
56 #include <Time/light.hxx>
57 #include <Include/general.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Cockpit/hud.hxx>
60 #include <Model/panelnode.hxx>
61 #include <Model/modelmgr.hxx>
62 #include <Model/acmodel.hxx>
63 #include <Scenery/scenery.hxx>
64 #include <Scenery/tilemgr.hxx>
65 #include <Sound/beacon.hxx>
66 #include <Sound/morse.hxx>
67 #include <FDM/flight.hxx>
68 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
69 // #include <FDM/ADA.hxx>
70 #include <ATC/ATCdisplay.hxx>
71 #include <ATC/ATCmgr.hxx>
72 #include <ATC/AIMgr.hxx>
73 #include <Replay/replay.hxx>
74 #include <Time/tmp.hxx>
75 #include <Time/fg_timer.hxx>
76 #include <Environment/environment_mgr.hxx>
77 #include <GUI/new_gui.hxx>
78
79 #ifdef FG_MPLAYER_AS
80 #include <MultiPlayer/multiplaytxmgr.hxx>
81 #include <MultiPlayer/multiplayrxmgr.hxx>
82 #endif
83
84
85
86 #include "fg_commands.hxx"
87 #include "fg_io.hxx"
88 #include "renderer.hxx"
89 #include "splash.hxx"
90 #include "main.hxx"
91
92
93
94 static double real_delta_time_sec = 0.0;
95 double delta_time_sec = 0.0;
96 extern float init_volume;
97
98
99 #ifdef macintosh
100 #  include <console.h>          // -dw- for command line dialog
101 #endif
102
103 // This is a record containing a bit of global housekeeping information
104 FGGeneral general;
105
106 // Specify our current idle function state.  This is used to run all
107 // our initializations out of the idle callback so that we can get a
108 // splash screen up and running right away.
109 int idle_state = 0;
110 long global_multi_loop;
111
112 SGTimeStamp last_time_stamp;
113 SGTimeStamp current_time_stamp;
114
115 // The atexit() functio handler should know when the graphical subsystem
116 // is initialized.
117 extern int _bootstrap_OSInit;
118
119
120
121 // Update internal time dependent calculations (i.e. flight model)
122 // FIXME: this distinction is obsolete; all subsystems now get delta
123 // time on update.
124 void fgUpdateTimeDepCalcs() {
125     static bool inited = false;
126
127     static const SGPropertyNode *replay_state
128         = fgGetNode( "/sim/freeze/replay-state", true );
129     static SGPropertyNode *replay_time
130         = fgGetNode( "/sim/replay/time", true );
131     // static const SGPropertyNode *replay_end_time
132     //     = fgGetNode( "/sim/replay/end-time", true );
133
134     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
135
136     // Initialize the FDM here if it hasn't been and if we have a
137     // scenery elevation hit.
138
139     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
140     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
141
142     if ( !cur_fdm_state->get_inited() &&
143          globals->get_scenery()->get_cur_elev() > -9990 )
144     {
145         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
146         cur_fdm_state->init();
147         if ( cur_fdm_state->get_bound() ) {
148             cur_fdm_state->unbind();
149         }
150         cur_fdm_state->bind();
151     }
152
153     // conceptually, the following block could be done for each fdm
154     // instance ...
155     if ( cur_fdm_state->get_inited() ) {
156         // we have been inited, and  we are good to go ...
157
158         if ( !inited ) {
159             inited = true;
160         }
161
162         if ( replay_state->getIntValue() == 0 ) {
163             // replay off, run fdm
164             cur_fdm_state->update( delta_time_sec );
165         } else {
166             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
167             r->replay( replay_time->getDoubleValue() );
168             if ( replay_state->getIntValue() == 1 ) {
169                 // normal playback
170                 replay_time->setDoubleValue( replay_time->getDoubleValue()
171                                              + ( delta_time_sec
172                                                * fgGetInt("/sim/speed-up") ) );
173             } else if ( replay_state->getIntValue() == 2 ) {
174                 // paused playback (don't advance replay time)
175             }
176         }
177     } else {
178         // do nothing, fdm isn't inited yet
179     }
180
181     globals->get_model_mgr()->update(delta_time_sec);
182     globals->get_aircraft_model()->update(delta_time_sec);
183
184     // update the view angle
185     globals->get_viewmgr()->update(delta_time_sec);
186
187     // Update solar system
188     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
189                                   globals->get_time_params()->getLst(),
190                                   cur_fdm_state->get_Latitude() );
191
192 }
193
194
195 void fgInitTimeDepCalcs( void ) {
196     // noop for now
197 }
198
199
200 static const double alt_adjust_ft = 3.758099;
201 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
202
203
204 // What should we do when we have nothing else to do?  Let's get ready
205 // for the next move and update the display?
206 static void fgMainLoop( void ) {
207     int model_hz = fgGetInt("/sim/model-hz");
208
209     static const SGPropertyNode *longitude
210         = fgGetNode("/position/longitude-deg");
211     static const SGPropertyNode *latitude
212         = fgGetNode("/position/latitude-deg");
213     static const SGPropertyNode *altitude
214         = fgGetNode("/position/altitude-ft");
215     static const SGPropertyNode *clock_freeze
216         = fgGetNode("/sim/freeze/clock", true);
217     static const SGPropertyNode *cur_time_override
218         = fgGetNode("/sim/time/cur-time-override", true);
219
220     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
221
222     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
223
224     // Update the elapsed time.
225     static bool first_time = true;
226     if ( first_time ) {
227         last_time_stamp.stamp();
228         first_time = false;
229     }
230
231     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
232     if ( throttle_hz > 0.0 && scenery_loaded ) {
233         // optionally throttle the frame rate (to get consistant frame
234         // rates or reduce cpu usage.
235
236         double frame_us = 1000000.0 / throttle_hz;
237
238 #define FG_SLEEP_BASED_TIMING 1
239 #if defined(FG_SLEEP_BASED_TIMING)
240         // sleep based timing loop.
241         //
242         // Calling sleep, even usleep() on linux is less accurate than
243         // we like, but it does free up the cpu for other tasks during
244         // the sleep so it is desireable.  Because of the way sleep()
245         // is implimented in consumer operating systems like windows
246         // and linux, you almost always sleep a little longer than the
247         // requested amount.
248         // 
249         // To combat the problem of sleeping to long, we calculate the
250         // desired wait time and shorten it by 2000us (2ms) to avoid
251         // [hopefully] over-sleep'ing.  The 2ms value was arrived at
252         // via experimentation.  We follow this up at the end with a
253         // simple busy-wait loop to get the final pause timing exactly
254         // right.
255         // 
256         // Assuming we don't oversleep by more than 2000us, this
257         // should be a reasonable compromise between sleep based
258         // waiting, and busy waiting.
259
260         // sleep() will always overshoot by a bit so undersleep by
261         // 2000us in the hopes of never oversleeping.
262         frame_us -= 2000.0;
263         if ( frame_us < 0.0 ) {
264             frame_us = 0.0;
265         }
266         current_time_stamp.stamp();
267         /* Convert to ms */
268         double elapsed_us = current_time_stamp - last_time_stamp;
269         if ( elapsed_us < frame_us ) {
270             double requested_us = frame_us - elapsed_us;
271             ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
272         }
273 #endif
274
275         // busy wait timing loop.
276         // 
277         // This yields the most accurate timing.  If the previous
278         // ulMilliSecondSleep() call is ommitted this will peg the cpu
279         // (which is just fine if FG is the only app you care about.)
280         current_time_stamp.stamp();
281         while ( current_time_stamp - last_time_stamp < frame_us ) {
282             current_time_stamp.stamp();
283         }
284     } else {
285         // run as fast as the app will go
286         current_time_stamp.stamp();
287     }
288
289     real_delta_time_sec
290         = double(current_time_stamp - last_time_stamp) / 1000000.0;
291     // round the real time down to a multiple of 1/model-hz.
292     // this way all systems are updated the _same_ amount of dt.
293     {
294       static double rem = 0.0;
295       real_delta_time_sec += rem;
296       double hz = model_hz;
297       double nit = floor(real_delta_time_sec*hz);
298       rem = real_delta_time_sec - nit/hz;
299       real_delta_time_sec = nit/hz;
300     }
301
302
303     if (clock_freeze->getBoolValue() || !scenery_loaded) {
304         delta_time_sec = 0;
305     } else {
306         delta_time_sec = real_delta_time_sec;
307     }
308     last_time_stamp = current_time_stamp;
309     globals->inc_sim_time_sec( delta_time_sec );
310     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
311
312     // These are useful, especially for Nasal scripts.
313     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
314     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
315
316     static long remainder = 0;
317     long elapsed;
318 #ifdef FANCY_FRAME_COUNTER
319     int i;
320     double accum;
321 #else
322     static time_t last_time = 0;
323     static int frames = 0;
324 #endif // FANCY_FRAME_COUNTER
325
326     SGTime *t = globals->get_time_params();
327
328     globals->get_event_mgr()->update(delta_time_sec);
329
330     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
331     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
332
333 #if defined( ENABLE_PLIB_JOYSTICK )
334     // Read joystick and update control settings
335     // if ( fgGetString("/sim/control-mode") == "joystick" )
336     // {
337     //    fgJoystickRead();
338     // }
339 #endif
340
341     // Fix elevation.  I'm just sticking this here for now, it should
342     // probably move eventually
343
344     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
345            scenery.get_cur_elev(),
346            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
347            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
348
349     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
350            scenery.get_cur_elev(),
351            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
352            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
353
354     // cout << "Warp = " << globals->get_warp() << endl;
355
356     // update "time"
357     static bool last_clock_freeze = false;
358
359     if ( clock_freeze->getBoolValue() ) {
360         // clock freeze requested
361         if ( cur_time_override->getLongValue() == 0 ) {
362             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
363             globals->set_warp( 0 );
364         }
365     } else {
366         // no clock freeze requested
367         if ( last_clock_freeze == true ) {
368             // clock just unfroze, let's set warp as the difference
369             // between frozen time and current time so we don't get a
370             // time jump (and corresponding sky object and lighting
371             // jump.)
372             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
373             fgSetLong( "/sim/time/cur-time-override", 0 );
374         }
375         if ( globals->get_warp_delta() != 0 ) {
376             globals->inc_warp( globals->get_warp_delta() );
377         }
378     }
379
380     last_clock_freeze = clock_freeze->getBoolValue();
381
382     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
383                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
384                cur_time_override->getLongValue(),
385                globals->get_warp() );
386
387     if (globals->get_warp_delta() != 0) {
388         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
389         l->update( 0.5 );
390     }
391
392     // update magvar model
393     globals->get_mag()->update( longitude->getDoubleValue()
394                               * SGD_DEGREES_TO_RADIANS,
395                             latitude->getDoubleValue()
396                               * SGD_DEGREES_TO_RADIANS,
397                             altitude->getDoubleValue() * SG_FEET_TO_METER,
398                             globals->get_time_params()->getJD() );
399
400     // Get elapsed time (in usec) for this past frame
401     elapsed = fgGetTimeInterval();
402     SG_LOG( SG_ALL, SG_DEBUG, 
403             "Elapsed time interval is = " << elapsed 
404             << ", previous remainder is = " << remainder );
405
406     // Calculate frame rate average
407 #ifdef FANCY_FRAME_COUNTER
408     /* old fps calculation */
409     if ( elapsed > 0 ) {
410         double tmp;
411         accum = 0.0;
412         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
413             tmp = general.get_frame(i);
414             accum += tmp;
415             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
416             general.set_frame(i+1,tmp);
417         }
418         tmp = 1000000.0 / (float)elapsed;
419         general.set_frame(0,tmp);
420         // printf("frame[0] = %.2f\n", general.frames[0]);
421         accum += tmp;
422         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
423         // printf("ave = %.2f\n", general.frame_rate);
424     }
425 #else
426     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
427         general.set_frame_rate( frames );
428         fgSetInt("/sim/frame-rate", frames);
429         SG_LOG( SG_ALL, SG_DEBUG, 
430             "--> Frame rate is = " << general.get_frame_rate() );
431         frames = 0;
432     }
433     last_time = t->get_cur_time();
434     ++frames;
435 #endif
436
437     // Run ATC subsystem
438     if (fgGetBool("/sim/atc/enabled"))
439         globals->get_ATC_mgr()->update(delta_time_sec);
440
441     // Run the AI subsystem
442     if (fgGetBool("/sim/ai-traffic/enabled"))
443         globals->get_AI_mgr()->update(delta_time_sec);
444
445 #ifdef FG_MPLAYER_AS
446     // Update any multiplayer models
447     globals->get_multiplayer_rx_mgr()->Update();
448 #endif
449
450     // Run flight model
451
452     // Calculate model iterations needed for next frame
453     elapsed += remainder;
454
455     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
456     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
457     SG_LOG( SG_ALL, SG_DEBUG, 
458             "Model iterations needed = " << global_multi_loop
459             << ", new remainder = " << remainder );
460         
461     // chop max interations to something reasonable if the sim was
462     // delayed for an excesive amount of time
463     if ( global_multi_loop > 2.0 * model_hz ) {
464         global_multi_loop = (int)(2.0 * model_hz );
465         remainder = 0;
466     }
467
468     // flight model
469     if ( global_multi_loop > 0) {
470         // first run the flight model each frame until it is intialized
471         // then continue running each frame only after initial scenery load is complete.
472         fgUpdateTimeDepCalcs();
473     } else {
474         SG_LOG( SG_ALL, SG_DEBUG, 
475             "Elapsed time is zero ... we're zinging" );
476     }
477
478     // Do any I/O channel work that might need to be done
479     globals->get_io()->update( real_delta_time_sec );
480
481     // see if we need to load any deferred-load textures
482     globals->get_matlib()->load_next_deferred();
483
484     // Run audio scheduler
485 #ifdef ENABLE_AUDIO_SUPPORT
486     if ( globals->get_soundmgr()->is_working() ) {
487         globals->get_soundmgr()->update( delta_time_sec );
488     }
489 #endif
490
491     globals->get_subsystem_mgr()->update(delta_time_sec);
492
493     //
494     // Tile Manager updates - see if we need to load any new scenery tiles.
495     //   this code ties together the fdm, viewer and scenery classes...
496     //   we may want to move this to it's own class at some point
497     //
498     double visibility_meters = fgGetDouble("/environment/visibility-m");
499     FGViewer *current_view = globals->get_current_view();
500
501     // Let the scenery center follow the current view position with
502     // 30m increments.
503     //
504     // Having the scenery center near the view position will eliminate
505     // jitter of objects which are placed very near the view position
506     // and haveing it's center near that view position.
507     // So the 3d insruments of the aircraft will not jitter with this.
508     // 
509     // Following the view position exactly would introduce jitter of
510     // the scenery tiles (they would be from their center up to 10000m
511     // to the view and this will introduce roundoff too). By stepping
512     // at 30m incements the roundoff error of the scenery tiles is
513     // still present, but we will make exactly the same roundoff error
514     // at each frame until the center is switched to a new
515     // position. This roundoff is still visible but you will most
516     // propably not notice.
517     double *vp = globals->get_current_view()->get_absolute_view_pos();
518     Point3D cntr(vp[0], vp[1], vp[2]);
519     if (30.0*30.0 < cntr.distance3Dsquared(globals->get_scenery()->get_center())) {
520       globals->get_scenery()->set_next_center( cntr );
521     }
522
523     // get the location data for the primary FDM (now hardcoded to ac model)...
524     SGLocation *acmodel_loc = NULL;
525     acmodel_loc = (SGLocation *)globals->
526         get_aircraft_model()->get3DModel()->getSGLocation();
527
528     // update tile manager for FDM...
529     // ...only if location is different than the current-view location
530     // (to avoid duplicating effort)
531     if( !fgGetBool("/sim/current-view/config/from-model") ) {
532         if( acmodel_loc != NULL ) {
533             globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
534                                                      visibility_meters );
535             globals->get_tile_mgr()->
536                 update( acmodel_loc, visibility_meters,
537                         acmodel_loc->
538                         get_absolute_view_pos(globals->
539                                               get_scenery()->get_center()) );
540             globals->get_scenery()->set_center( cntr );
541
542             // save results of update in SGLocation for fdm...
543             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
544                 acmodel_loc->
545                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
546                 fgSetDouble("/position/ground-elev-m",
547                             globals->get_scenery()->get_cur_elev());
548             }
549             acmodel_loc->
550                 set_tile_center( globals->get_scenery()->get_next_center() );
551         }
552     }
553
554     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
555                                              visibility_meters );
556     // update tile manager for view...
557     // IMPORTANT!!! the tilemgr update for view location _must_ be
558     // done last after the FDM's until all of Flight Gear code
559     // references the viewer's location for elevation instead of the
560     // "scenery's" current elevation.
561     SGLocation *view_location = globals->get_current_view()->getSGLocation();
562     globals->get_tile_mgr()->update( view_location, visibility_meters,
563                                      current_view->get_absolute_view_pos() );
564     globals->get_scenery()->set_center( cntr );
565     // save results of update in SGLocation for fdm...
566     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
567         current_view->getSGLocation()->
568             set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
569     }
570     current_view->getSGLocation()->
571         set_tile_center( globals->get_scenery()->get_next_center() );
572
573 #ifdef ENABLE_AUDIO_SUPPORT
574     // Right now we make a simplifying assumption that the primary
575     // aircraft is the source of all sounds and that all sounds are
576     // positioned relative to the current view position.
577
578     static sgVec3 last_pos_offset;
579
580     // set positional offset for sources
581     sgVec3 source_pos_offset;
582     sgSubVec3( source_pos_offset,
583                view_location->get_view_pos(), acmodel_loc->get_view_pos() );
584     // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
585     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
586
587     // set the velocity
588     sgVec3 source_vel;
589     sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
590     sgScaleVec3( source_vel, delta_time_sec );
591     sgCopyVec3( last_pos_offset, source_pos_offset );
592     // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
593     globals->get_soundmgr()->set_source_vel_all( source_vel );
594
595     // Right now we make a simplifying assumption that the listener is
596     // always positioned at the origin.
597     sgVec3 listener_pos;
598     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
599     // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
600     globals->get_soundmgr()->set_listener_pos( listener_pos );
601 #endif
602
603     // If fdm location is same as viewer's then we didn't do the
604     // update for fdm location above so we need to save the viewer
605     // results in the fdm SGLocation as well...
606     if( fgGetBool("/sim/current-view/config/from-model") ) {
607         if( acmodel_loc != 0 ) {
608             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
609                 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
610                                              get_cur_elev() );
611                 fgSetDouble("/position/ground-elev-m",
612                             globals->get_scenery()->get_cur_elev());
613             }
614             acmodel_loc->set_tile_center( globals->get_scenery()->
615                                           get_next_center() );
616         }
617     }
618
619     // END Tile Manager udpates
620
621     if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
622         fgSetBool("sim/sceneryloaded",true);
623         fgSetFloat("/sim/sound/volume", init_volume);
624         globals->get_soundmgr()->set_volume(init_volume);
625     }
626
627     if (fgGetBool("/sim/rendering/specular-highlight")) {
628         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
629         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
630     } else {
631         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
632         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
633     }
634
635     fgRequestRedraw();
636
637     SG_LOG( SG_ALL, SG_DEBUG, "" );
638 }
639
640
641 // This is the top level master main function that is registered as
642 // our idle funciton
643
644 // The first few passes take care of initialization things (a couple
645 // per pass) and once everything has been initialized fgMainLoop from
646 // then on.
647
648 static void fgIdleFunction ( void ) {
649     if ( idle_state == 0 ) {
650         idle_state++;
651         fgSplashProgress("setting up scenegraph & user interface");
652
653
654     } else if ( idle_state == 1 ) {
655         idle_state++;
656         // This seems to be the absolute earliest in the init sequence
657         // that these calls will return valid info.  Too bad it's after
658         // we've already created and sized out window. :-(
659         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
660         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
661         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
662         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
663
664         GLint tmp;
665         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
666         general.set_glMaxTexSize( tmp );
667         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
668
669         glGetIntegerv( GL_DEPTH_BITS, &tmp );
670         general.set_glDepthBits( tmp );
671         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
672
673         // Initialize ssg (from plib).  Needs to come before we do any
674         // other ssg stuff, but after opengl has been initialized.
675         ssgInit();
676
677         // Initialize the user interface (we need to do this before
678         // passing off control to the OS main loop and before
679          // fgInitGeneral to get our fonts !!!
680         guiInit();
681         fgSplashProgress("reading aircraft list");
682
683
684     } else if ( idle_state == 2 ) {
685         idle_state++;
686         // Read the list of available aircrafts
687         fgReadAircraft();
688
689 #ifdef GL_EXT_texture_lod_bias
690         glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
691 #endif
692
693         // get the address of our OpenGL extensions
694         if ( fgGetBool("/sim/rendering/distance-attenuation") ) {
695             if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
696                 glPointParameterIsSupported = true;
697                 glPointParameterfPtr = (glPointParameterfProc)
698                                        SGLookupFunction("glPointParameterfEXT");
699                 glPointParameterfvPtr = (glPointParameterfvProc)
700                                         SGLookupFunction("glPointParameterfvEXT");
701
702             } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
703                 glPointParameterIsSupported = true;
704                 glPointParameterfPtr = (glPointParameterfProc)
705                                        SGLookupFunction("glPointParameterfARB");
706                 glPointParameterfvPtr = (glPointParameterfvProc)
707                                         SGLookupFunction("glPointParameterfvARB");
708             } else
709                 glPointParameterIsSupported = false;
710         }
711         fgSplashProgress("reading airport & navigation data");
712
713
714     } else if ( idle_state == 3 ) {
715         idle_state++;
716         fgInitNav();
717         fgSplashProgress("setting up scenery");
718
719
720     } else if ( idle_state == 4 ) {
721         idle_state++;
722         // based on the requested presets, calculate the true starting
723         // lon, lat
724         fgInitPosition();
725
726         SGTime *t = fgInitTime();
727         globals->set_time_params( t );
728
729         // Do some quick general initializations
730         if( !fgInitGeneral()) {
731             SG_LOG( SG_GENERAL, SG_ALERT, 
732                 "General initializations failed ..." );
733             exit(-1);
734         }
735
736         ////////////////////////////////////////////////////////////////////
737         // Initialize the property-based built-in commands
738         ////////////////////////////////////////////////////////////////////
739         fgInitCommands();
740
741
742         ////////////////////////////////////////////////////////////////////
743         // Initialize the material manager
744         ////////////////////////////////////////////////////////////////////
745         globals->set_matlib( new SGMaterialLib );
746         globals->set_model_lib(new SGModelLib);
747
748
749         ////////////////////////////////////////////////////////////////////
750         // Initialize the TG scenery subsystem.
751         ////////////////////////////////////////////////////////////////////
752         globals->set_scenery( new FGScenery );
753         globals->get_scenery()->init();
754         globals->get_scenery()->bind();
755         globals->set_tile_mgr( new FGTileMgr );
756
757
758         ////////////////////////////////////////////////////////////////////
759         // Initialize the general model subsystem.
760         ////////////////////////////////////////////////////////////////////
761         globals->set_model_mgr(new FGModelMgr);
762         globals->get_model_mgr()->init();
763         globals->get_model_mgr()->bind();
764         fgSplashProgress("loading aircraft");
765
766
767     } else if ( idle_state == 5 ) {
768         idle_state++;
769         ////////////////////////////////////////////////////////////////////
770         // Initialize the 3D aircraft model subsystem (has a dependency on
771         // the scenery subsystem.)
772         ////////////////////////////////////////////////////////////////////
773         globals->set_aircraft_model(new FGAircraftModel);
774         globals->get_aircraft_model()->init();
775         globals->get_aircraft_model()->bind();
776
777         ////////////////////////////////////////////////////////////////////
778         // Initialize the view manager subsystem.
779         ////////////////////////////////////////////////////////////////////
780         FGViewMgr *viewmgr = new FGViewMgr;
781         globals->set_viewmgr( viewmgr );
782         viewmgr->init();
783         viewmgr->bind();
784         fgSplashProgress("generating sky elements");
785
786
787     } else if ( idle_state == 6 ) {
788         idle_state++;
789         // Initialize the sky
790         SGPath ephem_data_path( globals->get_fg_root() );
791         ephem_data_path.append( "Astro" );
792         SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
793         ephem->update( globals->get_time_params()->getMjd(),
794                        globals->get_time_params()->getLst(),
795                        0.0 );
796         globals->set_ephem( ephem );
797
798         // TODO: move to environment mgr
799         thesky = new SGSky;
800         SGPath texture_path(globals->get_fg_root());
801         texture_path.append("Textures");
802         texture_path.append("Sky");
803         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
804             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
805             thesky->add_cloud_layer(layer);
806         }
807
808         SGPath sky_tex_path( globals->get_fg_root() );
809         sky_tex_path.append( "Textures" );
810         sky_tex_path.append( "Sky" );
811         thesky->texture_path( sky_tex_path.str() );
812
813         // The sun and moon diameters are scaled down numbers of the
814         // actual diameters. This was needed to fit bot the sun and the
815         // moon within the distance to the far clip plane.
816         // Moon diameter:    3,476 kilometers
817         // Sun diameter: 1,390,000 kilometers
818         thesky->build( 80000.0, 80000.0,
819                        463.3, 361.8,
820                        globals->get_ephem()->getNumPlanets(), 
821                        globals->get_ephem()->getPlanets(),
822                        globals->get_ephem()->getNumStars(),
823                        globals->get_ephem()->getStars() );
824
825         // Initialize MagVar model
826         SGMagVar *magvar = new SGMagVar();
827         globals->set_mag( magvar );
828
829
830                                     // kludge to initialize mag compass
831                                     // (should only be done for in-flight
832                                     // startup)
833         // update magvar model
834         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
835                                     * SGD_DEGREES_TO_RADIANS,
836                                     fgGetDouble("/position/latitude-deg")
837                                     * SGD_DEGREES_TO_RADIANS,
838                                     fgGetDouble("/position/altitude-ft")
839                                     * SG_FEET_TO_METER,
840                                     globals->get_time_params()->getJD() );
841         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
842         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
843
844         // airport = new ssgBranch;
845         // airport->setName( "Airport Lighting" );
846         // lighting->addKid( airport );
847
848         // build our custom render states
849         globals->get_renderer()->build_states();
850         fgSplashProgress("initializing subsystems");
851
852
853     } else if ( idle_state == 7 ) {
854         idle_state++;
855         // Initialize audio support
856 #ifdef ENABLE_AUDIO_SUPPORT
857
858         // Start the intro music
859         if ( fgGetBool("/sim/startup/intro-music") ) {
860             SGPath mp3file( globals->get_fg_root() );
861             mp3file.append( "Sounds/intro.mp3" );
862
863             SG_LOG( SG_GENERAL, SG_INFO, 
864                 "Starting intro music: " << mp3file.str() );
865
866 #if defined( __CYGWIN__ )
867             string command = "start /m `cygpath -w " + mp3file.str() + "`";
868 #elif defined( WIN32 )
869             string command = "start /m " + mp3file.str();
870 #else
871             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
872 #endif
873
874             system ( command.c_str() );
875         }
876 #endif
877
878         // These are a few miscellaneous things that aren't really
879         // "subsystems" but still need to be initialized.
880
881 #ifdef USE_GLIDE
882         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
883             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
884         }
885 #endif
886
887         // This is the top level init routine which calls all the
888         // other subsystem initialization routines.  If you are adding
889         // a subsystem to flightgear, its initialization call should
890         // located in this routine.
891         if( !fgInitSubsystems()) {
892             SG_LOG( SG_GENERAL, SG_ALERT,
893                 "Subsystem initializations failed ..." );
894             exit(-1);
895         }
896         fgSplashProgress("setting up time & renderer");
897
898
899     } else if ( idle_state == 8 ) {
900         idle_state = 1000;
901         // Initialize the time offset (warp) after fgInitSubsystem
902         // (which initializes the lighting interpolation tables.)
903         fgInitTimeOffset();
904
905         // setup OpenGL view parameters
906         globals->get_renderer()->init();
907
908         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
909         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
910                                          fgGetInt("/sim/startup/ysize") );
911
912         fgSplashProgress("loading scenery objects");
913
914     }
915
916     if ( idle_state == 1000 ) {
917         // We've finished all our initialization steps, from now on we
918         // run the main loop.
919         fgSetBool("sim/sceneryloaded", false);
920         fgRegisterIdleHandler( fgMainLoop );
921     }
922 }
923
924
925 // Main top level initialization
926 bool fgMainInit( int argc, char **argv ) {
927
928 #if defined( macintosh )
929     freopen ("stdout.txt", "w", stdout );
930     freopen ("stderr.txt", "w", stderr );
931     argc = ccommand( &argv );
932 #endif
933
934     // set default log levels
935     sglog().setLogLevels( SG_ALL, SG_ALERT );
936
937     string version;
938 #ifdef FLIGHTGEAR_VERSION
939     version = FLIGHTGEAR_VERSION;
940 #else
941     version = "unknown version";
942 #endif
943     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
944             << version );
945     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
946
947     // Allocate global data structures.  This needs to happen before
948     // we parse command line options
949
950     globals = new FGGlobals;
951
952     // seed the random number generater
953     sg_srandom_time();
954
955     FGControls *controls = new FGControls;
956     globals->set_controls( controls );
957
958     string_list *col = new string_list;
959     globals->set_channel_options_list( col );
960
961     // Scan the config file(s) and command line options to see if
962     // fg_root was specified (ignore all other options for now)
963     fgInitFGRoot(argc, argv);
964
965     // Check for the correct base package version
966     static char required_version[] = "0.9.8";
967     string base_version = fgBasePackageVersion();
968     if ( !(base_version == required_version) ) {
969         // tell the operator how to use this application
970
971         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
972         cerr << endl << "Base package check failed ... " \
973              << "Found version " << base_version << " at: " \
974              << globals->get_fg_root() << endl;
975         cerr << "Please upgrade to version: " << required_version << endl;
976 #ifdef _MSC_VER
977         cerr << "Hit a key to continue..." << endl;
978         cin.get();
979 #endif
980         exit(-1);
981     }
982
983     sgUseDisplayList = fgGetBool( "/sim/rendering/use-display-list", true );
984
985     // Initialize the Aircraft directory to "" (UIUC)
986     aircraft_dir = "";
987
988     // Load the configuration parameters.  (Command line options
989     // overrides config file options.  Config file options override
990     // defaults.)
991     if ( !fgInitConfig(argc, argv) ) {
992         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
993         exit(-1);
994     }
995
996     // Initialize the Window/Graphics environment.
997 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
998     // Mac OS X command line ("non-bundle") applications call this
999     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
1000     // feel free to add comments...
1001     fgOSInit(&argc, argv);
1002     _bootstrap_OSInit++;
1003 #endif
1004
1005     fgRegisterWindowResizeHandler( &FGRenderer::resize );
1006     fgRegisterIdleHandler( &fgIdleFunction );
1007     fgRegisterDrawHandler( &FGRenderer::update );
1008
1009 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1010     bool get_stencil_buffer = true;
1011 #else
1012     bool get_stencil_buffer = false;
1013 #endif
1014
1015     // Initialize plib net interface
1016     netInit( &argc, argv );
1017
1018     // Clouds3D requires an alpha channel
1019     // clouds may require stencil buffer
1020     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1021                     fgGetInt("/sim/startup/ysize"),
1022                     fgGetInt("/sim/rendering/bits-per-pixel"),
1023                     fgGetBool("/sim/rendering/clouds3d"),
1024                     get_stencil_buffer,
1025                     fgGetBool("/sim/startup/fullscreen") );
1026
1027     // Initialize the splash screen right away
1028     fntInit();
1029     fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1030
1031     // pass control off to the master event handler
1032     fgOSMainLoop();
1033
1034     // we never actually get here ... but to avoid compiler warnings,
1035     // etc.
1036     return false;
1037 }
1038
1039