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