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