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