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