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