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