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