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