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/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/io/HTTPRequest.hxx>
28 #include <FDM/flight.hxx>
30 #include <GUI/new_gui.hxx>
31 #include <GUI/dialog.hxx>
32 #include <Aircraft/replay.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scripting/NasalSys.hxx>
35 #include <Sound/sample_queue.hxx>
36 #include <Airports/xmlloader.hxx>
37 #include <Network/HTTPClient.hxx>
38 #include <Viewer/viewmgr.hxx>
39 #include <Viewer/viewer.hxx>
40 #include <Environment/presets.hxx>
42 #include "fg_init.hxx"
45 #include "fg_commands.hxx"
46 #include "fg_props.hxx"
47 #include "globals.hxx"
51 #include "positioninit.hxx"
53 #include <boost/scoped_array.hpp>
55 #ifdef FG_HAVE_GPERFTOOLS
56 # include <google/profiler.h>
64 ////////////////////////////////////////////////////////////////////////
65 // Static helper functions.
66 ////////////////////////////////////////////////////////////////////////
69 static inline SGPropertyNode *
70 get_prop (const SGPropertyNode * arg)
72 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
75 static inline SGPropertyNode *
76 get_prop2 (const SGPropertyNode * arg)
78 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
83 * Get a double value and split it as required.
86 split_value (double full_value, const char * mask,
87 double * unmodifiable, double * modifiable)
89 if (!strcmp("integer", mask)) {
90 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
91 *unmodifiable = full_value - *modifiable;
92 } else if (!strcmp("decimal", mask)) {
93 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
94 *modifiable = full_value - *unmodifiable;
96 if (strcmp("all", mask))
97 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
98 << " assuming 'all'");
100 *modifiable = full_value;
106 * Clamp or wrap a value as specified.
109 limit_value (double * value, const SGPropertyNode * arg)
111 const SGPropertyNode * min_node = arg->getChild("min");
112 const SGPropertyNode * max_node = arg->getChild("max");
114 bool wrap = arg->getBoolValue("wrap");
116 if (min_node == 0 || max_node == 0)
119 if (wrap) { // wrap such that min <= x < max
120 double min_val = min_node->getDoubleValue();
121 double max_val = max_node->getDoubleValue();
122 double resolution = arg->getDoubleValue("resolution");
123 if (resolution > 0.0) {
124 // snap to (min + N*resolution), taking special care to handle imprecision
125 int n = (int)floor((*value - min_val) / resolution + 0.5);
126 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
127 SG_NORMALIZE_RANGE(n, 0, steps);
128 *value = min_val + resolution * n;
130 // plain circular wrapping
131 SG_NORMALIZE_RANGE(*value, min_val, max_val);
133 } else { // clamp such that min <= x <= max
134 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
135 *value = min_node->getDoubleValue();
136 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
137 *value = max_node->getDoubleValue();
142 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
144 switch (value1->getType()) {
145 case simgear::props::BOOL:
146 return (value1->getBoolValue() == value2->getBoolValue());
147 case simgear::props::INT:
148 return (value1->getIntValue() == value2->getIntValue());
149 case simgear::props::LONG:
150 return (value1->getLongValue() == value2->getLongValue());
151 case simgear::props::FLOAT:
152 return (value1->getFloatValue() == value2->getFloatValue());
153 case simgear::props::DOUBLE:
154 return (value1->getDoubleValue() == value2->getDoubleValue());
156 return !strcmp(value1->getStringValue(), value2->getStringValue());
162 ////////////////////////////////////////////////////////////////////////
163 // Command implementations.
164 ////////////////////////////////////////////////////////////////////////
168 * Built-in command: do nothing.
171 do_null (const SGPropertyNode * arg)
177 * Built-in command: run a Nasal script.
180 do_nasal (const SGPropertyNode * arg)
182 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
186 * Built-in command: exit FlightGear.
188 * status: the exit status to return to the operating system (defaults to 0)
191 do_exit (const SGPropertyNode * arg)
193 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
194 fgSetBool("/sim/signals/exit", true);
195 globals->saveUserSettings();
196 fgOSExit(arg->getIntValue("status", 0));
202 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
205 do_reset (const SGPropertyNode * arg)
207 fgReInitSubsystems();
212 * Built-in command: replay the FDR buffer
215 do_replay (const SGPropertyNode * arg)
217 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
222 * Built-in command: pause/unpause the sim
225 do_pause (const SGPropertyNode * arg)
227 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
228 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
234 fgSetBool("/sim/freeze/master",!paused);
235 fgSetBool("/sim/freeze/clock",!paused);
238 SGPropertyNode_ptr args(new SGPropertyNode);
239 args->setStringValue("id", "sim-pause");
241 args->setStringValue("label", "Simulation is paused");
242 globals->get_commands()->execute("show-message", args);
244 globals->get_commands()->execute("clear-message", args);
251 * Built-in command: load flight.
253 * file (optional): the name of the file to load (relative to current
254 * directory). Defaults to "fgfs.sav"
257 do_load (const SGPropertyNode * arg)
259 string file = arg->getStringValue("file", "fgfs.sav");
260 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
263 if (!fgValidatePath(file.c_str(), false)) {
264 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
265 "(unauthorized access)");
269 ifstream input(file.c_str());
270 if (input.good() && fgLoadFlight(input)) {
272 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
275 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
282 * Built-in command: save flight.
284 * file (optional): the name of the file to save (relative to the
285 * current directory). Defaults to "fgfs.sav".
288 do_save (const SGPropertyNode * arg)
290 string file = arg->getStringValue("file", "fgfs.sav");
291 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
294 if (!fgValidatePath(file.c_str(), false)) {
295 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
296 "(unauthorized access)");
300 bool write_all = arg->getBoolValue("write-all", false);
301 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
302 ofstream output(file.c_str());
303 if (output.good() && fgSaveFlight(output, write_all)) {
305 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
308 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
314 * Built-in command: save flight recorder tape.
318 do_save_tape (const SGPropertyNode * arg)
320 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
321 replay->saveTape(arg);
326 * Built-in command: load flight recorder tape.
330 do_load_tape (const SGPropertyNode * arg)
332 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
333 replay->loadTape(arg);
339 * Built-in command: (re)load the panel.
341 * path (optional): the file name to load the panel from
342 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
343 * and if that's unspecified, to "Panels/Default/default.xml".
346 do_panel_load (const SGPropertyNode * arg)
348 string panel_path = arg->getStringValue("path");
349 if (!panel_path.empty()) {
350 // write to the standard property, which will force a load
351 fgSetString("/sim/panel/path", panel_path.c_str());
358 * Built-in command: (re)load preferences.
360 * path (optional): the file name to load the panel from (relative
361 * to FG_ROOT). Defaults to "preferences.xml".
364 do_preferences_load (const SGPropertyNode * arg)
367 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
368 globals->get_props());
369 } catch (const sg_exception &e) {
370 guiErrorMessage("Error reading global preferences: ", e);
373 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
380 globals->get_current_view()->setHeadingOffset_deg(0.0);
381 globals->get_viewmgr()->next_view();
387 globals->get_current_view()->setHeadingOffset_deg(0.0);
388 globals->get_viewmgr()->prev_view();
392 * An fgcommand to toggle fullscreen mode.
396 do_toggle_fullscreen(const SGPropertyNode *arg)
403 * Built-in command: cycle view.
406 do_view_cycle (const SGPropertyNode * arg)
408 globals->get_current_view()->setHeadingOffset_deg(0.0);
409 globals->get_viewmgr()->next_view();
414 * Built-in command: capture screen.
417 do_screen_capture (const SGPropertyNode * arg)
419 return fgDumpSnapShot();
423 do_reload_shaders (const SGPropertyNode*)
425 simgear::reload_shaders();
430 do_dump_scene_graph (const SGPropertyNode*)
437 do_dump_terrain_branch (const SGPropertyNode*)
439 fgDumpTerrainBranch();
441 double lon_deg = fgGetDouble("/position/longitude-deg");
442 double lat_deg = fgGetDouble("/position/latitude-deg");
443 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
444 SGVec3d zero = SGVec3d::fromGeod(geodPos);
446 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
447 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
448 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
454 do_print_visible_scene_info(const SGPropertyNode*)
456 fgPrintVisibleSceneInfoCommand();
461 * Built-in command: hires capture screen.
464 do_hires_screen_capture (const SGPropertyNode * arg)
472 * Reload the tile cache.
475 do_tile_cache_reload (const SGPropertyNode * arg)
477 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
478 bool freeze = master_freeze->getBoolValue();
479 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
481 master_freeze->setBoolValue(true);
484 globals->get_subsystem("tile-manager")->reinit();
487 master_freeze->setBoolValue(false);
493 * Reload the materials definition
496 do_materials_reload (const SGPropertyNode * arg)
498 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
499 SGMaterialLib* new_matlib = new SGMaterialLib;
500 SGPath mpath( globals->get_fg_root() );
501 mpath.append( fgGetString("/sim/rendering/materials-file") );
502 bool loaded = new_matlib->load(globals->get_fg_root(),
504 globals->get_props());
507 SG_LOG( SG_GENERAL, SG_ALERT,
508 "Error loading materials file " << mpath.str() );
512 globals->set_matlib(new_matlib);
518 These do_set_(some-environment-parameters) are deprecated and no longer
519 useful/functional - Torsten Dreyer, January 2011
521 * Set the sea level outside air temperature and assigning that to all
522 * boundary and aloft environment layers.
525 do_set_sea_level_degc ( double temp_sea_level_degc)
527 SGPropertyNode *node, *child;
530 node = fgGetNode( "/environment/config/boundary" );
531 if ( node != NULL ) {
533 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
534 child->setDoubleValue( "temperature-sea-level-degc",
535 temp_sea_level_degc );
541 node = fgGetNode( "/environment/config/aloft" );
542 if ( node != NULL ) {
544 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
545 child->setDoubleValue( "temperature-sea-level-degc",
546 temp_sea_level_degc );
555 do_set_sea_level_degc (const SGPropertyNode * arg)
557 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
562 * Set the outside air temperature at the "current" altitude by first
563 * calculating the corresponding sea level temp, and assigning that to
564 * all boundary and aloft environment layers.
567 do_set_oat_degc (const SGPropertyNode * arg)
569 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
570 // check for an altitude specified in the arguments, otherwise use
571 // current aircraft altitude.
572 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
573 if ( altitude_ft == NULL ) {
574 altitude_ft = fgGetNode("/position/altitude-ft");
577 FGEnvironment dummy; // instantiate a dummy so we can leech a method
578 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
579 dummy.set_temperature_degc( oat_degc );
580 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
584 * Set the sea level outside air dewpoint and assigning that to all
585 * boundary and aloft environment layers.
588 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
591 SGPropertyNode *node, *child;
594 node = fgGetNode( "/environment/config/boundary" );
595 if ( node != NULL ) {
597 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
598 child->setDoubleValue( "dewpoint-sea-level-degc",
599 dewpoint_sea_level_degc );
605 node = fgGetNode( "/environment/config/aloft" );
606 if ( node != NULL ) {
608 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
609 child->setDoubleValue( "dewpoint-sea-level-degc",
610 dewpoint_sea_level_degc );
619 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
621 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
625 * Set the outside air dewpoint at the "current" altitude by first
626 * calculating the corresponding sea level dewpoint, and assigning
627 * that to all boundary and aloft environment layers.
630 do_set_dewpoint_degc (const SGPropertyNode * arg)
632 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
634 // check for an altitude specified in the arguments, otherwise use
635 // current aircraft altitude.
636 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
637 if ( altitude_ft == NULL ) {
638 altitude_ft = fgGetNode("/position/altitude-ft");
641 FGEnvironment dummy; // instantiate a dummy so we can leech a method
642 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
643 dummy.set_dewpoint_degc( dewpoint_degc );
644 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
649 * Built-in command: toggle a bool property value.
651 * property: The name of the property to toggle.
654 do_property_toggle (const SGPropertyNode * arg)
656 SGPropertyNode * prop = get_prop(arg);
657 return prop->setBoolValue(!prop->getBoolValue());
662 * Built-in command: assign a value to a property.
664 * property: the name of the property to assign.
665 * value: the value to assign; or
666 * property[1]: the property to copy from.
669 do_property_assign (const SGPropertyNode * arg)
671 SGPropertyNode * prop = get_prop(arg);
672 const SGPropertyNode * value = arg->getNode("value");
675 return prop->setUnspecifiedValue(value->getStringValue());
678 const SGPropertyNode * prop2 = get_prop2(arg);
680 return prop->setUnspecifiedValue(prop2->getStringValue());
688 * Built-in command: increment or decrement a property value.
690 * If the 'step' argument is present, it will be used; otherwise,
691 * the command uses 'offset' and 'factor', usually from the mouse.
693 * property: the name of the property to increment or decrement.
694 * step: the amount of the increment or decrement (default: 0).
695 * offset: offset from the current setting (used for the mouse; multiplied
697 * factor: scaling amount for the offset (defaults to 1).
698 * min: the minimum allowed value (default: no minimum).
699 * max: the maximum allowed value (default: no maximum).
700 * mask: 'integer' to apply only to the left of the decimal point,
701 * 'decimal' to apply only to the right of the decimal point,
702 * or 'all' to apply to the whole number (the default).
703 * wrap: true if the value should be wrapped when it passes min or max;
704 * both min and max must be present for this to work (default:
708 do_property_adjust (const SGPropertyNode * arg)
710 SGPropertyNode * prop = get_prop(arg);
713 if (arg->hasValue("step"))
714 amount = arg->getDoubleValue("step");
716 amount = (arg->getDoubleValue("factor", 1)
717 * arg->getDoubleValue("offset"));
719 double unmodifiable, modifiable;
720 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
721 &unmodifiable, &modifiable);
722 modifiable += amount;
723 limit_value(&modifiable, arg);
725 prop->setDoubleValue(unmodifiable + modifiable);
732 * Built-in command: multiply a property value.
734 * property: the name of the property to multiply.
735 * factor: the amount by which to multiply.
736 * min: the minimum allowed value (default: no minimum).
737 * max: the maximum allowed value (default: no maximum).
738 * mask: 'integer' to apply only to the left of the decimal point,
739 * 'decimal' to apply only to the right of the decimal point,
740 * or 'all' to apply to the whole number (the default).
741 * wrap: true if the value should be wrapped when it passes min or max;
742 * both min and max must be present for this to work (default:
746 do_property_multiply (const SGPropertyNode * arg)
748 SGPropertyNode * prop = get_prop(arg);
749 double factor = arg->getDoubleValue("factor", 1);
751 double unmodifiable, modifiable;
752 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
753 &unmodifiable, &modifiable);
754 modifiable *= factor;
755 limit_value(&modifiable, arg);
757 prop->setDoubleValue(unmodifiable + modifiable);
764 * Built-in command: swap two property values.
766 * property[0]: the name of the first property.
767 * property[1]: the name of the second property.
770 do_property_swap (const SGPropertyNode * arg)
772 SGPropertyNode * prop1 = get_prop(arg);
773 SGPropertyNode * prop2 = get_prop2(arg);
775 // FIXME: inefficient
776 const string & tmp = prop1->getStringValue();
777 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
778 prop2->setUnspecifiedValue(tmp.c_str()));
783 * Built-in command: Set a property to an axis or other moving input.
785 * property: the name of the property to set.
786 * setting: the current input setting, usually between -1.0 and 1.0.
787 * offset: the offset to shift by, before applying the factor.
788 * factor: the factor to multiply by (use negative to reverse).
791 do_property_scale (const SGPropertyNode * arg)
793 SGPropertyNode * prop = get_prop(arg);
794 double setting = arg->getDoubleValue("setting");
795 double offset = arg->getDoubleValue("offset", 0.0);
796 double factor = arg->getDoubleValue("factor", 1.0);
797 bool squared = arg->getBoolValue("squared", false);
798 int power = arg->getIntValue("power", (squared ? 2 : 1));
800 int sign = (setting < 0 ? -1 : 1);
806 setting = setting * setting * sign;
809 setting = setting * setting * setting;
812 setting = setting * setting * setting * setting * sign;
815 setting = pow(setting, power);
816 if ((power % 2) == 0)
821 return prop->setDoubleValue((setting + offset) * factor);
826 * Built-in command: cycle a property through a set of values.
828 * If the current value isn't in the list, the cycle will
829 * (re)start from the beginning.
831 * property: the name of the property to cycle.
832 * value[*]: the list of values to cycle through.
835 do_property_cycle (const SGPropertyNode * arg)
837 SGPropertyNode * prop = get_prop(arg);
838 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
840 int nSelections = values.size();
842 if (nSelections < 1) {
843 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
847 // Try to find the current selection
848 for (int i = 0; i < nSelections; i++) {
849 if (compare_values(prop, values[i])) {
855 // Default or wrap to the first selection
856 if (selection < 0 || selection >= nSelections)
859 prop->setUnspecifiedValue(values[selection]->getStringValue());
865 * Built-in command: randomize a numeric property value.
867 * property: the name of the property value to randomize.
868 * min: the minimum allowed value.
869 * max: the maximum allowed value.
872 do_property_randomize (const SGPropertyNode * arg)
874 SGPropertyNode * prop = get_prop(arg);
875 double min = arg->getDoubleValue("min", DBL_MIN);
876 double max = arg->getDoubleValue("max", DBL_MAX);
877 prop->setDoubleValue(sg_random() * (max - min) + min);
882 * Built-in command: interpolate a property value over time
884 * property: the name of the property value to interpolate.
885 * type: the interpolation type ("numeric", "color", etc.)
886 * easing: name of easing function (see http://easings.net/)
887 * value[0..n] any number of constant values to interpolate
888 * time/rate[0..n] time between each value, number of time elements must
889 * match those of value elements. Instead of time also rate can
890 * be used which automatically calculates the time to change
891 * the property value at the given speed.
893 * property[1..n+1] any number of target values taken from named properties
894 * time/rate[0..n] time between each value, number of time elements must
895 * match those of value elements. Instead of time also rate can
896 * be used which automatically calculates the time to change
897 * the property value at the given speed.
900 do_property_interpolate (const SGPropertyNode * arg)
902 SGPropertyNode * prop = get_prop(arg);
906 simgear::PropertyList time_nodes = arg->getChildren("time");
907 simgear::PropertyList rate_nodes = arg->getChildren("rate");
909 if( !time_nodes.empty() && !rate_nodes.empty() )
910 // mustn't specify time and rate
913 simgear::PropertyList::size_type num_times = time_nodes.empty()
917 simgear::PropertyList value_nodes = arg->getChildren("value");
918 if( value_nodes.empty() )
920 simgear::PropertyList prop_nodes = arg->getChildren("property");
922 // must have one more property node
923 if( prop_nodes.size() != num_times + 1 )
926 value_nodes.reserve(num_times);
927 for( size_t i = 1; i < prop_nodes.size(); ++i )
928 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
932 if( value_nodes.size() != num_times )
936 deltas.reserve(num_times);
938 if( !time_nodes.empty() )
940 for( size_t i = 0; i < num_times; ++i )
941 deltas.push_back( time_nodes[i]->getDoubleValue() );
945 for( size_t i = 0; i < num_times; ++i )
947 // TODO calculate delta based on property type
948 double delta = value_nodes[i]->getDoubleValue()
950 ? value_nodes[i - 1]->getDoubleValue()
951 : prop->getDoubleValue()
953 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
957 return prop->interpolate
959 arg->getStringValue("type", "numeric"),
962 arg->getStringValue("easing", "linear")
967 * Built-in command: reinit the data logging system based on the
968 * current contents of the /logger tree.
971 do_data_logging_commit (const SGPropertyNode * arg)
973 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
979 * Built-in command: Add a dialog to the GUI system. Does *not*
980 * display the dialog. The property node should have the same format
981 * as a dialog XML configuration. It must include:
983 * name: the name of the GUI dialog for future reference.
986 do_dialog_new (const SGPropertyNode * arg)
988 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
993 // Note the casting away of const: this is *real*. Doing a
994 // "dialog-apply" command later on will mutate this property node.
995 // I'm not convinced that this isn't the Right Thing though; it
996 // allows client to create a node, pass it to dialog-new, and get
997 // the values back from the dialog by reading the same node.
998 // Perhaps command arguments are not as "const" as they would
1000 gui->newDialog((SGPropertyNode*)arg);
1005 * Built-in command: Show an XML-configured dialog.
1007 * dialog-name: the name of the GUI dialog to display.
1010 do_dialog_show (const SGPropertyNode * arg)
1012 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1013 gui->showDialog(arg->getStringValue("dialog-name"));
1019 * Built-in Command: Hide the active XML-configured dialog.
1022 do_dialog_close (const SGPropertyNode * arg)
1024 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1025 if(arg->hasValue("dialog-name"))
1026 return gui->closeDialog(arg->getStringValue("dialog-name"));
1027 return gui->closeActiveDialog();
1032 * Update a value in the active XML-configured dialog.
1034 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1037 do_dialog_update (const SGPropertyNode * arg)
1039 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1041 if (arg->hasValue("dialog-name"))
1042 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1044 dialog = gui->getActiveDialog();
1047 dialog->updateValues(arg->getStringValue("object-name"));
1055 do_open_browser (const SGPropertyNode * arg)
1058 if (arg->hasValue("path"))
1059 path = arg->getStringValue("path");
1061 if (arg->hasValue("url"))
1062 path = arg->getStringValue("url");
1066 return openBrowser(path);
1070 * Apply a value in the active XML-configured dialog.
1072 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1075 do_dialog_apply (const SGPropertyNode * arg)
1077 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1079 if (arg->hasValue("dialog-name"))
1080 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1082 dialog = gui->getActiveDialog();
1085 dialog->applyValues(arg->getStringValue("object-name"));
1094 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1098 do_gui_redraw (const SGPropertyNode * arg)
1100 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1107 * Adds model to the scenery. The path to the added branch (/models/model[*])
1108 * is returned in property "property".
1111 do_add_model (const SGPropertyNode * arg)
1113 SGPropertyNode * model = fgGetNode("models", true);
1115 for (i = 0; model->hasChild("model",i); i++);
1116 model = model->getChild("model", i, true);
1117 copyProperties(arg, model);
1118 if (model->hasValue("elevation-m"))
1119 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1120 * SG_METER_TO_FEET);
1121 model->getNode("load", true);
1122 model->removeChildren("load");
1123 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1128 * Built-in command: play an audio message (i.e. a wav file) This is
1129 * fire and forget. Call this once per message and it will get dumped
1130 * into a queue. Messages are played sequentially so they do not
1134 do_play_audio_sample (const SGPropertyNode * arg)
1136 SGSoundMgr *smgr = globals->get_soundmgr();
1138 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1142 string path = arg->getStringValue("path");
1143 string file = arg->getStringValue("file");
1144 float volume = arg->getFloatValue("volume");
1145 // cout << "playing " << path << " / " << file << endl;
1147 static FGSampleQueue *queue = 0;
1149 queue = new FGSampleQueue(smgr, "chatter");
1150 queue->tie_to_listener();
1153 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1154 msg->set_volume( volume );
1159 } catch (const sg_io_exception&) {
1160 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1161 "failed to load" << path << '/' << file);
1167 * Built-in command: commit presets (read from in /sim/presets/)
1170 do_presets_commit (const SGPropertyNode * arg)
1172 if (fgGetBool("/sim/initialized", false)) {
1173 fgReInitSubsystems();
1175 // Nasal can trigger this during initial init, which confuses
1176 // the logic in ReInitSubsystems, since initial state has not been
1177 // saved at that time. Short-circuit everything here.
1178 flightgear::initPosition();
1185 * Built-in command: set log level (0 ... 7)
1188 do_log_level (const SGPropertyNode * arg)
1190 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1197 do_decrease_visibility (const SGPropertyNode * arg)
1199 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1204 do_increase_visibility (const SGPropertyNode * arg)
1206 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1211 * An fgcommand to allow loading of xml files via nasal,
1212 * the xml file's structure will be made available within
1213 * a property tree node defined under argument "targetnode",
1214 * or in the given argument tree under "data" otherwise.
1216 * @param filename a string to hold the complete path & filename of an XML file
1217 * @param targetnode a string pointing to a location within the property tree
1218 * where to store the parsed XML file. If <targetnode> is undefined, then the
1219 * file contents are stored under a node <data> in the argument tree.
1223 do_load_xml_to_proptree(const SGPropertyNode * arg)
1225 SGPath file(arg->getStringValue("filename"));
1226 if (file.str().empty())
1229 if (file.extension() != "xml")
1230 file.concat(".xml");
1232 std::string icao = arg->getStringValue("icao");
1234 if (file.isRelative()) {
1235 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1236 if (!absPath.isNull())
1240 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1241 << file.str() << "'.");
1246 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1247 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1248 << file.str() << " at ICAO:" << icao);
1253 if (!fgValidatePath(file.c_str(), false)) {
1254 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1255 "(unauthorized access)");
1259 SGPropertyNode *targetnode;
1260 if (arg->hasValue("targetnode"))
1261 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1263 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1266 readProperties(file.c_str(), targetnode, true);
1267 } catch (const sg_exception &e) {
1268 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1275 class RemoteXMLRequest : public simgear::HTTP::Request
1278 SGPropertyNode_ptr _complete;
1279 SGPropertyNode_ptr _status;
1280 SGPropertyNode_ptr _failed;
1281 SGPropertyNode_ptr _target;
1283 mutable string _requestBody;
1284 int _requestBodyLength;
1287 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1288 simgear::HTTP::Request(url),
1289 _target(targetNode),
1290 _requestBodyLength(-1),
1295 void setCompletionProp(SGPropertyNode_ptr p)
1300 void setStatusProp(SGPropertyNode_ptr p)
1305 void setFailedProp(SGPropertyNode_ptr p)
1310 void setRequestData(const SGPropertyNode* body)
1313 std::stringstream buf;
1314 writeProperties(buf, body, true);
1315 _requestBody = buf.str();
1316 _requestBodyLength = _requestBody.size();
1319 virtual std::string method() const
1324 virtual int requestBodyLength() const
1326 return _requestBodyLength;
1329 virtual void getBodyData(char* s, int& count) const
1331 int toRead = std::min(count, (int) _requestBody.size());
1332 memcpy(s, _requestBody.c_str(), toRead);
1334 _requestBody = _requestBody.substr(count);
1337 virtual std::string requestBodyType() const
1339 return "application/xml";
1342 virtual void gotBodyData(const char* s, int n)
1344 propsData += string(s, n);
1347 virtual void failed()
1349 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1351 _failed->setBoolValue(true);
1355 virtual void responseComplete()
1357 simgear::HTTP::Request::responseComplete();
1359 int response = responseCode();
1360 bool failed = false;
1361 if (response == 200) {
1363 const char* buffer = propsData.c_str();
1364 readProperties(buffer, propsData.size(), _target, true);
1365 } catch (const sg_exception &e) {
1366 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1368 response = 406; // 'not acceptable', anything better?
1373 // now the response data is output, signal Nasal / listeners
1374 if (_complete) _complete->setBoolValue(true);
1375 if (_status) _status->setIntValue(response);
1376 if (_failed && failed) _failed->setBoolValue(true);
1382 do_load_xml_from_url(const SGPropertyNode * arg)
1384 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1386 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1390 std::string url(arg->getStringValue("url"));
1394 SGPropertyNode *targetnode;
1395 if (arg->hasValue("targetnode"))
1396 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1398 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1400 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1402 if (arg->hasChild("body"))
1403 req->setRequestData(arg->getChild("body"));
1405 // connect up optional reporting properties
1406 if (arg->hasValue("complete"))
1407 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1408 if (arg->hasValue("failure"))
1409 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1410 if (arg->hasValue("status"))
1411 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1413 http->makeRequest(req);
1419 * An fgcommand to allow saving of xml files via nasal,
1420 * the file's structure will be determined based on what's
1421 * encountered in the passed (source) property tree node
1423 * @param filename a string to hold the complete path & filename of the (new)
1425 * @param sourcenode a string pointing to a location within the property tree
1426 * where to find the nodes that should be written recursively into an XML file
1427 * @param data if no sourcenode is given, then the file contents are taken from
1428 * the argument tree's "data" node.
1432 do_save_xml_from_proptree(const SGPropertyNode * arg)
1434 SGPath file(arg->getStringValue("filename"));
1435 if (file.str().empty())
1438 if (file.extension() != "xml")
1439 file.concat(".xml");
1441 if (!fgValidatePath(file.c_str(), true)) {
1442 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1443 "(unauthorized access)");
1447 SGPropertyNode *sourcenode;
1448 if (arg->hasValue("sourcenode"))
1449 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1450 else if (arg->getNode("data", false))
1451 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1456 writeProperties (file.c_str(), sourcenode, true);
1457 } catch (const sg_exception &e) {
1458 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1466 do_press_cockpit_button (const SGPropertyNode *arg)
1468 const char *prefix = arg->getStringValue("prefix");
1470 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1473 string prop = string(prefix) + "-button";
1476 if (arg->getBoolValue("latching"))
1477 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1481 fgSetDouble(prop.c_str(), value);
1482 fgSetBool(arg->getStringValue("discrete"), value > 0);
1488 do_release_cockpit_button (const SGPropertyNode *arg)
1490 const char *prefix = arg->getStringValue("prefix");
1492 if (arg->getBoolValue("guarded")) {
1493 string prop = string(prefix) + "-guard";
1494 if (fgGetDouble(prop.c_str()) < 1) {
1495 fgSetDouble(prop.c_str(), 1);
1500 if (! arg->getBoolValue("latching")) {
1501 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1502 fgSetBool(arg->getStringValue("discrete"), false);
1508 // Optional profiling commands using gperftools:
1509 // http://code.google.com/p/gperftools/
1511 #ifndef FG_HAVE_GPERFTOOLS
1513 no_profiling_support()
1519 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1525 do_profiler_start(const SGPropertyNode *arg)
1527 #ifdef FG_HAVE_GPERFTOOLS
1528 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1529 ProfilerStart(filename);
1532 no_profiling_support();
1538 do_profiler_stop(const SGPropertyNode *arg)
1540 #ifdef FG_HAVE_GPERFTOOLS
1544 no_profiling_support();
1550 ////////////////////////////////////////////////////////////////////////
1552 ////////////////////////////////////////////////////////////////////////
1556 * Table of built-in commands.
1558 * New commands do not have to be added here; any module in the application
1559 * can add a new command using globals->get_commands()->addCommand(...).
1563 SGCommandMgr::command_t command;
1565 { "null", do_null },
1566 { "nasal", do_nasal },
1567 { "exit", do_exit },
1568 { "reset", do_reset },
1569 { "pause", do_pause },
1570 { "load", do_load },
1571 { "save", do_save },
1572 { "save-tape", do_save_tape },
1573 { "load-tape", do_load_tape },
1574 { "panel-load", do_panel_load },
1575 { "preferences-load", do_preferences_load },
1576 { "toggle-fullscreen", do_toggle_fullscreen },
1577 { "view-cycle", do_view_cycle },
1578 { "screen-capture", do_screen_capture },
1579 { "hires-screen-capture", do_hires_screen_capture },
1580 { "tile-cache-reload", do_tile_cache_reload },
1582 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1583 { "set-outside-air-temp-degc", do_set_oat_degc },
1584 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1585 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1587 { "property-toggle", do_property_toggle },
1588 { "property-assign", do_property_assign },
1589 { "property-adjust", do_property_adjust },
1590 { "property-multiply", do_property_multiply },
1591 { "property-swap", do_property_swap },
1592 { "property-scale", do_property_scale },
1593 { "property-cycle", do_property_cycle },
1594 { "property-randomize", do_property_randomize },
1595 { "property-interpolate", do_property_interpolate },
1596 { "data-logging-commit", do_data_logging_commit },
1597 { "dialog-new", do_dialog_new },
1598 { "dialog-show", do_dialog_show },
1599 { "dialog-close", do_dialog_close },
1600 { "dialog-update", do_dialog_update },
1601 { "dialog-apply", do_dialog_apply },
1602 { "open-browser", do_open_browser },
1603 { "gui-redraw", do_gui_redraw },
1604 { "add-model", do_add_model },
1605 { "play-audio-sample", do_play_audio_sample },
1606 { "presets-commit", do_presets_commit },
1607 { "log-level", do_log_level },
1608 { "replay", do_replay },
1610 { "decrease-visibility", do_decrease_visibility },
1611 { "increase-visibility", do_increase_visibility },
1613 { "loadxml", do_load_xml_to_proptree},
1614 { "savexml", do_save_xml_from_proptree },
1615 { "xmlhttprequest", do_load_xml_from_url },
1616 { "press-cockpit-button", do_press_cockpit_button },
1617 { "release-cockpit-button", do_release_cockpit_button },
1618 { "dump-scenegraph", do_dump_scene_graph },
1619 { "dump-terrainbranch", do_dump_terrain_branch },
1620 { "print-visible-scene", do_print_visible_scene_info },
1621 { "reload-shaders", do_reload_shaders },
1622 { "reload-materials", do_materials_reload },
1624 { "profiler-start", do_profiler_start },
1625 { "profiler-stop", do_profiler_stop },
1627 { 0, 0 } // zero-terminated
1632 * Initialize the default built-in commands.
1634 * Other commands may be added by other parts of the application.
1639 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1640 for (int i = 0; built_ins[i].name != 0; i++) {
1641 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1642 globals->get_commands()->addCommand(built_ins[i].name,
1643 built_ins[i].command);
1646 typedef bool (*dummy)();
1647 fgTie( "/command/view/next", dummy(0), do_view_next );
1648 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1650 SGPropertyNode* profiler_available =
1651 globals->get_props()->getNode("/sim/debug/profiler-available", true);
1652 #ifdef FG_HAVE_GPERFTOOLS
1653 profiler_available->setBoolValue(true);
1655 profiler_available->setBoolValue(false);
1657 profiler_available->setAttributes(SGPropertyNode::READ);
1660 // end of fg_commands.cxx