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