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