]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Fix line endings
[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 STL_STRING
12 #include STL_FSTREAM
13
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/structure/exception.hxx>
18 #include <simgear/structure/commands.hxx>
19 #include <simgear/props/props.hxx>
20
21 #include <Cockpit/panel.hxx>
22 #include <Cockpit/panel_io.hxx>
23 #include <Cockpit/hud.hxx>
24 #include <Environment/environment.hxx>
25 #include <FDM/flight.hxx>
26 #include <GUI/gui.h>
27 #include <GUI/new_gui.hxx>
28 #include <GUI/dialog.hxx>
29 #include <Aircraft/replay.hxx>
30 #include <Scenery/tilemgr.hxx>
31 #if defined(HAVE_PLIB_PSL)
32 #  include <Scripting/scriptmgr.hxx>
33 #endif
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 SG_USING_STD(string);
50 SG_USING_STD(ifstream);
51 SG_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 SGPropertyNode::BOOL:
137         return (value1->getBoolValue() == value2->getBoolValue());
138     case SGPropertyNode::INT:
139         return (value1->getIntValue() == value2->getIntValue());
140     case SGPropertyNode::LONG:
141         return (value1->getLongValue() == value2->getLongValue());
142     case SGPropertyNode::FLOAT:
143         return (value1->getFloatValue() == value2->getFloatValue());
144     case SGPropertyNode::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 #if defined(HAVE_PLIB_PSL)
168 /**
169  * Built-in command: run a PSL script.
170  *
171  * script: the PSL script to execute
172  */
173 static bool
174 do_script (const SGPropertyNode * arg)
175 {
176     FGScriptMgr * mgr = (FGScriptMgr *)globals->get_subsystem("scripting");
177     return mgr->run(arg->getStringValue("script"));
178 }
179 #endif // HAVE_PLIB_PSL
180
181 /**
182  * Built-in command: run a Nasal script.
183  */
184 static bool
185 do_nasal (const SGPropertyNode * arg)
186 {
187     return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
188 }
189
190 /**
191  * Built-in command: exit FlightGear.
192  *
193  * status: the exit status to return to the operating system (defaults to 0)
194  */
195 static bool
196 do_exit (const SGPropertyNode * arg)
197 {
198     SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
199     fgSetBool("/sim/signals/exit", true);
200
201     if (fgGetBool("/sim/startup/save-on-exit")) {
202 #ifdef _MSC_VER
203         char* envp = ::getenv( "APPDATA" );
204         if ( envp != NULL ) {
205             SGPath config( envp );
206             config.append( "flightgear.org" );
207 #else
208         if ( homedir != NULL ) {
209             SGPath config( homedir );
210             config.append( ".fgfs" );
211 #endif
212             config.append( "autosave.xml" );
213             config.create_dir( 0700 );
214             SG_LOG(SG_IO, SG_INFO, "Saving user settings to autosave.xml");
215             try {
216                 writeProperties(config.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
217             } catch (const sg_exception &e) {
218                 guiErrorMessage("Error writing autosave.xml: ", e);
219             }
220
221             SG_LOG(SG_INPUT, SG_BULK, "Finished Saving user settings");
222         }
223     }
224     fgExit(arg->getIntValue("status", 0));
225     return true;
226 }
227
228
229 /**
230  * Built-in command: reinitialize one or more subsystems.
231  *
232  * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
233  * none is specified, reinitialize all of them.
234  */
235 static bool
236 do_reinit (const SGPropertyNode * arg)
237 {
238     bool result = true;
239
240     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
241     if (subsystems.size() == 0) {
242         globals->get_subsystem_mgr()->reinit();
243     } else {
244         for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
245             const char * name = subsystems[i]->getStringValue();
246             SGSubsystem * subsystem = globals->get_subsystem(name);
247             if (subsystem == 0) {
248                 result = false;
249                 SG_LOG( SG_GENERAL, SG_ALERT,
250                         "Subsystem " << name << "not found" );
251             } else {
252                 subsystem->reinit();
253             }
254         }
255     }
256
257     globals->get_event_mgr()->reinit();
258
259     return result;
260 }
261
262 #if 0
263   //
264   // these routines look useful ??? but are never used in the code ???
265   //
266
267 /**
268  * Built-in command: suspend one or more subsystems.
269  *
270  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
271  */
272 static bool
273 do_suspend (const SGPropertyNode * arg)
274 {
275     bool result = true;
276
277     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
278     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
279         const char * name = subsystems[i]->getStringValue();
280         SGSubsystem * subsystem = globals->get_subsystem(name);
281         if (subsystem == 0) {
282             result = false;
283             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
284         } else {
285             subsystem->suspend();
286         }
287     }
288     return result;
289 }
290
291 /**
292  * Built-in command: suspend one or more subsystems.
293  *
294  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
295  */
296 static bool
297 do_resume (const SGPropertyNode * arg)
298 {
299     bool result = true;
300
301     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
302     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
303         const char * name = subsystems[i]->getStringValue();
304         SGSubsystem * subsystem = globals->get_subsystem(name);
305         if (subsystem == 0) {
306             result = false;
307             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
308         } else {
309             subsystem->resume();
310         }
311     }
312     return result;
313 }
314
315 #endif
316
317
318 /**
319  * Built-in command: load flight.
320  *
321  * file (optional): the name of the file to load (relative to current
322  *   directory).  Defaults to "fgfs.sav"
323  */
324 static bool
325 do_load (const SGPropertyNode * arg)
326 {
327   const string &file = arg->getStringValue("file", "fgfs.sav");
328   ifstream input(file.c_str());
329   if (input.good() && fgLoadFlight(input)) {
330     input.close();
331     SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
332     return true;
333   } else {
334     SG_LOG(SG_INPUT, SG_ALERT, "Cannot load flight from " << file);
335     return false;
336   }
337 }
338
339
340 /**
341  * Built-in command: save flight.
342  *
343  * file (optional): the name of the file to save (relative to the
344  * current directory).  Defaults to "fgfs.sav".
345  */
346 static bool
347 do_save (const SGPropertyNode * arg)
348 {
349   const string &file = arg->getStringValue("file", "fgfs.sav");
350   bool write_all = arg->getBoolValue("write-all", false);
351   SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
352   ofstream output(file.c_str());
353   if (output.good() && fgSaveFlight(output, write_all)) {
354     output.close();
355     SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
356     return true;
357   } else {
358     SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
359     return false;
360   }
361 }
362
363
364 /**
365  * Built-in command: (re)load the panel.
366  *
367  * path (optional): the file name to load the panel from 
368  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
369  * and if that's unspecified, to "Panels/Default/default.xml".
370  */
371 static bool
372 do_panel_load (const SGPropertyNode * arg)
373 {
374   string panel_path =
375     arg->getStringValue("path",
376                         fgGetString("/sim/panel/path",
377                                     "Panels/Default/default.xml"));
378   FGPanel * new_panel = fgReadPanel(panel_path);
379   if (new_panel == 0) {
380     SG_LOG(SG_INPUT, SG_ALERT,
381            "Error reading new panel from " << panel_path);
382     return false;
383   }
384   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
385   globals->get_current_panel()->unbind();
386   delete globals->get_current_panel();
387   globals->set_current_panel( new_panel );
388   globals->get_current_panel()->bind();
389   return true;
390 }
391
392
393 /**
394  * Built-in command: pass a mouse click to the panel.
395  *
396  * button: the mouse button number, zero-based.
397  * is-down: true if the button is down, false if it is up.
398  * x-pos: the x position of the mouse click.
399  * y-pos: the y position of the mouse click.
400  */
401 static bool
402 do_panel_mouse_click (const SGPropertyNode * arg)
403 {
404   if (globals->get_current_panel() != 0)
405     return globals->get_current_panel()
406       ->doMouseAction(arg->getIntValue("button"),
407                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
408                       arg->getIntValue("x-pos"),
409                       arg->getIntValue("y-pos"));
410   else
411     return false;
412 }
413
414
415 /**
416  * Built-in command: (re)load preferences.
417  *
418  * path (optional): the file name to load the panel from (relative
419  * to FG_ROOT). Defaults to "preferences.xml".
420  */
421 static bool
422 do_preferences_load (const SGPropertyNode * arg)
423 {
424   try {
425     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
426                 globals->get_props());
427   } catch (const sg_exception &e) {
428     guiErrorMessage("Error reading global preferences: ", e);
429     return false;
430   }
431   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
432   return true;
433 }
434
435
436 static void
437 fix_hud_visibility()
438 {
439   if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
440       globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
441       if ( globals->get_viewmgr()->get_current() == 1 ) {
442           globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
443       }
444   }
445 }
446
447 static void
448 do_view_next( bool )
449 {
450     globals->get_current_view()->setHeadingOffset_deg(0.0);
451     globals->get_viewmgr()->next_view();
452     fix_hud_visibility();
453     globals->get_tile_mgr()->refresh_view_timestamps();
454 }
455
456 static void
457 do_view_prev( bool )
458 {
459     globals->get_current_view()->setHeadingOffset_deg(0.0);
460     globals->get_viewmgr()->prev_view();
461     fix_hud_visibility();
462     globals->get_tile_mgr()->refresh_view_timestamps();
463 }
464
465 /**
466  * Built-in command: cycle view.
467  */
468 static bool
469 do_view_cycle (const SGPropertyNode * arg)
470 {
471   globals->get_current_view()->setHeadingOffset_deg(0.0);
472   globals->get_viewmgr()->next_view();
473   fix_hud_visibility();
474   globals->get_tile_mgr()->refresh_view_timestamps();
475 //   fgReshape(fgGetInt("/sim/startup/xsize"), fgGetInt("/sim/startup/ysize"));
476   return true;
477 }
478
479 /**
480  * Built-in command: capture screen.
481  */
482 static bool
483 do_screen_capture (const SGPropertyNode * arg)
484 {
485   fgDumpSnapShot();
486   return true;
487 }
488
489
490 /**
491  * Built-in command: hires capture screen.
492  */
493 static bool
494 do_hires_screen_capture (const SGPropertyNode * arg)
495 {
496   fgHiResDump();
497   return true;
498 }
499
500
501 /**
502  * Reload the tile cache.
503  */
504 static bool
505 do_tile_cache_reload (const SGPropertyNode * arg)
506 {
507     static const SGPropertyNode *master_freeze
508         = fgGetNode("/sim/freeze/master");
509     bool freeze = master_freeze->getBoolValue();
510     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
511     if ( !freeze ) {
512         fgSetBool("/sim/freeze/master", true);
513     }
514     // BusyCursor(0);
515     if ( globals->get_tile_mgr()->init() ) {
516         // Load the local scenery data
517         double visibility_meters = fgGetDouble("/environment/visibility-m");
518         globals->get_tile_mgr()->update( visibility_meters );
519     } else {
520         SG_LOG( SG_GENERAL, SG_ALERT, 
521                 "Error in Tile Manager initialization!" );
522         exit(-1);
523     }
524     // BusyCursor(1);
525     if ( !freeze ) {
526         fgSetBool("/sim/freeze/master", false);
527     }
528     return true;
529 }
530
531
532 /**
533  * Set the sea level outside air temperature and assigning that to all
534  * boundary and aloft environment layers.
535  */
536 static bool
537 do_set_sea_level_degc (const SGPropertyNode * arg)
538 {
539     double temp_sea_level_degc = arg->getDoubleValue("temp-degc", 15.0);
540
541     SGPropertyNode *node, *child;
542
543     // boundary layers
544     node = fgGetNode( "/environment/config/boundary" );
545     if ( node != NULL ) {
546       int i = 0;
547       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
548         child->setDoubleValue( "temperature-sea-level-degc",
549                                temp_sea_level_degc );
550         ++i;
551       }
552     }
553
554     // aloft layers
555     node = fgGetNode( "/environment/config/aloft" );
556     if ( node != NULL ) {
557       int i = 0;
558       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
559         child->setDoubleValue( "temperature-sea-level-degc",
560                                temp_sea_level_degc );
561         ++i;
562       }
563     }
564
565     return true;
566 }
567
568
569 /**
570  * Set the outside air temperature at the "current" altitude by first
571  * calculating the corresponding sea level temp, and assigning that to
572  * all boundary and aloft environment layers.
573  */
574 static bool
575 do_set_oat_degc (const SGPropertyNode * arg)
576 {
577     const string &temp_str = arg->getStringValue("temp-degc", "15.0");
578
579     // check for an altitude specified in the arguments, otherwise use
580     // current aircraft altitude.
581     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
582     if ( altitude_ft == NULL ) {
583         altitude_ft = fgGetNode("/position/altitude-ft");
584     }
585
586     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
587     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
588     dummy.set_temperature_degc( atof( temp_str.c_str() ) );
589     double temp_sea_level_degc = dummy.get_temperature_sea_level_degc();
590
591     //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
592     //cout << "Temp at alt (C) = " << atof( temp_str.c_str() ) << endl;
593     //cout << "Temp sea level (C) = " << temp_sea_level_degc << endl;
594  
595     SGPropertyNode *node, *child;
596
597     // boundary layers
598     node = fgGetNode( "/environment/config/boundary" );
599     if ( node != NULL ) {
600       int i = 0;
601       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
602         child->setDoubleValue( "temperature-sea-level-degc",
603                                temp_sea_level_degc );
604         ++i;
605       }
606     }
607
608     // aloft layers
609     node = fgGetNode( "/environment/config/aloft" );
610     if ( node != NULL ) {
611       int i = 0;
612       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
613         child->setDoubleValue( "temperature-sea-level-degc",
614                                temp_sea_level_degc );
615         ++i;
616       }
617     }
618
619     return true;
620 }
621
622 /**
623  * Set the sea level outside air dewpoint and assigning that to all
624  * boundary and aloft environment layers.
625  */
626 static bool
627 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
628 {
629     double dewpoint_sea_level_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
630
631     SGPropertyNode *node, *child;
632
633     // boundary layers
634     node = fgGetNode( "/environment/config/boundary" );
635     if ( node != NULL ) {
636       int i = 0;
637       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
638         child->setDoubleValue( "dewpoint-sea-level-degc",
639                                dewpoint_sea_level_degc );
640         ++i;
641       }
642     }
643
644     // aloft layers
645     node = fgGetNode( "/environment/config/aloft" );
646     if ( node != NULL ) {
647       int i = 0;
648       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
649         child->setDoubleValue( "dewpoint-sea-level-degc",
650                                dewpoint_sea_level_degc );
651         ++i;
652       }
653     }
654
655     return true;
656 }
657
658
659 /**
660  * Set the outside air dewpoint at the "current" altitude by first
661  * calculating the corresponding sea level dewpoint, and assigning
662  * that to all boundary and aloft environment layers.
663  */
664 static bool
665 do_set_dewpoint_degc (const SGPropertyNode * arg)
666 {
667     const string &dewpoint_str = arg->getStringValue("dewpoint-degc", "5.0");
668
669     // check for an altitude specified in the arguments, otherwise use
670     // current aircraft altitude.
671     const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
672     if ( altitude_ft == NULL ) {
673         altitude_ft = fgGetNode("/position/altitude-ft");
674     }
675
676     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
677     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
678     dummy.set_dewpoint_degc( atof( dewpoint_str.c_str() ) );
679     double dewpoint_sea_level_degc = dummy.get_dewpoint_sea_level_degc();
680
681     //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
682     //cout << "Dewpoint at alt (C) = " << atof( dewpoint_str.c_str() ) << endl;
683     //cout << "Dewpoint at sea level (C) = " << dewpoint_sea_level_degc << endl;
684  
685     SGPropertyNode *node, *child;
686
687     // boundary layers
688     node = fgGetNode( "/environment/config/boundary" );
689     if ( node != NULL ) {
690       int i = 0;
691       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
692         child->setDoubleValue( "dewpoint-sea-level-degc",
693                                dewpoint_sea_level_degc );
694         ++i;
695       }
696     }
697
698     // aloft layers
699     node = fgGetNode( "/environment/config/aloft" );
700     if ( node != NULL ) {
701       int i = 0;
702       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
703         child->setDoubleValue( "dewpoint-sea-level-degc",
704                                dewpoint_sea_level_degc );
705         ++i;
706       }
707     }
708
709     return true;
710 }
711
712 /**
713  * Update the lighting manually.
714  */
715 static bool
716 do_timeofday (const SGPropertyNode * arg)
717 {
718     const string &offset_type = arg->getStringValue("timeofday", "noon");
719
720     static const SGPropertyNode *longitude
721         = fgGetNode("/position/longitude-deg");
722     static const SGPropertyNode *latitude
723         = fgGetNode("/position/latitude-deg");
724     static const SGPropertyNode *cur_time_override
725         = fgGetNode("/sim/time/cur-time-override", true);
726
727     int orig_warp = globals->get_warp();
728     SGTime *t = globals->get_time_params();
729     time_t cur_time = t->get_cur_time();
730     // cout << "cur_time = " << cur_time << endl;
731     // cout << "orig_warp = " << orig_warp << endl;
732
733     int warp = 0;
734     if ( offset_type == "real" ) {
735         warp = -orig_warp;
736     } else if ( offset_type == "dawn" ) {
737         warp = fgTimeSecondsUntilSunAngle( cur_time,
738                                            longitude->getDoubleValue()
739                                              * SGD_DEGREES_TO_RADIANS,
740                                            latitude->getDoubleValue()
741                                              * SGD_DEGREES_TO_RADIANS,
742                                            90.0, true ); 
743     } else if ( offset_type == "morning" ) {
744         warp = fgTimeSecondsUntilSunAngle( cur_time,
745                                            longitude->getDoubleValue()
746                                              * SGD_DEGREES_TO_RADIANS,
747                                            latitude->getDoubleValue()
748                                              * SGD_DEGREES_TO_RADIANS,
749                                            75.0, true ); 
750     } else if ( offset_type == "noon" ) {
751         warp = fgTimeSecondsUntilSunAngle( cur_time,
752                                            longitude->getDoubleValue()
753                                              * SGD_DEGREES_TO_RADIANS,
754                                            latitude->getDoubleValue()
755                                              * SGD_DEGREES_TO_RADIANS,
756                                            0.0, true ); 
757     } else if ( offset_type == "afternoon" ) {
758         warp = fgTimeSecondsUntilSunAngle( cur_time,
759                                            longitude->getDoubleValue()
760                                              * SGD_DEGREES_TO_RADIANS,
761                                            latitude->getDoubleValue()
762                                              * SGD_DEGREES_TO_RADIANS,
763                                            60.0, false ); 
764      } else if ( offset_type == "dusk" ) {
765         warp = fgTimeSecondsUntilSunAngle( cur_time,
766                                            longitude->getDoubleValue()
767                                              * SGD_DEGREES_TO_RADIANS,
768                                            latitude->getDoubleValue()
769                                              * SGD_DEGREES_TO_RADIANS,
770                                            90.0, false ); 
771      } else if ( offset_type == "evening" ) {
772         warp = fgTimeSecondsUntilSunAngle( cur_time,
773                                            longitude->getDoubleValue()
774                                              * SGD_DEGREES_TO_RADIANS,
775                                            latitude->getDoubleValue()
776                                              * SGD_DEGREES_TO_RADIANS,
777                                            100.0, false ); 
778     } else if ( offset_type == "midnight" ) {
779         warp = fgTimeSecondsUntilSunAngle( cur_time,
780                                            longitude->getDoubleValue()
781                                              * SGD_DEGREES_TO_RADIANS,
782                                            latitude->getDoubleValue()
783                                              * SGD_DEGREES_TO_RADIANS,
784                                            180.0, false ); 
785     }
786     // cout << "warp = " << warp << endl;
787     globals->set_warp( orig_warp + warp );
788
789     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
790                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
791                cur_time_override->getLongValue(),
792                globals->get_warp() );
793
794     return true;
795 }
796
797
798 /**
799  * Built-in command: toggle a bool property value.
800  *
801  * property: The name of the property to toggle.
802  */
803 static bool
804 do_property_toggle (const SGPropertyNode * arg)
805 {
806   SGPropertyNode * prop = get_prop(arg);
807   return prop->setBoolValue(!prop->getBoolValue());
808 }
809
810
811 /**
812  * Built-in command: assign a value to a property.
813  *
814  * property: the name of the property to assign.
815  * value: the value to assign; or
816  * property[1]: the property to copy from.
817  */
818 static bool
819 do_property_assign (const SGPropertyNode * arg)
820 {
821   SGPropertyNode * prop = get_prop(arg);
822   const SGPropertyNode * prop2 = get_prop2(arg);
823   const SGPropertyNode * value = arg->getNode("value");
824
825   if (value != 0)
826       return prop->setUnspecifiedValue(value->getStringValue());
827   else if (prop2)
828       return prop->setUnspecifiedValue(prop2->getStringValue());
829   else
830       return false;
831 }
832
833
834 /**
835  * Built-in command: increment or decrement a property value.
836  *
837  * If the 'step' argument is present, it will be used; otherwise,
838  * the command uses 'offset' and 'factor', usually from the mouse.
839  *
840  * property: the name of the property to increment or decrement.
841  * step: the amount of the increment or decrement (default: 0).
842  * offset: offset from the current setting (used for the mouse; multiplied 
843  *         by factor)
844  * factor: scaling amount for the offset (defaults to 1).
845  * min: the minimum allowed value (default: no minimum).
846  * max: the maximum allowed value (default: no maximum).
847  * mask: 'integer' to apply only to the left of the decimal point, 
848  *       'decimal' to apply only to the right of the decimal point,
849  *       or 'all' to apply to the whole number (the default).
850  * wrap: true if the value should be wrapped when it passes min or max;
851  *       both min and max must be present for this to work (default:
852  *       false).
853  */
854 static bool
855 do_property_adjust (const SGPropertyNode * arg)
856 {
857   SGPropertyNode * prop = get_prop(arg);
858
859   double amount = 0;
860   if (arg->hasValue("step"))
861       amount = arg->getDoubleValue("step");
862   else
863       amount = (arg->getDoubleValue("factor", 1)
864                 * arg->getDoubleValue("offset"));
865           
866   double unmodifiable, modifiable;
867   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
868               &unmodifiable, &modifiable);
869   modifiable += amount;
870   limit_value(&modifiable, arg);
871
872   prop->setDoubleValue(unmodifiable + modifiable);
873
874   return true;
875 }
876
877
878 /**
879  * Built-in command: multiply a property value.
880  *
881  * property: the name of the property to multiply.
882  * factor: the amount by which to multiply.
883  * min: the minimum allowed value (default: no minimum).
884  * max: the maximum allowed value (default: no maximum).
885  * mask: 'integer' to apply only to the left of the decimal point, 
886  *       'decimal' to apply only to the right of the decimal point,
887  *       or 'all' to apply to the whole number (the default).
888  * wrap: true if the value should be wrapped when it passes min or max;
889  *       both min and max must be present for this to work (default:
890  *       false).
891  */
892 static bool
893 do_property_multiply (const SGPropertyNode * arg)
894 {
895   SGPropertyNode * prop = get_prop(arg);
896   double factor = arg->getDoubleValue("factor", 1);
897
898   double unmodifiable, modifiable;
899   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
900               &unmodifiable, &modifiable);
901   modifiable *= factor;
902   limit_value(&modifiable, arg);
903
904   prop->setDoubleValue(unmodifiable + modifiable);
905
906   return true;
907 }
908
909
910 /**
911  * Built-in command: swap two property values.
912  *
913  * property[0]: the name of the first property.
914  * property[1]: the name of the second property.
915  */
916 static bool
917 do_property_swap (const SGPropertyNode * arg)
918 {
919   SGPropertyNode * prop1 = get_prop(arg);
920   SGPropertyNode * prop2 = get_prop2(arg);
921
922                                 // FIXME: inefficient
923   const string & tmp = prop1->getStringValue();
924   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
925           prop2->setUnspecifiedValue(tmp.c_str()));
926 }
927
928
929 /**
930  * Built-in command: Set a property to an axis or other moving input.
931  *
932  * property: the name of the property to set.
933  * setting: the current input setting, usually between -1.0 and 1.0.
934  * offset: the offset to shift by, before applying the factor.
935  * factor: the factor to multiply by (use negative to reverse).
936  */
937 static bool
938 do_property_scale (const SGPropertyNode * arg)
939 {
940   SGPropertyNode * prop = get_prop(arg);
941   double setting = arg->getDoubleValue("setting");
942   double offset = arg->getDoubleValue("offset", 0.0);
943   double factor = arg->getDoubleValue("factor", 1.0);
944   bool squared = arg->getBoolValue("squared", false);
945   int power = arg->getIntValue("power", (squared ? 2 : 1));
946
947   int sign = (setting < 0 ? -1 : 1);
948
949   switch (power) {
950   case 1:
951       break;
952   case 2:
953       setting = setting * setting * sign;
954       break;
955   case 3:
956       setting = setting * setting * setting;
957       break;
958   case 4:
959       setting = setting * setting * setting * setting * sign;
960       break;
961   default:
962       setting =  pow(setting, power);
963       if ((power % 2) == 0)
964           setting *= sign;
965       break;
966   }
967
968   return prop->setDoubleValue((setting + offset) * factor);
969 }
970
971
972 /**
973  * Built-in command: cycle a property through a set of values.
974  *
975  * If the current value isn't in the list, the cycle will
976  * (re)start from the beginning.
977  *
978  * property: the name of the property to cycle.
979  * value[*]: the list of values to cycle through.
980  */
981 static bool
982 do_property_cycle (const SGPropertyNode * arg)
983 {
984     SGPropertyNode * prop = get_prop(arg);
985     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
986     int selection = -1;
987     int nSelections = values.size();
988
989     if (nSelections < 1) {
990         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
991         return false;
992     }
993
994                                 // Try to find the current selection
995     for (int i = 0; i < nSelections; i++) {
996         if (compare_values(prop, values[i])) {
997             selection = i + 1;
998             break;
999         }
1000     }
1001
1002                                 // Default or wrap to the first selection
1003     if (selection < 0 || selection >= nSelections)
1004         selection = 0;
1005
1006     prop->setUnspecifiedValue(values[selection]->getStringValue());
1007     return true;
1008 }
1009
1010
1011 /**
1012  * Built-in command: randomize a numeric property value.
1013  *
1014  * property: the name of the property value to randomize.
1015  * min: the minimum allowed value.
1016  * max: the maximum allowed value.
1017  */
1018 static bool
1019 do_property_randomize (const SGPropertyNode * arg)
1020 {
1021     SGPropertyNode * prop = get_prop(arg);
1022     double min = arg->getDoubleValue("min", DBL_MIN);
1023     double max = arg->getDoubleValue("max", DBL_MAX);
1024     prop->setDoubleValue(sg_random() * (max - min) + min);
1025     return true;
1026 }
1027
1028
1029 /**
1030  * Built-in command: reinit the data logging system based on the
1031  * current contents of the /logger tree.
1032  */
1033 static bool
1034 do_data_logging_commit (const SGPropertyNode * arg)
1035 {
1036     FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1037     log->reinit();
1038     return true;
1039 }
1040
1041 /**
1042  * Built-in command: Add a dialog to the GUI system.  Does *not*
1043  * display the dialog.  The property node should have the same format
1044  * as a dialog XML configuration.  It must include:
1045  *
1046  * name: the name of the GUI dialog for future reference.
1047  */
1048 static bool
1049 do_dialog_new (const SGPropertyNode * arg)
1050 {
1051     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1052
1053     // Note the casting away of const: this is *real*.  Doing a
1054     // "dialog-apply" command later on will mutate this property node.
1055     // I'm not convinced that this isn't the Right Thing though; it
1056     // allows client to create a node, pass it to dialog-new, and get
1057     // the values back from the dialog by reading the same node.
1058     // Perhaps command arguments are not as "const" as they would
1059     // seem?
1060     gui->newDialog((SGPropertyNode*)arg);
1061     return true;
1062 }
1063
1064 /**
1065  * Built-in command: Show an XML-configured dialog.
1066  *
1067  * dialog-name: the name of the GUI dialog to display.
1068  */
1069 static bool
1070 do_dialog_show (const SGPropertyNode * arg)
1071 {
1072     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1073     gui->showDialog(arg->getStringValue("dialog-name"));
1074     return true;
1075 }
1076
1077
1078 /**
1079  * Built-in Command: Hide the active XML-configured dialog.
1080  */
1081 static bool
1082 do_dialog_close (const SGPropertyNode * arg)
1083 {
1084     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1085     if(arg->hasValue("dialog-name"))
1086         return gui->closeDialog(arg->getStringValue("dialog-name"));
1087     return gui->closeActiveDialog();
1088 }
1089
1090
1091 /**
1092  * Update a value in the active XML-configured dialog.
1093  *
1094  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1095  */
1096 static bool
1097 do_dialog_update (const SGPropertyNode * arg)
1098 {
1099     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1100     FGDialog * dialog = gui->getActiveDialog();
1101     if (dialog != 0) {
1102         if (arg->hasValue("object-name")) {
1103             dialog->updateValue(arg->getStringValue("object-name"));
1104         } else {
1105             dialog->updateValues();
1106         }
1107         return true;
1108     } else {
1109         return false;
1110     }
1111 }
1112
1113
1114 /**
1115  * Apply a value in the active XML-configured dialog.
1116  *
1117  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1118  */
1119 static bool
1120 do_dialog_apply (const SGPropertyNode * arg)
1121 {
1122     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1123     FGDialog * dialog = gui->getActiveDialog();
1124     if (dialog != 0) {
1125         if (arg->hasValue("object-name")) {
1126             const char * name = arg->getStringValue("object-name");
1127             dialog->applyValue(name);
1128             dialog->updateValue(name);
1129         } else {
1130             dialog->applyValues();
1131             dialog->updateValues();
1132         }
1133         return true;
1134     } else {
1135         return false;
1136     }
1137 }
1138
1139
1140 /**
1141  * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1142  * unlike reinit().
1143  */
1144 static bool
1145 do_gui_redraw (const SGPropertyNode * arg)
1146 {
1147     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1148     gui->redraw();
1149     return true;
1150 }
1151
1152 /**
1153  * Built-in command: play an audio message (i.e. a wav file) This is
1154  * fire and forget.  Call this once per message and it will get dumped
1155  * into a queue.  Messages are played sequentially so they do not
1156  * overlap.
1157  */
1158 static bool
1159 do_play_audio_message (const SGPropertyNode * arg)
1160 {
1161     FGFX *fx = (FGFX *)globals->get_subsystem("fx");
1162     string path = arg->getStringValue("path");
1163     string file = arg->getStringValue("file");
1164     // cout << "playing " << path << " / " << file << endl;
1165     fx->play_message( path, file );
1166
1167     return true;
1168 }
1169
1170 /**
1171  * Built-in command: commit presets (read from in /sim/presets/)
1172  */
1173 static bool
1174 do_presets_commit (const SGPropertyNode * arg)
1175 {
1176     // unbind the current fdm state so property changes
1177     // don't get lost when we subsequently delete this fdm
1178     // and create a new one.
1179     cur_fdm_state->unbind();
1180         
1181     // set position from presets
1182     fgInitPosition();
1183
1184     // BusyCursor(0);
1185     fgReInitSubsystems();
1186
1187     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
1188
1189 #if 0
1190     if ( ! fgGetBool("/sim/presets/onground") ) {
1191         fgSetBool( "/sim/freeze/master", true );
1192         fgSetBool( "/sim/freeze/clock", true );
1193     }
1194 #endif
1195
1196     return true;
1197 }
1198
1199 /**
1200  * Built-in command: set log level (0 ... 7)
1201  */
1202 static bool
1203 do_log_level (const SGPropertyNode * arg)
1204 {
1205    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1206
1207    return true;
1208 }
1209
1210 /**
1211  * Built-in command: replay the FDR buffer
1212  */
1213 static bool
1214 do_replay (const SGPropertyNode * arg)
1215 {
1216     // freeze the master fdm
1217     fgSetInt( "/sim/freeze/replay-state", 1 );
1218
1219     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
1220
1221     fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
1222     fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
1223     double duration = fgGetDouble( "/sim/replay/duration" );
1224     if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
1225         fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
1226     } else {
1227         fgSetDouble( "/sim/replay/time", r->get_start_time() );
1228     }
1229
1230     // cout << "start = " << r->get_start_time()
1231     //      << "  end = " << r->get_end_time() << endl;
1232
1233     return true;
1234 }
1235
1236
1237
1238 static bool
1239 do_decrease_visibility (const SGPropertyNode * arg)
1240 {
1241     double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
1242     fgSetDouble("/environment/visibility-m", new_value);
1243     fgDefaultWeatherValue("visibility-m", new_value);
1244     globals->get_subsystem("environment")->reinit();
1245
1246     return true;
1247 }
1248  
1249 static bool
1250 do_increase_visibility (const SGPropertyNode * arg)
1251 {
1252     double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1253     fgSetDouble("/environment/visibility-m", new_value);
1254     fgDefaultWeatherValue("visibility-m", new_value);
1255     globals->get_subsystem("environment")->reinit();
1256
1257     return true;
1258 }
1259
1260 static bool
1261 do_hud_brightkey(const SGPropertyNode *)
1262 {
1263     HUD_brightkey( true );
1264     return true;
1265 }
1266
1267 static bool
1268 do_hud_masterswitch(const SGPropertyNode *)
1269 {
1270     HUD_masterswitch( true );
1271     return true;
1272 }
1273
1274 static bool
1275 do_hud_init(const SGPropertyNode *)
1276 {
1277     fgHUDInit(0); // minimal HUD
1278     return true;
1279 }
1280
1281 static bool
1282 do_hud_init2(const SGPropertyNode *)
1283 {
1284     fgHUDInit2(0);  // normal HUD
1285     return true;
1286 }
1287
1288 /**
1289  * An fgcommand to allow loading of xml files via nasal,
1290  * the xml file's structure will be made available within
1291  * a (definable) property tree node
1292  *
1293  * @param filename a string to hold the complete path & filename of a XML file
1294  * @param targetnode a string pointing to a location within the property tree
1295  * where to store the parsed XML file
1296  */
1297
1298 static bool 
1299 do_load_xml_to_proptree(const SGPropertyNode * node)
1300 {
1301     // SG_LOG(SG_GENERAL, SG_ALERT, "fgcommand loadxml executed");
1302
1303     SGPropertyNode * targetnode;
1304     targetnode = fgGetNode(node->getNode("targetnode")->getStringValue(),true);
1305                 
1306     const char *filename = node->getNode("filename")->getStringValue();
1307     try {
1308         fgLoadProps(filename, targetnode);
1309     } catch (const sg_exception &e) {
1310         string errmsg = "Error reading file " + string(filename) + ":\n";
1311         guiErrorMessage(errmsg.c_str(), e);
1312         return false;
1313     }
1314
1315     return  true;
1316 }
1317
1318
1319 /**
1320  * an fgcommand to allow saving of xml files via nasal,
1321  * the file's structure will be determined based on what's
1322  * encountered in the passed (source) property tree node
1323  *
1324  * @param filename a string to hold the complete path & filename of the (new)
1325  * XML file
1326  * @param sourcenode a string pointing to a location within the property tree
1327  * where to find the nodes that should be written recursively into an XML file
1328  *
1329  * TODO: 
1330  *   deal with already existing filenames, optionally return error/success
1331  *   values in a separate node to provide status information
1332  *
1333  * note: it's directly using writeProperties, which is not necessarily
1334  *       preferable, but for now it should work ...
1335  */
1336
1337 static bool 
1338 do_save_xml_from_proptree(const SGPropertyNode * node)
1339 {
1340     //TODO: do Parameter validation !
1341     SGPropertyNode * sourcenode;
1342     sourcenode = fgGetNode(node->getNode("sourcenode")->getStringValue(),true);
1343
1344     const char *filename = node->getNode("filename")->getStringValue();
1345     try {
1346         writeProperties (filename, sourcenode, true);
1347     } catch (const sg_exception &e) {
1348         string errmsg = "Error writing file " + string(filename) + ":\n";
1349         guiErrorMessage(errmsg.c_str(), e);
1350         return false;
1351     }
1352
1353     return true;
1354 }
1355
1356
1357 ////////////////////////////////////////////////////////////////////////
1358 // Command setup.
1359 ////////////////////////////////////////////////////////////////////////
1360
1361
1362 /**
1363  * Table of built-in commands.
1364  *
1365  * New commands do not have to be added here; any module in the application
1366  * can add a new command using globals->get_commands()->addCommand(...).
1367  */
1368 static struct {
1369   const char * name;
1370   SGCommandMgr::command_t command;
1371 } built_ins [] = {
1372     { "null", do_null },
1373 #if defined(HAVE_PLIB_PSL)
1374     { "script", do_script },
1375 #endif // HAVE_PLIB_PSL
1376     { "nasal", do_nasal },
1377     { "exit", do_exit },
1378     { "reinit", do_reinit },
1379     { "suspend", do_reinit },
1380     { "resume", do_reinit },
1381     { "load", do_load },
1382     { "save", do_save },
1383     { "panel-load", do_panel_load },
1384     { "panel-mouse-click", do_panel_mouse_click },
1385     { "preferences-load", do_preferences_load },
1386     { "view-cycle", do_view_cycle },
1387     { "screen-capture", do_screen_capture },
1388     { "hires-screen-capture", do_hires_screen_capture },
1389     { "tile-cache-reload", do_tile_cache_reload },
1390     { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1391     { "set-outside-air-temp-degc", do_set_oat_degc },
1392     { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1393     { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1394     { "timeofday", do_timeofday },
1395     { "property-toggle", do_property_toggle },
1396     { "property-assign", do_property_assign },
1397     { "property-adjust", do_property_adjust },
1398     { "property-multiply", do_property_multiply },
1399     { "property-swap", do_property_swap },
1400     { "property-scale", do_property_scale },
1401     { "property-cycle", do_property_cycle },
1402     { "property-randomize", do_property_randomize },
1403     { "data-logging-commit", do_data_logging_commit },
1404     { "dialog-new", do_dialog_new },
1405     { "dialog-show", do_dialog_show },
1406     { "dialog-close", do_dialog_close },
1407     { "dialog-update", do_dialog_update },
1408     { "dialog-apply", do_dialog_apply },
1409     { "gui-redraw", do_gui_redraw },
1410     { "play-audio-message", do_play_audio_message },
1411     { "presets-commit", do_presets_commit },
1412     { "log-level", do_log_level },
1413     { "replay", do_replay },
1414     { "decrease-visibility", do_decrease_visibility },
1415     { "increase-visibility", do_increase_visibility },
1416     { "hud-brightkey", do_hud_brightkey },
1417     { "hud-masterswitch", do_hud_masterswitch },
1418     { "hud-init", do_hud_init },
1419     { "hud-init2", do_hud_init2 },
1420     { "loadxml", do_load_xml_to_proptree},
1421     { "savexml", do_save_xml_from_proptree },    
1422     { 0, 0 }                    // zero-terminated
1423 };
1424
1425
1426 /**
1427  * Initialize the default built-in commands.
1428  *
1429  * Other commands may be added by other parts of the application.
1430  */
1431 void
1432 fgInitCommands ()
1433 {
1434   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1435   for (int i = 0; built_ins[i].name != 0; i++) {
1436     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
1437     globals->get_commands()->addCommand(built_ins[i].name,
1438                                         built_ins[i].command);
1439   }
1440
1441   typedef bool (*dummy)();
1442   fgTie( "/command/view/next", dummy(0), do_view_next );
1443   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1444 }
1445
1446 // end of fg_commands.cxx