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