1 // fg_commands.cxx - internal FGFS commands.
7 #include <string.h> // strcmp()
9 #include <simgear/compiler.h>
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/structure/event_mgr.hxx>
23 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <Cockpit/panel.hxx>
26 #include <Cockpit/panel_io.hxx>
27 #include <Cockpit/hud.hxx>
28 #include <Environment/environment.hxx>
29 #include <FDM/flight.hxx>
31 #include <GUI/new_gui.hxx>
32 #include <GUI/dialog.hxx>
33 #include <Aircraft/replay.hxx>
34 #include <Scenery/tilemgr.hxx>
35 #include <Scenery/scenery.hxx>
36 #include <Scripting/NasalSys.hxx>
37 #include <Sound/sample_queue.hxx>
38 #include <Time/sunsolver.hxx>
39 #include <Time/tmp.hxx>
41 #include "fg_init.hxx"
44 #include "fg_commands.hxx"
45 #include "fg_props.hxx"
46 #include "globals.hxx"
49 #include "viewmgr.hxx"
51 #include <Main/viewer.hxx>
59 ////////////////////////////////////////////////////////////////////////
60 // Static helper functions.
61 ////////////////////////////////////////////////////////////////////////
64 static inline SGPropertyNode *
65 get_prop (const SGPropertyNode * arg)
67 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
70 static inline SGPropertyNode *
71 get_prop2 (const SGPropertyNode * arg)
73 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
78 * Get a double value and split it as required.
81 split_value (double full_value, const char * mask,
82 double * unmodifiable, double * modifiable)
84 if (!strcmp("integer", mask)) {
85 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
86 *unmodifiable = full_value - *modifiable;
87 } else if (!strcmp("decimal", mask)) {
88 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
89 *modifiable = full_value - *unmodifiable;
91 if (strcmp("all", mask))
92 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
93 << " assuming 'all'");
95 *modifiable = full_value;
101 * Clamp or wrap a value as specified.
104 limit_value (double * value, const SGPropertyNode * arg)
106 const SGPropertyNode * min_node = arg->getChild("min");
107 const SGPropertyNode * max_node = arg->getChild("max");
109 bool wrap = arg->getBoolValue("wrap");
111 if (min_node == 0 || max_node == 0)
114 if (wrap) { // wrap such that min <= x < max
115 double min_val = min_node->getDoubleValue();
116 double max_val = max_node->getDoubleValue();
117 double resolution = arg->getDoubleValue("resolution");
118 if (resolution > 0.0) {
119 // snap to (min + N*resolution), taking special care to handle imprecision
120 int n = (int)floor((*value - min_val) / resolution + 0.5);
121 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
122 SG_NORMALIZE_RANGE(n, 0, steps);
123 *value = min_val + resolution * n;
125 // plain circular wrapping
126 SG_NORMALIZE_RANGE(*value, min_val, max_val);
128 } else { // clamp such that min <= x <= max
129 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
130 *value = min_node->getDoubleValue();
131 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
132 *value = max_node->getDoubleValue();
137 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
139 switch (value1->getType()) {
140 case simgear::props::BOOL:
141 return (value1->getBoolValue() == value2->getBoolValue());
142 case simgear::props::INT:
143 return (value1->getIntValue() == value2->getIntValue());
144 case simgear::props::LONG:
145 return (value1->getLongValue() == value2->getLongValue());
146 case simgear::props::FLOAT:
147 return (value1->getFloatValue() == value2->getFloatValue());
148 case simgear::props::DOUBLE:
149 return (value1->getDoubleValue() == value2->getDoubleValue());
151 return !strcmp(value1->getStringValue(), value2->getStringValue());
157 ////////////////////////////////////////////////////////////////////////
158 // Command implementations.
159 ////////////////////////////////////////////////////////////////////////
163 * Built-in command: do nothing.
166 do_null (const SGPropertyNode * arg)
172 * Built-in command: run a Nasal script.
175 do_nasal (const SGPropertyNode * arg)
177 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
181 * Built-in command: exit FlightGear.
183 * status: the exit status to return to the operating system (defaults to 0)
186 do_exit (const SGPropertyNode * arg)
188 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
189 fgSetBool("/sim/signals/exit", true);
191 if (fgGetBool("/sim/startup/save-on-exit")) {
193 char* envp = ::getenv( "APPDATA" );
194 if ( envp != NULL ) {
195 SGPath config( envp );
196 config.append( "flightgear.org" );
198 if ( homedir != NULL ) {
199 SGPath config( homedir );
200 config.append( ".fgfs" );
202 config.append( "autosave.xml" );
203 config.create_dir( 0700 );
204 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << config.str());
206 writeProperties(config.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
207 } catch (const sg_exception &e) {
208 guiErrorMessage("Error writing autosave.xml: ", e);
211 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
214 fgExit(arg->getIntValue("status", 0));
220 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
223 do_reset (const SGPropertyNode * arg)
231 * Built-in command: reinitialize one or more subsystems.
233 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
234 * none is specified, reinitialize all of them.
237 do_reinit (const SGPropertyNode * arg)
241 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
242 if (subsystems.size() == 0) {
243 globals->get_subsystem_mgr()->reinit();
245 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
246 const char * name = subsystems[i]->getStringValue();
247 SGSubsystem * subsystem = globals->get_subsystem(name);
248 if (subsystem == 0) {
250 SG_LOG( SG_GENERAL, SG_ALERT,
251 "Subsystem " << name << "not found" );
258 globals->get_event_mgr()->reinit();
265 // these routines look useful ??? but are never used in the code ???
269 * Built-in command: suspend one or more subsystems.
271 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
274 do_suspend (const SGPropertyNode * arg)
278 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
279 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
280 const char * name = subsystems[i]->getStringValue();
281 SGSubsystem * subsystem = globals->get_subsystem(name);
282 if (subsystem == 0) {
284 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
286 subsystem->suspend();
293 * Built-in command: suspend one or more subsystems.
295 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
298 do_resume (const SGPropertyNode * arg)
302 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
303 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
304 const char * name = subsystems[i]->getStringValue();
305 SGSubsystem * subsystem = globals->get_subsystem(name);
306 if (subsystem == 0) {
308 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
320 * Built-in command: load flight.
322 * file (optional): the name of the file to load (relative to current
323 * directory). Defaults to "fgfs.sav"
326 do_load (const SGPropertyNode * arg)
328 string file = arg->getStringValue("file", "fgfs.sav");
329 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
332 if (!fgValidatePath(file.c_str(), false)) {
333 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
334 "(unauthorized access)");
338 ifstream input(file.c_str());
339 if (input.good() && fgLoadFlight(input)) {
341 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
344 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
351 * Built-in command: save flight.
353 * file (optional): the name of the file to save (relative to the
354 * current directory). Defaults to "fgfs.sav".
357 do_save (const SGPropertyNode * arg)
359 string file = arg->getStringValue("file", "fgfs.sav");
360 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
363 if (!fgValidatePath(file.c_str(), false)) {
364 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
365 "(unauthorized access)");
369 bool write_all = arg->getBoolValue("write-all", false);
370 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
371 ofstream output(file.c_str());
372 if (output.good() && fgSaveFlight(output, write_all)) {
374 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
377 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
384 * Built-in command: (re)load the panel.
386 * path (optional): the file name to load the panel from
387 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
388 * and if that's unspecified, to "Panels/Default/default.xml".
391 do_panel_load (const SGPropertyNode * arg)
394 arg->getStringValue("path",
395 fgGetString("/sim/panel/path",
396 "Panels/Default/default.xml"));
397 FGPanel * new_panel = fgReadPanel(panel_path);
398 if (new_panel == 0) {
399 SG_LOG(SG_INPUT, SG_ALERT,
400 "Error reading new panel from " << panel_path);
403 SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
404 globals->get_current_panel()->unbind();
405 delete globals->get_current_panel();
406 globals->set_current_panel( new_panel );
407 globals->get_current_panel()->bind();
413 * Built-in command: pass a mouse click to the panel.
415 * button: the mouse button number, zero-based.
416 * is-down: true if the button is down, false if it is up.
417 * x-pos: the x position of the mouse click.
418 * y-pos: the y position of the mouse click.
421 do_panel_mouse_click (const SGPropertyNode * arg)
423 if (globals->get_current_panel() != 0)
424 return globals->get_current_panel()
425 ->doMouseAction(arg->getIntValue("button"),
426 arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
427 arg->getIntValue("x-pos"),
428 arg->getIntValue("y-pos"));
435 * Built-in command: (re)load preferences.
437 * path (optional): the file name to load the panel from (relative
438 * to FG_ROOT). Defaults to "preferences.xml".
441 do_preferences_load (const SGPropertyNode * arg)
444 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
445 globals->get_props());
446 } catch (const sg_exception &e) {
447 guiErrorMessage("Error reading global preferences: ", e);
450 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
458 if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
459 globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
460 if ( globals->get_viewmgr()->get_current() == 1 ) {
461 globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
469 globals->get_current_view()->setHeadingOffset_deg(0.0);
470 globals->get_viewmgr()->next_view();
471 fix_hud_visibility();
477 globals->get_current_view()->setHeadingOffset_deg(0.0);
478 globals->get_viewmgr()->prev_view();
479 fix_hud_visibility();
483 * Built-in command: cycle view.
486 do_view_cycle (const SGPropertyNode * arg)
488 globals->get_current_view()->setHeadingOffset_deg(0.0);
489 globals->get_viewmgr()->next_view();
490 fix_hud_visibility();
495 * Built-in command: capture screen.
498 do_screen_capture (const SGPropertyNode * arg)
500 return fgDumpSnapShot();
504 do_reload_shaders (const SGPropertyNode*)
506 simgear::reload_shaders();
511 do_dump_scene_graph (const SGPropertyNode*)
518 do_dump_terrain_branch (const SGPropertyNode*)
520 fgDumpTerrainBranch();
522 double lon_deg = fgGetDouble("/position/longitude-deg");
523 double lat_deg = fgGetDouble("/position/latitude-deg");
524 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
525 SGVec3d zero = SGVec3d::fromGeod(geodPos);
527 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
528 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
529 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
535 * Built-in command: hires capture screen.
538 do_hires_screen_capture (const SGPropertyNode * arg)
546 * Reload the tile cache.
549 do_tile_cache_reload (const SGPropertyNode * arg)
551 static const SGPropertyNode *master_freeze
552 = fgGetNode("/sim/freeze/master");
553 bool freeze = master_freeze->getBoolValue();
554 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
556 fgSetBool("/sim/freeze/master", true);
558 if ( globals->get_tile_mgr()->init() ) {
559 // Load the local scenery data
560 double visibility_meters = fgGetDouble("/environment/visibility-m");
561 globals->get_tile_mgr()->update( visibility_meters );
563 SG_LOG( SG_GENERAL, SG_ALERT,
564 "Error in Tile Manager initialization!" );
568 fgSetBool("/sim/freeze/master", false);
575 * Set the sea level outside air temperature and assigning that to all
576 * boundary and aloft environment layers.
579 do_set_sea_level_degc ( double temp_sea_level_degc)
581 SGPropertyNode *node, *child;
584 node = fgGetNode( "/environment/config/boundary" );
585 if ( node != NULL ) {
587 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
588 child->setDoubleValue( "temperature-sea-level-degc",
589 temp_sea_level_degc );
595 node = fgGetNode( "/environment/config/aloft" );
596 if ( node != NULL ) {
598 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
599 child->setDoubleValue( "temperature-sea-level-degc",
600 temp_sea_level_degc );
609 do_set_sea_level_degc (const SGPropertyNode * arg)
611 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
616 * Set the outside air temperature at the "current" altitude by first
617 * calculating the corresponding sea level temp, and assigning that to
618 * all boundary and aloft environment layers.
621 do_set_oat_degc (const SGPropertyNode * arg)
623 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
624 // check for an altitude specified in the arguments, otherwise use
625 // current aircraft altitude.
626 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
627 if ( altitude_ft == NULL ) {
628 altitude_ft = fgGetNode("/position/altitude-ft");
631 FGEnvironment dummy; // instantiate a dummy so we can leech a method
632 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
633 dummy.set_temperature_degc( oat_degc );
634 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
638 * Set the sea level outside air dewpoint and assigning that to all
639 * boundary and aloft environment layers.
642 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
645 SGPropertyNode *node, *child;
648 node = fgGetNode( "/environment/config/boundary" );
649 if ( node != NULL ) {
651 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
652 child->setDoubleValue( "dewpoint-sea-level-degc",
653 dewpoint_sea_level_degc );
659 node = fgGetNode( "/environment/config/aloft" );
660 if ( node != NULL ) {
662 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
663 child->setDoubleValue( "dewpoint-sea-level-degc",
664 dewpoint_sea_level_degc );
673 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
675 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
679 * Set the outside air dewpoint at the "current" altitude by first
680 * calculating the corresponding sea level dewpoint, and assigning
681 * that to all boundary and aloft environment layers.
684 do_set_dewpoint_degc (const SGPropertyNode * arg)
686 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
688 // check for an altitude specified in the arguments, otherwise use
689 // current aircraft altitude.
690 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
691 if ( altitude_ft == NULL ) {
692 altitude_ft = fgGetNode("/position/altitude-ft");
695 FGEnvironment dummy; // instantiate a dummy so we can leech a method
696 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
697 dummy.set_dewpoint_degc( dewpoint_degc );
698 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
702 * Update the lighting manually.
705 do_timeofday (const SGPropertyNode * arg)
707 const string &offset_type = arg->getStringValue("timeofday", "noon");
709 static const SGPropertyNode *longitude
710 = fgGetNode("/position/longitude-deg");
711 static const SGPropertyNode *latitude
712 = fgGetNode("/position/latitude-deg");
713 static const SGPropertyNode *cur_time_override
714 = fgGetNode("/sim/time/cur-time-override", true);
716 int orig_warp = globals->get_warp();
717 SGTime *t = globals->get_time_params();
718 time_t cur_time = t->get_cur_time();
719 // cout << "cur_time = " << cur_time << endl;
720 // cout << "orig_warp = " << orig_warp << endl;
723 if ( offset_type == "real" ) {
725 } else if ( offset_type == "dawn" ) {
726 warp = fgTimeSecondsUntilSunAngle( cur_time,
727 longitude->getDoubleValue()
728 * SGD_DEGREES_TO_RADIANS,
729 latitude->getDoubleValue()
730 * SGD_DEGREES_TO_RADIANS,
732 } else if ( offset_type == "morning" ) {
733 warp = fgTimeSecondsUntilSunAngle( cur_time,
734 longitude->getDoubleValue()
735 * SGD_DEGREES_TO_RADIANS,
736 latitude->getDoubleValue()
737 * SGD_DEGREES_TO_RADIANS,
739 } else if ( offset_type == "noon" ) {
740 warp = fgTimeSecondsUntilSunAngle( cur_time,
741 longitude->getDoubleValue()
742 * SGD_DEGREES_TO_RADIANS,
743 latitude->getDoubleValue()
744 * SGD_DEGREES_TO_RADIANS,
746 } else if ( offset_type == "afternoon" ) {
747 warp = fgTimeSecondsUntilSunAngle( cur_time,
748 longitude->getDoubleValue()
749 * SGD_DEGREES_TO_RADIANS,
750 latitude->getDoubleValue()
751 * SGD_DEGREES_TO_RADIANS,
753 } else if ( offset_type == "dusk" ) {
754 warp = fgTimeSecondsUntilSunAngle( cur_time,
755 longitude->getDoubleValue()
756 * SGD_DEGREES_TO_RADIANS,
757 latitude->getDoubleValue()
758 * SGD_DEGREES_TO_RADIANS,
760 } else if ( offset_type == "evening" ) {
761 warp = fgTimeSecondsUntilSunAngle( cur_time,
762 longitude->getDoubleValue()
763 * SGD_DEGREES_TO_RADIANS,
764 latitude->getDoubleValue()
765 * SGD_DEGREES_TO_RADIANS,
767 } else if ( offset_type == "midnight" ) {
768 warp = fgTimeSecondsUntilSunAngle( cur_time,
769 longitude->getDoubleValue()
770 * SGD_DEGREES_TO_RADIANS,
771 latitude->getDoubleValue()
772 * SGD_DEGREES_TO_RADIANS,
775 // cout << "warp = " << warp << endl;
776 globals->set_warp( orig_warp + warp );
778 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
779 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
780 cur_time_override->getLongValue(),
781 globals->get_warp() );
788 * Built-in command: toggle a bool property value.
790 * property: The name of the property to toggle.
793 do_property_toggle (const SGPropertyNode * arg)
795 SGPropertyNode * prop = get_prop(arg);
796 return prop->setBoolValue(!prop->getBoolValue());
801 * Built-in command: assign a value to a property.
803 * property: the name of the property to assign.
804 * value: the value to assign; or
805 * property[1]: the property to copy from.
808 do_property_assign (const SGPropertyNode * arg)
810 SGPropertyNode * prop = get_prop(arg);
811 const SGPropertyNode * prop2 = get_prop2(arg);
812 const SGPropertyNode * value = arg->getNode("value");
815 return prop->setUnspecifiedValue(value->getStringValue());
817 return prop->setUnspecifiedValue(prop2->getStringValue());
824 * Built-in command: increment or decrement a property value.
826 * If the 'step' argument is present, it will be used; otherwise,
827 * the command uses 'offset' and 'factor', usually from the mouse.
829 * property: the name of the property to increment or decrement.
830 * step: the amount of the increment or decrement (default: 0).
831 * offset: offset from the current setting (used for the mouse; multiplied
833 * factor: scaling amount for the offset (defaults to 1).
834 * min: the minimum allowed value (default: no minimum).
835 * max: the maximum allowed value (default: no maximum).
836 * mask: 'integer' to apply only to the left of the decimal point,
837 * 'decimal' to apply only to the right of the decimal point,
838 * or 'all' to apply to the whole number (the default).
839 * wrap: true if the value should be wrapped when it passes min or max;
840 * both min and max must be present for this to work (default:
844 do_property_adjust (const SGPropertyNode * arg)
846 SGPropertyNode * prop = get_prop(arg);
849 if (arg->hasValue("step"))
850 amount = arg->getDoubleValue("step");
852 amount = (arg->getDoubleValue("factor", 1)
853 * arg->getDoubleValue("offset"));
855 double unmodifiable, modifiable;
856 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
857 &unmodifiable, &modifiable);
858 modifiable += amount;
859 limit_value(&modifiable, arg);
861 prop->setDoubleValue(unmodifiable + modifiable);
868 * Built-in command: multiply a property value.
870 * property: the name of the property to multiply.
871 * factor: the amount by which to multiply.
872 * min: the minimum allowed value (default: no minimum).
873 * max: the maximum allowed value (default: no maximum).
874 * mask: 'integer' to apply only to the left of the decimal point,
875 * 'decimal' to apply only to the right of the decimal point,
876 * or 'all' to apply to the whole number (the default).
877 * wrap: true if the value should be wrapped when it passes min or max;
878 * both min and max must be present for this to work (default:
882 do_property_multiply (const SGPropertyNode * arg)
884 SGPropertyNode * prop = get_prop(arg);
885 double factor = arg->getDoubleValue("factor", 1);
887 double unmodifiable, modifiable;
888 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
889 &unmodifiable, &modifiable);
890 modifiable *= factor;
891 limit_value(&modifiable, arg);
893 prop->setDoubleValue(unmodifiable + modifiable);
900 * Built-in command: swap two property values.
902 * property[0]: the name of the first property.
903 * property[1]: the name of the second property.
906 do_property_swap (const SGPropertyNode * arg)
908 SGPropertyNode * prop1 = get_prop(arg);
909 SGPropertyNode * prop2 = get_prop2(arg);
911 // FIXME: inefficient
912 const string & tmp = prop1->getStringValue();
913 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
914 prop2->setUnspecifiedValue(tmp.c_str()));
919 * Built-in command: Set a property to an axis or other moving input.
921 * property: the name of the property to set.
922 * setting: the current input setting, usually between -1.0 and 1.0.
923 * offset: the offset to shift by, before applying the factor.
924 * factor: the factor to multiply by (use negative to reverse).
927 do_property_scale (const SGPropertyNode * arg)
929 SGPropertyNode * prop = get_prop(arg);
930 double setting = arg->getDoubleValue("setting");
931 double offset = arg->getDoubleValue("offset", 0.0);
932 double factor = arg->getDoubleValue("factor", 1.0);
933 bool squared = arg->getBoolValue("squared", false);
934 int power = arg->getIntValue("power", (squared ? 2 : 1));
936 int sign = (setting < 0 ? -1 : 1);
942 setting = setting * setting * sign;
945 setting = setting * setting * setting;
948 setting = setting * setting * setting * setting * sign;
951 setting = pow(setting, power);
952 if ((power % 2) == 0)
957 return prop->setDoubleValue((setting + offset) * factor);
962 * Built-in command: cycle a property through a set of values.
964 * If the current value isn't in the list, the cycle will
965 * (re)start from the beginning.
967 * property: the name of the property to cycle.
968 * value[*]: the list of values to cycle through.
971 do_property_cycle (const SGPropertyNode * arg)
973 SGPropertyNode * prop = get_prop(arg);
974 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
976 int nSelections = values.size();
978 if (nSelections < 1) {
979 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
983 // Try to find the current selection
984 for (int i = 0; i < nSelections; i++) {
985 if (compare_values(prop, values[i])) {
991 // Default or wrap to the first selection
992 if (selection < 0 || selection >= nSelections)
995 prop->setUnspecifiedValue(values[selection]->getStringValue());
1001 * Built-in command: randomize a numeric property value.
1003 * property: the name of the property value to randomize.
1004 * min: the minimum allowed value.
1005 * max: the maximum allowed value.
1008 do_property_randomize (const SGPropertyNode * arg)
1010 SGPropertyNode * prop = get_prop(arg);
1011 double min = arg->getDoubleValue("min", DBL_MIN);
1012 double max = arg->getDoubleValue("max", DBL_MAX);
1013 prop->setDoubleValue(sg_random() * (max - min) + min);
1019 * Built-in command: reinit the data logging system based on the
1020 * current contents of the /logger tree.
1023 do_data_logging_commit (const SGPropertyNode * arg)
1025 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1031 * Built-in command: Add a dialog to the GUI system. Does *not*
1032 * display the dialog. The property node should have the same format
1033 * as a dialog XML configuration. It must include:
1035 * name: the name of the GUI dialog for future reference.
1038 do_dialog_new (const SGPropertyNode * arg)
1040 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1042 // Note the casting away of const: this is *real*. Doing a
1043 // "dialog-apply" command later on will mutate this property node.
1044 // I'm not convinced that this isn't the Right Thing though; it
1045 // allows client to create a node, pass it to dialog-new, and get
1046 // the values back from the dialog by reading the same node.
1047 // Perhaps command arguments are not as "const" as they would
1049 gui->newDialog((SGPropertyNode*)arg);
1054 * Built-in command: Show an XML-configured dialog.
1056 * dialog-name: the name of the GUI dialog to display.
1059 do_dialog_show (const SGPropertyNode * arg)
1061 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1062 gui->showDialog(arg->getStringValue("dialog-name"));
1068 * Built-in Command: Hide the active XML-configured dialog.
1071 do_dialog_close (const SGPropertyNode * arg)
1073 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1074 if(arg->hasValue("dialog-name"))
1075 return gui->closeDialog(arg->getStringValue("dialog-name"));
1076 return gui->closeActiveDialog();
1081 * Update a value in the active XML-configured dialog.
1083 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1086 do_dialog_update (const SGPropertyNode * arg)
1088 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1090 if (arg->hasValue("dialog-name"))
1091 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1093 dialog = gui->getActiveDialog();
1096 dialog->updateValues(arg->getStringValue("object-name"));
1105 * Apply a value in the active XML-configured dialog.
1107 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1110 do_dialog_apply (const SGPropertyNode * arg)
1112 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1114 if (arg->hasValue("dialog-name"))
1115 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1117 dialog = gui->getActiveDialog();
1120 dialog->applyValues(arg->getStringValue("object-name"));
1129 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1133 do_gui_redraw (const SGPropertyNode * arg)
1135 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1142 * Adds model to the scenery. The path to the added branch (/models/model[*])
1143 * is returned in property "property".
1146 do_add_model (const SGPropertyNode * arg)
1148 SGPropertyNode * model = fgGetNode("models", true);
1149 for (int i = 0;; i++) {
1152 if (!model->getChild("model", i, false)) {
1153 model = model->getChild("model", i, true);
1157 copyProperties(arg, model);
1158 if (model->hasValue("elevation-m"))
1159 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1160 * SG_METER_TO_FEET);
1161 model->getNode("load", true);
1162 model->removeChildren("load");
1163 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1169 * Set mouse cursor coordinates and cursor shape.
1172 do_set_cursor (const SGPropertyNode * arg)
1174 if (arg->hasValue("x") || arg->hasValue("y")) {
1175 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1176 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1177 int x = arg->getIntValue("x", mx->getIntValue());
1178 int y = arg->getIntValue("y", my->getIntValue());
1184 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1185 if (cursor->getType() != simgear::props::NONE)
1186 fgSetMouseCursor(cursor->getIntValue());
1188 cursor->setIntValue(fgGetMouseCursor());
1194 * Built-in command: play an audio message (i.e. a wav file) This is
1195 * fire and forget. Call this once per message and it will get dumped
1196 * into a queue. Messages are played sequentially so they do not
1200 do_play_audio_sample (const SGPropertyNode * arg)
1202 string path = arg->getStringValue("path");
1203 string file = arg->getStringValue("file");
1204 float volume = arg->getFloatValue("volume");
1205 // cout << "playing " << path << " / " << file << endl;
1207 static FGSampleQueue *queue = 0;
1209 SGSoundMgr *smgr = globals->get_soundmgr();
1210 queue = new FGSampleQueue(smgr, "chatter");
1211 queue->tie_to_listener();
1214 SGSoundSample *msg = new SGSoundSample(path.c_str(), file.c_str());
1215 msg->set_volume( volume );
1220 } catch (const sg_io_exception&) {
1221 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1222 "failed to load" << path << '/' << file);
1228 * Built-in command: commit presets (read from in /sim/presets/)
1231 do_presets_commit (const SGPropertyNode * arg)
1233 // unbind the current fdm state so property changes
1234 // don't get lost when we subsequently delete this fdm
1235 // and create a new one.
1236 cur_fdm_state->unbind();
1238 // set position from presets
1241 fgReInitSubsystems();
1243 globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
1246 if ( ! fgGetBool("/sim/presets/onground") ) {
1247 fgSetBool( "/sim/freeze/master", true );
1248 fgSetBool( "/sim/freeze/clock", true );
1256 * Built-in command: set log level (0 ... 7)
1259 do_log_level (const SGPropertyNode * arg)
1261 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1267 * Built-in command: replay the FDR buffer
1270 do_replay (const SGPropertyNode * arg)
1272 // freeze the master fdm
1273 fgSetInt( "/sim/freeze/replay-state", 1 );
1275 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
1277 fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
1278 fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
1279 double duration = fgGetDouble( "/sim/replay/duration" );
1280 if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
1281 fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
1283 fgSetDouble( "/sim/replay/time", r->get_start_time() );
1286 // cout << "start = " << r->get_start_time()
1287 // << " end = " << r->get_end_time() << endl;
1294 do_decrease_visibility (const SGPropertyNode * arg)
1296 double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
1297 fgSetDouble("/environment/visibility-m", new_value);
1298 fgDefaultWeatherValue("visibility-m", new_value);
1299 globals->get_subsystem("environment")->reinit();
1305 do_increase_visibility (const SGPropertyNode * arg)
1307 double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1308 fgSetDouble("/environment/visibility-m", new_value);
1309 fgDefaultWeatherValue("visibility-m", new_value);
1310 globals->get_subsystem("environment")->reinit();
1316 do_hud_init(const SGPropertyNode *)
1318 fgHUDInit(0); // minimal HUD
1323 do_hud_init2(const SGPropertyNode *)
1325 fgHUDInit2(0); // normal HUD
1331 * An fgcommand to allow loading of xml files via nasal,
1332 * the xml file's structure will be made available within
1333 * a property tree node defined under argument "targetnode",
1334 * or in the given argument tree under "data" otherwise.
1336 * @param filename a string to hold the complete path & filename of an XML file
1337 * @param targetnode a string pointing to a location within the property tree
1338 * where to store the parsed XML file. If <targetnode> is undefined, then the
1339 * file contents are stored under a node <data> in the argument tree.
1343 do_load_xml_to_proptree(const SGPropertyNode * arg)
1345 SGPath file(arg->getStringValue("filename"));
1346 if (file.str().empty())
1349 if (file.extension() != "xml")
1350 file.concat(".xml");
1352 if (!fgValidatePath(file.c_str(), false)) {
1353 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1354 "(unauthorized access)");
1358 SGPropertyNode *targetnode;
1359 if (arg->hasValue("targetnode"))
1360 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1362 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1365 readProperties(file.c_str(), targetnode, true);
1366 } catch (const sg_exception &e) {
1367 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1376 * An fgcommand to allow saving of xml files via nasal,
1377 * the file's structure will be determined based on what's
1378 * encountered in the passed (source) property tree node
1380 * @param filename a string to hold the complete path & filename of the (new)
1382 * @param sourcenode a string pointing to a location within the property tree
1383 * where to find the nodes that should be written recursively into an XML file
1384 * @param data if no sourcenode is given, then the file contents are taken from
1385 * the argument tree's "data" node.
1389 do_save_xml_from_proptree(const SGPropertyNode * arg)
1391 SGPath file(arg->getStringValue("filename"));
1392 if (file.str().empty())
1395 if (file.extension() != "xml")
1396 file.concat(".xml");
1398 if (!fgValidatePath(file.c_str(), true)) {
1399 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1400 "(unauthorized access)");
1404 SGPropertyNode *sourcenode;
1405 if (arg->hasValue("sourcenode"))
1406 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1407 else if (arg->getNode("data", false))
1408 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1413 writeProperties (file.c_str(), sourcenode, true);
1414 } catch (const sg_exception &e) {
1415 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1423 do_press_cockpit_button (const SGPropertyNode *arg)
1425 const char *prefix = arg->getStringValue("prefix");
1427 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1430 string prop = string(prefix) + "-button";
1433 if (arg->getBoolValue("latching"))
1434 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1438 fgSetDouble(prop.c_str(), value);
1439 fgSetBool(arg->getStringValue("discrete"), value > 0);
1445 do_release_cockpit_button (const SGPropertyNode *arg)
1447 const char *prefix = arg->getStringValue("prefix");
1449 if (arg->getBoolValue("guarded")) {
1450 string prop = string(prefix) + "-guard";
1451 if (fgGetDouble(prop.c_str()) < 1) {
1452 fgSetDouble(prop.c_str(), 1);
1457 if (! arg->getBoolValue("latching")) {
1458 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1459 fgSetBool(arg->getStringValue("discrete"), false);
1466 ////////////////////////////////////////////////////////////////////////
1468 ////////////////////////////////////////////////////////////////////////
1472 * Table of built-in commands.
1474 * New commands do not have to be added here; any module in the application
1475 * can add a new command using globals->get_commands()->addCommand(...).
1479 SGCommandMgr::command_t command;
1481 { "null", do_null },
1482 { "nasal", do_nasal },
1483 { "exit", do_exit },
1484 { "reset", do_reset },
1485 { "reinit", do_reinit },
1486 { "suspend", do_reinit },
1487 { "resume", do_reinit },
1488 { "load", do_load },
1489 { "save", do_save },
1490 { "panel-load", do_panel_load },
1491 { "panel-mouse-click", do_panel_mouse_click },
1492 { "preferences-load", do_preferences_load },
1493 { "view-cycle", do_view_cycle },
1494 { "screen-capture", do_screen_capture },
1495 { "hires-screen-capture", do_hires_screen_capture },
1496 { "tile-cache-reload", do_tile_cache_reload },
1497 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1498 { "set-outside-air-temp-degc", do_set_oat_degc },
1499 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1500 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1501 { "timeofday", do_timeofday },
1502 { "property-toggle", do_property_toggle },
1503 { "property-assign", do_property_assign },
1504 { "property-adjust", do_property_adjust },
1505 { "property-multiply", do_property_multiply },
1506 { "property-swap", do_property_swap },
1507 { "property-scale", do_property_scale },
1508 { "property-cycle", do_property_cycle },
1509 { "property-randomize", do_property_randomize },
1510 { "data-logging-commit", do_data_logging_commit },
1511 { "dialog-new", do_dialog_new },
1512 { "dialog-show", do_dialog_show },
1513 { "dialog-close", do_dialog_close },
1514 { "dialog-update", do_dialog_update },
1515 { "dialog-apply", do_dialog_apply },
1516 { "gui-redraw", do_gui_redraw },
1517 { "add-model", do_add_model },
1518 { "set-cursor", do_set_cursor },
1519 { "play-audio-sample", do_play_audio_sample },
1520 { "presets-commit", do_presets_commit },
1521 { "log-level", do_log_level },
1522 { "replay", do_replay },
1523 { "decrease-visibility", do_decrease_visibility },
1524 { "increase-visibility", do_increase_visibility },
1525 { "hud-init", do_hud_init },
1526 { "hud-init2", do_hud_init2 },
1527 { "loadxml", do_load_xml_to_proptree},
1528 { "savexml", do_save_xml_from_proptree },
1529 { "press-cockpit-button", do_press_cockpit_button },
1530 { "release-cockpit-button", do_release_cockpit_button },
1531 { "dump-scenegraph", do_dump_scene_graph },
1532 { "dump-terrainbranch", do_dump_terrain_branch },
1533 { "reload-shaders", do_reload_shaders },
1534 { 0, 0 } // zero-terminated
1539 * Initialize the default built-in commands.
1541 * Other commands may be added by other parts of the application.
1546 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1547 for (int i = 0; built_ins[i].name != 0; i++) {
1548 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1549 globals->get_commands()->addCommand(built_ins[i].name,
1550 built_ins[i].command);
1553 typedef bool (*dummy)();
1554 fgTie( "/command/view/next", dummy(0), do_view_next );
1555 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1558 // end of fg_commands.cxx