]> git.mxchange.org Git - flightgear.git/blob - src/Main/options.cxx
Improve timing statistics
[flightgear.git] / src / Main / options.cxx
1 // options.cxx -- class to handle command line options
2 //
3 // Written by Curtis Olson, started April 1998.
4 //
5 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33
34 #include <math.h>               // rint()
35 #include <stdio.h>
36 #include <stdlib.h>             // atof(), atoi()
37 #include <string.h>             // strcmp()
38 #include <algorithm>
39
40 #include <iostream>
41 #include <string>
42
43 #include <simgear/math/sg_random.h>
44 #include <simgear/props/props_io.hxx>
45 #include <simgear/misc/sgstream.hxx>
46 #include <simgear/misc/sg_path.hxx>
47 #include <simgear/scene/material/mat.hxx>
48 #include <simgear/sound/soundmgr_openal.hxx>
49 #include <simgear/misc/strutils.hxx>
50 #include <Autopilot/route_mgr.hxx>
51 #include <GUI/gui.h>
52
53 #include "globals.hxx"
54 #include "fg_init.hxx"
55 #include "fg_props.hxx"
56 #include "options.hxx"
57 #include "util.hxx"
58 #include "viewmgr.hxx"
59 #include <Main/viewer.hxx>
60 #include <Environment/presets.hxx>
61
62 #include <simgear/version.h>
63 #include <osg/Version>
64
65 using std::string;
66 using std::sort;
67 using std::cout;
68 using std::cerr;
69 using std::endl;
70
71 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
72 #  include <Include/version.h>
73 #else
74 #  include <Include/no_version.h>
75 #endif
76
77 #define NEW_DEFAULT_MODEL_HZ 120
78
79 enum
80 {
81     FG_OPTIONS_OK = 0,
82     FG_OPTIONS_HELP = 1,
83     FG_OPTIONS_ERROR = 2,
84     FG_OPTIONS_EXIT = 3,
85     FG_OPTIONS_VERBOSE_HELP = 4,
86     FG_OPTIONS_SHOW_AIRCRAFT = 5,
87     FG_OPTIONS_SHOW_SOUND_DEVICES = 6
88 };
89
90 static double
91 atof( const string& str )
92 {
93     return ::atof( str.c_str() );
94 }
95
96 static int
97 atoi( const string& str )
98 {
99     return ::atoi( str.c_str() );
100 }
101
102 static int fgSetupProxy( const char *arg );
103
104 /**
105  * Set a few fail-safe default property values.
106  *
107  * These should all be set in $FG_ROOT/preferences.xml, but just
108  * in case, we provide some initial sane values here. This method
109  * should be invoked *before* reading any init files.
110  */
111 void
112 fgSetDefaults ()
113 {
114     // set a possibly independent location for scenery data
115     const char *envp = ::getenv( "FG_SCENERY" );
116
117     if ( envp != NULL ) {
118         // fg_root could be anywhere, so default to environmental
119         // variable $FG_ROOT if it is set.
120         globals->set_fg_scenery(envp);
121     } else {
122         // Otherwise, default to Scenery being in $FG_ROOT/Scenery
123         globals->set_fg_scenery("");
124     }
125
126                                 // Position (deliberately out of range)
127     fgSetDouble("/position/longitude-deg", 9999.0);
128     fgSetDouble("/position/latitude-deg", 9999.0);
129     fgSetDouble("/position/altitude-ft", -9999.0);
130
131                                 // Orientation
132     fgSetDouble("/orientation/heading-deg", 9999.0);
133     fgSetDouble("/orientation/roll-deg", 0.0);
134     fgSetDouble("/orientation/pitch-deg", 0.424);
135
136                                 // Velocities
137     fgSetDouble("/velocities/uBody-fps", 0.0);
138     fgSetDouble("/velocities/vBody-fps", 0.0);
139     fgSetDouble("/velocities/wBody-fps", 0.0);
140     fgSetDouble("/velocities/speed-north-fps", 0.0);
141     fgSetDouble("/velocities/speed-east-fps", 0.0);
142     fgSetDouble("/velocities/speed-down-fps", 0.0);
143     fgSetDouble("/velocities/airspeed-kt", 0.0);
144     fgSetDouble("/velocities/mach", 0.0);
145
146                                 // Presets
147     fgSetDouble("/sim/presets/longitude-deg", 9999.0);
148     fgSetDouble("/sim/presets/latitude-deg", 9999.0);
149     fgSetDouble("/sim/presets/altitude-ft", -9999.0);
150
151     fgSetDouble("/sim/presets/heading-deg", 9999.0);
152     fgSetDouble("/sim/presets/roll-deg", 0.0);
153     fgSetDouble("/sim/presets/pitch-deg", 0.424);
154
155     fgSetString("/sim/presets/speed-set", "knots");
156     fgSetDouble("/sim/presets/airspeed-kt", 0.0);
157     fgSetDouble("/sim/presets/mach", 0.0);
158     fgSetDouble("/sim/presets/uBody-fps", 0.0);
159     fgSetDouble("/sim/presets/vBody-fps", 0.0);
160     fgSetDouble("/sim/presets/wBody-fps", 0.0);
161     fgSetDouble("/sim/presets/speed-north-fps", 0.0);
162     fgSetDouble("/sim/presets/speed-east-fps", 0.0);
163     fgSetDouble("/sim/presets/speed-down-fps", 0.0);
164
165     fgSetBool("/sim/presets/onground", true);
166     fgSetBool("/sim/presets/trim", false);
167
168                                 // Miscellaneous
169     fgSetBool("/sim/startup/game-mode", false);
170     fgSetBool("/sim/startup/splash-screen", true);
171     fgSetBool("/sim/startup/intro-music", true);
172     // we want mouse-pointer to have an undefined value if nothing is
173     // specified so we can do the right thing for voodoo-1/2 cards.
174     // fgSetString("/sim/startup/mouse-pointer", "disabled");
175     fgSetString("/sim/control-mode", "joystick");
176     fgSetBool("/sim/auto-coordination", false);
177 #if defined(WIN32)
178     fgSetString("/sim/startup/browser-app", "webrun.bat");
179 #elif defined(__APPLE__)
180     fgSetString("/sim/startup/browser-app", "open");
181 #elif defined(sgi)
182     fgSetString("/sim/startup/browser-app", "launchWebJumper");
183 #else
184     envp = ::getenv( "WEBBROWSER" );
185     if (!envp) envp = "netscape";
186     fgSetString("/sim/startup/browser-app", envp);
187 #endif
188     fgSetString("/sim/logging/priority", "alert");
189
190                                 // Features
191     fgSetBool("/sim/hud/color/antialiased", false);
192     fgSetBool("/sim/hud/enable3d[1]", true);
193     fgSetBool("/sim/hud/visibility[1]", false);
194     fgSetBool("/sim/panel/visibility", true);
195     fgSetBool("/sim/sound/enabled", true);
196     fgSetBool("/sim/sound/working", true);
197
198                                 // Flight Model options
199     fgSetString("/sim/flight-model", "jsb");
200     fgSetString("/sim/aero", "c172");
201     fgSetInt("/sim/model-hz", NEW_DEFAULT_MODEL_HZ);
202     fgSetInt("/sim/speed-up", 1);
203
204                                 // Rendering options
205     fgSetString("/sim/rendering/fog", "nicest");
206     fgSetBool("/environment/clouds/status", true);
207     fgSetBool("/sim/startup/fullscreen", false);
208     fgSetBool("/sim/rendering/shading", true);
209     fgSetBool("/sim/rendering/skyblend", true);
210     fgSetBool("/sim/rendering/textures", true);
211     fgTie( "/sim/rendering/filtering", SGGetTextureFilter, SGSetTextureFilter, false);
212     fgSetInt("/sim/rendering/filtering", 1);
213     fgSetBool("/sim/rendering/wireframe", false);
214     fgSetBool("/sim/rendering/horizon-effect", false);
215     fgSetBool("/sim/rendering/enhanced-lighting", false);
216     fgSetBool("/sim/rendering/distance-attenuation", false);
217     fgSetBool("/sim/rendering/specular-highlight", true);
218     fgSetInt("/sim/startup/xsize", 800);
219     fgSetInt("/sim/startup/ysize", 600);
220     fgSetInt("/sim/rendering/bits-per-pixel", 16);
221     fgSetString("/sim/view-mode", "pilot");
222     fgSetDouble("/sim/current-view/heading-offset-deg", 0);
223
224                                 // HUD options
225     fgSetString("/sim/startup/units", "feet");
226     fgSetString("/sim/hud/frame-stat-type", "tris");
227
228                                 // Time options
229     fgSetInt("/sim/startup/time-offset", 0);
230     fgSetString("/sim/startup/time-offset-type", "system-offset");
231     fgSetLong("/sim/time/cur-time-override", 0);
232
233                                 // Freeze options
234     fgSetBool("/sim/freeze/master", false);
235     fgSetBool("/sim/freeze/position", false);
236     fgSetBool("/sim/freeze/clock", false);
237     fgSetBool("/sim/freeze/fuel", false);
238
239     fgSetString("/sim/multiplay/callsign", "callsign");
240     fgSetString("/sim/multiplay/rxhost", "0");
241     fgSetString("/sim/multiplay/txhost", "0");
242     fgSetInt("/sim/multiplay/rxport", 0);
243     fgSetInt("/sim/multiplay/txport", 0);
244     
245     fgSetString("/sim/version/flightgear", FLIGHTGEAR_VERSION);
246     fgSetString("/sim/version/simgear", SG_STRINGIZE(SIMGEAR_VERSION));
247     fgSetString("/sim/version/openscenegraph", osgGetVersion());
248     fgSetString("/sim/version/revision", REVISION);
249     fgSetInt("/sim/version/build-number", HUDSON_BUILD_NUMBER);
250     fgSetString("/sim/version/build-id", HUDSON_BUILD_ID);
251     if( (envp = ::getenv( "http_proxy" )) != NULL )
252       fgSetupProxy( envp );
253 }
254
255 static bool
256 parse_wind (const string &wind, double * min_hdg, double * max_hdg,
257             double * speed, double * gust)
258 {
259   string::size_type pos = wind.find('@');
260   if (pos == string::npos)
261     return false;
262   string dir = wind.substr(0, pos);
263   string spd = wind.substr(pos+1);
264   pos = dir.find(':');
265   if (pos == string::npos) {
266     *min_hdg = *max_hdg = atof(dir.c_str());
267   } else {
268     *min_hdg = atof(dir.substr(0,pos).c_str());
269     *max_hdg = atof(dir.substr(pos+1).c_str());
270   }
271   pos = spd.find(':');
272   if (pos == string::npos) {
273     *speed = *gust = atof(spd.c_str());
274   } else {
275     *speed = atof(spd.substr(0,pos).c_str());
276     *gust = atof(spd.substr(pos+1).c_str());
277   }
278   return true;
279 }
280
281 // parse a time string ([+/-]%f[:%f[:%f]]) into hours
282 static double
283 parse_time(const string& time_in) {
284     char *time_str, num[256];
285     double hours, minutes, seconds;
286     double result = 0.0;
287     int sign = 1;
288     int i;
289
290     time_str = (char *)time_in.c_str();
291
292     // printf("parse_time(): %s\n", time_str);
293
294     // check for sign
295     if ( strlen(time_str) ) {
296         if ( time_str[0] == '+' ) {
297             sign = 1;
298             time_str++;
299         } else if ( time_str[0] == '-' ) {
300             sign = -1;
301             time_str++;
302         }
303     }
304     // printf("sign = %d\n", sign);
305
306     // get hours
307     if ( strlen(time_str) ) {
308         i = 0;
309         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
310             num[i] = time_str[0];
311             time_str++;
312             i++;
313         }
314         if ( time_str[0] == ':' ) {
315             time_str++;
316         }
317         num[i] = '\0';
318         hours = atof(num);
319         // printf("hours = %.2lf\n", hours);
320
321         result += hours;
322     }
323
324     // get minutes
325     if ( strlen(time_str) ) {
326         i = 0;
327         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
328             num[i] = time_str[0];
329             time_str++;
330             i++;
331         }
332         if ( time_str[0] == ':' ) {
333             time_str++;
334         }
335         num[i] = '\0';
336         minutes = atof(num);
337         // printf("minutes = %.2lf\n", minutes);
338
339         result += minutes / 60.0;
340     }
341
342     // get seconds
343     if ( strlen(time_str) ) {
344         i = 0;
345         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
346             num[i] = time_str[0];
347             time_str++;
348             i++;
349         }
350         num[i] = '\0';
351         seconds = atof(num);
352         // printf("seconds = %.2lf\n", seconds);
353
354         result += seconds / 3600.0;
355     }
356
357     SG_LOG( SG_GENERAL, SG_INFO, " parse_time() = " << sign * result );
358
359     return(sign * result);
360 }
361
362
363 // parse a date string (yyyy:mm:dd:hh:mm:ss) into a time_t (seconds)
364 static long int
365 parse_date( const string& date)
366 {
367     struct tm gmt;
368     char * date_str, num[256];
369     int i;
370     // initialize to zero
371     gmt.tm_sec = 0;
372     gmt.tm_min = 0;
373     gmt.tm_hour = 0;
374     gmt.tm_mday = 0;
375     gmt.tm_mon = 0;
376     gmt.tm_year = 0;
377     gmt.tm_isdst = 0; // ignore daylight savings time for the moment
378     date_str = (char *)date.c_str();
379     // get year
380     if ( strlen(date_str) ) {
381         i = 0;
382         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
383             num[i] = date_str[0];
384             date_str++;
385             i++;
386         }
387         if ( date_str[0] == ':' ) {
388             date_str++;
389         }
390         num[i] = '\0';
391         gmt.tm_year = atoi(num) - 1900;
392     }
393     // get month
394     if ( strlen(date_str) ) {
395         i = 0;
396         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
397             num[i] = date_str[0];
398             date_str++;
399             i++;
400         }
401         if ( date_str[0] == ':' ) {
402             date_str++;
403         }
404         num[i] = '\0';
405         gmt.tm_mon = atoi(num) -1;
406     }
407     // get day
408     if ( strlen(date_str) ) {
409         i = 0;
410         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
411             num[i] = date_str[0];
412             date_str++;
413             i++;
414         }
415         if ( date_str[0] == ':' ) {
416             date_str++;
417         }
418         num[i] = '\0';
419         gmt.tm_mday = atoi(num);
420     }
421     // get hour
422     if ( strlen(date_str) ) {
423         i = 0;
424         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
425             num[i] = date_str[0];
426             date_str++;
427             i++;
428         }
429         if ( date_str[0] == ':' ) {
430             date_str++;
431         }
432         num[i] = '\0';
433         gmt.tm_hour = atoi(num);
434     }
435     // get minute
436     if ( strlen(date_str) ) {
437         i = 0;
438         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
439             num[i] = date_str[0];
440             date_str++;
441             i++;
442         }
443         if ( date_str[0] == ':' ) {
444             date_str++;
445         }
446         num[i] = '\0';
447         gmt.tm_min = atoi(num);
448     }
449     // get second
450     if ( strlen(date_str) ) {
451         i = 0;
452         while ( (date_str[0] != ':') && (date_str[0] != '\0') ) {
453             num[i] = date_str[0];
454             date_str++;
455             i++;
456         }
457         if ( date_str[0] == ':' ) {
458             date_str++;
459         }
460         num[i] = '\0';
461         gmt.tm_sec = atoi(num);
462     }
463     time_t theTime = sgTimeGetGMT( gmt.tm_year, gmt.tm_mon, gmt.tm_mday,
464                                    gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
465     //printf ("Date is %s\n", ctime(&theTime));
466     //printf ("in seconds that is %d\n", theTime);
467     //exit(1);
468     return (theTime);
469 }
470
471
472 // parse angle in the form of [+/-]ddd:mm:ss into degrees
473 static double
474 parse_degree( const string& degree_str) {
475     double result = parse_time( degree_str );
476
477     // printf("Degree = %.4f\n", result);
478
479     return(result);
480 }
481
482
483 // parse time offset string into seconds
484 static int
485 parse_time_offset( const string& time_str) {
486     int result;
487
488     // printf("time offset = %s\n", time_str);
489
490 #ifdef HAVE_RINT
491     result = (int)rint(parse_time(time_str) * 3600.0);
492 #else
493     result = (int)(parse_time(time_str) * 3600.0);
494 #endif
495
496     // printf("parse_time_offset(): %d\n", result);
497
498     return( result );
499 }
500
501
502 // Parse --fov=x.xx type option
503 static double
504 parse_fov( const string& arg ) {
505     double fov = atof(arg);
506
507     if ( fov < FG_FOV_MIN ) { fov = FG_FOV_MIN; }
508     if ( fov > FG_FOV_MAX ) { fov = FG_FOV_MAX; }
509
510     fgSetDouble("/sim/view[0]/config/default-field-of-view-deg", fov);
511
512     // printf("parse_fov(): result = %.4f\n", fov);
513
514     return fov;
515 }
516
517
518 // Parse I/O channel option
519 //
520 // Format is "--protocol=medium,direction,hz,medium_options,..."
521 //
522 //   protocol = { native, nmea, garmin, AV400, AV400Sim, fgfs, rul, pve, etc. }
523 //   medium = { serial, socket, file, etc. }
524 //   direction = { in, out, bi }
525 //   hz = number of times to process channel per second (floating
526 //        point values are ok.
527 //
528 // Serial example "--nmea=serial,dir,hz,device,baud" where
529 //
530 //  device = OS device name of serial line to be open()'ed
531 //  baud = {300, 1200, 2400, ..., 230400}
532 //
533 // Socket exacmple "--native=socket,dir,hz,machine,port,style" where
534 //
535 //  machine = machine name or ip address if client (leave empty if server)
536 //  port = port, leave empty to let system choose
537 //  style = tcp or udp
538 //
539 // File example "--garmin=file,dir,hz,filename" where
540 //
541 //  filename = file system file name
542
543 static bool
544 add_channel( const string& type, const string& channel_str ) {
545     // This check is neccessary to prevent fgviewer from segfaulting when given
546     // weird options. (It doesn't run the full initailization)
547     if(!globals->get_channel_options_list())
548     {
549         SG_LOG(SG_GENERAL, SG_ALERT, "Option " << type << "=" << channel_str
550                                      << " ignored.");
551         return false;
552     }
553     SG_LOG(SG_GENERAL, SG_INFO, "Channel string = " << channel_str );
554     globals->get_channel_options_list()->push_back( type + "," + channel_str );
555     return true;
556 }
557
558
559 // The parse wp and parse flight-plan options don't work anymore, because
560 // the route manager and the airport subsystems have not yet been initialized
561 // at this stage.
562
563 // Parse --wp=ID[@alt]
564 static void
565 parse_wp( const string& arg ) {
566     string_list *waypoints = globals->get_initial_waypoints();
567     if (!waypoints) {
568         waypoints = new string_list;
569         globals->set_initial_waypoints(waypoints);
570     }
571     waypoints->push_back(arg);
572 }
573
574
575 // Parse --flight-plan=[file]
576 static bool
577 parse_flightplan(const string& arg)
578 {
579     string_list *waypoints = globals->get_initial_waypoints();
580     if (!waypoints) {
581         waypoints = new string_list;
582         globals->set_initial_waypoints(waypoints);
583     }
584
585     sg_gzifstream in(arg.c_str());
586     if ( !in.is_open() )
587         return false;
588
589     while ( true ) {
590         string line;
591         getline( in, line, '\n' );
592
593         // catch extraneous (DOS) line ending character
594         if ( line[line.length() - 1] < 32 )
595             line = line.substr( 0, line.length()-1 );
596
597         if ( in.eof() )
598             break;
599
600         waypoints->push_back(line);
601     }
602     return true;
603 }
604
605
606 static int
607 fgOptLanguage( const char *arg )
608 {
609     globals->set_locale( fgInitLocale( arg ) );
610     return FG_OPTIONS_OK;
611 }
612
613 static void
614 clearLocation ()
615 {
616     fgSetString("/sim/presets/airport-id", "");
617     fgSetString("/sim/presets/vor-id", "");
618     fgSetString("/sim/presets/ndb-id", "");
619     fgSetString("/sim/presets/carrier", "");
620     fgSetString("/sim/presets/parkpos", "");
621     fgSetString("/sim/presets/fix", "");
622 }
623
624 static int
625 fgOptVOR( const char * arg )
626 {
627     clearLocation();
628     fgSetString("/sim/presets/vor-id", arg);
629     return FG_OPTIONS_OK;
630 }
631
632 static int
633 fgOptNDB( const char * arg )
634 {
635     clearLocation();
636     fgSetString("/sim/presets/ndb-id", arg);
637     return FG_OPTIONS_OK;
638 }
639
640 static int
641 fgOptCarrier( const char * arg )
642 {
643     clearLocation();
644     fgSetString("/sim/presets/carrier", arg);
645     return FG_OPTIONS_OK;
646 }
647
648 static int
649 fgOptParkpos( const char * arg )
650 {
651     fgSetString("/sim/presets/parkpos", arg);
652     return FG_OPTIONS_OK;
653 }
654
655 static int
656 fgOptFIX( const char * arg )
657 {
658     clearLocation();
659     fgSetString("/sim/presets/fix", arg);
660     return FG_OPTIONS_OK;
661 }
662
663 static int
664 fgOptLon( const char *arg )
665 {
666     clearLocation();
667     fgSetDouble("/sim/presets/longitude-deg", parse_degree( arg ));
668     fgSetDouble("/position/longitude-deg", parse_degree( arg ));
669     return FG_OPTIONS_OK;
670 }
671
672 static int
673 fgOptLat( const char *arg )
674 {
675     clearLocation();
676     fgSetDouble("/sim/presets/latitude-deg", parse_degree( arg ));
677     fgSetDouble("/position/latitude-deg", parse_degree( arg ));
678     return FG_OPTIONS_OK;
679 }
680
681 static int
682 fgOptAltitude( const char *arg )
683 {
684     fgSetBool("/sim/presets/onground", false);
685     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
686         fgSetDouble("/sim/presets/altitude-ft", atof( arg ));
687     else
688         fgSetDouble("/sim/presets/altitude-ft",
689                     atof( arg ) * SG_METER_TO_FEET);
690     return FG_OPTIONS_OK;
691 }
692
693 static int
694 fgOptUBody( const char *arg )
695 {
696     fgSetString("/sim/presets/speed-set", "UVW");
697     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
698         fgSetDouble("/sim/presets/uBody-fps", atof( arg ));
699     else
700         fgSetDouble("/sim/presets/uBody-fps",
701                     atof( arg ) * SG_METER_TO_FEET);
702     return FG_OPTIONS_OK;
703 }
704
705 static int
706 fgOptVBody( const char *arg )
707 {
708     fgSetString("/sim/presets/speed-set", "UVW");
709     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
710         fgSetDouble("/sim/presets/vBody-fps", atof( arg ));
711     else
712         fgSetDouble("/sim/presets/vBody-fps",
713                             atof( arg ) * SG_METER_TO_FEET);
714     return FG_OPTIONS_OK;
715 }
716
717 static int
718 fgOptWBody( const char *arg )
719 {
720     fgSetString("/sim/presets/speed-set", "UVW");
721     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
722         fgSetDouble("/sim/presets/wBody-fps", atof(arg));
723     else
724         fgSetDouble("/sim/presets/wBody-fps",
725                             atof(arg) * SG_METER_TO_FEET);
726     return FG_OPTIONS_OK;
727 }
728
729 static int
730 fgOptVNorth( const char *arg )
731 {
732     fgSetString("/sim/presets/speed-set", "NED");
733     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
734         fgSetDouble("/sim/presets/speed-north-fps", atof( arg ));
735     else
736         fgSetDouble("/sim/presets/speed-north-fps",
737                             atof( arg ) * SG_METER_TO_FEET);
738     return FG_OPTIONS_OK;
739 }
740
741 static int
742 fgOptVEast( const char *arg )
743 {
744     fgSetString("/sim/presets/speed-set", "NED");
745     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
746         fgSetDouble("/sim/presets/speed-east-fps", atof(arg));
747     else
748         fgSetDouble("/sim/presets/speed-east-fps",
749                     atof(arg) * SG_METER_TO_FEET);
750     return FG_OPTIONS_OK;
751 }
752
753 static int
754 fgOptVDown( const char *arg )
755 {
756     fgSetString("/sim/presets/speed-set", "NED");
757     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
758         fgSetDouble("/sim/presets/speed-down-fps", atof(arg));
759     else
760         fgSetDouble("/sim/presets/speed-down-fps",
761                             atof(arg) * SG_METER_TO_FEET);
762     return FG_OPTIONS_OK;
763 }
764
765 static int
766 fgOptVc( const char *arg )
767 {
768     // fgSetString("/sim/presets/speed-set", "knots");
769     // fgSetDouble("/velocities/airspeed-kt", atof(arg.substr(5)));
770     fgSetString("/sim/presets/speed-set", "knots");
771     fgSetDouble("/sim/presets/airspeed-kt", atof(arg));
772     return FG_OPTIONS_OK;
773 }
774
775 static int
776 fgOptMach( const char *arg )
777 {
778     fgSetString("/sim/presets/speed-set", "mach");
779     fgSetDouble("/sim/presets/mach", atof(arg));
780     return FG_OPTIONS_OK;
781 }
782
783 static int
784 fgOptRoc( const char *arg )
785 {
786     fgSetDouble("/velocities/vertical-speed-fps", atof(arg)/60);
787     return FG_OPTIONS_OK;
788 }
789
790 static int
791 fgOptFgRoot( const char *arg )
792 {
793     // this option is dealt with by fgInitFGRoot
794     return FG_OPTIONS_OK;
795 }
796
797 static int
798 fgOptFgScenery( const char *arg )
799 {
800     globals->set_fg_scenery(arg);
801     return FG_OPTIONS_OK;
802 }
803
804 static int
805 fgOptFgAircraft(const char* arg)
806 {
807   // this option is dealt with by fgInitFGAircraft
808   return FG_OPTIONS_OK;
809 }
810
811 static int
812 fgOptFov( const char *arg )
813 {
814     parse_fov( arg );
815     return FG_OPTIONS_OK;
816 }
817
818 static int
819 fgOptGeometry( const char *arg )
820 {
821     bool geometry_ok = true;
822     int xsize = 0, ysize = 0;
823     string geometry = arg;
824     string::size_type i = geometry.find('x');
825
826     if (i != string::npos) {
827         xsize = atoi(geometry.substr(0, i));
828         ysize = atoi(geometry.substr(i+1));
829     } else {
830         geometry_ok = false;
831     }
832
833     if ( xsize <= 0 || ysize <= 0 ) {
834         xsize = 640;
835         ysize = 480;
836         geometry_ok = false;
837     }
838
839     if ( !geometry_ok ) {
840         SG_LOG( SG_GENERAL, SG_ALERT, "Unknown geometry: " << geometry );
841         SG_LOG( SG_GENERAL, SG_ALERT,
842                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
843     } else {
844         SG_LOG( SG_GENERAL, SG_INFO,
845                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
846         fgSetInt("/sim/startup/xsize", xsize);
847         fgSetInt("/sim/startup/ysize", ysize);
848     }
849     return FG_OPTIONS_OK;
850 }
851
852 static int
853 fgOptBpp( const char *arg )
854 {
855     string bits_per_pix = arg;
856     if ( bits_per_pix == "16" ) {
857         fgSetInt("/sim/rendering/bits-per-pixel", 16);
858     } else if ( bits_per_pix == "24" ) {
859         fgSetInt("/sim/rendering/bits-per-pixel", 24);
860     } else if ( bits_per_pix == "32" ) {
861         fgSetInt("/sim/rendering/bits-per-pixel", 32);
862     } else {
863         SG_LOG(SG_GENERAL, SG_ALERT, "Unsupported bpp " << bits_per_pix);
864     }
865     return FG_OPTIONS_OK;
866 }
867
868 static int
869 fgOptTimeOffset( const char *arg )
870 {
871     fgSetInt("/sim/startup/time-offset",
872                 parse_time_offset( arg ));
873     fgSetString("/sim/startup/time-offset-type", "system-offset");
874     return FG_OPTIONS_OK;
875 }
876
877 static int
878 fgOptStartDateSys( const char *arg )
879 {
880     fgSetInt("/sim/startup/time-offset", parse_date( arg ) );
881     fgSetString("/sim/startup/time-offset-type", "system");
882     return FG_OPTIONS_OK;
883 }
884
885 static int
886 fgOptStartDateLat( const char *arg )
887 {
888     fgSetInt("/sim/startup/time-offset", parse_date( arg ) );
889     fgSetString("/sim/startup/time-offset-type", "latitude");
890     return FG_OPTIONS_OK;
891 }
892
893 static int
894 fgOptStartDateGmt( const char *arg )
895 {
896     fgSetInt("/sim/startup/time-offset", parse_date( arg ) );
897     fgSetString("/sim/startup/time-offset-type", "gmt");
898     return FG_OPTIONS_OK;
899 }
900
901 static int
902 fgSetupProxy( const char *arg )
903 {
904     string options = simgear::strutils::strip( arg );
905     string host, port, auth;
906     string::size_type pos;
907
908     // this is NURLP - NURLP is not an url parser
909     if( simgear::strutils::starts_with( options, "http://" ) )
910         options = options.substr( 7 );
911     if( simgear::strutils::ends_with( options, "/" ) )
912         options = options.substr( 0, options.length() - 1 );
913
914     host = port = auth = "";
915     if ((pos = options.find("@")) != string::npos)
916         auth = options.substr(0, pos++);
917     else
918         pos = 0;
919
920     host = options.substr(pos, options.size());
921     if ((pos = host.find(":")) != string::npos) {
922         port = host.substr(++pos, host.size());
923         host.erase(--pos, host.size());
924     }
925
926     fgSetString("/sim/presets/proxy/host", host.c_str());
927     fgSetString("/sim/presets/proxy/port", port.c_str());
928     fgSetString("/sim/presets/proxy/authentication", auth.c_str());
929
930     return FG_OPTIONS_OK;
931 }
932
933 static int
934 fgOptTraceRead( const char *arg )
935 {
936     string name = arg;
937     SG_LOG(SG_GENERAL, SG_INFO, "Tracing reads for property " << name);
938     fgGetNode(name.c_str(), true)
939         ->setAttribute(SGPropertyNode::TRACE_READ, true);
940     return FG_OPTIONS_OK;
941 }
942
943 static int
944 fgOptLogLevel( const char *arg )
945 {
946     fgSetString("/sim/logging/classes", "all");
947     fgSetString("/sim/logging/priority", arg);
948
949     string priority = arg;
950     logbuf::set_log_classes(SG_ALL);
951     if (priority == "bulk") {
952       logbuf::set_log_priority(SG_BULK);
953     } else if (priority == "debug") {
954       logbuf::set_log_priority(SG_DEBUG);
955     } else if (priority == "info") {
956       logbuf::set_log_priority(SG_INFO);
957     } else if (priority == "warn") {
958       logbuf::set_log_priority(SG_WARN);
959     } else if (priority == "alert") {
960       logbuf::set_log_priority(SG_ALERT);
961     } else {
962       SG_LOG(SG_GENERAL, SG_WARN, "Unknown logging priority " << priority);
963     }
964     SG_LOG(SG_GENERAL, SG_DEBUG, "Logging priority is " << priority);
965
966     return FG_OPTIONS_OK;
967 }
968
969
970 static int
971 fgOptTraceWrite( const char *arg )
972 {
973     string name = arg;
974     SG_LOG(SG_GENERAL, SG_INFO, "Tracing writes for property " << name);
975     fgGetNode(name.c_str(), true)
976         ->setAttribute(SGPropertyNode::TRACE_WRITE, true);
977     return FG_OPTIONS_OK;
978 }
979
980 static int
981 fgOptViewOffset( const char *arg )
982 {
983     // $$$ begin - added VS Renganathan, 14 Oct 2K
984     // for multi-window outside window imagery
985     string woffset = arg;
986     double default_view_offset = 0.0;
987     if ( woffset == "LEFT" ) {
988             default_view_offset = SGD_PI * 0.25;
989     } else if ( woffset == "RIGHT" ) {
990         default_view_offset = SGD_PI * 1.75;
991     } else if ( woffset == "CENTER" ) {
992         default_view_offset = 0.00;
993     } else {
994         default_view_offset = atof( woffset.c_str() ) * SGD_DEGREES_TO_RADIANS;
995     }
996     /* apparently not used (CLO, 11 Jun 2002)
997         FGViewer *pilot_view =
998             (FGViewer *)globals->get_viewmgr()->get_view( 0 ); */
999     // this will work without calls to the viewer...
1000     fgSetDouble( "/sim/current-view/heading-offset-deg",
1001                     default_view_offset  * SGD_RADIANS_TO_DEGREES );
1002     // $$$ end - added VS Renganathan, 14 Oct 2K
1003     return FG_OPTIONS_OK;
1004 }
1005
1006 static int
1007 fgOptVisibilityMeters( const char *arg )
1008 {
1009     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) );
1010     return FG_OPTIONS_OK;
1011 }
1012
1013 static int
1014 fgOptVisibilityMiles( const char *arg )
1015 {
1016     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) * 5280.0 * SG_FEET_TO_METER );
1017     return FG_OPTIONS_OK;
1018 }
1019
1020 static int
1021 fgOptRandomWind( const char *arg )
1022 {
1023     double min_hdg = sg_random() * 360.0;
1024     double max_hdg = min_hdg + (20 - sqrt(sg_random() * 400));
1025     double speed = sg_random() * sg_random() * 40;
1026     double gust = speed + (10 - sqrt(sg_random() * 100));
1027     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1028     return FG_OPTIONS_OK;
1029 }
1030
1031 static int
1032 fgOptWind( const char *arg )
1033 {
1034     double min_hdg = 0.0, max_hdg = 0.0, speed = 0.0, gust = 0.0;
1035     if (!parse_wind( arg, &min_hdg, &max_hdg, &speed, &gust)) {
1036         SG_LOG( SG_GENERAL, SG_ALERT, "bad wind value " << arg );
1037         return FG_OPTIONS_ERROR;
1038     }
1039     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1040     return FG_OPTIONS_OK;
1041 }
1042
1043 static int
1044 fgOptTurbulence( const char *arg )
1045 {
1046     Environment::Presets::TurbulenceSingleton::instance()->preset( atof(arg) );
1047     return FG_OPTIONS_OK;
1048 }
1049
1050 static int
1051 fgOptCeiling( const char *arg )
1052 {
1053     double elevation, thickness;
1054     string spec = arg;
1055     string::size_type pos = spec.find(':');
1056     if (pos == string::npos) {
1057         elevation = atof(spec.c_str());
1058         thickness = 2000;
1059     } else {
1060         elevation = atof(spec.substr(0, pos).c_str());
1061         thickness = atof(spec.substr(pos + 1).c_str());
1062     }
1063     Environment::Presets::CeilingSingleton::instance()->preset( elevation, thickness );
1064     return FG_OPTIONS_OK;
1065 }
1066
1067 static int
1068 fgOptWp( const char *arg )
1069 {
1070     parse_wp( arg );
1071     return FG_OPTIONS_OK;
1072 }
1073
1074 static int
1075 fgOptFlightPlan( const char *arg )
1076 {
1077     parse_flightplan ( arg );
1078     return FG_OPTIONS_OK;
1079 }
1080
1081 static int
1082 fgOptConfig( const char *arg )
1083 {
1084     string file = arg;
1085     try {
1086         readProperties(file, globals->get_props());
1087     } catch (const sg_exception &e) {
1088         string message = "Error loading config file: ";
1089         message += e.getFormattedMessage() + e.getOrigin();
1090         SG_LOG(SG_INPUT, SG_ALERT, message);
1091         exit(2);
1092     }
1093     return FG_OPTIONS_OK;
1094 }
1095
1096 static bool
1097 parse_colon (const string &s, double * val1, double * val2)
1098 {
1099     string::size_type pos = s.find(':');
1100     if (pos == string::npos) {
1101         *val2 = atof(s);
1102         return false;
1103     } else {
1104         *val1 = atof(s.substr(0, pos).c_str());
1105         *val2 = atof(s.substr(pos+1).c_str());
1106         return true;
1107     }
1108 }
1109
1110
1111 static int
1112 fgOptFailure( const char * arg )
1113 {
1114     string a = arg;
1115     if (a == "pitot") {
1116         fgSetBool("/systems/pitot/serviceable", false);
1117     } else if (a == "static") {
1118         fgSetBool("/systems/static/serviceable", false);
1119     } else if (a == "vacuum") {
1120         fgSetBool("/systems/vacuum/serviceable", false);
1121     } else if (a == "electrical") {
1122         fgSetBool("/systems/electrical/serviceable", false);
1123     } else {
1124         SG_LOG(SG_INPUT, SG_ALERT, "Unknown failure mode: " << a);
1125         return FG_OPTIONS_ERROR;
1126     }
1127
1128     return FG_OPTIONS_OK;
1129 }
1130
1131
1132 static int
1133 fgOptNAV1( const char * arg )
1134 {
1135     double radial, freq;
1136     if (parse_colon(arg, &radial, &freq))
1137         fgSetDouble("/instrumentation/nav[0]/radials/selected-deg", radial);
1138     fgSetDouble("/instrumentation/nav[0]/frequencies/selected-mhz", freq);
1139     return FG_OPTIONS_OK;
1140 }
1141
1142 static int
1143 fgOptNAV2( const char * arg )
1144 {
1145     double radial, freq;
1146     if (parse_colon(arg, &radial, &freq))
1147         fgSetDouble("/instrumentation/nav[1]/radials/selected-deg", radial);
1148     fgSetDouble("/instrumentation/nav[1]/frequencies/selected-mhz", freq);
1149     return FG_OPTIONS_OK;
1150 }
1151
1152 static int
1153 fgOptADF( const char * arg )
1154 {
1155     double rot, freq;
1156     if (parse_colon(arg, &rot, &freq))
1157         fgSetDouble("/instrumentation/adf/rotation-deg", rot);
1158     fgSetDouble("/instrumentation/adf/frequencies/selected-khz", freq);
1159     return FG_OPTIONS_OK;
1160 }
1161
1162 static int
1163 fgOptDME( const char *arg )
1164 {
1165     string opt = arg;
1166     if (opt == "nav1") {
1167         fgSetInt("/instrumentation/dme/switch-position", 1);
1168         fgSetString("/instrumentation/dme/frequencies/source",
1169                     "/instrumentation/nav[0]/frequencies/selected-mhz");
1170     } else if (opt == "nav2") {
1171         fgSetInt("/instrumentation/dme/switch-position", 3);
1172         fgSetString("/instrumentation/dme/frequencies/source",
1173                     "/instrumentation/nav[1]/frequencies/selected-mhz");
1174     } else {
1175         fgSetInt("/instrumentation/dme/switch-position", 2);
1176         fgSetString("/instrumentation/dme/frequencies/source",
1177                     "/instrumentation/dme/frequencies/selected-mhz");
1178         fgSetString("/instrumentation/dme/frequencies/selected-mhz", arg);
1179     }
1180     return FG_OPTIONS_OK;
1181 }
1182
1183 static int
1184 fgOptLivery( const char *arg )
1185 {
1186     string opt = arg;
1187     string livery_path = "livery/" + opt;
1188     fgSetString("/sim/model/texture-path", livery_path.c_str() );
1189     return FG_OPTIONS_OK;
1190 }
1191
1192 static int
1193 fgOptScenario( const char *arg )
1194 {
1195     SGPropertyNode_ptr ai_node = fgGetNode( "/sim/ai", true );
1196     vector<SGPropertyNode_ptr> scenarii = ai_node->getChildren( "scenario" );
1197     int index = -1;
1198     for ( size_t i = 0; i < scenarii.size(); ++i ) {
1199         int ind = scenarii[i]->getIndex();
1200         if ( index < ind ) {
1201             index = ind;
1202         }
1203     }
1204     SGPropertyNode_ptr scenario = ai_node->getNode( "scenario", index + 1, true );
1205     scenario->setStringValue( arg );
1206     ai_node->setBoolValue( "enabled", true );
1207     return FG_OPTIONS_OK;
1208 }
1209
1210 static int
1211 fgOptRunway( const char *arg )
1212 {
1213     fgSetString("/sim/presets/runway", arg );
1214     fgSetBool("/sim/presets/runway-requested", true );
1215     return FG_OPTIONS_OK;
1216 }
1217
1218 static int
1219 fgOptParking( const char *arg )
1220 {
1221     cerr << "Processing argument " << arg << endl;
1222     fgSetString("/sim/presets/parking", arg );
1223     fgSetBool  ("/sim/presets/parking-requested", true );
1224     return FG_OPTIONS_OK;
1225 }
1226
1227 static int
1228 fgOptVersion( const char *arg )
1229 {
1230     cerr << "FlightGear version: " << FLIGHTGEAR_VERSION << endl;
1231     cerr << "Revision: " << REVISION << endl;
1232     cerr << "Build-Id: " << HUDSON_BUILD_ID << endl;
1233     cerr << "FG_ROOT=" << globals->get_fg_root() << endl;
1234     cerr << "FG_HOME=" << fgGetString("/sim/fg-home") << endl;
1235     cerr << "FG_SCENERY=";
1236
1237     int didsome = 0;
1238     string_list scn = globals->get_fg_scenery();
1239     for (string_list::const_iterator it = scn.begin(); it != scn.end(); it++)
1240     {
1241         if (didsome) cerr << ":";
1242         didsome++;
1243         cerr << *it;
1244     }
1245     cerr << endl;
1246     cerr << "SimGear version: " << SG_STRINGIZE(SIMGEAR_VERSION) << endl;
1247     cerr << "PLIB version: " << PLIB_VERSION << endl;
1248     return FG_OPTIONS_EXIT;
1249 }
1250
1251 static int
1252 fgOptFpe(const char* arg)
1253 {
1254     // Actually handled in bootstrap.cxx
1255     return FG_OPTIONS_OK;
1256 }
1257
1258 static int
1259 fgOptFgviewer(const char* arg)
1260 {
1261     // Actually handled in bootstrap.cxx
1262     return FG_OPTIONS_OK;
1263 }
1264
1265 static int
1266 fgOptCallSign(const char * arg)
1267 {
1268     int i;
1269     char callsign[11];
1270     strncpy(callsign,arg,10);
1271     callsign[10]=0;
1272     for (i=0;callsign[i];i++)
1273     {
1274         char c = callsign[i];
1275         if (c >= 'A' && c <= 'Z') continue;
1276         if (c >= 'a' && c <= 'z') continue;
1277         if (c >= '0' && c <= '9') continue;
1278         if (c == '-' || c == '_') continue;
1279         // convert any other illegal characters
1280         callsign[i]='-';
1281     }
1282     fgSetString("sim/multiplay/callsign", callsign );
1283     return FG_OPTIONS_OK;
1284 }
1285
1286
1287 static map<string,size_t> fgOptionMap;
1288
1289 /*
1290    option       has_param type        property         b_param s_param  func
1291
1292 where:
1293  option    : name of the option
1294  has_param : option is --name=value if true or --name if false
1295  type      : OPTION_BOOL    - property is a boolean
1296              OPTION_STRING  - property is a string
1297              OPTION_DOUBLE  - property is a double
1298              OPTION_INT     - property is an integer
1299              OPTION_CHANNEL - name of option is the name of a channel
1300              OPTION_FUNC    - the option trigger a function
1301  b_param   : if type==OPTION_BOOL,
1302              value set to the property (has_param is false for boolean)
1303  s_param   : if type==OPTION_STRING,
1304              value set to the property if has_param is false
1305  func      : function called if type==OPTION_FUNC. if has_param is true,
1306              the value is passed to the function as a string, otherwise,
1307              s_param is passed.
1308
1309     For OPTION_DOUBLE and OPTION_INT, the parameter value is converted into a
1310     double or an integer and set to the property.
1311
1312     For OPTION_CHANNEL, add_channel is called with the parameter value as the
1313     argument.
1314 */
1315
1316 enum OptionType { OPTION_BOOL, OPTION_STRING, OPTION_DOUBLE, OPTION_INT, OPTION_CHANNEL, OPTION_FUNC };
1317 struct OptionDesc {
1318     const char *option;
1319     bool has_param;
1320     enum OptionType type;
1321     const char *property;
1322     bool b_param;
1323     const char *s_param;
1324     int (*func)( const char * );
1325     } fgOptionArray[] = {
1326
1327     {"language",                     true,  OPTION_FUNC,   "", false, "", fgOptLanguage },
1328     {"disable-game-mode",            false, OPTION_BOOL,   "/sim/startup/game-mode", false, "", 0 },
1329     {"enable-game-mode",             false, OPTION_BOOL,   "/sim/startup/game-mode", true, "", 0 },
1330     {"disable-splash-screen",        false, OPTION_BOOL,   "/sim/startup/splash-screen", false, "", 0 },
1331     {"enable-splash-screen",         false, OPTION_BOOL,   "/sim/startup/splash-screen", true, "", 0 },
1332     {"disable-intro-music",          false, OPTION_BOOL,   "/sim/startup/intro-music", false, "", 0 },
1333     {"enable-intro-music",           false, OPTION_BOOL,   "/sim/startup/intro-music", true, "", 0 },
1334     {"disable-mouse-pointer",        false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "disabled", 0 },
1335     {"enable-mouse-pointer",         false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "enabled", 0 },
1336     {"disable-random-objects",       false, OPTION_BOOL,   "/sim/rendering/random-objects", false, "", 0 },
1337     {"enable-random-objects",        false, OPTION_BOOL,   "/sim/rendering/random-objects", true, "", 0 },
1338     {"disable-real-weather-fetch",   false, OPTION_BOOL,   "/environment/realwx/enabled", false, "", 0 },
1339     {"enable-real-weather-fetch",    false, OPTION_BOOL,   "/environment/realwx/enabled", true,  "", 0 },
1340     {"metar",                        true,  OPTION_STRING, "/environment/metar/data", false, "", 0 },
1341     {"disable-ai-models",            false, OPTION_BOOL,   "/sim/ai/enabled", false, "", 0 },
1342     {"enable-ai-models",             false, OPTION_BOOL,   "/sim/ai/enabled", true, "", 0 },
1343     {"disable-ai-traffic",           false, OPTION_BOOL,   "/sim/traffic-manager/enabled", false, "", 0 },
1344     {"enable-ai-traffic",            false, OPTION_BOOL,   "/sim/traffic-manager/enabled", true,  "", 0 },
1345     {"disable-freeze",               false, OPTION_BOOL,   "/sim/freeze/master", false, "", 0 },
1346     {"enable-freeze",                false, OPTION_BOOL,   "/sim/freeze/master", true, "", 0 },
1347     {"disable-fuel-freeze",          false, OPTION_BOOL,   "/sim/freeze/fuel", false, "", 0 },
1348     {"enable-fuel-freeze",           false, OPTION_BOOL,   "/sim/freeze/fuel", true, "", 0 },
1349     {"disable-clock-freeze",         false, OPTION_BOOL,   "/sim/freeze/clock", false, "", 0 },
1350     {"enable-clock-freeze",          false, OPTION_BOOL,   "/sim/freeze/clock", true, "", 0 },
1351     {"disable-hud-3d",               false, OPTION_BOOL,   "/sim/hud/enable3d[1]", false, "", 0 },
1352     {"enable-hud-3d",                false, OPTION_BOOL,   "/sim/hud/enable3d[1]", true, "", 0 },
1353     {"disable-anti-alias-hud",       false, OPTION_BOOL,   "/sim/hud/color/antialiased", false, "", 0 },
1354     {"enable-anti-alias-hud",        false, OPTION_BOOL,   "/sim/hud/color/antialiased", true, "", 0 },
1355     {"control",                      true,  OPTION_STRING, "/sim/control-mode", false, "", 0 },
1356     {"disable-auto-coordination",    false, OPTION_BOOL,   "/sim/auto-coordination", false, "", 0 },
1357     {"enable-auto-coordination",     false, OPTION_BOOL,   "/sim/auto-coordination", true, "", 0 },
1358     {"browser-app",                  true,  OPTION_STRING, "/sim/startup/browser-app", false, "", 0 },
1359     {"disable-hud",                  false, OPTION_BOOL,   "/sim/hud/visibility[1]", false, "", 0 },
1360     {"enable-hud",                   false, OPTION_BOOL,   "/sim/hud/visibility[1]", true, "", 0 },
1361     {"disable-panel",                false, OPTION_BOOL,   "/sim/panel/visibility", false, "", 0 },
1362     {"enable-panel",                 false, OPTION_BOOL,   "/sim/panel/visibility", true, "", 0 },
1363     {"disable-sound",                false, OPTION_BOOL,   "/sim/sound/working", false, "", 0 },
1364     {"enable-sound",                 false, OPTION_BOOL,   "/sim/sound/working", true, "", 0 },
1365     {"sound-device",                 true,  OPTION_STRING, "/sim/sound/device-name", false, "", 0 },
1366     {"airport",                      true,  OPTION_STRING, "/sim/presets/airport-id", false, "", 0 },
1367     {"runway",                       true,  OPTION_FUNC,   "", false, "", fgOptRunway },
1368     {"vor",                          true,  OPTION_FUNC,   "", false, "", fgOptVOR },
1369     {"ndb",                          true,  OPTION_FUNC,   "", false, "", fgOptNDB },
1370     {"carrier",                      true,  OPTION_FUNC,   "", false, "", fgOptCarrier },
1371     {"parkpos",                      true,  OPTION_FUNC,   "", false, "", fgOptParkpos },
1372     {"fix",                          true,  OPTION_FUNC,   "", false, "", fgOptFIX },
1373     {"offset-distance",              true,  OPTION_DOUBLE, "/sim/presets/offset-distance-nm", false, "", 0 },
1374     {"offset-azimuth",               true,  OPTION_DOUBLE, "/sim/presets/offset-azimuth-deg", false, "", 0 },
1375     {"lon",                          true,  OPTION_FUNC,   "", false, "", fgOptLon },
1376     {"lat",                          true,  OPTION_FUNC,   "", false, "", fgOptLat },
1377     {"altitude",                     true,  OPTION_FUNC,   "", false, "", fgOptAltitude },
1378     {"uBody",                        true,  OPTION_FUNC,   "", false, "", fgOptUBody },
1379     {"vBody",                        true,  OPTION_FUNC,   "", false, "", fgOptVBody },
1380     {"wBody",                        true,  OPTION_FUNC,   "", false, "", fgOptWBody },
1381     {"vNorth",                       true,  OPTION_FUNC,   "", false, "", fgOptVNorth },
1382     {"vEast",                        true,  OPTION_FUNC,   "", false, "", fgOptVEast },
1383     {"vDown",                        true,  OPTION_FUNC,   "", false, "", fgOptVDown },
1384     {"vc",                           true,  OPTION_FUNC,   "", false, "", fgOptVc },
1385     {"mach",                         true,  OPTION_FUNC,   "", false, "", fgOptMach },
1386     {"heading",                      true,  OPTION_DOUBLE, "/sim/presets/heading-deg", false, "", 0 },
1387     {"roll",                         true,  OPTION_DOUBLE, "/sim/presets/roll-deg", false, "", 0 },
1388     {"pitch",                        true,  OPTION_DOUBLE, "/sim/presets/pitch-deg", false, "", 0 },
1389     {"glideslope",                   true,  OPTION_DOUBLE, "/sim/presets/glideslope-deg", false, "", 0 },
1390     {"roc",                          true,  OPTION_FUNC,   "", false, "", fgOptRoc },
1391     {"fg-root",                      true,  OPTION_FUNC,   "", false, "", fgOptFgRoot },
1392     {"fg-scenery",                   true,  OPTION_FUNC,   "", false, "", fgOptFgScenery },
1393     {"fg-aircraft",                  true,  OPTION_FUNC,   "", false, "", fgOptFgAircraft },
1394     {"fdm",                          true,  OPTION_STRING, "/sim/flight-model", false, "", 0 },
1395     {"aero",                         true,  OPTION_STRING, "/sim/aero", false, "", 0 },
1396     {"aircraft-dir",                 true,  OPTION_STRING, "/sim/aircraft-dir", false, "", 0 },
1397     {"model-hz",                     true,  OPTION_INT,    "/sim/model-hz", false, "", 0 },
1398     {"speed",                        true,  OPTION_INT,    "/sim/speed-up", false, "", 0 },
1399     {"trim",                         false, OPTION_BOOL,   "/sim/presets/trim", true, "", 0 },
1400     {"notrim",                       false, OPTION_BOOL,   "/sim/presets/trim", false, "", 0 },
1401     {"on-ground",                    false, OPTION_BOOL,   "/sim/presets/onground", true, "", 0 },
1402     {"in-air",                       false, OPTION_BOOL,   "/sim/presets/onground", false, "", 0 },
1403     {"fog-disable",                  false, OPTION_STRING, "/sim/rendering/fog", false, "disabled", 0 },
1404     {"fog-fastest",                  false, OPTION_STRING, "/sim/rendering/fog", false, "fastest", 0 },
1405     {"fog-nicest",                   false, OPTION_STRING, "/sim/rendering/fog", false, "nicest", 0 },
1406     {"disable-horizon-effect",       false, OPTION_BOOL,   "/sim/rendering/horizon-effect", false, "", 0 },
1407     {"enable-horizon-effect",        false, OPTION_BOOL,   "/sim/rendering/horizon-effect", true, "", 0 },
1408     {"disable-enhanced-lighting",    false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", false, "", 0 },
1409     {"enable-enhanced-lighting",     false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", true, "", 0 },
1410     {"disable-distance-attenuation", false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", false, "", 0 },
1411     {"enable-distance-attenuation",  false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", true, "", 0 },
1412     {"disable-specular-highlight",   false, OPTION_BOOL,   "/sim/rendering/specular-highlight", false, "", 0 },
1413     {"enable-specular-highlight",    false, OPTION_BOOL,   "/sim/rendering/specular-highlight", true, "", 0 },
1414     {"disable-clouds",               false, OPTION_BOOL,   "/environment/clouds/status", false, "", 0 },
1415     {"enable-clouds",                false, OPTION_BOOL,   "/environment/clouds/status", true, "", 0 },
1416     {"disable-clouds3d",             false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", false, "", 0 },
1417     {"enable-clouds3d",              false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", true, "", 0 },
1418     {"fov",                          true,  OPTION_FUNC,   "", false, "", fgOptFov },
1419     {"aspect-ratio-multiplier",      true,  OPTION_DOUBLE, "/sim/current-view/aspect-ratio-multiplier", false, "", 0 },
1420     {"disable-fullscreen",           false, OPTION_BOOL,   "/sim/startup/fullscreen", false, "", 0 },
1421     {"enable-fullscreen",            false, OPTION_BOOL,   "/sim/startup/fullscreen", true, "", 0 },
1422     {"disable-save-on-exit",         false, OPTION_BOOL,   "/sim/startup/save-on-exit", false, "", 0 },
1423     {"enable-save-on-exit",          false, OPTION_BOOL,   "/sim/startup/save-on-exit", true, "", 0 },
1424     {"shading-flat",                 false, OPTION_BOOL,   "/sim/rendering/shading", false, "", 0 },
1425     {"shading-smooth",               false, OPTION_BOOL,   "/sim/rendering/shading", true, "", 0 },
1426     {"disable-skyblend",             false, OPTION_BOOL,   "/sim/rendering/skyblend", false, "", 0 },
1427     {"enable-skyblend",              false, OPTION_BOOL,   "/sim/rendering/skyblend", true, "", 0 },
1428     {"disable-textures",             false, OPTION_BOOL,   "/sim/rendering/textures", false, "", 0 },
1429     {"enable-textures",              false, OPTION_BOOL,   "/sim/rendering/textures", true, "", 0 },
1430     {"texture-filtering",            false, OPTION_INT,    "/sim/rendering/filtering", 1, "", 0 },
1431     {"disable-wireframe",            false, OPTION_BOOL,   "/sim/rendering/wireframe", false, "", 0 },
1432     {"enable-wireframe",             false, OPTION_BOOL,   "/sim/rendering/wireframe", true, "", 0 },
1433     {"geometry",                     true,  OPTION_FUNC,   "", false, "", fgOptGeometry },
1434     {"bpp",                          true,  OPTION_FUNC,   "", false, "", fgOptBpp },
1435     {"units-feet",                   false, OPTION_STRING, "/sim/startup/units", false, "feet", 0 },
1436     {"units-meters",                 false, OPTION_STRING, "/sim/startup/units", false, "meters", 0 },
1437     {"timeofday",                    true,  OPTION_STRING, "/sim/startup/time-offset-type", false, "noon", 0 },
1438     {"season",                       true,  OPTION_STRING, "/sim/startup/season", false, "summer", 0 },
1439     {"time-offset",                  true,  OPTION_FUNC,   "", false, "", fgOptTimeOffset },
1440     {"time-match-real",              false, OPTION_STRING, "/sim/startup/time-offset-type", false, "system-offset", 0 },
1441     {"time-match-local",             false, OPTION_STRING, "/sim/startup/time-offset-type", false, "latitude-offset", 0 },
1442     {"start-date-sys",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateSys },
1443     {"start-date-lat",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateLat },
1444     {"start-date-gmt",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateGmt },
1445     {"hud-tris",                     false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "tris", 0 },
1446     {"hud-culled",                   false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "culled", 0 },
1447     {"atcsim",                       true,  OPTION_CHANNEL, "", false, "dummy", 0 },
1448     {"atlas",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1449     {"httpd",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1450 #ifdef FG_JPEG_SERVER
1451     {"jpg-httpd",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1452 #endif
1453     {"native",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1454     {"native-ctrls",                 true,  OPTION_CHANNEL, "", false, "", 0 },
1455     {"native-fdm",                   true,  OPTION_CHANNEL, "", false, "", 0 },
1456     {"native-gui",                   true,  OPTION_CHANNEL, "", false, "", 0 },
1457     {"opengc",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1458     {"AV400",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1459     {"AV400Sim",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1460     {"garmin",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1461     {"nmea",                         true,  OPTION_CHANNEL, "", false, "", 0 },
1462     {"generic",                      true,  OPTION_CHANNEL, "", false, "", 0 },
1463     {"props",                        true,  OPTION_CHANNEL, "", false, "", 0 },
1464     {"telnet",                       true,  OPTION_CHANNEL, "", false, "", 0 },
1465     {"pve",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1466     {"ray",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1467     {"rul",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1468     {"joyclient",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1469     {"jsclient",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1470     {"proxy",                        true,  OPTION_FUNC,    "", false, "", fgSetupProxy },
1471     {"callsign",                     true,  OPTION_FUNC,    "", false, "", fgOptCallSign},
1472     {"multiplay",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1473 #ifdef FG_HAVE_HLA
1474     {"hla",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1475 #endif
1476     {"trace-read",                   true,  OPTION_FUNC,   "", false, "", fgOptTraceRead },
1477     {"trace-write",                  true,  OPTION_FUNC,   "", false, "", fgOptTraceWrite },
1478     {"log-level",                    true,  OPTION_FUNC,   "", false, "", fgOptLogLevel },
1479     {"view-offset",                  true,  OPTION_FUNC,   "", false, "", fgOptViewOffset },
1480     {"visibility",                   true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMeters },
1481     {"visibility-miles",             true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMiles },
1482     {"random-wind",                  false, OPTION_FUNC,   "", false, "", fgOptRandomWind },
1483     {"wind",                         true,  OPTION_FUNC,   "", false, "", fgOptWind },
1484     {"turbulence",                   true,  OPTION_FUNC,   "", false, "", fgOptTurbulence },
1485     {"ceiling",                      true,  OPTION_FUNC,   "", false, "", fgOptCeiling },
1486     {"wp",                           true,  OPTION_FUNC,   "", false, "", fgOptWp },
1487     {"flight-plan",                  true,  OPTION_FUNC,   "", false, "", fgOptFlightPlan },
1488     {"config",                       true,  OPTION_FUNC,   "", false, "", fgOptConfig },
1489     {"aircraft",                     true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1490     {"vehicle",                      true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1491     {"failure",                      true,  OPTION_FUNC,   "", false, "", fgOptFailure },
1492     {"com1",                         true,  OPTION_DOUBLE, "/instrumentation/comm[0]/frequencies/selected-mhz", false, "", 0 },
1493     {"com2",                         true,  OPTION_DOUBLE, "/instrumentation/comm[1]/frequencies/selected-mhz", false, "", 0 },
1494     {"nav1",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV1 },
1495     {"nav2",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV2 },
1496     {"adf",                          true,  OPTION_FUNC,   "", false, "", fgOptADF },
1497     {"dme",                          true,  OPTION_FUNC,   "", false, "", fgOptDME },
1498     {"min-status",                   true,  OPTION_STRING,  "/sim/aircraft-min-status", false, "all", 0 },
1499     {"livery",                       true,  OPTION_FUNC,   "", false, "", fgOptLivery },
1500     {"ai-scenario",                  true,  OPTION_FUNC,   "", false, "", fgOptScenario },
1501     {"parking-id",                   true,  OPTION_FUNC,   "", false, "", fgOptParking  },
1502     {"version",                      false, OPTION_FUNC,   "", false, "", fgOptVersion },
1503     {"enable-fpe",                   false, OPTION_FUNC,   "", false, "", fgOptFpe},
1504     {"fgviewer",                     false, OPTION_FUNC,   "", false, "", fgOptFgviewer},
1505     {0}
1506 };
1507
1508
1509 // Set a property for the --prop: option. Syntax: --prop:[<type>:]<name>=<value>
1510 // <type> can be "double" etc. but also only the first letter "d".
1511 // Examples:  --prop:alpha=1  --prop:bool:beta=true  --prop:d:gamma=0.123
1512 static bool
1513 set_property(const string& arg)
1514 {
1515     string::size_type pos = arg.find('=');
1516     if (pos == arg.npos || pos == 0 || pos + 1 == arg.size())
1517         return false;
1518
1519     string name = arg.substr(0, pos);
1520     string value = arg.substr(pos + 1);
1521     string type;
1522     pos = name.find(':');
1523
1524     if (pos != name.npos && pos != 0 && pos + 1 != name.size()) {
1525         type = name.substr(0, pos);
1526         name = name.substr(pos + 1);
1527     }
1528     SGPropertyNode *n = fgGetNode(name.c_str(), true);
1529
1530     bool writable = n->getAttribute(SGPropertyNode::WRITE);
1531     if (!writable)
1532         n->setAttribute(SGPropertyNode::WRITE, true);
1533
1534     bool ret = false;
1535     if (type.empty())
1536         ret = n->setUnspecifiedValue(value.c_str());
1537     else if (type == "s" || type == "string")
1538         ret = n->setStringValue(value.c_str());
1539     else if (type == "d" || type == "double")
1540         ret = n->setDoubleValue(strtod(value.c_str(), 0));
1541     else if (type == "f" || type == "float")
1542         ret = n->setFloatValue(atof(value.c_str()));
1543     else if (type == "l" || type == "long")
1544         ret =  n->setLongValue(strtol(value.c_str(), 0, 0));
1545     else if (type == "i" || type == "int")
1546         ret =  n->setIntValue(atoi(value.c_str()));
1547     else if (type == "b" || type == "bool")
1548         ret =  n->setBoolValue(value == "true" || atoi(value.c_str()) != 0);
1549
1550     if (!writable)
1551         n->setAttribute(SGPropertyNode::WRITE, false);
1552     return ret;
1553 }
1554
1555
1556 // Parse a single option
1557 static int
1558 parse_option (const string& arg)
1559 {
1560     if ( fgOptionMap.size() == 0 ) {
1561         size_t i = 0;
1562         OptionDesc *pt = &fgOptionArray[ 0 ];
1563         while ( pt->option != 0 ) {
1564             fgOptionMap[ pt->option ] = i;
1565             i += 1;
1566             pt += 1;
1567         }
1568     }
1569
1570     // General Options
1571     if ( (arg == "--help") || (arg == "-h") ) {
1572         // help/usage request
1573         return(FG_OPTIONS_HELP);
1574     } else if ( (arg == "--verbose") || (arg == "-v") ) {
1575         // verbose help/usage request
1576         return(FG_OPTIONS_VERBOSE_HELP);
1577     } else if ( arg.find( "--show-aircraft") == 0) {
1578         return(FG_OPTIONS_SHOW_AIRCRAFT);
1579     } else if ( arg.find( "--show-sound-devices") == 0) {
1580         return(FG_OPTIONS_SHOW_SOUND_DEVICES);
1581     } else if ( arg.find( "--prop:" ) == 0 ) {
1582         if (!set_property(arg.substr(7))) {
1583             SG_LOG( SG_GENERAL, SG_ALERT, "Bad property assignment: " << arg );
1584             return FG_OPTIONS_ERROR;
1585         }
1586     } else if ( arg.find("-psn_") == 0) {
1587     // on Mac, when launched from the GUI, we are passed the ProcessSerialNumber
1588     // as an argument (and no others). Silently ignore the argument here.
1589         return FG_OPTIONS_OK;
1590     } else if ( arg.find( "--" ) == 0 ) {
1591         size_t pos = arg.find( '=' );
1592         string arg_name, arg_value;
1593         if ( pos == string::npos ) {
1594             arg_name = arg.substr( 2 );
1595         } else {
1596             arg_name = arg.substr( 2, pos - 2 );
1597             arg_value = arg.substr( pos + 1);
1598         }
1599         map<string,size_t>::iterator it = fgOptionMap.find( arg_name );
1600         if ( it != fgOptionMap.end() ) {
1601             OptionDesc *pt = &fgOptionArray[ it->second ];
1602             switch ( pt->type ) {
1603                 case OPTION_BOOL:
1604                     fgSetBool( pt->property, pt->b_param );
1605                     break;
1606                 case OPTION_STRING:
1607                     if ( pt->has_param && !arg_value.empty() ) {
1608                         fgSetString( pt->property, arg_value.c_str() );
1609                     } else if ( !pt->has_param && arg_value.empty() ) {
1610                         fgSetString( pt->property, pt->s_param );
1611                     } else if ( pt->has_param ) {
1612                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' needs a parameter" );
1613                         return FG_OPTIONS_ERROR;
1614                     } else {
1615                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' does not have a parameter" );
1616                         return FG_OPTIONS_ERROR;
1617                     }
1618                     break;
1619                 case OPTION_DOUBLE:
1620                     if ( !arg_value.empty() ) {
1621                         fgSetDouble( pt->property, atof( arg_value ) );
1622                     } else {
1623                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' needs a parameter" );
1624                         return FG_OPTIONS_ERROR;
1625                     }
1626                     break;
1627                 case OPTION_INT:
1628                     if ( !arg_value.empty() ) {
1629                         fgSetInt( pt->property, atoi( arg_value ) );
1630                     } else {
1631                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' needs a parameter" );
1632                         return FG_OPTIONS_ERROR;
1633                     }
1634                     break;
1635                 case OPTION_CHANNEL:
1636                     // XXX return value of add_channel should be checked?
1637                     if ( pt->has_param && !arg_value.empty() ) {
1638                         add_channel( pt->option, arg_value );
1639                     } else if ( !pt->has_param && arg_value.empty() ) {
1640                         add_channel( pt->option, pt->s_param );
1641                     } else if ( pt->has_param ) {
1642                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' needs a parameter" );
1643                         return FG_OPTIONS_ERROR;
1644                     } else {
1645                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' does not have a parameter" );
1646                         return FG_OPTIONS_ERROR;
1647                     }
1648                     break;
1649                 case OPTION_FUNC:
1650                     if ( pt->has_param && !arg_value.empty() ) {
1651                         return pt->func( arg_value.c_str() );
1652                     } else if ( !pt->has_param && arg_value.empty() ) {
1653                         return pt->func( pt->s_param );
1654                     } else if ( pt->has_param ) {
1655                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' needs a parameter" );
1656                         return FG_OPTIONS_ERROR;
1657                     } else {
1658                         SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << arg << "' does not have a parameter" );
1659                         return FG_OPTIONS_ERROR;
1660                     }
1661                     break;
1662             }
1663         } else {
1664             SG_LOG( SG_GENERAL, SG_ALERT, "Unknown option '" << arg << "'" );
1665             return FG_OPTIONS_ERROR;
1666         }
1667     } else {
1668         SG_LOG( SG_GENERAL, SG_ALERT, "Unknown option '" << arg << "'" );
1669         return FG_OPTIONS_ERROR;
1670     }
1671
1672     return FG_OPTIONS_OK;
1673 }
1674
1675
1676 // Parse the command line options
1677 void
1678 fgParseArgs (int argc, char **argv)
1679 {
1680     bool in_options = true;
1681     bool verbose = false;
1682     bool help = false;
1683
1684     SG_LOG(SG_GENERAL, SG_ALERT, "Processing command line arguments");
1685
1686     for (int i = 1; i < argc; i++) {
1687         string arg = argv[i];
1688
1689         if (in_options && (arg.find('-') == 0)) {
1690           if (arg == "--") {
1691             in_options = false;
1692           } else {
1693             int result = parse_option(arg);
1694             if ((result == FG_OPTIONS_HELP) || (result == FG_OPTIONS_ERROR))
1695               help = true;
1696
1697             else if (result == FG_OPTIONS_VERBOSE_HELP)
1698               verbose = true;
1699
1700             else if (result == FG_OPTIONS_SHOW_AIRCRAFT) {
1701               fgOptLogLevel( "alert" );
1702               SGPath path( globals->get_fg_root() );
1703               path.append("Aircraft");
1704               fgShowAircraft(path);
1705               exit(0);
1706
1707             } else if (result == FG_OPTIONS_SHOW_SOUND_DEVICES) {
1708               SGSoundMgr smgr;
1709
1710               smgr.init();
1711               string vendor = smgr.get_vendor();
1712               string renderer = smgr.get_renderer();
1713               cout << renderer << " provided by " << vendor << endl;
1714               cout << endl << "No. Device" << endl;
1715
1716               vector <const char*>devices = smgr.get_available_devices();
1717               for (vector <const char*>::size_type i=0; i<devices.size(); i++) {
1718                 cout << i << ".  \"" << devices[i] << "\"" << endl;
1719               }
1720               devices.clear();
1721               exit(0);
1722             }
1723
1724             else if (result == FG_OPTIONS_EXIT)
1725                exit(0);
1726           }
1727         } else {
1728           in_options = false;
1729           SG_LOG(SG_GENERAL, SG_INFO,
1730                  "Reading command-line property file " << arg);
1731           readProperties(arg, globals->get_props());
1732         }
1733     }
1734
1735     if (help) {
1736        fgOptLogLevel( "alert" );
1737        fgUsage(verbose);
1738        exit(0);
1739     }
1740
1741     SG_LOG(SG_GENERAL, SG_INFO, "Finished command line arguments");
1742 }
1743
1744
1745 // Parse config file options
1746 void
1747 fgParseOptions (const string& path) {
1748     sg_gzifstream in( path );
1749     if ( !in.is_open() ) {
1750         return;
1751     }
1752
1753     SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path );
1754
1755     in >> skipcomment;
1756     while ( ! in.eof() ) {
1757         string line;
1758         getline( in, line, '\n' );
1759
1760         // catch extraneous (DOS) line ending character
1761         int i;
1762         for (i = line.length(); i > 0; i--)
1763             if (line[i - 1] > 32)
1764                 break;
1765         line = line.substr( 0, i );
1766
1767         if ( parse_option( line ) == FG_OPTIONS_ERROR ) {
1768             cerr << endl << "Config file parse error: " << path << " '"
1769                     << line << "'" << endl;
1770             fgUsage();
1771             exit(-1);
1772         }
1773         in >> skipcomment;
1774     }
1775 }
1776
1777
1778 // Print usage message
1779 void
1780 fgUsage (bool verbose)
1781 {
1782     SGPropertyNode *locale = globals->get_locale();
1783
1784     SGPropertyNode options_root;
1785
1786     SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on Windows
1787     cout << endl;
1788
1789     try {
1790         fgLoadProps("options.xml", &options_root);
1791     } catch (const sg_exception &) {
1792         cout << "Unable to read the help file." << endl;
1793         cout << "Make sure the file options.xml is located in the FlightGear base directory," << endl;
1794         cout << "and the location of the base directory is specified by setting $FG_ROOT or" << endl;
1795         cout << "by adding --fg-root=path as a program argument." << endl;
1796
1797         exit(-1);
1798     }
1799
1800     SGPropertyNode *options = options_root.getNode("options");
1801     if (!options) {
1802         SG_LOG( SG_GENERAL, SG_ALERT,
1803                 "Error reading options.xml: <options> directive not found." );
1804         exit(-1);
1805     }
1806
1807     SGPropertyNode *usage = locale->getNode(options->getStringValue("usage"));
1808     if (usage) {
1809         cout << "Usage: " << usage->getStringValue() << endl;
1810     }
1811
1812     vector<SGPropertyNode_ptr>section = options->getChildren("section");
1813     for (unsigned int j = 0; j < section.size(); j++) {
1814         string msg = "";
1815
1816         vector<SGPropertyNode_ptr>option = section[j]->getChildren("option");
1817         for (unsigned int k = 0; k < option.size(); k++) {
1818
1819             SGPropertyNode *name = option[k]->getNode("name");
1820             SGPropertyNode *short_name = option[k]->getNode("short");
1821             SGPropertyNode *key = option[k]->getNode("key");
1822             SGPropertyNode *arg = option[k]->getNode("arg");
1823             bool brief = option[k]->getNode("brief") != 0;
1824
1825             if ((brief || verbose) && name) {
1826                 string tmp = name->getStringValue();
1827
1828                 if (key){
1829                     tmp.append(":");
1830                     tmp.append(key->getStringValue());
1831                 }
1832                 if (arg) {
1833                     tmp.append("=");
1834                     tmp.append(arg->getStringValue());
1835                 }
1836                 if (short_name) {
1837                     tmp.append(", -");
1838                     tmp.append(short_name->getStringValue());
1839                 }
1840
1841                 if (tmp.size() <= 25) {
1842                     msg+= "   --";
1843                     msg += tmp;
1844                     msg.append( 27-tmp.size(), ' ');
1845                 } else {
1846                     msg += "\n   --";
1847                     msg += tmp + '\n';
1848                     msg.append(32, ' ');
1849                 }
1850                 // There may be more than one <description> tag assosiated
1851                 // with one option
1852
1853                 vector<SGPropertyNode_ptr> desc;
1854                 desc = option[k]->getChildren("description");
1855                 if (desc.size() > 0) {
1856                    for ( unsigned int l = 0; l < desc.size(); l++) {
1857
1858                       // There may be more than one translation line.
1859
1860                       string t = desc[l]->getStringValue();
1861                       SGPropertyNode *n = locale->getNode("strings");
1862                       vector<SGPropertyNode_ptr>trans_desc =
1863                                n->getChildren(t.substr(8).c_str());
1864
1865                       for ( unsigned int m = 0; m < trans_desc.size(); m++ ) {
1866                          string t_str = trans_desc[m]->getStringValue();
1867
1868                          if ((m > 0) || ((l > 0) && m == 0)) {
1869                             msg.append( 32, ' ');
1870                          }
1871
1872                          // If the string is too large to fit on the screen,
1873                          // then split it up in several pieces.
1874
1875                          while ( t_str.size() > 47 ) {
1876
1877                             unsigned int m = t_str.rfind(' ', 47);
1878                             msg += t_str.substr(0, m) + '\n';
1879                             msg.append( 32, ' ');
1880
1881                             t_str.erase(t_str.begin(), t_str.begin() + m + 1);
1882                         }
1883                         msg += t_str + '\n';
1884                      }
1885                   }
1886                }
1887             }
1888         }
1889
1890         SGPropertyNode *name;
1891         name = locale->getNode(section[j]->getStringValue("name"));
1892
1893         if (!msg.empty() && name) {
1894            cout << endl << name->getStringValue() << ":" << endl;
1895            cout << msg;
1896            msg.erase();
1897         }
1898     }
1899
1900     if ( !verbose ) {
1901         cout << endl;
1902         cout << "For a complete list of options use --help --verbose" << endl;
1903     }
1904 #ifdef _MSC_VER
1905     cout << "Hit a key to continue..." << endl;
1906     cin.get();
1907 #endif
1908 }