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