]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
56c90562a7bb47cc5f260235da8793108f95a955
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson for OpenGL, started May 1997.
4 //
5 // Copyright (C) 1997 - 1999  Curtis L. Olson  - curt@flightgear.org
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 #define MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
25
26
27 #ifdef HAVE_CONFIG_H
28 #  include <config.h>
29 #endif
30
31 #ifdef FG_MATH_EXCEPTION_CLASH
32 #  include <math.h>
33 #endif
34
35 #ifdef HAVE_WINDOWS_H
36 #  include <windows.h>                     
37 #  include <float.h>                    
38 #endif
39
40 #include <GL/glut.h>
41 #include <simgear/xgl/xgl.h>
42
43 #include <stdio.h>
44 #include <string.h>
45 #include <string>
46
47 #ifdef HAVE_STDLIB_H
48 #   include <stdlib.h>
49 #endif
50
51 #ifdef HAVE_SYS_STAT_H
52 #  include <sys/stat.h> /* for stat() */
53 #endif
54
55 #ifdef HAVE_UNISTD_H
56 #  include <unistd.h>    /* for stat() */
57 #endif
58
59 #include <plib/pu.h>                    // plib include
60 #include <plib/ssg.h>           // plib include
61
62 #ifdef ENABLE_AUDIO_SUPPORT
63 #  include <plib/sl.h>          // plib include
64 #  include <plib/sm.h>          // plib include
65 #endif
66
67 #include <simgear/constants.h>  // for VERSION
68 #include <simgear/debug/logstream.hxx>
69 #include <simgear/math/fg_geodesy.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/fg_random.h>
72 #include <simgear/misc/fgpath.hxx>
73
74 #include <Include/general.hxx>
75
76 #include <Aircraft/aircraft.hxx>
77 #include <Ephemeris/ephemeris.hxx>
78
79 #include <Autopilot/autopilot.hxx>
80 #include <Cockpit/cockpit.hxx>
81 #include <Cockpit/steam.hxx>
82 #include <GUI/gui.h>
83 #include <Joystick/joystick.hxx>
84 #ifdef FG_NETWORK_OLK
85 #include <NetworkOLK/network.h>
86 #endif
87 #include <Objects/materialmgr.hxx>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Sky/sky.hxx>
91 #include <Time/event.hxx>
92 #include <Time/fg_time.hxx>
93 #include <Time/fg_timer.hxx>
94 #include <Time/sunpos.hxx>
95
96 #ifndef FG_OLD_WEATHER
97 #  include <WeatherCM/FGLocalWeatherDatabase.h>
98 #else
99 #  include <Weather/weather.hxx>
100 #endif
101
102 #include "fg_init.hxx"
103 #include "fg_io.hxx"
104 #include "keyboard.hxx"
105 #include "options.hxx"
106 #include "splash.hxx"
107 #include "views.hxx"
108
109
110 // -dw- use custom sioux settings so I can see output window
111 #ifdef MACOS
112 #  ifndef FG_NDEBUG
113 #    include <sioux.h> // settings for output window
114 #  endif
115 #  include <console.h>
116 #endif
117
118
119 // This is a record containing a bit of global housekeeping information
120 FGGeneral general;
121
122 // Specify our current idle function state.  This is used to run all
123 // our initializations out of the glutIdleLoop() so that we can get a
124 // splash screen up and running right away.
125 static int idle_state = 0;
126 static int global_multi_loop;
127
128 // Another hack
129 int use_signals = 0;
130
131 // Global structures for the Audio library
132 #ifdef ENABLE_AUDIO_SUPPORT
133 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
134 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
135 slScheduler *audio_sched;
136 smMixer *audio_mixer;
137 slSample *s1;
138 slSample *s2;
139 #endif
140
141
142 // ssg variables
143 ssgRoot *scene = NULL;
144 ssgBranch *terrain = NULL;
145 ssgSelector *penguin_sel = NULL;
146 ssgTransform *penguin_pos = NULL;
147
148 #ifdef FG_NETWORK_OLK
149 ssgSelector *fgd_sel = NULL;
150 ssgTransform *fgd_pos = NULL;
151 //sgMat4 sgTUX;
152 #endif
153
154 // current fdm/position used for view
155 FGInterface cur_view_fdm;
156
157 // Sky structures
158 FGEphemeris *ephem;
159 SGSky *thesky;
160
161 // hack
162 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
163 {
164   {  1.0f,  0.0f,  0.0f,  0.0f },
165   {  0.0f,  0.0f, -1.0f,  0.0f },
166   {  0.0f,  1.0f,  0.0f,  0.0f },
167   {  0.0f,  0.0f,  0.0f,  1.0f }
168 } ;
169
170 // The following defines flight gear options. Because glutlib will also
171 // want to parse its own options, those options must not be included here
172 // or they will get parsed by the main program option parser. Hence case
173 // is significant for any option added that might be in conflict with
174 // glutlib's parser.
175 //
176 // glutlib parses for:
177 //    -display
178 //    -direct   (invalid in Win32)
179 //    -geometry
180 //    -gldebug
181 //    -iconized
182 //    -indirect (invalid in Win32)
183 //    -synce
184 //
185 // Note that glutlib depends upon strings while this program's
186 // option parser wants only initial characters followed by numbers
187 // or pathnames.
188 //
189
190
191 ssgSimpleState *default_state;
192 ssgSimpleState *hud_and_panel;
193 ssgSimpleState *menus;
194
195 void fgBuildRenderStates( void ) {
196     default_state = new ssgSimpleState;
197     default_state->disable( GL_TEXTURE_2D );
198     default_state->enable( GL_CULL_FACE );
199     default_state->disable( GL_COLOR_MATERIAL );
200     default_state->disable( GL_BLEND );
201     default_state->disable( GL_ALPHA_TEST );
202     default_state->disable( GL_LIGHTING );
203     default_state->setMaterial( GL_AMBIENT_AND_DIFFUSE, 1.0, 1.0, 1.0, 1.0 );
204
205     hud_and_panel = new ssgSimpleState;
206     hud_and_panel->disable( GL_CULL_FACE );
207     hud_and_panel->disable( GL_TEXTURE_2D );
208     hud_and_panel->disable( GL_LIGHTING );
209
210     menus = new ssgSimpleState;
211     menus->disable( GL_CULL_FACE );
212     menus->disable( GL_TEXTURE_2D );
213     menus->enable( GL_BLEND );
214 }
215
216
217 // fgInitVisuals() -- Initialize various GL/view parameters
218 void fgInitVisuals( void ) {
219     fgLIGHT *l;
220
221     l = &cur_light_params;
222
223 #ifndef GLUT_WRONG_VERSION
224     // Go full screen if requested ...
225     if ( current_options.get_fullscreen() ) {
226         glutFullScreen();
227     }
228 #endif
229
230     // If enabled, normal vectors specified with glNormal are scaled
231     // to unit length after transformation.  See glNormal.
232     // glEnable( GL_NORMALIZE );
233
234     glEnable( GL_LIGHTING );
235     glEnable( GL_LIGHT0 );
236     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
237
238     sgVec3 sunpos;
239     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
240     ssgGetLight( 0 ) -> setPosition( sunpos );
241
242     // glFogi (GL_FOG_MODE, GL_LINEAR);
243     glFogi (GL_FOG_MODE, GL_EXP2);
244     if ( (current_options.get_fog() == 1) || 
245          (current_options.get_shading() == 0) ) {
246         // if fastest fog requested, or if flat shading force fastest
247         glHint ( GL_FOG_HINT, GL_FASTEST );
248     } else if ( current_options.get_fog() == 2 ) {
249         glHint ( GL_FOG_HINT, GL_NICEST );
250     }
251     if ( current_options.get_wireframe() ) {
252         // draw wire frame
253         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
254     }
255
256     // This is the default anyways, but it can't hurt
257     glFrontFace ( GL_CCW );
258
259     // Just testing ...
260     // glEnable(GL_POINT_SMOOTH);
261     // glEnable(GL_LINE_SMOOTH);
262     // glEnable(GL_POLYGON_SMOOTH);      
263 }
264
265
266 // Update all Visuals (redraws anything graphics related)
267 void fgRenderFrame( void ) {
268     fgLIGHT *l = &cur_light_params;
269     FGTime *t = FGTime::cur_time_params;
270     // FGView *v = &current_view;
271     static double last_visibility = -9999;
272     static bool in_puff = false;
273     static double puff_length = 0;
274     static double puff_progression = 0;
275     const double ramp_up = 0.15;
276     const double ramp_down = 0.15;
277
278     double angle;
279     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
280     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
281     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
282     // GLfloat mat_shininess[] = { 10.0 };
283     GLbitfield clear_mask;
284     
285     if ( idle_state != 1000 ) {
286         // still initializing, draw the splash screen
287         if ( current_options.get_splash_screen() == 1 ) {
288             fgSplashUpdate(0.0);
289         }
290     } else {
291         // idle_state is now 1000 meaning we've finished all our
292         // initializations and are running the main loop, so this will
293         // now work without seg faulting the system.
294
295         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
296         //        FG_Altitude * FEET_TO_METER);
297     
298         // this is just a temporary hack, to make me understand Pui
299         // timerText -> setLabel (ctime (&t->cur_time));
300         // end of hack
301
302         // update view volume parameters
303         // cout << "before pilot_view update" << endl;
304         pilot_view.UpdateViewParams(*cur_fdm_state);
305         // cout << "after pilot_view update" << endl;
306         current_view.UpdateViewParams(cur_view_fdm);
307
308         // set the sun position
309         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
310
311         clear_mask = GL_DEPTH_BUFFER_BIT;
312         if ( current_options.get_wireframe() ) {
313             clear_mask |= GL_COLOR_BUFFER_BIT;
314         }
315         if ( current_options.get_panel_status() ) {
316             // we can't clear the screen when the panel is active
317         } else if ( current_options.get_skyblend() ) {
318             if ( current_options.get_textures() ) {
319                 // glClearColor(black[0], black[1], black[2], black[3]);
320                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
321                              l->adj_fog_color[2], l->adj_fog_color[3]);
322                 clear_mask |= GL_COLOR_BUFFER_BIT;
323             }
324         } else {
325             glClearColor(l->sky_color[0], l->sky_color[1], 
326                          l->sky_color[2], l->sky_color[3]);
327             clear_mask |= GL_COLOR_BUFFER_BIT;
328         }
329         glClear( clear_mask );
330
331         // Tell GL we are switching to model view parameters
332
333         // I really should create a derived ssg node or use a call
334         // back or something so that I can draw the sky within the
335         // ssgCullandDraw() function, but for now I just mimic what
336         // ssg does to set up the model view matrix
337         glMatrixMode(GL_MODELVIEW);
338         glLoadIdentity();
339         ssgSetCamera( current_view.VIEW );
340
341         /*
342         sgMat4 vm_tmp, view_mat;
343         sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
344         sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
345         sgPreMultMat4( view_mat, vm_tmp ) ;
346         glLoadMatrixf( (float *)view_mat );
347         */
348
349         // set the opengl state to known default values
350         default_state->force();
351
352         // draw sky dome
353         if ( current_options.get_skyblend() ) {
354             sgVec3 view_pos;
355             sgSetVec3( view_pos,
356                        current_view.get_view_pos().x(),
357                        current_view.get_view_pos().y(),
358                        current_view.get_view_pos().z() );
359
360             sgVec3 zero_elev;
361             sgSetVec3( zero_elev,
362                        current_view.get_cur_zero_elev().x(),
363                        current_view.get_cur_zero_elev().y(),
364                        current_view.get_cur_zero_elev().z() );
365
366             /* cout << "thesky->repaint() sky_color = "
367                  << cur_light_params.sky_color[0] << " "
368                  << cur_light_params.sky_color[1] << " "
369                  << cur_light_params.sky_color[2] << " "
370                  << cur_light_params.sky_color[3] << endl;
371             cout << "    fog = "
372                  << cur_light_params.fog_color[0] << " "
373                  << cur_light_params.fog_color[1] << " "
374                  << cur_light_params.fog_color[2] << " "
375                  << cur_light_params.fog_color[3] << endl;
376             cout << "    sun_angle = " << cur_light_params.sun_angle
377                  << "    moon_angle = " << cur_light_params.moon_angle
378                  << endl; */
379             thesky->repaint( cur_light_params.sky_color,
380                              cur_light_params.adj_fog_color,
381                              cur_light_params.sun_angle,
382                              cur_light_params.moon_angle,
383                              ephem->getNumPlanets(), ephem->getPlanets(),
384                              ephem->getNumStars(), ephem->getStars() );
385  
386             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
387                  << view_pos[1] << " " << view_pos[2] << endl;
388             cout << "    zero_elev = " << zero_elev[0] << " "
389                  << zero_elev[1] << " " << zero_elev[2]
390                  << " lon = " << cur_fdm_state->get_Longitude()
391                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
392             cout << "    sun_rot = " << cur_light_params.sun_rotation
393                  << " gst = " << FGTime::cur_time_params->getGst() << endl;
394             cout << "    sun ra = " << ephem->getSunRightAscension()
395                  << " sun dec = " << ephem->getSunDeclination() 
396                  << " moon ra = " << ephem->getMoonRightAscension()
397                  << " moon dec = " << ephem->getMoonDeclination() << endl; */
398
399             thesky->reposition( view_pos, zero_elev, 
400                                 cur_fdm_state->get_Longitude(),
401                                 cur_fdm_state->get_Latitude(),
402                                 cur_light_params.sun_rotation,
403                                 FGTime::cur_time_params->getGst(),
404                                 ephem->getSunRightAscension(),
405                                 ephem->getSunDeclination(), 50000.0,
406                                 ephem->getMoonRightAscension(),
407                                 ephem->getMoonDeclination(), 50000.0 );
408         }
409
410         glEnable( GL_DEPTH_TEST );
411         if ( current_options.get_fog() > 0 ) {
412             glEnable( GL_FOG );
413             glFogi( GL_FOG_MODE, GL_EXP2 );
414             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
415         }
416
417         // update fog params if visibility has changed
418 #ifndef FG_OLD_WEATHER
419         double cur_visibility = WeatherDatabase->getWeatherVisibility();
420 #else
421         double cur_visibility = current_weather.get_visibility();
422 #endif
423         double actual_visibility = cur_visibility;
424
425         if ( current_options.get_clouds() ) {
426             double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
427                                 current_options.get_clouds_asl() );
428             // cout << "altitude diff = " << diff << endl;
429             if ( diff < 75 ) {
430                 if ( ! in_puff ) {
431                     // calc chance of entering cloud puff
432                     double rnd = fg_random();
433                     double chance = rnd * rnd * rnd;
434                     if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
435                         in_puff = true;
436                         do {
437                             puff_length = fg_random() * 2.0; // up to 2 seconds
438                         } while ( puff_length <= 0.0 );
439                         puff_progression = 0.0;
440                     }
441                 }
442
443                 actual_visibility = cur_visibility * (diff - 25) / 50.0;
444
445                 if ( in_puff ) {
446                     // modify actual_visibility based on puff envelope
447
448                     if ( puff_progression <= ramp_up ) {
449                         double x = FG_PI_2 * puff_progression / ramp_up;
450                         double factor = 1.0 - sin( x );
451                         actual_visibility = actual_visibility * factor;
452                     } else if ( puff_progression >= ramp_up + puff_length ) {
453                         double x = FG_PI_2 * 
454                             (puff_progression - (ramp_up + puff_length)) /
455                             ramp_down;
456                         double factor = sin( x );
457                         actual_visibility = actual_visibility * factor;
458                     } else {
459                         actual_visibility = 0.0;
460                     }
461
462                     /* cout << "len = " << puff_length
463                          << "  x = " << x 
464                          << "  factor = " << factor
465                          << "  actual_visibility = " << actual_visibility 
466                          << endl; */
467
468                     puff_progression += ( global_multi_loop * 
469                                           current_options.get_speed_up() ) /
470                         (double)current_options.get_model_hz();
471
472                     /* cout << "gml = " << global_multi_loop 
473                          << "  speed up = " << current_options.get_speed_up()
474                          << "  hz = " << current_options.get_model_hz() << endl;
475                          */ 
476
477                     if ( puff_progression > puff_length + ramp_up + ramp_down) {
478                         in_puff = false; 
479                     }
480                 }
481
482                 // never let visibility drop below zero
483                 if ( actual_visibility < 0 ) {
484                     actual_visibility = 0;
485                 }
486             }
487         }
488
489         // cout << "actual visibility = " << actual_visibility << endl;
490
491         if ( actual_visibility != last_visibility ) {
492             last_visibility = actual_visibility;
493
494             // cout << "----> updating fog params" << endl;
495                 
496             GLfloat fog_exp_density;
497             GLfloat fog_exp2_density;
498     
499             // for GL_FOG_EXP
500             fog_exp_density = -log(0.01 / actual_visibility);
501     
502             // for GL_FOG_EXP2
503             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
504     
505             // Set correct opengl fog density
506             glFogf (GL_FOG_DENSITY, fog_exp2_density);
507         }
508  
509         // set lighting parameters
510         glLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
511         glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
512         // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
513
514         // texture parameters
515         // glEnable( GL_TEXTURE_2D );
516         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
517         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
518         // set base color (I don't think this is doing anything here)
519         // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
520         //  (GL_FRONT, GL_DIFFUSE, white);
521         // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
522         // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
523
524         sgVec3 sunpos;
525         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
526         ssgGetLight( 0 ) -> setPosition( sunpos );
527
528         // glMatrixMode( GL_PROJECTION );
529         // glLoadIdentity();
530         float fov = current_options.get_fov();
531         ssgSetFOV(fov * current_view.get_win_ratio(), fov);
532
533         double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
534             - scenery.cur_elev;
535
536         // FG_LOG( FG_ALL, FG_INFO, "visibility is " 
537         //         << current_weather.get_visibility() );
538             
539         if ( agl > 10.0 ) {
540             ssgSetNearFar( 10.0f, 120000.0f );
541         } else {
542             ssgSetNearFar( 0.5f, 120000.0f );
543         }
544
545         if ( current_options.get_view_mode() == 
546              fgOPTIONS::FG_VIEW_PILOT )
547         {
548             // disable TuX
549             penguin_sel->select(0);
550         } else if ( current_options.get_view_mode() == 
551                     fgOPTIONS::FG_VIEW_FOLLOW )
552         {
553             // select view matrix from front of view matrix queue
554             // FGMat4Wrapper tmp = current_view.follow.front();
555             // sgCopyMat4( sgVIEW, tmp.m );
556
557             // enable TuX and set up his position and orientation
558             penguin_sel->select(1);
559
560             sgMat4 sgTRANS;
561             sgMakeTransMat4( sgTRANS, 
562                              pilot_view.view_pos.x(),
563                              pilot_view.view_pos.y(),
564                              pilot_view.view_pos.z() );
565
566             sgVec3 ownship_up;
567             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
568
569             sgMat4 sgROT;
570             sgMakeRotMat4( sgROT, -90.0, ownship_up );
571
572             sgMat4 sgTMP;
573             sgMat4 sgTUX;
574             sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
575             sgMultMat4( sgTUX, sgTMP, sgTRANS );
576         
577             sgCoord tuxpos;
578             sgSetCoord( &tuxpos, sgTUX );
579             penguin_pos->setTransform( &tuxpos );
580         }
581
582 # ifdef FG_NETWORK_OLK
583         if ( current_options.get_network_olk() ) {
584             sgCoord fgdpos;
585             other = head->next;             /* put listpointer to start  */
586             while ( other != tail) {        /* display all except myself */
587                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
588                     other->fgd_sel->select(1);
589                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
590                     other->fgd_pos->setTransform( &fgdpos );
591                 }
592                 other = other->next;
593             }
594
595             // fgd_sel->select(1);
596             // sgCopyMat4( sgTUX, current_view.sgVIEW);
597             // sgCoord fgdpos;
598             // sgSetCoord( &fgdpos, sgFGD_VIEW );
599             // fgd_pos->setTransform( &fgdpos);
600         }
601 # endif
602
603         // ssgSetCamera( current_view.VIEW );
604
605         // position tile nodes and update range selectors
606         global_tile_mgr.prep_ssg_nodes();
607
608         // force the default state so ssg can get back on track if
609         // we've changed things elsewhere
610         FGMaterialSlot m_slot;
611         FGMaterialSlot *m_ptr = &m_slot;
612         if ( material_mgr.find( "Default", m_ptr ) ) {
613             m_ptr->get_state()->force();
614         }
615
616         // draw the ssg scene
617         ssgCullAndDraw( scene );
618
619
620         // display HUD && Panel
621         glDisable( GL_FOG );
622         glDisable( GL_DEPTH_TEST );
623         // glDisable( GL_CULL_FACE );
624         // glDisable( GL_TEXTURE_2D );
625         hud_and_panel->apply();
626         fgCockpitUpdate();
627
628         // We can do translucent menus, so why not. :-)
629         // glEnable ( GL_BLEND ) ;
630         menus->apply();
631         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
632         puDisplay();
633         // glDisable ( GL_BLEND ) ;
634
635         // glEnable( GL_FOG );
636     }
637
638     glutSwapBuffers();
639 }
640
641
642 // Update internal time dependent calculations (i.e. flight model)
643 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
644     static fdm_state_list fdm_list;
645     // FGInterface fdm_state;
646     fgLIGHT *l = &cur_light_params;
647     FGTime *t = FGTime::cur_time_params;
648     // FGView *v = &current_view;
649     int i;
650
651     // update the flight model
652     if ( multi_loop < 0 ) {
653         multi_loop = 1;
654     }
655
656     if ( !t->getPause() ) {
657         // run Autopilot system
658         fgAPRun();
659
660         // printf("updating flight model x %d\n", multi_loop);
661         /* fgFDMUpdate( current_options.get_flight_model(), 
662                      fdm_state, 
663                      multi_loop * current_options.get_speed_up(),
664                      remainder ); */
665         cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
666         FGSteam::update( multi_loop * current_options.get_speed_up() );
667     } else {
668         // fgFDMUpdate( current_options.get_flight_model(), 
669         //              fdm_state, 0, remainder );
670         cur_fdm_state->update( 0 );
671         FGSteam::update( 0 );
672     }
673
674     fdm_list.push_back( *cur_fdm_state );
675     while ( fdm_list.size() > 15 ) {
676         fdm_list.pop_front();
677     }
678
679     if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
680         cur_view_fdm = *cur_fdm_state;
681         // do nothing
682     } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
683         cur_view_fdm = fdm_list.front();
684     }
685
686     // update the view angle
687     for ( i = 0; i < multi_loop; i++ ) {
688         if ( fabs(current_view.get_goal_view_offset() - 
689                   current_view.get_view_offset()) < 0.05 )
690         {
691             current_view.set_view_offset( current_view.get_goal_view_offset() );
692             break;
693         } else {
694             // move current_view.view_offset towards current_view.goal_view_offset
695             if ( current_view.get_goal_view_offset() > 
696                  current_view.get_view_offset() )
697             {
698                 if ( current_view.get_goal_view_offset() - 
699                      current_view.get_view_offset() < FG_PI )
700                 {
701                     current_view.inc_view_offset( 0.01 );
702                 } else {
703                     current_view.inc_view_offset( -0.01 );
704                 }
705             } else {
706                 if ( current_view.get_view_offset() - 
707                      current_view.get_goal_view_offset() < FG_PI )
708                 {
709                     current_view.inc_view_offset( -0.01 );
710                 } else {
711                     current_view.inc_view_offset( 0.01 );
712                 }
713             }
714             if ( current_view.get_view_offset() > FG_2PI ) {
715                 current_view.inc_view_offset( -FG_2PI );
716             } else if ( current_view.get_view_offset() < 0 ) {
717                 current_view.inc_view_offset( FG_2PI );
718             }
719         }
720     }
721
722     double tmp = -(l->sun_rotation + FG_PI) 
723         - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
724     while ( tmp < 0.0 ) {
725         tmp += FG_2PI;
726     }
727     while ( tmp > FG_2PI ) {
728         tmp -= FG_2PI;
729     }
730     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
731            FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG, 
732            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
733     l->UpdateAdjFog();
734
735     // Update solar system
736     ephem->update( t, cur_fdm_state->get_Latitude() );
737 }
738
739
740 void fgInitTimeDepCalcs( void ) {
741     // initialize timer
742
743     // #ifdef HAVE_SETITIMER
744     //   fgTimerInit( 1.0 / current_options.get_model_hz(), 
745     //                fgUpdateTimeDepCalcs );
746     // #endif HAVE_SETITIMER
747 }
748
749
750 static const double alt_adjust_ft = 3.758099;
751 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
752
753
754 // What should we do when we have nothing else to do?  Let's get ready
755 // for the next move and update the display?
756 static void fgMainLoop( void ) {
757     FGTime *t;
758     static long remainder = 0;
759     long elapsed;
760 #ifdef FANCY_FRAME_COUNTER
761     int i;
762     double accum;
763 #else
764     static time_t last_time = 0;
765     static int frames = 0;
766 #endif // FANCY_FRAME_COUNTER
767
768     t = FGTime::cur_time_params;
769
770     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
771     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
772
773 #ifdef FG_NETWORK_OLK
774     if ( current_options.get_network_olk() ) {
775         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
776             // printf("FGD: Netupdate\n");
777             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
778             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
779         }
780     }
781 #endif
782
783 #if defined( ENABLE_PLIB_JOYSTICK )
784     // Read joystick and update control settings
785     if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
786         fgJoystickRead();
787     }
788 #elif defined( ENABLE_GLUT_JOYSTICK )
789     // Glut joystick support works by feeding a joystick handler
790     // function to glut.  This is taken care of once in the joystick
791     // init routine and we don't have to worry about it again.
792 #endif
793
794 #ifdef FG_OLD_WEATHER
795     current_weather.Update();
796 #endif
797
798     // Fix elevation.  I'm just sticking this here for now, it should
799     // probably move eventually
800
801     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
802            scenery.cur_elev,
803            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
804            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
805
806     if ( scenery.cur_elev > -9990 ) {
807         if ( cur_fdm_state->get_Altitude() * FEET_TO_METER < 
808              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
809             // now set aircraft altitude above ground
810             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
811                    cur_fdm_state->get_Altitude() * FEET_TO_METER,
812                    scenery.cur_elev + alt_adjust_m - 3.0,
813                    scenery.cur_elev + alt_adjust_m );
814             fgFDMForceAltitude( current_options.get_flight_model(), 
815                                 scenery.cur_elev + alt_adjust_m );
816
817             FG_LOG( FG_ALL, FG_DEBUG, 
818                     "<*> resetting altitude to " 
819                     << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
820         }
821         fgFDMSetGroundElevation( current_options.get_flight_model(),
822                                  scenery.cur_elev );  // meters
823     }
824
825     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
826            scenery.cur_elev,
827            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
828            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
829
830     // update "time"
831     t->update( cur_fdm_state->get_Longitude() );
832
833     // Get elapsed time (in usec) for this past frame
834     elapsed = fgGetTimeInterval();
835     FG_LOG( FG_ALL, FG_DEBUG, 
836             "Elapsed time interval is = " << elapsed 
837             << ", previous remainder is = " << remainder );
838
839     // Calculate frame rate average
840 #ifdef FANCY_FRAME_COUNTER
841     /* old fps calculation */
842     if ( elapsed > 0 ) {
843         double tmp;
844         accum = 0.0;
845         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
846             tmp = general.get_frame(i);
847             accum += tmp;
848             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
849             general.set_frame(i+1,tmp);
850         }
851         tmp = 1000000.0 / (float)elapsed;
852         general.set_frame(0,tmp);
853         // printf("frame[0] = %.2f\n", general.frames[0]);
854         accum += tmp;
855         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
856         // printf("ave = %.2f\n", general.frame_rate);
857     }
858 #else
859     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
860         general.set_frame_rate( frames );
861         FG_LOG( FG_ALL, FG_DEBUG, 
862                 "--> Frame rate is = " << general.get_frame_rate() );
863         frames = 0;
864     }
865     last_time = t->get_cur_time();
866     ++frames;
867 #endif
868
869     // Run flight model
870     if ( ! use_signals ) {
871         // Calculate model iterations needed for next frame
872         elapsed += remainder;
873
874         global_multi_loop = (int)(((double)elapsed * 0.000001) * 
875                            current_options.get_model_hz());
876         remainder = elapsed - ( (global_multi_loop*1000000) / 
877                                 current_options.get_model_hz() );
878         FG_LOG( FG_ALL, FG_DEBUG, 
879                 "Model iterations needed = " << global_multi_loop
880                 << ", new remainder = " << remainder );
881         
882         // flight model
883         if ( global_multi_loop > 0 ) {
884             fgUpdateTimeDepCalcs(global_multi_loop, remainder);
885         } else {
886             FG_LOG( FG_ALL, FG_DEBUG, 
887                     "Elapsed time is zero ... we're zinging" );
888         }
889     }
890
891 #if ! defined( MACOS )
892     // Do any I/O channel work that might need to be done
893     fgIOProcess();
894 #endif
895
896     // see if we need to load any new scenery tiles
897     global_tile_mgr.update();
898
899     // Process/manage pending events
900     global_events.Process();
901
902     // Run audio scheduler
903 #ifdef ENABLE_AUDIO_SUPPORT
904     if ( current_options.get_sound() && !audio_sched->not_working() ) {
905
906 #   ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
907
908         // note: all these factors are relative to the sample.  our
909         // sample format should really contain a conversion factor so
910         // that we can get prop speed right for arbitrary samples.
911         // Note that for normal-size props, there is a point at which
912         // the prop tips approach the speed of sound; that is a pretty
913         // strong limit to how fast the prop can go.
914
915         // multiplication factor is prime pitch control; add some log
916         // component for verisimilitude
917
918         double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
919         //fprintf(stderr, "pitch1: %f ", pitch);
920         if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
921             //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
922             // only add relative wind and AoA if prop is moving
923             // or we're really flying at idle throttle
924             if (pitch < 5.4) {  // this needs tuning
925                 // prop tips not breaking sound barrier
926                 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
927             } else {
928                 // prop tips breaking sound barrier
929                 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
930             }
931             //fprintf(stderr, "pitch2: %f ", pitch);
932             //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
933
934             // Angle of Attack next... -x^3(e^x) is my best guess Just
935             // need to calculate some reasonable scaling factor and
936             // then clamp it on the positive aoa (neg adj) side
937             double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
938             double tmp = 3.0;
939             double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
940             if (aoa_adj < -0.8) aoa_adj = -0.8;
941             pitch += aoa_adj;
942             //fprintf(stderr, "pitch3: %f ", pitch);
943
944             // don't run at absurdly slow rates -- not realistic
945             // and sounds bad to boot.  :-)
946             if (pitch < 0.8) pitch = 0.8;
947         }
948         //fprintf(stderr, "pitch4: %f\n", pitch);
949
950         double volume = controls.get_throttle(0) * 1.15 + 0.3 +
951             log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
952         // fprintf(stderr, "volume: %f\n", volume);
953
954         pitch_envelope.setStep  ( 0, 0.01, pitch );
955         volume_envelope.setStep ( 0, 0.01, volume );
956
957 #   else
958
959        double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
960        pitch_envelope.setStep  ( 0, 0.01, param );
961        volume_envelope.setStep ( 0, 0.01, param );
962
963 #   endif // experimental throttle patch
964
965         audio_sched -> update();
966     }
967 #endif
968
969     // redraw display
970     fgRenderFrame();
971
972     FG_LOG( FG_ALL, FG_DEBUG, "" );
973 }
974
975
976 // This is the top level master main function that is registered as
977 // our idle funciton
978 //
979
980 // The first few passes take care of initialization things (a couple
981 // per pass) and once everything has been initialized fgMainLoop from
982 // then on.
983
984 static void fgIdleFunction ( void ) {
985     // printf("idle state == %d\n", idle_state);
986
987     if ( idle_state == 0 ) {
988         // Initialize the splash screen right away
989         if ( current_options.get_splash_screen() ) {
990             fgSplashInit();
991         }
992         
993         idle_state++;
994     } else if ( idle_state == 1 ) {
995         // Start the intro music
996 #if !defined(WIN32)
997         if ( current_options.get_intro_music() ) {
998             string lockfile = "/tmp/mpg123.running";
999             FGPath mp3file( current_options.get_fg_root() );
1000             mp3file.append( "Sounds/intro.mp3" );
1001
1002             string command = "(touch " + lockfile + "; mpg123 "
1003                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1004                 + lockfile + ") &";
1005             FG_LOG( FG_GENERAL, FG_INFO, 
1006                     "Starting intro music: " << mp3file.str() );
1007             system ( command.c_str() );
1008         }
1009 #endif
1010
1011         idle_state++;
1012     } else if ( idle_state == 2 ) {
1013         // These are a few miscellaneous things that aren't really
1014         // "subsystems" but still need to be initialized.
1015
1016 #ifdef USE_GLIDE
1017         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1018             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1019         }
1020 #endif
1021
1022         idle_state++;
1023     } else if ( idle_state == 3 ) {
1024         // This is the top level init routine which calls all the
1025         // other subsystem initialization routines.  If you are adding
1026         // a subsystem to flight gear, its initialization call should
1027         // located in this routine.
1028         if( !fgInitSubsystems()) {
1029             FG_LOG( FG_GENERAL, FG_ALERT,
1030                     "Subsystem initializations failed ..." );
1031             exit(-1);
1032         }
1033
1034         idle_state++;
1035     } else if ( idle_state == 4 ) {
1036         // setup OpenGL view parameters
1037         fgInitVisuals();
1038
1039         if ( use_signals ) {
1040             // init timer routines, signals, etc.  Arrange for an alarm
1041             // signal to be generated, etc.
1042             fgInitTimeDepCalcs();
1043         }
1044
1045         idle_state++;
1046     } else if ( idle_state == 5 ) {
1047
1048         idle_state++;
1049     } else if ( idle_state == 6 ) {
1050         // Initialize audio support
1051 #ifdef ENABLE_AUDIO_SUPPORT
1052
1053 #if !defined(WIN32)
1054         if ( current_options.get_intro_music() ) {
1055             // Let's wait for mpg123 to finish
1056             string lockfile = "/tmp/mpg123.running";
1057             struct stat stat_buf;
1058
1059             FG_LOG( FG_GENERAL, FG_INFO, 
1060                     "Waiting for mpg123 player to finish ..." );
1061             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1062                 // file exist, wait ...
1063                 sleep(1);
1064                 FG_LOG( FG_GENERAL, FG_INFO, ".");
1065             }
1066             FG_LOG( FG_GENERAL, FG_INFO, "");
1067         }
1068 #endif // WIN32
1069
1070         if ( current_options.get_sound() ) {
1071             audio_sched = new slScheduler ( 8000 );
1072             audio_mixer = new smMixer;
1073             audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
1074             audio_sched -> setSafetyMargin ( 1.0 ) ;
1075
1076             FGPath slfile( current_options.get_fg_root() );
1077             slfile.append( "Sounds/wasp.wav" );
1078
1079             s1 = new slSample ( (char *)slfile.c_str() );
1080             FG_LOG( FG_GENERAL, FG_INFO,
1081                     "Rate = " << s1 -> getRate()
1082                     << "  Bps = " << s1 -> getBps()
1083                     << "  Stereo = " << s1 -> getStereo() );
1084             audio_sched -> loopSample ( s1 );
1085
1086             if ( audio_sched->not_working() ) {
1087                 // skip
1088             } else {
1089                 pitch_envelope.setStep  ( 0, 0.01, 0.6 );
1090                 volume_envelope.setStep ( 0, 0.01, 0.6 );
1091
1092                 audio_sched -> addSampleEnvelope( s1, 0, 0, 
1093                                                   &pitch_envelope,
1094                                                   SL_PITCH_ENVELOPE );
1095                 audio_sched -> addSampleEnvelope( s1, 0, 1, 
1096                                                   &volume_envelope,
1097                                                   SL_VOLUME_ENVELOPE );
1098             }
1099
1100             // strcpy(slfile, path);
1101             // strcat(slfile, "thunder.wav");
1102             // s2 -> loadFile ( slfile );
1103             // s2 -> adjustVolume(0.5);
1104             // audio_sched -> playSample ( s2 );
1105         }
1106 #endif
1107
1108         // sleep(1);
1109         idle_state = 1000;
1110     } 
1111
1112     if ( idle_state == 1000 ) {
1113         // We've finished all our initialization steps, from now on we
1114         // run the main loop.
1115
1116         fgMainLoop();
1117     } else {
1118         if ( current_options.get_splash_screen() == 1 ) {
1119             fgSplashUpdate(0.0);
1120         }
1121     }
1122 }
1123
1124 // options.cxx needs to see this for toggle_panel()
1125 // Handle new window size or exposure
1126 void fgReshape( int width, int height ) {
1127     if ( ! current_options.get_panel_status() ) {
1128         current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1129         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1130     } else {
1131         current_view.set_win_ratio( (GLfloat) width / 
1132                                     ((GLfloat) (height)*0.4232) );
1133         glViewport(0, (GLint)((height)*0.5768), (GLint)(width), 
1134                     (GLint)((height)*0.4232) );
1135     }
1136
1137     current_view.set_winWidth( width );
1138     current_view.set_winHeight( height );
1139     current_view.force_update_fov_math();
1140
1141     // set these fov to be the same as in fgRenderFrame()
1142     float x_fov = current_options.get_fov();
1143     float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1144     ssgSetFOV( x_fov, y_fov );
1145
1146     glViewport ( 0, 0, width, height );
1147     float fov = current_options.get_fov();
1148     ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1149
1150     if ( idle_state == 1000 ) {
1151         // yes we've finished all our initializations and are running
1152         // the main loop, so this will now work without seg faulting
1153         // the system.
1154         current_view.UpdateViewParams(cur_view_fdm);
1155         if ( current_options.get_panel_status() ) {
1156             FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1157         }
1158     }
1159 }
1160
1161
1162 // Initialize GLUT and define a main window
1163 int fgGlutInit( int *argc, char **argv ) {
1164
1165 #if !defined( MACOS )
1166     // GLUT will extract all glut specific options so later on we only
1167     // need wory about our own.
1168     glutInit(argc, argv);
1169 #endif
1170
1171     // Define Display Parameters
1172     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1173
1174     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1175             current_options.get_xsize() << "x" << current_options.get_ysize() );
1176
1177     // Define initial window size
1178     glutInitWindowSize( current_options.get_xsize(),
1179                          current_options.get_ysize() );
1180
1181     // Initialize windows
1182     if ( current_options.get_game_mode() == 0 ) {
1183         // Open the regular window
1184         glutCreateWindow("Flight Gear");
1185 #ifndef GLUT_WRONG_VERSION
1186     } else {
1187         // Open the cool new 'game mode' window
1188         char game_mode_str[256];
1189         sprintf( game_mode_str, "width=%d height=%d bpp=32",
1190                  current_options.get_xsize(),
1191                  current_options.get_ysize() );
1192
1193         FG_LOG( FG_GENERAL, FG_INFO, 
1194                 "game mode params = " << game_mode_str );
1195         glutGameModeString( game_mode_str );
1196         glutEnterGameMode();
1197 #endif
1198     }
1199
1200     // This seems to be the absolute earliest in the init sequence
1201     // that these calls will return valid info.  Too bad it's after
1202     // we've already created and sized out window. :-(
1203     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1204     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1205     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1206
1207     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1208
1209 #if 0
1210     // try to determine if we should adjust the initial default
1211     // display resolution.  The options class defaults (is
1212     // initialized) to 640x480.
1213     string renderer = general.glRenderer;
1214
1215     // currently we only know how to deal with Mesa/Glide/Voodoo cards
1216     if ( renderer.find( "Glide" ) != string::npos ) {
1217         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1218         if ( renderer.find( "FB/8" ) != string::npos ) {
1219             // probably a voodoo-2
1220             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1221                 // probably two SLI'd Voodoo-2's
1222                 current_options.set_xsize( 1024 );
1223                 current_options.set_ysize( 768 );
1224                 FG_LOG( FG_GENERAL, FG_INFO,
1225                         "It looks like you have two sli'd voodoo-2's." << endl
1226                         << "upgrading your win resolution to 1024 x 768" );
1227                 glutReshapeWindow(1024, 768);
1228             } else {
1229                 // probably a single non-SLI'd Voodoo-2
1230                 current_options.set_xsize( 800 );
1231                 current_options.set_ysize( 600 );
1232                 FG_LOG( FG_GENERAL, FG_INFO,
1233                         "It looks like you have a voodoo-2." << endl
1234                         << "upgrading your win resolution to 800 x 600" );
1235                 glutReshapeWindow(800, 600);
1236             }
1237         } else if ( renderer.find( "FB/2" ) != string::npos ) {
1238             // probably a voodoo-1, stick with the default
1239         }
1240     } else {
1241         // we have no special knowledge of this card, stick with the default
1242     }
1243 #endif
1244
1245     return(1);
1246 }
1247
1248
1249 // Initialize GLUT event handlers
1250 int fgGlutInitEvents( void ) {
1251     // call fgReshape() on window resizes
1252     glutReshapeFunc( fgReshape );
1253
1254     // call GLUTkey() on keyboard event
1255     glutKeyboardFunc( GLUTkey );
1256     glutSpecialFunc( GLUTspecialkey );
1257
1258     // call guiMouseFunc() whenever our little rodent is used
1259     glutMouseFunc ( guiMouseFunc );
1260     glutMotionFunc (guiMotionFunc );
1261     glutPassiveMotionFunc (guiMotionFunc );
1262
1263     // call fgMainLoop() whenever there is
1264     // nothing else to do
1265     glutIdleFunc( fgIdleFunction );
1266
1267     // draw the scene
1268     glutDisplayFunc( fgRenderFrame );
1269
1270     return(1);
1271 }
1272
1273
1274 // Main ...
1275 int main( int argc, char **argv ) {
1276
1277 #if defined( MACOS )
1278     argc = ccommand( &argv );
1279 #endif
1280
1281 #ifdef HAVE_BC5PLUS
1282     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1283 #endif
1284
1285     // Initialize ssg (from plib).  Needs to come before we do any
1286     // other ssg related stuff
1287     ssgInit();
1288
1289     // set default log levels
1290     fglog().setLogLevels( FG_ALL, FG_INFO );
1291
1292     FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear:  Version " << VERSION << endl );
1293
1294     // seed the random number generater
1295     fg_srandom();
1296
1297     // Load the configuration parameters
1298     if ( !fgInitConfig(argc, argv) ) {
1299         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1300         exit(-1);
1301     }
1302
1303     // Initialize the Window/Graphics environment.
1304     if( !fgGlutInit(&argc, argv) ) {
1305         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1306         exit(-1);
1307     }
1308
1309     // Initialize the various GLUT Event Handlers.
1310     if( !fgGlutInitEvents() ) {
1311         FG_LOG( FG_GENERAL, FG_ALERT, 
1312                 "GLUT event handler initialization failed ..." );
1313         exit(-1);
1314     }
1315
1316     // Initialize the user interface (we need to do this before
1317     // passing off control to glut and before fgInitGeneral to get our
1318     // fonts !!!
1319     guiInit();
1320
1321     // Initialize time
1322     FGTime::cur_time_params = new FGTime();
1323     // FGTime::cur_time_params->init( cur_fdm_state->get_Longitude(), 
1324     //                                cur_fdm_state->get_Latitude() );
1325     // FGTime::cur_time_params->update( cur_fdm_state->get_Longitude() );
1326     FGTime::cur_time_params->init( 0.0, 0.0 );
1327     FGTime::cur_time_params->update( 0.0 );
1328
1329     // Do some quick general initializations
1330     if( !fgInitGeneral()) {
1331         FG_LOG( FG_GENERAL, FG_ALERT, 
1332                 "General initializations failed ..." );
1333         exit(-1);
1334     }
1335
1336     //
1337     // some ssg test stuff (requires data from the plib source
1338     // distribution) specifically from the ssg tux example
1339     //
1340
1341     FGPath modelpath( current_options.get_fg_root() );
1342     modelpath.append( "Models" );
1343     modelpath.append( "Geometry" );
1344   
1345     FGPath texturepath( current_options.get_fg_root() );
1346     texturepath.append( "Models" );
1347     texturepath.append( "Textures" );
1348   
1349     ssgModelPath( (char *)modelpath.c_str() );
1350     ssgTexturePath( (char *)texturepath.c_str() );
1351
1352     // Scene graph root
1353     scene = new ssgRoot;
1354     scene->setName( "Scene" );
1355
1356     // Initialize the sky
1357     FGPath ephem_data_path( current_options.get_fg_root() );
1358     ephem_data_path.append( "Astro" );
1359     ephem = new FGEphemeris( ephem_data_path.c_str() );
1360     ephem->update( FGTime::cur_time_params, 0.0 );
1361
1362     FGPath sky_tex_path( current_options.get_fg_root() );
1363     sky_tex_path.append( "Textures" );
1364     sky_tex_path.append( "Sky" );
1365     thesky = new SGSky;
1366     thesky->texture_path( sky_tex_path.str() );
1367
1368     ssgBranch *sky = thesky->build( 550.0, 550.0,
1369                                     ephem->getNumPlanets(), 
1370                                     ephem->getPlanets(), 60000.0,
1371                                     ephem->getNumStars(),
1372                                     ephem->getStars(), 60000.0 );
1373     scene->addKid( sky );
1374
1375     // Terrain branch
1376     terrain = new ssgBranch;
1377     terrain->setName( "Terrain" );
1378     scene->addKid( terrain );
1379
1380     // temporary visible aircraft "own ship"
1381     penguin_sel = new ssgSelector;
1382     penguin_pos = new ssgTransform;
1383     // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1384     ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1385     // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1386
1387     penguin_pos->addKid( tux_obj );
1388     penguin_sel->addKid( penguin_pos );
1389     ssgFlatten( tux_obj );
1390     ssgStripify( penguin_sel );
1391     penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1392     scene->addKid( penguin_sel );
1393
1394 #ifdef FG_NETWORK_OLK
1395     // Do the network intialization
1396     if ( current_options.get_network_olk() ) {
1397         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1398     }
1399 #endif
1400
1401     // build our custom render states
1402     fgBuildRenderStates();
1403
1404     // pass control off to the master GLUT event handler
1405     glutMainLoop();
1406
1407     // we never actually get here ... but to avoid compiler warnings,
1408     // etc.
1409     return 0;
1410 }