]> git.mxchange.org Git - flightgear.git/blob - src/Main/fg_commands.cxx
Depreciate NetworkOLK. A big thanks goes to Oliver Delise for implementing it in...
[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 <Time/sunsolver.hxx>
30 #include <Time/tmp.hxx>
31
32 #include "fg_init.hxx"
33 #include "fg_commands.hxx"
34 #include "fg_props.hxx"
35
36 SG_USING_STD(string);
37 SG_USING_STD(ifstream);
38 SG_USING_STD(ofstream);
39
40 #include "fg_props.hxx"
41 #include "fg_io.hxx"
42 #include "globals.hxx"
43 #include "util.hxx"
44 #include "viewmgr.hxx"
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 /**
176  * Built-in command: exit FlightGear.
177  *
178  * status: the exit status to return to the operating system (defaults to 0)
179  */
180 static bool
181 do_exit (const SGPropertyNode * arg)
182 {
183   SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
184   fgExit(arg->getIntValue("status", 0));
185   return true;
186 }
187
188
189 /**
190  * Built-in command: reinitialize one or more subsystems.
191  *
192  * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
193  * none is specified, reinitialize all of them.
194  */
195 static bool
196 do_reinit (const SGPropertyNode * arg)
197 {
198     bool result = true;
199
200     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
201     if (subsystems.size() == 0) {
202         globals->get_subsystem_mgr()->reinit();
203     } else {
204         for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
205             const char * name = subsystems[i]->getStringValue();
206             SGSubsystem * subsystem = globals->get_subsystem(name);
207             if (subsystem == 0) {
208                 result = false;
209                 SG_LOG( SG_GENERAL, SG_ALERT,
210                         "Subsystem " << name << "not found" );
211             } else {
212                 subsystem->reinit();
213             }
214         }
215     }
216
217     globals->get_event_mgr()->reinit();
218
219     return result;
220 }
221
222 /**
223  * Built-in command: suspend one or more subsystems.
224  *
225  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
226  */
227 static bool
228 do_suspend (const SGPropertyNode * arg)
229 {
230     bool result = true;
231
232     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
233     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
234         const char * name = subsystems[i]->getStringValue();
235         SGSubsystem * subsystem = globals->get_subsystem(name);
236         if (subsystem == 0) {
237             result = false;
238             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
239         } else {
240             subsystem->suspend();
241         }
242     }
243     return result;
244 }
245
246 /**
247  * Built-in command: suspend one or more subsystems.
248  *
249  * subsystem[*] - the name(s) of the subsystem(s) to suspend.
250  */
251 static bool
252 do_resume (const SGPropertyNode * arg)
253 {
254     bool result = true;
255
256     vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
257     for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
258         const char * name = subsystems[i]->getStringValue();
259         SGSubsystem * subsystem = globals->get_subsystem(name);
260         if (subsystem == 0) {
261             result = false;
262             SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
263         } else {
264             subsystem->resume();
265         }
266     }
267     return result;
268 }
269
270
271 /**
272  * Built-in command: load flight.
273  *
274  * file (optional): the name of the file to load (relative to current
275  *   directory).  Defaults to "fgfs.sav"
276  */
277 static bool
278 do_load (const SGPropertyNode * arg)
279 {
280   const string &file = arg->getStringValue("file", "fgfs.sav");
281   ifstream input(file.c_str());
282   if (input.good() && fgLoadFlight(input)) {
283     input.close();
284     SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
285     return true;
286   } else {
287     SG_LOG(SG_INPUT, SG_ALERT, "Cannot load flight from " << file);
288     return false;
289   }
290 }
291
292
293 /**
294  * Built-in command: save flight.
295  *
296  * file (optional): the name of the file to save (relative to the
297  * current directory).  Defaults to "fgfs.sav".
298  */
299 static bool
300 do_save (const SGPropertyNode * arg)
301 {
302   const string &file = arg->getStringValue("file", "fgfs.sav");
303   bool write_all = arg->getBoolValue("write-all", false);
304   SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
305   ofstream output(file.c_str());
306   if (output.good() && fgSaveFlight(output, write_all)) {
307     output.close();
308     SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
309     return true;
310   } else {
311     SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
312     return false;
313   }
314 }
315
316
317 /**
318  * Built-in command: (re)load the panel.
319  *
320  * path (optional): the file name to load the panel from 
321  * (relative to FG_ROOT).  Defaults to the value of /sim/panel/path,
322  * and if that's unspecified, to "Panels/Default/default.xml".
323  */
324 static bool
325 do_panel_load (const SGPropertyNode * arg)
326 {
327   string panel_path =
328     arg->getStringValue("path",
329                         fgGetString("/sim/panel/path",
330                                     "Panels/Default/default.xml"));
331   FGPanel * new_panel = fgReadPanel(panel_path);
332   if (new_panel == 0) {
333     SG_LOG(SG_INPUT, SG_ALERT,
334            "Error reading new panel from " << panel_path);
335     return false;
336   }
337   SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
338   globals->get_current_panel()->unbind();
339   delete globals->get_current_panel();
340   globals->set_current_panel( new_panel );
341   globals->get_current_panel()->bind();
342   return true;
343 }
344
345
346 /**
347  * Built-in command: pass a mouse click to the panel.
348  *
349  * button: the mouse button number, zero-based.
350  * is-down: true if the button is down, false if it is up.
351  * x-pos: the x position of the mouse click.
352  * y-pos: the y position of the mouse click.
353  */
354 static bool
355 do_panel_mouse_click (const SGPropertyNode * arg)
356 {
357   if (globals->get_current_panel() != 0)
358     return globals->get_current_panel()
359       ->doMouseAction(arg->getIntValue("button"),
360                       arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
361                       arg->getIntValue("x-pos"),
362                       arg->getIntValue("y-pos"));
363   else
364     return false;
365 }
366
367
368 /**
369  * Built-in command: (re)load preferences.
370  *
371  * path (optional): the file name to load the panel from (relative
372  * to FG_ROOT). Defaults to "preferences.xml".
373  */
374 static bool
375 do_preferences_load (const SGPropertyNode * arg)
376 {
377   try {
378     fgLoadProps(arg->getStringValue("path", "preferences.xml"),
379                 globals->get_props());
380   } catch (const sg_exception &e) {
381     guiErrorMessage("Error reading global preferences: ", e);
382     return false;
383   }
384   SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
385   return true;
386 }
387
388
389 static void
390 fix_hud_visibility()
391 {
392   if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
393       globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
394       if ( globals->get_viewmgr()->get_current() == 1 ) {
395           globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
396       }
397   }
398 }
399
400 static void
401 do_view_next( bool )
402 {
403     globals->get_current_view()->setHeadingOffset_deg(0.0);
404     globals->get_viewmgr()->next_view();
405     fix_hud_visibility();
406     globals->get_tile_mgr()->refresh_view_timestamps();
407 }
408
409 static void
410 do_view_prev( bool )
411 {
412     globals->get_current_view()->setHeadingOffset_deg(0.0);
413     globals->get_viewmgr()->prev_view();
414     fix_hud_visibility();
415     globals->get_tile_mgr()->refresh_view_timestamps();
416 }
417
418 /**
419  * Built-in command: cycle view.
420  */
421 static bool
422 do_view_cycle (const SGPropertyNode * arg)
423 {
424   globals->get_current_view()->setHeadingOffset_deg(0.0);
425   globals->get_viewmgr()->next_view();
426   fix_hud_visibility();
427   globals->get_tile_mgr()->refresh_view_timestamps();
428 //   fgReshape(fgGetInt("/sim/startup/xsize"), fgGetInt("/sim/startup/ysize"));
429   return true;
430 }
431
432 /**
433  * Built-in command: capture screen.
434  */
435 static bool
436 do_screen_capture (const SGPropertyNode * arg)
437 {
438   fgDumpSnapShot();
439   return true;
440 }
441
442
443 /**
444  * Reload the tile cache.
445  */
446 static bool
447 do_tile_cache_reload (const SGPropertyNode * arg)
448 {
449     static const SGPropertyNode *master_freeze
450         = fgGetNode("/sim/freeze/master");
451     bool freeze = master_freeze->getBoolValue();
452     SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
453     if ( !freeze ) {
454         fgSetBool("/sim/freeze/master", true);
455     }
456     // BusyCursor(0);
457     if ( globals->get_tile_mgr()->init() ) {
458         // Load the local scenery data
459         double visibility_meters = fgGetDouble("/environment/visibility-m");
460         globals->get_tile_mgr()->update( visibility_meters );
461     } else {
462         SG_LOG( SG_GENERAL, SG_ALERT, 
463                 "Error in Tile Manager initialization!" );
464         exit(-1);
465     }
466     // BusyCursor(1);
467     if ( !freeze ) {
468         fgSetBool("/sim/freeze/master", false);
469     }
470     return true;
471 }
472
473
474 /**
475  * Set the outside air temperature at the "current" altitude by first
476  * calculating the corresponding sea level temp, and assigning that to
477  * all boundary and aloft environment layers.
478  */
479 static bool
480 do_set_oat_degc (const SGPropertyNode * arg)
481 {
482     const string &temp_str = arg->getStringValue("temp-degc", "15.0");
483
484     static const SGPropertyNode *altitude_ft
485       = fgGetNode("/position/altitude-ft");
486
487     FGEnvironment dummy;        // instantiate a dummy so we can leech a method
488     dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
489     dummy.set_temperature_degc( atof( temp_str.c_str() ) );
490     double temp_sea_level_degc = dummy.get_temperature_sea_level_degc();
491
492     cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
493     cout << "Temp at alt (C) = " << atof( temp_str.c_str() ) << endl;
494     cout << "Temp sea level (C) = " << temp_sea_level_degc << endl;
495  
496     SGPropertyNode *node, *child;
497
498     // boundary layers
499     node = fgGetNode( "/environment/config/boundary" );
500     if ( node != NULL ) {
501       int i = 0;
502       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
503         child->setDoubleValue( "temperature-sea-level-degc",
504                                temp_sea_level_degc );
505         ++i;
506       }
507     }
508
509     // aloft layers
510     node = fgGetNode( "/environment/config/aloft" );
511     if ( node != NULL ) {
512       int i = 0;
513       while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
514         child->setDoubleValue( "temperature-sea-level-degc",
515                                temp_sea_level_degc );
516         ++i;
517       }
518     }
519
520     return true;
521 }
522
523 /**
524  * Update the lighting manually.
525  */
526 static bool
527 do_timeofday (const SGPropertyNode * arg)
528 {
529     const string &offset_type = arg->getStringValue("timeofday", "noon");
530
531     static const SGPropertyNode *longitude
532         = fgGetNode("/position/longitude-deg");
533     static const SGPropertyNode *latitude
534         = fgGetNode("/position/latitude-deg");
535     static const SGPropertyNode *cur_time_override
536         = fgGetNode("/sim/time/cur-time-override", true);
537
538     int orig_warp = globals->get_warp();
539     SGTime *t = globals->get_time_params();
540     time_t cur_time = t->get_cur_time();
541     // cout << "cur_time = " << cur_time << endl;
542     // cout << "orig_warp = " << orig_warp << endl;
543
544     int warp = 0;
545     if ( offset_type == "real" ) {
546         warp = -orig_warp;
547     } else if ( offset_type == "dawn" ) {
548         warp = fgTimeSecondsUntilSunAngle( cur_time,
549                                            longitude->getDoubleValue()
550                                              * SGD_DEGREES_TO_RADIANS,
551                                            latitude->getDoubleValue()
552                                              * SGD_DEGREES_TO_RADIANS,
553                                            90.0, true ); 
554     } else if ( offset_type == "morning" ) {
555         warp = fgTimeSecondsUntilSunAngle( cur_time,
556                                            longitude->getDoubleValue()
557                                              * SGD_DEGREES_TO_RADIANS,
558                                            latitude->getDoubleValue()
559                                              * SGD_DEGREES_TO_RADIANS,
560                                            75.0, true ); 
561     } else if ( offset_type == "noon" ) {
562         warp = fgTimeSecondsUntilSunAngle( cur_time,
563                                            longitude->getDoubleValue()
564                                              * SGD_DEGREES_TO_RADIANS,
565                                            latitude->getDoubleValue()
566                                              * SGD_DEGREES_TO_RADIANS,
567                                            0.0, true ); 
568     } else if ( offset_type == "afternoon" ) {
569         warp = fgTimeSecondsUntilSunAngle( cur_time,
570                                            longitude->getDoubleValue()
571                                              * SGD_DEGREES_TO_RADIANS,
572                                            latitude->getDoubleValue()
573                                              * SGD_DEGREES_TO_RADIANS,
574                                            60.0, false ); 
575      } else if ( offset_type == "dusk" ) {
576         warp = fgTimeSecondsUntilSunAngle( cur_time,
577                                            longitude->getDoubleValue()
578                                              * SGD_DEGREES_TO_RADIANS,
579                                            latitude->getDoubleValue()
580                                              * SGD_DEGREES_TO_RADIANS,
581                                            90.0, false ); 
582      } else if ( offset_type == "evening" ) {
583         warp = fgTimeSecondsUntilSunAngle( cur_time,
584                                            longitude->getDoubleValue()
585                                              * SGD_DEGREES_TO_RADIANS,
586                                            latitude->getDoubleValue()
587                                              * SGD_DEGREES_TO_RADIANS,
588                                            100.0, false ); 
589     } else if ( offset_type == "midnight" ) {
590         warp = fgTimeSecondsUntilSunAngle( cur_time,
591                                            longitude->getDoubleValue()
592                                              * SGD_DEGREES_TO_RADIANS,
593                                            latitude->getDoubleValue()
594                                              * SGD_DEGREES_TO_RADIANS,
595                                            180.0, false ); 
596     }
597     // cout << "warp = " << warp << endl;
598     globals->set_warp( orig_warp + warp );
599
600     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
601                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
602                cur_time_override->getLongValue(),
603                globals->get_warp() );
604
605     return true;
606 }
607
608
609 /**
610  * Built-in command: toggle a bool property value.
611  *
612  * property: The name of the property to toggle.
613  */
614 static bool
615 do_property_toggle (const SGPropertyNode * arg)
616 {
617   SGPropertyNode * prop = get_prop(arg);
618   return prop->setBoolValue(!prop->getBoolValue());
619 }
620
621
622 /**
623  * Built-in command: assign a value to a property.
624  *
625  * property: the name of the property to assign.
626  * value: the value to assign; or
627  * property[1]: the property to copy from.
628  */
629 static bool
630 do_property_assign (const SGPropertyNode * arg)
631 {
632   SGPropertyNode * prop = get_prop(arg);
633   const SGPropertyNode * prop2 = get_prop2(arg);
634   const SGPropertyNode * value = arg->getNode("value");
635
636   if (value != 0)
637       return prop->setUnspecifiedValue(value->getStringValue());
638   else if (prop2)
639       return prop->setUnspecifiedValue(prop2->getStringValue());
640   else
641       return false;
642 }
643
644
645 /**
646  * Built-in command: increment or decrement a property value.
647  *
648  * If the 'step' argument is present, it will be used; otherwise,
649  * the command uses 'offset' and 'factor', usually from the mouse.
650  *
651  * property: the name of the property to increment or decrement.
652  * step: the amount of the increment or decrement (default: 0).
653  * offset: offset from the current setting (used for the mouse; multiplied 
654  *         by factor)
655  * factor: scaling amount for the offset (defaults to 1).
656  * min: the minimum allowed value (default: no minimum).
657  * max: the maximum allowed value (default: no maximum).
658  * mask: 'integer' to apply only to the left of the decimal point, 
659  *       'decimal' to apply only to the right of the decimal point,
660  *       or 'all' to apply to the whole number (the default).
661  * wrap: true if the value should be wrapped when it passes min or max;
662  *       both min and max must be present for this to work (default:
663  *       false).
664  */
665 static bool
666 do_property_adjust (const SGPropertyNode * arg)
667 {
668   SGPropertyNode * prop = get_prop(arg);
669
670   double amount = 0;
671   if (arg->hasValue("step"))
672       amount = arg->getDoubleValue("step");
673   else
674       amount = (arg->getDoubleValue("factor", 1)
675                 * arg->getDoubleValue("offset"));
676           
677   double unmodifiable, modifiable;
678   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
679               &unmodifiable, &modifiable);
680   modifiable += amount;
681   limit_value(&modifiable, arg);
682
683   prop->setDoubleValue(unmodifiable + modifiable);
684
685   return true;
686 }
687
688
689 /**
690  * Built-in command: multiply a property value.
691  *
692  * property: the name of the property to multiply.
693  * factor: the amount by which to multiply.
694  * min: the minimum allowed value (default: no minimum).
695  * max: the maximum allowed value (default: no maximum).
696  * mask: 'integer' to apply only to the left of the decimal point, 
697  *       'decimal' to apply only to the right of the decimal point,
698  *       or 'all' to apply to the whole number (the default).
699  * wrap: true if the value should be wrapped when it passes min or max;
700  *       both min and max must be present for this to work (default:
701  *       false).
702  */
703 static bool
704 do_property_multiply (const SGPropertyNode * arg)
705 {
706   SGPropertyNode * prop = get_prop(arg);
707   double factor = arg->getDoubleValue("factor", 1);
708
709   double unmodifiable, modifiable;
710   split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
711               &unmodifiable, &modifiable);
712   modifiable *= factor;
713   limit_value(&modifiable, arg);
714
715   prop->setDoubleValue(unmodifiable + modifiable);
716
717   return true;
718 }
719
720
721 /**
722  * Built-in command: swap two property values.
723  *
724  * property[0]: the name of the first property.
725  * property[1]: the name of the second property.
726  */
727 static bool
728 do_property_swap (const SGPropertyNode * arg)
729 {
730   SGPropertyNode * prop1 = get_prop(arg);
731   SGPropertyNode * prop2 = get_prop2(arg);
732
733                                 // FIXME: inefficient
734   const string & tmp = prop1->getStringValue();
735   return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
736           prop2->setUnspecifiedValue(tmp.c_str()));
737 }
738
739
740 /**
741  * Built-in command: Set a property to an axis or other moving input.
742  *
743  * property: the name of the property to set.
744  * setting: the current input setting, usually between -1.0 and 1.0.
745  * offset: the offset to shift by, before applying the factor.
746  * factor: the factor to multiply by (use negative to reverse).
747  */
748 static bool
749 do_property_scale (const SGPropertyNode * arg)
750 {
751   SGPropertyNode * prop = get_prop(arg);
752   double setting = arg->getDoubleValue("setting");
753   double offset = arg->getDoubleValue("offset", 0.0);
754   double factor = arg->getDoubleValue("factor", 1.0);
755   bool squared = arg->getBoolValue("squared", false);
756   int power = arg->getIntValue("power", (squared ? 2 : 1));
757
758   int sign = (setting < 0 ? -1 : 1);
759
760   switch (power) {
761   case 1:
762       break;
763   case 2:
764       setting = setting * setting * sign;
765       break;
766   case 3:
767       setting = setting * setting * setting;
768       break;
769   case 4:
770       setting = setting * setting * setting * setting * sign;
771       break;
772   default:
773       setting =  pow(setting, power);
774       if ((power % 2) == 0)
775           setting *= sign;
776       break;
777   }
778
779   return prop->setDoubleValue((setting + offset) * factor);
780 }
781
782
783 /**
784  * Built-in command: cycle a property through a set of values.
785  *
786  * If the current value isn't in the list, the cycle will
787  * (re)start from the beginning.
788  *
789  * property: the name of the property to cycle.
790  * value[*]: the list of values to cycle through.
791  */
792 static bool
793 do_property_cycle (const SGPropertyNode * arg)
794 {
795     SGPropertyNode * prop = get_prop(arg);
796     vector<SGPropertyNode_ptr> values = arg->getChildren("value");
797     int selection = -1;
798     int nSelections = values.size();
799
800     if (nSelections < 1) {
801         SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
802         return false;
803     }
804
805                                 // Try to find the current selection
806     for (int i = 0; i < nSelections; i++) {
807         if (compare_values(prop, values[i])) {
808             selection = i + 1;
809             break;
810         }
811     }
812
813                                 // Default or wrap to the first selection
814     if (selection < 0 || selection >= nSelections)
815         selection = 0;
816
817     prop->setUnspecifiedValue(values[selection]->getStringValue());
818     return true;
819 }
820
821
822 /**
823  * Built-in command: randomize a numeric property value.
824  *
825  * property: the name of the property value to randomize.
826  * min: the minimum allowed value.
827  * max: the maximum allowed value.
828  */
829 static bool
830 do_property_randomize (const SGPropertyNode * arg)
831 {
832     SGPropertyNode * prop = get_prop(arg);
833     double min = arg->getDoubleValue("min", DBL_MIN);
834     double max = arg->getDoubleValue("max", DBL_MAX);
835     prop->setDoubleValue(sg_random() * (max - min) + min);
836     return true;
837 }
838
839
840 /**
841  * Built-in command: Show an XML-configured dialog.
842  *
843  * dialog-name: the name of the GUI dialog to display.
844  */
845 static bool
846 do_dialog_show (const SGPropertyNode * arg)
847 {
848     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
849     gui->showDialog(arg->getStringValue("dialog-name"));
850     return true;
851 }
852
853
854 /**
855  * Built-in Command: Hide the active XML-configured dialog.
856  */
857 static bool
858 do_dialog_close (const SGPropertyNode * arg)
859 {
860     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
861     return gui->closeActiveDialog();
862 }
863
864
865 /**
866  * Update a value in the active XML-configured dialog.
867  *
868  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
869  */
870 static bool
871 do_dialog_update (const SGPropertyNode * arg)
872 {
873     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
874     FGDialog * dialog = gui->getActiveDialog();
875     if (dialog != 0) {
876         if (arg->hasValue("object-name")) {
877             dialog->updateValue(arg->getStringValue("object-name"));
878         } else {
879             dialog->updateValues();
880         }
881         return true;
882     } else {
883         return false;
884     }
885 }
886
887
888 /**
889  * Apply a value in the active XML-configured dialog.
890  *
891  * object-name: The name of the GUI object(s) (all GUI objects if omitted).
892  */
893 static bool
894 do_dialog_apply (const SGPropertyNode * arg)
895 {
896     NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
897     FGDialog * dialog = gui->getActiveDialog();
898     if (dialog != 0) {
899         if (arg->hasValue("object-name")) {
900             const char * name = arg->getStringValue("object-name");
901             dialog->applyValue(name);
902             dialog->updateValue(name);
903         } else {
904             dialog->applyValues();
905             dialog->updateValues();
906         }
907         return true;
908     } else {
909         return false;
910     }
911 }
912
913
914 /**
915  * Built-in command: commit presets (read from in /sim/presets/)
916  */
917 static bool
918 do_presets_commit (const SGPropertyNode * arg)
919 {
920     // unbind the current fdm state so property changes
921     // don't get lost when we subsequently delete this fdm
922     // and create a new one.
923     cur_fdm_state->unbind();
924         
925     // set position from presets
926     fgInitPosition();
927
928     // BusyCursor(0);
929     fgReInitSubsystems();
930
931     globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
932
933 #if 0
934     if ( ! fgGetBool("/sim/presets/onground") ) {
935         fgSetBool( "/sim/freeze/master", true );
936         fgSetBool( "/sim/freeze/clock", true );
937     }
938 #endif
939
940     return true;
941 }
942
943 /**
944  * Built-in command: set log level (0 ... 7)
945  */
946 static bool
947 do_log_level (const SGPropertyNode * arg)
948 {
949    sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
950
951    return true;
952 }
953
954 /**
955  * Built-in command: replay the FDR buffer
956  */
957 static bool
958 do_replay (const SGPropertyNode * arg)
959 {
960     // freeze the master fdm
961     fgSetBool( "/sim/freeze/replay", true );
962
963     FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
964
965     fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
966     fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
967     double duration = fgGetDouble( "/sim/replay/duration" );
968     if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
969         fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
970     } else {
971         fgSetDouble( "/sim/replay/time", r->get_start_time() );
972     }
973
974     cout << "start = " << r->get_start_time()
975          << "  end = " << r->get_end_time() << endl;
976
977     return true;
978 }
979
980
981
982 static bool
983 do_decrease_visibility (const SGPropertyNode * arg)
984 {
985     double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
986     fgSetDouble("/environment/visibility-m", new_value);
987     fgDefaultWeatherValue("visibility-m", new_value);
988     globals->get_subsystem("environment")->reinit();
989
990     return true;
991 }
992  
993 static bool
994 do_increase_visibility (const SGPropertyNode * arg)
995 {
996     double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
997     fgSetDouble("/environment/visibility-m", new_value);
998     fgDefaultWeatherValue("visibility-m", new_value);
999     globals->get_subsystem("environment")->reinit();
1000
1001     return true;
1002 }
1003
1004
1005 ////////////////////////////////////////////////////////////////////////
1006 // Command setup.
1007 ////////////////////////////////////////////////////////////////////////
1008
1009
1010 /**
1011  * Table of built-in commands.
1012  *
1013  * New commands do not have to be added here; any module in the application
1014  * can add a new command using globals->get_commands()->addCommand(...).
1015  */
1016 static struct {
1017   const char * name;
1018   SGCommandMgr::command_t command;
1019 } built_ins [] = {
1020     { "null", do_null },
1021 #if defined(HAVE_PLIB_PSL)
1022     { "script", do_script },
1023 #endif // HAVE_PLIB_PSL
1024     { "exit", do_exit },
1025     { "reinit", do_reinit },
1026     { "suspend", do_reinit },
1027     { "resume", do_reinit },
1028     { "load", do_load },
1029     { "save", do_save },
1030     { "panel-load", do_panel_load },
1031     { "panel-mouse-click", do_panel_mouse_click },
1032     { "preferences-load", do_preferences_load },
1033     { "view-cycle", do_view_cycle },
1034     { "screen-capture", do_screen_capture },
1035     { "tile-cache-reload", do_tile_cache_reload },
1036     { "set-outside-air-temp-degc", do_set_oat_degc },
1037     { "timeofday", do_timeofday },
1038     { "property-toggle", do_property_toggle },
1039     { "property-assign", do_property_assign },
1040     { "property-adjust", do_property_adjust },
1041     { "property-multiply", do_property_multiply },
1042     { "property-swap", do_property_swap },
1043     { "property-scale", do_property_scale },
1044     { "property-cycle", do_property_cycle },
1045     { "property-randomize", do_property_randomize },
1046     { "dialog-show", do_dialog_show },
1047     { "dialog-close", do_dialog_close },
1048     { "dialog-show", do_dialog_show },
1049     { "dialog-update", do_dialog_update },
1050     { "dialog-apply", do_dialog_apply },
1051     { "presets-commit", do_presets_commit },
1052     { "log-level", do_log_level },
1053     { "replay", do_replay },
1054     { "decrease-visibility", do_decrease_visibility },
1055     { "increase-visibility", do_increase_visibility },
1056     { 0, 0 }                    // zero-terminated
1057 };
1058
1059
1060 /**
1061  * Initialize the default built-in commands.
1062  *
1063  * Other commands may be added by other parts of the application.
1064  */
1065 void
1066 fgInitCommands ()
1067 {
1068   SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1069   for (int i = 0; built_ins[i].name != 0; i++) {
1070     SG_LOG(SG_GENERAL, SG_INFO, "  " << built_ins[i].name);
1071     globals->get_commands()->addCommand(built_ins[i].name,
1072                                         built_ins[i].command);
1073   }
1074
1075   typedef bool (*dummy)();
1076   fgTie( "/command/view/next", dummy(0), do_view_next );
1077   fgTie( "/command/view/prev", dummy(0), do_view_prev );
1078 }
1079
1080 // end of fg_commands.cxx