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