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