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