]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_init.cxx
Various SGI portability tweaks.
[flightgear.git] / src / Main / fg_init.cxx
1 //
2 // fg_init.cxx -- Flight Gear top level initialization routines
3 //
4 // Written by Curtis Olson, started August 1997.
5 //
6 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 //
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 // For BC 5.01 this must be included before OpenGL includes.
31 #ifdef FG_MATH_EXCEPTION_CLASH
32 #  include <math.h>
33 #endif
34
35 #include <GL/glut.h>
36 #include <XGL/xgl.h>
37
38 #include <stdio.h>
39 #include <stdlib.h>
40
41 // work around a stdc++ lib bug in some versions of linux, but doesn't
42 // seem to hurt to have this here for all versions of Linux.
43 #ifdef linux
44 #  define _G_NO_EXTERN_TEMPLATES
45 #endif
46
47 #include <Include/compiler.h>
48
49 #include STL_STRING
50
51 #include <Debug/logstream.hxx>
52 #include <Aircraft/aircraft.hxx>
53 #include <Airports/simple.hxx>
54 #include <Astro/sky.hxx>
55 #include <Astro/stars.hxx>
56 #include <Astro/solarsystem.hxx>
57 #include <Autopilot/autopilot.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Include/fg_constants.h>
60 #include <Include/general.hxx>
61 #include <Joystick/joystick.hxx>
62 #include <Math/fg_geodesy.hxx>
63 #include <Math/point3d.hxx>
64 #include <Math/polar3d.hxx>
65 #include <Misc/fgpath.hxx>
66 #include <Scenery/scenery.hxx>
67 #include <Scenery/tilemgr.hxx>
68 #include <Time/event.hxx>
69 #include <Time/fg_time.hxx>
70 #include <Time/light.hxx>
71 #include <Time/sunpos.hxx>
72 #include <Time/moonpos.hxx>
73
74 #ifdef FG_NEW_WEATHER
75 #  include <WeatherCM/FGLocalWeatherDatabase.h>
76 #else
77 #  include <Weather/weather.hxx>
78 #endif
79
80 #include "fg_init.hxx"
81 #include "options.hxx"
82 #include "views.hxx"
83 #include "fg_serial.hxx"
84
85 #if defined(FX) && defined(XMESA)
86 #include <GL/xmesa.h>
87 #endif
88
89 FG_USING_STD(string);
90
91 extern const char *default_root;
92
93
94 // Read in configuration (file and command line)
95 bool fgInitConfig ( int argc, char **argv ) {
96     // Attempt to locate and parse a config file
97     // First check fg_root
98     FGPath config( current_options.get_fg_root() );
99     config.append( "system.fgfsrc" );
100     current_options.parse_config_file( config.str() );
101
102     // Next check home directory
103     char* envp = ::getenv( "HOME" );
104     if ( envp != NULL ) {
105         config.set( envp );
106         config.append( ".fgfsrc" );
107         current_options.parse_config_file( config.str() );
108     }
109
110     // Parse remaining command line options
111     // These will override anything specified in a config file
112     if ( current_options.parse_command_line(argc, argv) !=
113          fgOPTIONS::FG_OPTIONS_OK )
114     {
115         // Something must have gone horribly wrong with the command
116         // line parsing or maybe the user just requested help ... :-)
117         current_options.usage();
118         FG_LOG( FG_GENERAL, FG_ALERT, "\nExiting ...");
119         return false;
120     }
121
122     return true;
123 }
124
125
126 // Set initial position and orientation
127 bool fgInitPosition( void ) {
128     string id;
129     FGInterface *f;
130
131     f = current_aircraft.fdm_state;
132
133     id = current_options.get_airport_id();
134     if ( id.length() ) {
135         // set initial position from airport id
136
137         fgAIRPORTS airports;
138         fgAIRPORT a;
139
140         FG_LOG( FG_GENERAL, FG_INFO,
141                 "Attempting to set starting position from airport code "
142                 << id );
143
144         airports.load("apt_simple");
145         if ( ! airports.search( id, &a ) ) {
146             FG_LOG( FG_GENERAL, FG_ALERT,
147                     "Failed to find " << id << " in database." );
148             exit(-1);
149         } else {
150             f->set_Longitude( a.longitude * DEG_TO_RAD );
151             f->set_Latitude( a.latitude * DEG_TO_RAD );
152         }
153     } else {
154         // set initial position from default or command line coordinates
155
156         f->set_Longitude( current_options.get_lon() * DEG_TO_RAD );
157         f->set_Latitude( current_options.get_lat() * DEG_TO_RAD );
158     }
159
160     FG_LOG( FG_GENERAL, FG_INFO,
161             "starting altitude is = " << current_options.get_altitude() );
162
163     f->set_Altitude( current_options.get_altitude() * METER_TO_FEET );
164     fgFDMSetGroundElevation( current_options.get_flight_model(),
165                              (f->get_Altitude() - 3.758099) * FEET_TO_METER );
166
167     FG_LOG( FG_GENERAL, FG_INFO,
168             "Initial position is: ("
169             << (f->get_Longitude() * RAD_TO_DEG) << ", "
170             << (f->get_Latitude() * RAD_TO_DEG) << ", "
171             << (f->get_Altitude() * FEET_TO_METER) << ")" );
172
173     return true;
174 }
175
176
177 // General house keeping initializations
178 bool fgInitGeneral( void ) {
179     string root;
180     char *mesa_win_state;
181
182     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
183     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
184
185     root = current_options.get_fg_root();
186     if ( ! root.length() ) {
187         // No root path set? Then bail ...
188         FG_LOG( FG_GENERAL, FG_ALERT,
189                 "Cannot continue without environment variable FG_ROOT"
190                 << "being defined." );
191         exit(-1);
192     }
193     FG_LOG( FG_GENERAL, FG_INFO, "FG_ROOT = " << '"' << root << '"' << endl );
194
195 #if defined(FX) && defined(XMESA)
196     // initialize full screen flag
197     global_fullscreen = false;
198     if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
199         // Test for the MESA_GLX_FX env variable
200         if ( (mesa_win_state = getenv( "MESA_GLX_FX" )) != NULL) {
201             // test if we are fullscreen mesa/glide
202             if ( (mesa_win_state[0] == 'f') ||
203                  (mesa_win_state[0] == 'F') ) {
204                 global_fullscreen = true;
205             }
206         }
207     }
208 #endif
209
210     return true;
211 }
212
213
214 // This is the top level init routine which calls all the other
215 // initialization routines.  If you are adding a subsystem to flight
216 // gear, its initialization call should located in this routine.
217 // Returns non-zero if a problem encountered.
218 bool fgInitSubsystems( void ) {
219     FGTime::cur_time_params = new FGTime();
220
221     fgLIGHT *l = &cur_light_params;
222     FGTime *t = FGTime::cur_time_params;
223     FGView *v = &current_view;
224
225     FG_LOG( FG_GENERAL, FG_INFO, "Initialize Subsystems");
226     FG_LOG( FG_GENERAL, FG_INFO, "========== ==========");
227
228     // allocates structures so must happen before any of the flight
229     // model or control parameters are set
230     fgAircraftInit();   // In the future this might not be the case.
231
232     // set the initial position
233     fgInitPosition();
234
235     // Initialize the Scenery Management subsystem
236     if ( fgSceneryInit() ) {
237         // Scenery initialized ok.
238     } else {
239         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Scenery initialization!" );
240         exit(-1);
241     }
242
243     if( global_tile_mgr.init() ) {
244         // Load the local scenery data
245         global_tile_mgr.update();
246     } else {
247         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
248         exit(-1);
249     }
250
251     FG_LOG( FG_GENERAL, FG_DEBUG,
252             "Current terrain elevation after tile mgr init " <<
253             scenery.cur_elev );
254
255     // Calculate ground elevation at starting point (we didn't have
256     // tmp_abs_view_pos calculated when fgTileMgrUpdate() was called above
257     //
258     // calculalate a cartesian point somewhere along the line between
259     // the center of the earth and our view position.  Doesn't have to
260     // be the exact elevation (this is good because we don't know it
261     // yet :-)
262
263     // now handled inside of the fgTileMgrUpdate()
264
265     /*
266     geod_pos = Point3D( cur_fdm_state.get_Longitude(), cur_fdm_state.get_Latitude(), 0.0);
267     tmp_abs_view_pos = fgGeodToCart(geod_pos);
268
269     FG_LOG( FG_GENERAL, FG_DEBUG,
270             "Initial abs_view_pos = " << tmp_abs_view_pos );
271     scenery.cur_elev =
272         fgTileMgrCurElev( cur_fdm_state.get_Longitude(), cur_fdm_state.get_Latitude(),
273                           tmp_abs_view_pos );
274     FG_LOG( FG_GENERAL, FG_DEBUG,
275             "Altitude after update " << scenery.cur_elev );
276     */
277
278     fgFDMSetGroundElevation( current_options.get_flight_model(),
279                              scenery.cur_elev );
280
281     // Reset our altitude if we are below ground
282     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = " << cur_fdm_state.get_Altitude() );
283     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " <<
284             cur_fdm_state.get_Runway_altitude() );
285
286     if ( cur_fdm_state.get_Altitude() < cur_fdm_state.get_Runway_altitude() + 3.758099) {
287         cur_fdm_state.set_Altitude( cur_fdm_state.get_Runway_altitude() + 3.758099 );
288     }
289
290     FG_LOG( FG_GENERAL, FG_INFO,
291             "Updated position (after elevation adj): ("
292             << (cur_fdm_state.get_Latitude() * RAD_TO_DEG) << ", "
293             << (cur_fdm_state.get_Longitude() * RAD_TO_DEG) << ", "
294             << (cur_fdm_state.get_Altitude() * FEET_TO_METER) << ")" );
295
296     // We need to calculate a few more values here that would normally
297     // be calculated by the FDM so that the v->UpdateViewMath()
298     // routine doesn't get hosed.
299
300     double sea_level_radius_meters;
301     double lat_geoc;
302     // Set the FG variables first
303     fgGeodToGeoc( cur_fdm_state.get_Latitude(), cur_fdm_state.get_Altitude(),
304                   &sea_level_radius_meters, &lat_geoc);
305     cur_fdm_state.set_Geocentric_Position( lat_geoc, cur_fdm_state.get_Longitude(),
306                                 cur_fdm_state.get_Altitude() +
307                                 (sea_level_radius_meters * METER_TO_FEET) );
308     cur_fdm_state.set_Sea_level_radius( sea_level_radius_meters * METER_TO_FEET );
309
310     cur_fdm_state.set_sin_cos_longitude(cur_fdm_state.get_Longitude());
311     cur_fdm_state.set_sin_cos_latitude(cur_fdm_state.get_Latitude());
312         
313     cur_fdm_state.set_sin_lat_geocentric(sin(lat_geoc));
314     cur_fdm_state.set_cos_lat_geocentric(cos(lat_geoc));
315
316     // The following section sets up the flight model EOM parameters
317     // and should really be read in from one or more files.
318
319     // Initial Velocity
320     cur_fdm_state.set_Velocities_Local( current_options.get_uBody(),
321                              current_options.get_vBody(),
322                              current_options.get_wBody());
323
324     // Initial Orientation
325     cur_fdm_state.set_Euler_Angles( current_options.get_roll() * DEG_TO_RAD,
326                          current_options.get_pitch() * DEG_TO_RAD,
327                          current_options.get_heading() * DEG_TO_RAD );
328
329     // Initial Angular Body rates
330     cur_fdm_state.set_Omega_Body( 7.206685E-05, 0.0, 9.492658E-05 );
331
332     cur_fdm_state.set_Earth_position_angle( 0.0 );
333
334     // Mass properties and geometry values
335     cur_fdm_state.set_Inertias( 8.547270E+01,
336                      1.048000E+03, 3.000000E+03, 3.530000E+03, 0.000000E+00 );
337
338     // CG position w.r.t. ref. point
339     cur_fdm_state.set_CG_Position( 0.0, 0.0, 0.0 );
340
341     // Initialize the event manager
342     global_events.Init();
343
344     // Output event stats every 60 seconds
345     global_events.Register( "fgEVENT_MGR::PrintStats()",
346                             fgMethodCallback<fgEVENT_MGR>( &global_events,
347                                                    &fgEVENT_MGR::PrintStats),
348                             fgEVENT::FG_EVENT_READY, 60000 );
349
350     // Initialize the time dependent variables
351     t->init(cur_fdm_state);
352     t->update(cur_fdm_state);
353
354     // Initialize view parameters
355     FG_LOG( FG_GENERAL, FG_DEBUG, "Before v->init()");
356     v->Init();
357     FG_LOG( FG_GENERAL, FG_DEBUG, "After v->init()");
358     v->UpdateViewMath(cur_fdm_state);
359     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = " << v->get_abs_view_pos());
360     // v->UpdateWorldToEye(f);
361
362     // Build the solar system
363     //fgSolarSystemInit(*t);
364     FG_LOG(FG_GENERAL, FG_INFO, "Building SolarSystem");
365     SolarSystem::theSolarSystem = new SolarSystem(t);
366
367     // Initialize the Stars subsystem
368     if( fgStarsInit() ) {
369         // Stars initialized ok.
370     } else {
371         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Stars initialization!" );
372         exit(-1);
373     }
374
375     // Initialize the planetary subsystem
376     // global_events.Register( "fgPlanetsInit()", fgPlanetsInit,
377     //                      fgEVENT::FG_EVENT_READY, 600000);
378
379     // Initialize the sun's position
380     // global_events.Register( "fgSunInit()", fgSunInit,
381     //                      fgEVENT::FG_EVENT_READY, 30000 );
382
383     // Intialize the moon's position
384     // global_events.Register( "fgMoonInit()", fgMoonInit,
385     //                      fgEVENT::FG_EVENT_READY, 600000 );
386
387     // register the periodic update of Sun, moon, and planets
388     global_events.Register( "ssolsysUpdate", solarSystemRebuild,
389                             fgEVENT::FG_EVENT_READY, 600000);
390
391     // fgUpdateSunPos() needs a few position and view parameters set
392     // so it can calculate local relative sun angle and a few other
393     // things for correctly orienting the sky.
394     fgUpdateSunPos();
395     fgUpdateMoonPos();
396     global_events.Register( "fgUpdateSunPos()", fgUpdateSunPos,
397                             fgEVENT::FG_EVENT_READY, 60000);
398     global_events.Register( "fgUpdateMoonPos()", fgUpdateMoonPos,
399                             fgEVENT::FG_EVENT_READY, 60000);
400
401     // Initialize Lighting interpolation tables
402     l->Init();
403
404     // update the lighting parameters (based on sun angle)
405     global_events.Register( "fgLight::Update()",
406                             fgMethodCallback<fgLIGHT>( &cur_light_params,
407                                                        &fgLIGHT::Update),
408                             fgEVENT::FG_EVENT_READY, 30000 );
409
410     // Initialize the weather modeling subsystem
411 #ifdef FG_NEW_WEATHER
412     // Initialize the WeatherDatabase
413     FG_LOG(FG_GENERAL, FG_INFO, "Creating LocalWeatherDatabase");
414     FGLocalWeatherDatabase::theFGLocalWeatherDatabase = 
415         new FGLocalWeatherDatabase(
416               Point3D( current_aircraft.fdm_state->get_Latitude(),
417                        current_aircraft.fdm_state->get_Longitude(),
418                        current_aircraft.fdm_state->get_Altitude() 
419                           * FEET_TO_METER) );
420
421     WeatherDatabase = FGLocalWeatherDatabase::theFGLocalWeatherDatabase;
422
423     // register the periodic update of the weather
424     global_events.Register( "weather update", fgUpdateWeatherDatabase,
425                             fgEVENT::FG_EVENT_READY, 30000);
426 #else
427     current_weather.Init();
428 #endif
429
430     // Initialize the Cockpit subsystem
431     if( fgCockpitInit( &current_aircraft )) {
432         // Cockpit initialized ok.
433     } else {
434         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Cockpit initialization!" );
435         exit(-1);
436     }
437
438     // Initialize the "sky"
439     fgSkyInit();
440
441     // Initialize the flight model subsystem data structures base on
442     // above values
443
444     fgFDMInit( current_options.get_flight_model(), cur_fdm_state,
445                1.0 / current_options.get_model_hz() );
446
447     // I'm just sticking this here for now, it should probably move
448     // eventually
449     scenery.cur_elev = cur_fdm_state.get_Runway_altitude() * FEET_TO_METER;
450
451     if ( cur_fdm_state.get_Altitude() < cur_fdm_state.get_Runway_altitude() + 3.758099) {
452         cur_fdm_state.set_Altitude( cur_fdm_state.get_Runway_altitude() + 3.758099 );
453     }
454
455     FG_LOG( FG_GENERAL, FG_INFO,
456             "Updated position (after elevation adj): ("
457             << (cur_fdm_state.get_Latitude() * RAD_TO_DEG) << ", "
458             << (cur_fdm_state.get_Longitude() * RAD_TO_DEG) << ", "
459             << (cur_fdm_state.get_Altitude() * FEET_TO_METER) << ")" );
460     // end of thing that I just stuck in that I should probably move
461
462     // Joystick support
463     if ( fgJoystickInit() ) {
464         // Joystick initialized ok.
465     } else {
466         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Joystick initialization!" );
467     }
468
469     // Autopilot init added here, by Jeff Goeke-Smith
470     fgAPInit(&current_aircraft);
471
472     // Initialize serial ports
473 #if ! defined( MACOS )
474     fgSerialInit();
475 #endif
476
477     FG_LOG( FG_GENERAL, FG_INFO, endl);
478
479     return true;
480 }
481
482
483 void fgReInitSubsystems( void )
484 {
485     FGView *v = &current_view;
486     FGTime *t = FGTime::cur_time_params;
487     
488     int toggle_pause = t->getPause();
489     
490     if( !toggle_pause )
491         t->togglePauseMode();
492     
493     fgInitPosition();
494     if( global_tile_mgr.init() ) {
495         // Load the local scenery data
496         global_tile_mgr.update();
497     } else {
498         FG_LOG( FG_GENERAL, FG_ALERT, "Error in Tile Manager initialization!" );
499                 exit(-1);
500     }
501     fgFDMSetGroundElevation( current_options.get_flight_model(), 
502                              scenery.cur_elev );
503
504     // Reset our altitude if we are below ground
505     FG_LOG( FG_GENERAL, FG_DEBUG, "Current altitude = " << cur_fdm_state.get_Altitude() );
506     FG_LOG( FG_GENERAL, FG_DEBUG, "Current runway altitude = " << 
507             cur_fdm_state.get_Runway_altitude() );
508
509     if ( cur_fdm_state.get_Altitude() < cur_fdm_state.get_Runway_altitude() + 3.758099) {
510         cur_fdm_state.set_Altitude( cur_fdm_state.get_Runway_altitude() + 3.758099 );
511     }
512     double sea_level_radius_meters;
513     double lat_geoc;
514     // Set the FG variables first
515     fgGeodToGeoc( cur_fdm_state.get_Latitude(), cur_fdm_state.get_Altitude(), 
516                   &sea_level_radius_meters, &lat_geoc);
517     cur_fdm_state.set_Geocentric_Position( lat_geoc, cur_fdm_state.get_Longitude(), 
518                                 cur_fdm_state.get_Altitude() + 
519                                 (sea_level_radius_meters * METER_TO_FEET) );
520     cur_fdm_state.set_Sea_level_radius( sea_level_radius_meters * METER_TO_FEET );
521         
522     cur_fdm_state.set_sin_cos_longitude(cur_fdm_state.get_Longitude());
523     cur_fdm_state.set_sin_cos_latitude(cur_fdm_state.get_Latitude());
524         
525     cur_fdm_state.set_sin_lat_geocentric(sin(lat_geoc));
526     cur_fdm_state.set_cos_lat_geocentric(cos(lat_geoc));
527
528     // The following section sets up the flight model EOM parameters
529     // and should really be read in from one or more files.
530
531     // Initial Velocity
532     cur_fdm_state.set_Velocities_Local( current_options.get_uBody(),
533                              current_options.get_vBody(),
534                              current_options.get_wBody());
535
536     // Initial Orientation
537     cur_fdm_state.set_Euler_Angles( current_options.get_roll() * DEG_TO_RAD,
538                          current_options.get_pitch() * DEG_TO_RAD,
539                          current_options.get_heading() * DEG_TO_RAD );
540
541     // Initial Angular Body rates
542     cur_fdm_state.set_Omega_Body( 7.206685E-05, 0.0, 9.492658E-05 );
543
544     cur_fdm_state.set_Earth_position_angle( 0.0 );
545
546     // Mass properties and geometry values
547     cur_fdm_state.set_Inertias( 8.547270E+01, 
548                      1.048000E+03, 3.000000E+03, 3.530000E+03, 0.000000E+00 );
549
550     // CG position w.r.t. ref. point
551     cur_fdm_state.set_CG_Position( 0.0, 0.0, 0.0 );
552
553     // Initialize view parameters
554     // FG_LOG( FG_GENERAL, FG_DEBUG, "Before v->init()");
555     // v->Init();
556     v->set_view_offset( 0.0 );
557     v->set_goal_view_offset( 0.0 );
558
559     FG_LOG( FG_GENERAL, FG_DEBUG, "After v->init()");
560     v->UpdateViewMath(cur_fdm_state);
561     FG_LOG( FG_GENERAL, FG_DEBUG, "  abs_view_pos = " << v->get_abs_view_pos());
562     // v->UpdateWorldToEye(f);
563
564     fgFDMInit( current_options.get_flight_model(), cur_fdm_state, 
565                1.0 / current_options.get_model_hz() );
566
567     scenery.cur_elev = cur_fdm_state.get_Runway_altitude() * FEET_TO_METER;
568
569     if ( cur_fdm_state.get_Altitude() < cur_fdm_state.get_Runway_altitude() + 3.758099) {
570         cur_fdm_state.set_Altitude( cur_fdm_state.get_Runway_altitude() + 3.758099 );
571     }
572
573     controls.reset_all();
574     fgAPReset();
575
576     if( !toggle_pause )
577         t->togglePauseMode();
578 }