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