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