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