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