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