]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Fix part of #263, --language option not working for --help.
[flightgear.git] / src / Main / fg_commands.cxx
1 // fg_commands.cxx - internal FGFS commands.
2
3 #ifdef HAVE_CONFIG_H
4 #  include "config.h"
5 #endif
6
7 #include <string.h>             // strcmp()
8
9 #include <simgear/compiler.h>
10
11 #include <string>
12 #include <fstream>
13
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/misc/interpolator.hxx>
27 #include <simgear/io/HTTPRequest.hxx>
28
29 #include <Cockpit/panel.hxx>
30 #include <Cockpit/panel_io.hxx>
31 #include <FDM/flight.hxx>
32 #include <GUI/gui.h>
33 #include <GUI/new_gui.hxx>
34 #include <GUI/dialog.hxx>
35 #include <Aircraft/replay.hxx>
36 #include <Scenery/scenery.hxx>
37 #include <Scripting/NasalSys.hxx>
38 #include <Sound/sample_queue.hxx>
39 #include <Airports/xmlloader.hxx>
40 #include <ATC/CommStation.hxx>
41 #include <Navaids/navrecord.hxx>
42 #include <Navaids/navlist.hxx>
43 #include <Network/HTTPClient.hxx>
44
45 #include "fg_init.hxx"
46 #include "fg_io.hxx"
47 #include "fg_os.hxx"
48 #include "fg_commands.hxx"
49 #include "fg_props.hxx"
50 #include "globals.hxx"
51 #include "logger.hxx"
52 #include "util.hxx"
53 #include "viewmgr.hxx"
54 #include "main.hxx"
55 #include <Main/viewer.hxx>
56 #include <Environment/presets.hxx>
57
58 #include <boost/scoped_array.hpp>
59
60 using std::string;
61 using std::ifstream;
62 using std::ofstream;
63
64
65 \f
66 ////////////////////////////////////////////////////////////////////////
67 // Static helper functions.
68 ////////////////////////////////////////////////////////////////////////
69
70
71 static inline SGPropertyNode *
72 get_prop (const SGPropertyNode * arg)
73 {
74     return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
75 }
76
77 static inline SGPropertyNode *
78 get_prop2 (const SGPropertyNode * arg)
79 {
80     return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
81 }
82
83
84 /**
85  * Get a double value and split it as required.
86  */
87 static void
88 split_value (double full_value, const char * mask,
89              double * unmodifiable, double * modifiable)
90 {
91     if (!strcmp("integer", mask)) {
92         *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
93         *unmodifiable = full_value - *modifiable;
94     } else if (!strcmp("decimal", mask)) {
95         *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
96         *modifiable = full_value - *unmodifiable;
97     } else {
98         if (strcmp("all", mask))
99             SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
100                    << " assuming 'all'");
101         *unmodifiable = 0;
102         *modifiable = full_value;
103     }
104 }
105
106
107 /**
108  * Clamp or wrap a value as specified.
109  */
110 static void
111 limit_value (double * value, const SGPropertyNode * arg)
112 {
113     const SGPropertyNode * min_node = arg->getChild("min");
114     const SGPropertyNode * max_node = arg->getChild("max");
115
116     bool wrap = arg->getBoolValue("wrap");
117
118     if (min_node == 0 || max_node == 0)
119         wrap = false;
120   
121     if (wrap) {                 // wrap such that min <= x < max
122         double min_val = min_node->getDoubleValue();
123         double max_val = max_node->getDoubleValue();
124         double resolution = arg->getDoubleValue("resolution");
125         if (resolution > 0.0) {
126             // snap to (min + N*resolution), taking special care to handle imprecision
127             int n = (int)floor((*value - min_val) / resolution + 0.5);
128             int steps = (int)floor((max_val - min_val) / resolution + 0.5);
129             SG_NORMALIZE_RANGE(n, 0, steps);
130             *value = min_val + resolution * n;
131         } else {
132             // plain circular wrapping
133             SG_NORMALIZE_RANGE(*value, min_val, max_val);
134         }
135     } else {                    // clamp such that min <= x <= max
136         if ((min_node != 0) && (*value < min_node->getDoubleValue()))
137             *value = min_node->getDoubleValue();
138         else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
139             *value = max_node->getDoubleValue();
140     }
141 }
142
143 static bool
144 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
145 {
146     switch (value1->getType()) {
147     case simgear::props::BOOL:
148         return (value1->getBoolValue() == value2->getBoolValue());
149     case simgear::props::INT:
150         return (value1->getIntValue() == value2->getIntValue());
151     case simgear::props::LONG:
152         return (value1->getLongValue() == value2->getLongValue());
153     case simgear::props::FLOAT:
154         return (value1->getFloatValue() == value2->getFloatValue());
155     case simgear::props::DOUBLE:
156         return (value1->getDoubleValue() == value2->getDoubleValue());
157     default:
158         return !strcmp(value1->getStringValue(), value2->getStringValue());
159     }
160 }
161
162
163 \f
164 ////////////////////////////////////////////////////////////////////////
165 // Command implementations.
166 ////////////////////////////////////////////////////////////////////////
167
168
169 /**
170  * Built-in command: do nothing.
171  */
172 static bool
173 do_null (const SGPropertyNode * arg)
174 {
175   return true;
176 }
177
178 /**
179  * Built-in command: run a Nasal script.
180  */
181 static bool
182 do_nasal (const SGPropertyNode * arg)
183 {
184     return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
185 }
186
187 /**
188  * Built-in command: exit FlightGear.
189  *
190  * status: the exit status to return to the operating system (defaults to 0)
191  */
192 static bool
193 do_exit (const SGPropertyNode * arg)
194 {
195     SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
196     fgSetBool("/sim/signals/exit", true);
197     globals->saveUserSettings();
198     fgOSExit(arg->getIntValue("status", 0));
199     return true;
200 }
201
202
203 /**
204  * Reset FlightGear (Shift-Escape or Menu->File->Reset)
205  */
206 static bool
207 do_reset (const SGPropertyNode * arg)
208 {
209     fgReInitSubsystems();
210     return true;
211 }
212
213
214 /**
215  * Built-in command: reinitialize one or more subsystems.
216  *
217  * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
218  * none is specified, reinitialize all of them.
219  */
220 static bool
221 do_reinit (const SGPropertyNode * arg)
222 {
223     bool result = true;
224
225     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
226     if (subsystems.size() == 0) {
227         globals->get_subsystem_mgr()->reinit();
228     } else {
229         for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
230             const char * name = subsystems[i]->getStringValue();
231             SGSubsystem * subsystem = globals->get_subsystem(name);
232             if (subsystem == 0) {
233                 result = false;
234                 SG_LOG( SG_GENERAL, SG_ALERT,
235                         "Subsystem " << name << " not found" );
236             } else {
237                 subsystem->reinit();
238             }
239         }
240     }
241
242     globals->get_event_mgr()->reinit();
243
244     return result;
245 }
246
247 #if 0
248   //
249   // these routines look useful ??? but are never used in the code ???
250   //
251
252 /**
253  * Built-in command: suspend one or more subsystems.
254  *
255  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
256  */
257 static bool
258 do_suspend (const SGPropertyNode * arg)
259 {
260     bool result = true;
261
262     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
263     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
264         const char * name = subsystems[i]->getStringValue();
265         SGSubsystem * subsystem = globals->get_subsystem(name);
266         if (subsystem == 0) {
267             result = false;
268             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
269         } else {
270             subsystem->suspend();
271         }
272     }
273     return result;
274 }
275
276 /**
277  * Built-in command: suspend one or more subsystems.
278  *
279  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
280  */
281 static bool
282 do_resume (const SGPropertyNode * arg)
283 {
284     bool result = true;
285
286     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
287     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
288         const char * name = subsystems[i]->getStringValue();
289         SGSubsystem * subsystem = globals->get_subsystem(name);
290         if (subsystem == 0) {
291             result = false;
292             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
293         } else {
294             subsystem->resume();
295         }
296     }
297     return result;
298 }
299
300 #endif
301
302 /**
303  * Built-in command: replay the FDR buffer
304  */
305 static bool
306 do_replay (const SGPropertyNode * arg)
307 {
308     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
309     return r->start();
310 }
311
312 /**
313  * Built-in command: pause/unpause the sim
314  */
315 static bool
316 do_pause (const SGPropertyNode * arg)
317 {
318     bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
319     if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
320     {
321         do_replay(NULL);
322     }
323     else
324     {
325         fgSetBool("/sim/freeze/master",!paused);
326         fgSetBool("/sim/freeze/clock",!paused);
327     }
328     return true;
329 }
330
331 /**
332  * Built-in command: load flight.
333  *
334  * file (optional): the name of the file to load (relative to current
335  *   directory).  Defaults to "fgfs.sav"
336  */
337 static bool
338 do_load (const SGPropertyNode * arg)
339 {
340     string file = arg->getStringValue("file", "fgfs.sav");
341     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
342         file += ".sav";
343
344     if (!fgValidatePath(file.c_str(), false)) {
345         SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
346                 "(unauthorized access)");
347         return false;
348     }
349
350     ifstream input(file.c_str());
351     if (input.good() && fgLoadFlight(input)) {
352         input.close();
353         SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
354         return true;
355     } else {
356         SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
357         return false;
358     }
359 }
360
361
362 /**
363  * Built-in command: save flight.
364  *
365  * file (optional): the name of the file to save (relative to the
366  * current directory).  Defaults to "fgfs.sav".
367  */
368 static bool
369 do_save (const SGPropertyNode * arg)
370 {
371     string file = arg->getStringValue("file", "fgfs.sav");
372     if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
373         file += ".sav";
374
375     if (!fgValidatePath(file.c_str(), false)) {
376         SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
377                 "(unauthorized access)");
378         return false;
379     }
380
381     bool write_all = arg->getBoolValue("write-all", false);
382     SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
383     ofstream output(file.c_str());
384     if (output.good() && fgSaveFlight(output, write_all)) {
385         output.close();
386         SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
387         return true;
388     } else {
389         SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
390         return false;
391     }
392 }
393
394
395 /**
396  * Built-in command: (re)load the panel.
397  *
398  * path (optional): the file name to load the panel from 
399  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
400  * and if that's unspecified, to "Panels/Default/default.xml".
401  */
402 static bool
403 do_panel_load (const SGPropertyNode * arg)
404 {
405   string panel_path =
406     arg->getStringValue("path", fgGetString("/sim/panel/path"));
407   if (panel_path.empty()) {
408     return false;
409   }
410   
411   FGPanel * new_panel = fgReadPanel(panel_path);
412   if (new_panel == 0) {
413     SG_LOG(SG_INPUT, SG_ALERT,
414            "Error reading new panel from " << panel_path);
415     return false;
416   }
417   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
418   globals->get_current_panel()->unbind();
419   globals->set_current_panel( new_panel );
420   globals->get_current_panel()->bind();
421   return true;
422 }
423
424
425 /**
426  * Built-in command: pass a mouse click to the panel.
427  *
428  * button: the mouse button number, zero-based.
429  * is-down: true if the button is down, false if it is up.
430  * x-pos: the x position of the mouse click.
431  * y-pos: the y position of the mouse click.
432  */
433 static bool
434 do_panel_mouse_click (const SGPropertyNode * arg)
435 {
436   if (globals->get_current_panel() != 0)
437     return globals->get_current_panel()
438       ->doMouseAction(arg->getIntValue("button"),
439                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
440                       arg->getIntValue("x-pos"),
441                       arg->getIntValue("y-pos"));
442   else
443     return false;
444 }
445
446
447 /**
448  * Built-in command: (re)load preferences.
449  *
450  * path (optional): the file name to load the panel from (relative
451  * to FG_ROOT). Defaults to "preferences.xml".
452  */
453 static bool
454 do_preferences_load (const SGPropertyNode * arg)
455 {
456   try {
457     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
458                 globals->get_props());
459   } catch (const sg_exception &e) {
460     guiErrorMessage("Error reading global preferences: ", e);
461     return false;
462   }
463   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
464   return true;
465 }
466
467 static void
468 do_view_next( bool )
469 {
470     globals->get_current_view()->setHeadingOffset_deg(0.0);
471     globals->get_viewmgr()->next_view();
472 }
473
474 static void
475 do_view_prev( bool )
476 {
477     globals->get_current_view()->setHeadingOffset_deg(0.0);
478     globals->get_viewmgr()->prev_view();
479 }
480
481 /**
482  * Built-in command: cycle view.
483  */
484 static bool
485 do_view_cycle (const SGPropertyNode * arg)
486 {
487   globals->get_current_view()->setHeadingOffset_deg(0.0);
488   globals->get_viewmgr()->next_view();
489   return true;
490 }
491
492 /**
493  * Built-in command: capture screen.
494  */
495 static bool
496 do_screen_capture (const SGPropertyNode * arg)
497 {
498   return fgDumpSnapShot();
499 }
500
501 static bool
502 do_reload_shaders (const SGPropertyNode*)
503 {
504     simgear::reload_shaders();
505     return true;
506 }
507
508 static bool
509 do_dump_scene_graph (const SGPropertyNode*)
510 {
511     fgDumpSceneGraph();
512     return true;
513 }
514
515 static bool
516 do_dump_terrain_branch (const SGPropertyNode*)
517 {
518     fgDumpTerrainBranch();
519
520     double lon_deg = fgGetDouble("/position/longitude-deg");
521     double lat_deg = fgGetDouble("/position/latitude-deg");
522     SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
523     SGVec3d zero = SGVec3d::fromGeod(geodPos);
524
525     SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
526     SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
527     SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
528
529     return true;
530 }
531
532 static bool
533 do_print_visible_scene_info(const SGPropertyNode*)
534 {
535     fgPrintVisibleSceneInfoCommand();
536     return true;
537 }
538
539 /**
540  * Built-in command: hires capture screen.
541  */
542 static bool
543 do_hires_screen_capture (const SGPropertyNode * arg)
544 {
545   fgHiResDump();
546   return true;
547 }
548
549
550 /**
551  * Reload the tile cache.
552  */
553 static bool
554 do_tile_cache_reload (const SGPropertyNode * arg)
555 {
556     static const SGPropertyNode *master_freeze
557         = fgGetNode("/sim/freeze/master");
558     bool freeze = master_freeze->getBoolValue();
559     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
560     if ( !freeze ) {
561         fgSetBool("/sim/freeze/master", true);
562     }
563
564     globals->get_subsystem("tile-manager")->reinit();
565
566     if ( !freeze ) {
567         fgSetBool("/sim/freeze/master", false);
568     }
569     return true;
570 }
571
572
573 #if 0
574 These do_set_(some-environment-parameters) are deprecated and no longer 
575 useful/functional - Torsten Dreyer, January 2011
576 /**
577  * Set the sea level outside air temperature and assigning that to all
578  * boundary and aloft environment layers.
579  */
580 static bool
581 do_set_sea_level_degc ( double temp_sea_level_degc)
582 {
583     SGPropertyNode *node, *child;
584
585     // boundary layers
586     node = fgGetNode( "/environment/config/boundary" );
587     if ( node != NULL ) {
588       int i = 0;
589       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
590         child->setDoubleValue( "temperature-sea-level-degc",
591                                temp_sea_level_degc );
592         ++i;
593       }
594     }
595
596     // aloft layers
597     node = fgGetNode( "/environment/config/aloft" );
598     if ( node != NULL ) {
599       int i = 0;
600       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
601         child->setDoubleValue( "temperature-sea-level-degc",
602                                temp_sea_level_degc );
603         ++i;
604       }
605     }
606
607     return true;
608 }
609
610 static bool
611 do_set_sea_level_degc (const SGPropertyNode * arg)
612 {
613     return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
614 }
615
616
617 /**
618  * Set the outside air temperature at the "current" altitude by first
619  * calculating the corresponding sea level temp, and assigning that to
620  * all boundary and aloft environment layers.
621  */
622 static bool
623 do_set_oat_degc (const SGPropertyNode * arg)
624 {
625     double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
626     // check for an altitude specified in the arguments, otherwise use
627     // current aircraft altitude.
628     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
629     if ( altitude_ft == NULL ) {
630         altitude_ft = fgGetNode("/position/altitude-ft");
631     }
632
633     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
634     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
635     dummy.set_temperature_degc( oat_degc );
636     return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
637 }
638
639 /**
640  * Set the sea level outside air dewpoint and assigning that to all
641  * boundary and aloft environment layers.
642  */
643 static bool
644 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
645 {
646
647     SGPropertyNode *node, *child;
648
649     // boundary layers
650     node = fgGetNode( "/environment/config/boundary" );
651     if ( node != NULL ) {
652       int i = 0;
653       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
654         child->setDoubleValue( "dewpoint-sea-level-degc",
655                                dewpoint_sea_level_degc );
656         ++i;
657       }
658     }
659
660     // aloft layers
661     node = fgGetNode( "/environment/config/aloft" );
662     if ( node != NULL ) {
663       int i = 0;
664       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
665         child->setDoubleValue( "dewpoint-sea-level-degc",
666                                dewpoint_sea_level_degc );
667         ++i;
668       }
669     }
670
671     return true;
672 }
673
674 static bool
675 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
676 {
677     return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
678 }
679
680 /**
681  * Set the outside air dewpoint at the "current" altitude by first
682  * calculating the corresponding sea level dewpoint, and assigning
683  * that to all boundary and aloft environment layers.
684  */
685 static bool
686 do_set_dewpoint_degc (const SGPropertyNode * arg)
687 {
688     double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
689
690     // check for an altitude specified in the arguments, otherwise use
691     // current aircraft altitude.
692     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
693     if ( altitude_ft == NULL ) {
694         altitude_ft = fgGetNode("/position/altitude-ft");
695     }
696
697     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
698     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
699     dummy.set_dewpoint_degc( dewpoint_degc );
700     return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
701 }
702 #endif
703
704 /**
705  * Built-in command: toggle a bool property value.
706  *
707  * property: The name of the property to toggle.
708  */
709 static bool
710 do_property_toggle (const SGPropertyNode * arg)
711 {
712   SGPropertyNode * prop = get_prop(arg);
713   return prop->setBoolValue(!prop->getBoolValue());
714 }
715
716
717 /**
718  * Built-in command: assign a value to a property.
719  *
720  * property: the name of the property to assign.
721  * value: the value to assign; or
722  * property[1]: the property to copy from.
723  */
724 static bool
725 do_property_assign (const SGPropertyNode * arg)
726 {
727   SGPropertyNode * prop = get_prop(arg);
728   const SGPropertyNode * value = arg->getNode("value");
729
730   if (value != 0)
731       return prop->setUnspecifiedValue(value->getStringValue());
732   else
733   {
734       const SGPropertyNode * prop2 = get_prop2(arg);
735       if (prop2)
736           return prop->setUnspecifiedValue(prop2->getStringValue());
737       else
738           return false;
739   }
740 }
741
742
743 /**
744  * Built-in command: increment or decrement a property value.
745  *
746  * If the 'step' argument is present, it will be used; otherwise,
747  * the command uses 'offset' and 'factor', usually from the mouse.
748  *
749  * property: the name of the property to increment or decrement.
750  * step: the amount of the increment or decrement (default: 0).
751  * offset: offset from the current setting (used for the mouse; multiplied 
752  *         by factor)
753  * factor: scaling amount for the offset (defaults to 1).
754  * min: the minimum allowed value (default: no minimum).
755  * max: the maximum allowed value (default: no maximum).
756  * mask: 'integer' to apply only to the left of the decimal point, 
757  *       'decimal' to apply only to the right of the decimal point,
758  *       or 'all' to apply to the whole number (the default).
759  * wrap: true if the value should be wrapped when it passes min or max;
760  *       both min and max must be present for this to work (default:
761  *       false).
762  */
763 static bool
764 do_property_adjust (const SGPropertyNode * arg)
765 {
766   SGPropertyNode * prop = get_prop(arg);
767
768   double amount = 0;
769   if (arg->hasValue("step"))
770       amount = arg->getDoubleValue("step");
771   else
772       amount = (arg->getDoubleValue("factor", 1)
773                 * arg->getDoubleValue("offset"));
774           
775   double unmodifiable, modifiable;
776   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
777               &unmodifiable, &modifiable);
778   modifiable += amount;
779   limit_value(&modifiable, arg);
780
781   prop->setDoubleValue(unmodifiable + modifiable);
782
783   return true;
784 }
785
786
787 /**
788  * Built-in command: multiply a property value.
789  *
790  * property: the name of the property to multiply.
791  * factor: the amount by which to multiply.
792  * min: the minimum allowed value (default: no minimum).
793  * max: the maximum allowed value (default: no maximum).
794  * mask: 'integer' to apply only to the left of the decimal point, 
795  *       'decimal' to apply only to the right of the decimal point,
796  *       or 'all' to apply to the whole number (the default).
797  * wrap: true if the value should be wrapped when it passes min or max;
798  *       both min and max must be present for this to work (default:
799  *       false).
800  */
801 static bool
802 do_property_multiply (const SGPropertyNode * arg)
803 {
804   SGPropertyNode * prop = get_prop(arg);
805   double factor = arg->getDoubleValue("factor", 1);
806
807   double unmodifiable, modifiable;
808   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
809               &unmodifiable, &modifiable);
810   modifiable *= factor;
811   limit_value(&modifiable, arg);
812
813   prop->setDoubleValue(unmodifiable + modifiable);
814
815   return true;
816 }
817
818
819 /**
820  * Built-in command: swap two property values.
821  *
822  * property[0]: the name of the first property.
823  * property[1]: the name of the second property.
824  */
825 static bool
826 do_property_swap (const SGPropertyNode * arg)
827 {
828   SGPropertyNode * prop1 = get_prop(arg);
829   SGPropertyNode * prop2 = get_prop2(arg);
830
831                                 // FIXME: inefficient
832   const string & tmp = prop1->getStringValue();
833   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
834           prop2->setUnspecifiedValue(tmp.c_str()));
835 }
836
837
838 /**
839  * Built-in command: Set a property to an axis or other moving input.
840  *
841  * property: the name of the property to set.
842  * setting: the current input setting, usually between -1.0 and 1.0.
843  * offset: the offset to shift by, before applying the factor.
844  * factor: the factor to multiply by (use negative to reverse).
845  */
846 static bool
847 do_property_scale (const SGPropertyNode * arg)
848 {
849   SGPropertyNode * prop = get_prop(arg);
850   double setting = arg->getDoubleValue("setting");
851   double offset = arg->getDoubleValue("offset", 0.0);
852   double factor = arg->getDoubleValue("factor", 1.0);
853   bool squared = arg->getBoolValue("squared", false);
854   int power = arg->getIntValue("power", (squared ? 2 : 1));
855
856   int sign = (setting < 0 ? -1 : 1);
857
858   switch (power) {
859   case 1:
860       break;
861   case 2:
862       setting = setting * setting * sign;
863       break;
864   case 3:
865       setting = setting * setting * setting;
866       break;
867   case 4:
868       setting = setting * setting * setting * setting * sign;
869       break;
870   default:
871       setting =  pow(setting, power);
872       if ((power % 2) == 0)
873           setting *= sign;
874       break;
875   }
876
877   return prop->setDoubleValue((setting + offset) * factor);
878 }
879
880
881 /**
882  * Built-in command: cycle a property through a set of values.
883  *
884  * If the current value isn't in the list, the cycle will
885  * (re)start from the beginning.
886  *
887  * property: the name of the property to cycle.
888  * value[*]: the list of values to cycle through.
889  */
890 static bool
891 do_property_cycle (const SGPropertyNode * arg)
892 {
893     SGPropertyNode * prop = get_prop(arg);
894     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
895     int selection = -1;
896     int nSelections = values.size();
897
898     if (nSelections < 1) {
899         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
900         return false;
901     }
902
903                                 // Try to find the current selection
904     for (int i = 0; i < nSelections; i++) {
905         if (compare_values(prop, values[i])) {
906             selection = i + 1;
907             break;
908         }
909     }
910
911                                 // Default or wrap to the first selection
912     if (selection < 0 || selection >= nSelections)
913         selection = 0;
914
915     prop->setUnspecifiedValue(values[selection]->getStringValue());
916     return true;
917 }
918
919
920 /**
921  * Built-in command: randomize a numeric property value.
922  *
923  * property: the name of the property value to randomize.
924  * min: the minimum allowed value.
925  * max: the maximum allowed value.
926  */
927 static bool
928 do_property_randomize (const SGPropertyNode * arg)
929 {
930     SGPropertyNode * prop = get_prop(arg);
931     double min = arg->getDoubleValue("min", DBL_MIN);
932     double max = arg->getDoubleValue("max", DBL_MAX);
933     prop->setDoubleValue(sg_random() * (max - min) + min);
934     return true;
935 }
936
937 /**
938  * Built-in command: interpolate a property value over time
939  *
940  * property: the name of the property value to interpolate.
941  * value[0..n] any number of constant values to interpolate
942  * time[0..n]  time between each value, number of time elements must
943  *          match those of value elements
944  * -or-
945  * property[1..n] any number of target values taken from named properties
946  * time[0..n]     time between each value, number of time elements must
947  *                match those of property elements minus one
948  */
949 static bool
950 do_property_interpolate (const SGPropertyNode * arg)
951 {
952     SGPropertyNode * prop = get_prop(arg);
953
954     simgear::PropertyList valueNodes = arg->getChildren( "value" );
955     simgear::PropertyList timeNodes = arg->getChildren( "time" );
956
957     boost::scoped_array<double> value;
958     boost::scoped_array<double> time;
959
960     if( valueNodes.size() > 0 ) {
961         // must match
962         if( timeNodes.size() != valueNodes.size() )
963             return false;
964
965         value.reset( new double[valueNodes.size()] );
966         for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
967             value[n] = valueNodes[n]->getDoubleValue();
968         }
969     } else {
970         valueNodes = arg->getChildren("property");
971         // must have one more property node
972         if( valueNodes.size() - 1 != timeNodes.size() )
973           return false;
974
975         value.reset( new double[valueNodes.size()-1] );
976         for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
977             value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
978         }
979
980     }
981
982     time.reset( new double[timeNodes.size()] );
983     for( simgear::PropertyList::size_type n = 0; n < timeNodes.size(); n++ ) {
984         time[n] = timeNodes[n]->getDoubleValue();
985     }
986
987     ((SGInterpolator*)globals->get_subsystem_mgr()
988       ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
989       ->interpolate(prop, timeNodes.size(), value.get(), time.get() );
990
991     return true;
992 }
993
994 /**
995  * Built-in command: reinit the data logging system based on the
996  * current contents of the /logger tree.
997  */
998 static bool
999 do_data_logging_commit (const SGPropertyNode * arg)
1000 {
1001     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1002     log->reinit();
1003     return true;
1004 }
1005
1006 /**
1007  * Built-in command: Add a dialog to the GUI system.  Does *not*
1008  * display the dialog.  The property node should have the same format
1009  * as a dialog XML configuration.  It must include:
1010  *
1011  * name: the name of the GUI dialog for future reference.
1012  */
1013 static bool
1014 do_dialog_new (const SGPropertyNode * arg)
1015 {
1016     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1017
1018     // Note the casting away of const: this is *real*.  Doing a
1019     // "dialog-apply" command later on will mutate this property node.
1020     // I'm not convinced that this isn't the Right Thing though; it
1021     // allows client to create a node, pass it to dialog-new, and get
1022     // the values back from the dialog by reading the same node.
1023     // Perhaps command arguments are not as "const" as they would
1024     // seem?
1025     gui->newDialog((SGPropertyNode*)arg);
1026     return true;
1027 }
1028
1029 /**
1030  * Built-in command: Show an XML-configured dialog.
1031  *
1032  * dialog-name: the name of the GUI dialog to display.
1033  */
1034 static bool
1035 do_dialog_show (const SGPropertyNode * arg)
1036 {
1037     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1038     gui->showDialog(arg->getStringValue("dialog-name"));
1039     return true;
1040 }
1041
1042
1043 /**
1044  * Built-in Command: Hide the active XML-configured dialog.
1045  */
1046 static bool
1047 do_dialog_close (const SGPropertyNode * arg)
1048 {
1049     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1050     if(arg->hasValue("dialog-name"))
1051         return gui->closeDialog(arg->getStringValue("dialog-name"));
1052     return gui->closeActiveDialog();
1053 }
1054
1055
1056 /**
1057  * Update a value in the active XML-configured dialog.
1058  *
1059  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1060  */
1061 static bool
1062 do_dialog_update (const SGPropertyNode * arg)
1063 {
1064     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1065     FGDialog * dialog;
1066     if (arg->hasValue("dialog-name"))
1067         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1068     else
1069         dialog = gui->getActiveDialog();
1070
1071     if (dialog != 0) {
1072         dialog->updateValues(arg->getStringValue("object-name"));
1073         return true;
1074     } else {
1075         return false;
1076     }
1077 }
1078
1079 static bool
1080 do_open_browser (const SGPropertyNode * arg)
1081 {
1082     string path;
1083     if (arg->hasValue("path"))
1084         path = arg->getStringValue("path");
1085     else
1086     if (arg->hasValue("url"))
1087         path = arg->getStringValue("url");
1088     else
1089         return false;
1090
1091     return openBrowser(path);
1092 }
1093
1094 /**
1095  * Apply a value in the active XML-configured dialog.
1096  *
1097  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1098  */
1099 static bool
1100 do_dialog_apply (const SGPropertyNode * arg)
1101 {
1102     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1103     FGDialog * dialog;
1104     if (arg->hasValue("dialog-name"))
1105         dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1106     else
1107         dialog = gui->getActiveDialog();
1108
1109     if (dialog != 0) {
1110         dialog->applyValues(arg->getStringValue("object-name"));
1111         return true;
1112     } else {
1113         return false;
1114     }
1115 }
1116
1117
1118 /**
1119  * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1120  * unlike reinit().
1121  */
1122 static bool
1123 do_gui_redraw (const SGPropertyNode * arg)
1124 {
1125     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1126     gui->redraw();
1127     return true;
1128 }
1129
1130
1131 /**
1132  * Adds model to the scenery. The path to the added branch (/models/model[*])
1133  * is returned in property "property".
1134  */
1135 static bool
1136 do_add_model (const SGPropertyNode * arg)
1137 {
1138     SGPropertyNode * model = fgGetNode("models", true);
1139     int i;
1140     for (i = 0; model->hasChild("model",i); i++);
1141     model = model->getChild("model", i, true);
1142     copyProperties(arg, model);
1143     if (model->hasValue("elevation-m"))
1144         model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1145                 * SG_METER_TO_FEET);
1146     model->getNode("load", true);
1147     model->removeChildren("load");
1148     const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1149     return true;
1150 }
1151
1152
1153 /**
1154  * Set mouse cursor coordinates and cursor shape.
1155  */
1156 static bool
1157 do_set_cursor (const SGPropertyNode * arg)
1158 {
1159     if (arg->hasValue("x") || arg->hasValue("y")) {
1160         SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1161         SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1162         int x = arg->getIntValue("x", mx->getIntValue());
1163         int y = arg->getIntValue("y", my->getIntValue());
1164         fgWarpMouse(x, y);
1165         mx->setIntValue(x);
1166         my->setIntValue(y);
1167     }
1168
1169     SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1170     if (cursor->getType() != simgear::props::NONE)
1171         fgSetMouseCursor(cursor->getIntValue());
1172
1173     cursor->setIntValue(fgGetMouseCursor());
1174     return true;
1175 }
1176
1177
1178 /**
1179  * Built-in command: play an audio message (i.e. a wav file) This is
1180  * fire and forget.  Call this once per message and it will get dumped
1181  * into a queue.  Messages are played sequentially so they do not
1182  * overlap.
1183  */
1184 static bool
1185 do_play_audio_sample (const SGPropertyNode * arg)
1186 {
1187     string path = arg->getStringValue("path");
1188     string file = arg->getStringValue("file");
1189     float volume = arg->getFloatValue("volume");
1190     // cout << "playing " << path << " / " << file << endl;
1191     try {
1192         static FGSampleQueue *queue = 0;
1193         if ( !queue ) {
1194            SGSoundMgr *smgr = globals->get_soundmgr();
1195            queue = new FGSampleQueue(smgr, "chatter");
1196            queue->tie_to_listener();
1197         }
1198
1199         SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1200         msg->set_volume( volume );
1201         queue->add( msg );
1202
1203         return true;
1204
1205     } catch (const sg_io_exception&) {
1206         SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1207                 "failed to load" << path << '/' << file);
1208         return false;
1209     }
1210 }
1211
1212 /**
1213  * Built-in command: commit presets (read from in /sim/presets/)
1214  */
1215 static bool
1216 do_presets_commit (const SGPropertyNode * arg)
1217 {
1218     if (fgGetBool("/sim/initialized", false)) {
1219       fgReInitSubsystems();
1220     } else {
1221       // Nasal can trigger this during initial init, which confuses
1222       // the logic in ReInitSubsystems, since initial state has not been
1223       // saved at that time. Short-circuit everything here.
1224       fgInitPosition();
1225     }
1226     
1227     return true;
1228 }
1229
1230 /**
1231  * Built-in command: set log level (0 ... 7)
1232  */
1233 static bool
1234 do_log_level (const SGPropertyNode * arg)
1235 {
1236    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1237
1238    return true;
1239 }
1240
1241 /*
1242 static bool
1243 do_decrease_visibility (const SGPropertyNode * arg)
1244 {
1245     Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1246     return true;
1247 }
1248  
1249 static bool
1250 do_increase_visibility (const SGPropertyNode * arg)
1251 {
1252     Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1253     return true;
1254 }
1255 */
1256 /**
1257  * An fgcommand to allow loading of xml files via nasal,
1258  * the xml file's structure will be made available within
1259  * a property tree node defined under argument "targetnode",
1260  * or in the given argument tree under "data" otherwise.
1261  *
1262  * @param filename a string to hold the complete path & filename of an XML file
1263  * @param targetnode a string pointing to a location within the property tree
1264  * where to store the parsed XML file. If <targetnode> is undefined, then the
1265  * file contents are stored under a node <data> in the argument tree.
1266  */
1267
1268 static bool
1269 do_load_xml_to_proptree(const SGPropertyNode * arg)
1270 {
1271     SGPath file(arg->getStringValue("filename"));
1272     if (file.str().empty())
1273         return false;
1274
1275     if (file.extension() != "xml")
1276         file.concat(".xml");
1277     
1278     std::string icao = arg->getStringValue("icao");
1279     if (icao.empty()) {
1280         if (file.isRelative()) {
1281           SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1282           if (!absPath.isNull())
1283               file = absPath;
1284           else
1285           {
1286               SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"  
1287                           << file.str() << "'.");
1288               return false;
1289           }
1290         }
1291     } else {
1292         if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1293           SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1294             << file.str() << " at ICAO:" << icao);
1295           return false;
1296         }
1297     }
1298     
1299     if (!fgValidatePath(file.c_str(), false)) {
1300         SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1301                 "(unauthorized access)");
1302         return false;
1303     }
1304
1305     SGPropertyNode *targetnode;
1306     if (arg->hasValue("targetnode"))
1307         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1308     else
1309         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1310
1311     try {
1312         readProperties(file.c_str(), targetnode, true);
1313     } catch (const sg_exception &e) {
1314         SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1315         return false;
1316     }
1317
1318     return true;
1319 }
1320
1321 class RemoteXMLRequest : public simgear::HTTP::Request
1322 {
1323 public:
1324     SGPropertyNode_ptr _complete;
1325     SGPropertyNode_ptr _status;
1326     SGPropertyNode_ptr _failed;
1327     SGPropertyNode_ptr _target;
1328     string propsData;
1329     
1330     RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) : 
1331         simgear::HTTP::Request(url),
1332         _target(targetNode)
1333     {
1334     }
1335     
1336     void setCompletionProp(SGPropertyNode_ptr p)
1337     {
1338         _complete = p;
1339     }
1340     
1341     void setStatusProp(SGPropertyNode_ptr p)
1342     {
1343         _status = p;
1344     }
1345     
1346     void setFailedProp(SGPropertyNode_ptr p)
1347     {
1348         _failed = p;
1349     }
1350 protected:
1351     virtual void gotBodyData(const char* s, int n)
1352     {
1353         propsData += string(s, n);
1354     }
1355     
1356     virtual void responseComplete()
1357     {
1358         int response = responseCode();
1359         bool failed = false;
1360         if (response == 200) {
1361             try {
1362                 const char* buffer = propsData.c_str();
1363                 readProperties(buffer, propsData.size(), _target, true);
1364             } catch (const sg_exception &e) {
1365                 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1366                 failed = true;
1367                 response = 406; // 'not acceptable', anything better?
1368             }
1369         } else {
1370             failed = true;
1371         }
1372     // now the response data is output, signal Nasal / listeners
1373         if (_complete) _complete->setBoolValue(true);
1374         if (_status) _status->setIntValue(response);
1375         if (_failed) _failed->setBoolValue(failed);
1376     }
1377 };
1378
1379
1380 static bool
1381 do_load_xml_from_url(const SGPropertyNode * arg)
1382 {
1383     std::string url(arg->getStringValue("url"));
1384     if (url.empty())
1385         return false;
1386         
1387     SGPropertyNode *targetnode;
1388     if (arg->hasValue("targetnode"))
1389         targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1390     else
1391         targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1392     
1393     RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1394     
1395 // connect up optional reporting properties
1396     if (arg->hasValue("complete")) 
1397         req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1398     if (arg->hasValue("failure")) 
1399         req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1400     if (arg->hasValue("status")) 
1401         req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1402         
1403     FGHTTPClient::instance()->makeRequest(req);
1404     
1405     return true;
1406 }
1407
1408
1409 /**
1410  * An fgcommand to allow saving of xml files via nasal,
1411  * the file's structure will be determined based on what's
1412  * encountered in the passed (source) property tree node
1413  *
1414  * @param filename a string to hold the complete path & filename of the (new)
1415  * XML file
1416  * @param sourcenode a string pointing to a location within the property tree
1417  * where to find the nodes that should be written recursively into an XML file
1418  * @param data if no sourcenode is given, then the file contents are taken from
1419  * the argument tree's "data" node.
1420  */
1421
1422 static bool
1423 do_save_xml_from_proptree(const SGPropertyNode * arg)
1424 {
1425     SGPath file(arg->getStringValue("filename"));
1426     if (file.str().empty())
1427         return false;
1428
1429     if (file.extension() != "xml")
1430         file.concat(".xml");
1431
1432     if (!fgValidatePath(file.c_str(), true)) {
1433         SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1434                 "(unauthorized access)");
1435         return false;
1436     }
1437
1438     SGPropertyNode *sourcenode;
1439     if (arg->hasValue("sourcenode"))
1440         sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1441     else if (arg->getNode("data", false))
1442         sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1443     else
1444         return false;
1445
1446     try {
1447         writeProperties (file.c_str(), sourcenode, true);
1448     } catch (const sg_exception &e) {
1449         SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1450         return false;
1451     }
1452
1453     return true;
1454 }
1455
1456 static bool
1457 do_press_cockpit_button (const SGPropertyNode *arg)
1458 {
1459   const char *prefix = arg->getStringValue("prefix");
1460
1461   if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1462     return true;
1463
1464   string prop = string(prefix) + "-button";
1465   double value;
1466
1467   if (arg->getBoolValue("latching"))
1468     value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1469   else
1470     value = 1;
1471
1472   fgSetDouble(prop.c_str(), value);
1473   fgSetBool(arg->getStringValue("discrete"), value > 0);
1474
1475   return true;
1476 }
1477
1478 static bool
1479 do_release_cockpit_button (const SGPropertyNode *arg)
1480 {
1481   const char *prefix = arg->getStringValue("prefix");
1482
1483   if (arg->getBoolValue("guarded")) {
1484     string prop = string(prefix) + "-guard";
1485     if (fgGetDouble(prop.c_str()) < 1) {
1486       fgSetDouble(prop.c_str(), 1);
1487       return true;
1488     }
1489   }
1490
1491   if (! arg->getBoolValue("latching")) {
1492     fgSetDouble((string(prefix) + "-button").c_str(), 0);
1493     fgSetBool(arg->getStringValue("discrete"), false);
1494   }
1495
1496   return true;
1497 }
1498
1499 static SGGeod commandSearchPos(const SGPropertyNode* arg)
1500 {
1501   if (arg->hasChild("longitude-deg") && arg->hasChild("latitude-deg")) {
1502     return SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1503                            arg->getDoubleValue("latitude-deg"));
1504   }
1505   
1506   // use current viewer/aircraft position
1507   return SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"), 
1508                          fgGetDouble("/position/latitude-deg"));
1509 }
1510   
1511 static bool
1512 do_comm_search(const SGPropertyNode* arg)
1513 {
1514   SGGeod pos = commandSearchPos(arg);
1515   int khz = static_cast<int>(arg->getDoubleValue("frequency-mhz") * 100.0 + 0.25);
1516   
1517   flightgear::CommStation* sta = flightgear::CommStation::findByFreq(khz, pos, NULL);
1518   if (!sta) {
1519     return true;
1520   }
1521   
1522   SGPropertyNode* result = fgGetNode(arg->getStringValue("result"));
1523   sta->createBinding(result);
1524   return true;
1525 }
1526
1527 static bool
1528 do_nav_search(const SGPropertyNode* arg)
1529 {
1530   SGGeod pos = commandSearchPos(arg);
1531   double mhz = arg->getDoubleValue("frequency-mhz");
1532
1533   FGNavList* navList = globals->get_navlist();
1534   string type(arg->getStringValue("type", "vor"));
1535   if (type == "dme") {
1536     navList = globals->get_dmelist();
1537   } else if (type == "tacan") {
1538     navList = globals->get_tacanlist();
1539   }
1540   
1541   FGNavRecord* nav = navList->findByFreq(mhz, pos);
1542   if (!nav && (type == "vor")) {
1543     // if we're searching VORs, look for localizers too
1544     nav = globals->get_loclist()->findByFreq(mhz, pos);
1545   }
1546   
1547   if (!nav) {
1548     return true;
1549   }
1550   
1551   SGPropertyNode* result = fgGetNode(arg->getStringValue("result"));
1552   nav->createBinding(result);
1553   return true;
1554 }
1555   
1556 ////////////////////////////////////////////////////////////////////////
1557 // Command setup.
1558 ////////////////////////////////////////////////////////////////////////
1559
1560
1561 /**
1562  * Table of built-in commands.
1563  *
1564  * New commands do not have to be added here; any module in the application
1565  * can add a new command using globals->get_commands()->addCommand(...).
1566  */
1567 static struct {
1568   const char * name;
1569   SGCommandMgr::command_t command;
1570 } built_ins [] = {
1571     { "null", do_null },
1572     { "nasal", do_nasal },
1573     { "exit", do_exit },
1574     { "reset", do_reset },
1575     { "reinit", do_reinit },
1576     { "suspend", do_reinit },
1577     { "resume", do_reinit },
1578     { "pause", do_pause },
1579     { "load", do_load },
1580     { "save", do_save },
1581     { "panel-load", do_panel_load },
1582     { "panel-mouse-click", do_panel_mouse_click },
1583     { "preferences-load", do_preferences_load },
1584     { "view-cycle", do_view_cycle },
1585     { "screen-capture", do_screen_capture },
1586     { "hires-screen-capture", do_hires_screen_capture },
1587     { "tile-cache-reload", do_tile_cache_reload },
1588     /*
1589     { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1590     { "set-outside-air-temp-degc", do_set_oat_degc },
1591     { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1592     { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1593     */
1594     { "property-toggle", do_property_toggle },
1595     { "property-assign", do_property_assign },
1596     { "property-adjust", do_property_adjust },
1597     { "property-multiply", do_property_multiply },
1598     { "property-swap", do_property_swap },
1599     { "property-scale", do_property_scale },
1600     { "property-cycle", do_property_cycle },
1601     { "property-randomize", do_property_randomize },
1602     { "property-interpolate", do_property_interpolate },
1603     { "data-logging-commit", do_data_logging_commit },
1604     { "dialog-new", do_dialog_new },
1605     { "dialog-show", do_dialog_show },
1606     { "dialog-close", do_dialog_close },
1607     { "dialog-update", do_dialog_update },
1608     { "dialog-apply", do_dialog_apply },
1609     { "open-browser", do_open_browser },
1610     { "gui-redraw", do_gui_redraw },
1611     { "add-model", do_add_model },
1612     { "set-cursor", do_set_cursor },
1613     { "play-audio-sample", do_play_audio_sample },
1614     { "presets-commit", do_presets_commit },
1615     { "log-level", do_log_level },
1616     { "replay", do_replay },
1617     /*
1618     { "decrease-visibility", do_decrease_visibility },
1619     { "increase-visibility", do_increase_visibility },
1620     */
1621     { "loadxml", do_load_xml_to_proptree},
1622     { "savexml", do_save_xml_from_proptree },
1623     { "xmlhttprequest", do_load_xml_from_url },
1624     { "press-cockpit-button", do_press_cockpit_button },
1625     { "release-cockpit-button", do_release_cockpit_button },
1626     { "dump-scenegraph", do_dump_scene_graph },
1627     { "dump-terrainbranch", do_dump_terrain_branch },
1628     { "print-visible-scene", do_print_visible_scene_info },
1629     { "reload-shaders", do_reload_shaders },
1630   
1631     { "find-navaid", do_nav_search },
1632     { "find-comm", do_comm_search },
1633   
1634     { 0, 0 }                    // zero-terminated
1635 };
1636
1637
1638 /**
1639  * Initialize the default built-in commands.
1640  *
1641  * Other commands may be added by other parts of the application.
1642  */
1643 void
1644 fgInitCommands ()
1645 {
1646   SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1647   for (int i = 0; built_ins[i].name != 0; i++) {
1648     SG_LOG(SG_GENERAL, SG_BULK, "  " << built_ins[i].name);
1649     globals->get_commands()->addCommand(built_ins[i].name,
1650                                         built_ins[i].command);
1651   }
1652
1653   typedef bool (*dummy)();
1654   fgTie( "/command/view/next", dummy(0), do_view_next );
1655   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1656 }
1657
1658 // end of fg_commands.cxx