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