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/misc/interpolator.hxx>
27 #include <simgear/io/HTTPRequest.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/scenery.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/sample_queue.hxx>
37 #include <Airports/xmlloader.hxx>
38 #include <Network/HTTPClient.hxx>
39 #include <Viewer/viewmgr.hxx>
40 #include <Viewer/viewer.hxx>
41 #include <Environment/presets.hxx>
43 #include "fg_init.hxx"
46 #include "fg_commands.hxx"
47 #include "fg_props.hxx"
48 #include "globals.hxx"
52 #include "positioninit.hxx"
54 #include <boost/scoped_array.hpp>
56 #ifdef FG_HAVE_GPERFTOOLS
57 # include <google/profiler.h>
65 ////////////////////////////////////////////////////////////////////////
66 // Static helper functions.
67 ////////////////////////////////////////////////////////////////////////
70 static inline SGPropertyNode *
71 get_prop (const SGPropertyNode * arg)
73 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
76 static inline SGPropertyNode *
77 get_prop2 (const SGPropertyNode * arg)
79 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
84 * Get a double value and split it as required.
87 split_value (double full_value, const char * mask,
88 double * unmodifiable, double * modifiable)
90 if (!strcmp("integer", mask)) {
91 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
92 *unmodifiable = full_value - *modifiable;
93 } else if (!strcmp("decimal", mask)) {
94 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
95 *modifiable = full_value - *unmodifiable;
97 if (strcmp("all", mask))
98 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
99 << " assuming 'all'");
101 *modifiable = full_value;
107 * Clamp or wrap a value as specified.
110 limit_value (double * value, const SGPropertyNode * arg)
112 const SGPropertyNode * min_node = arg->getChild("min");
113 const SGPropertyNode * max_node = arg->getChild("max");
115 bool wrap = arg->getBoolValue("wrap");
117 if (min_node == 0 || max_node == 0)
120 if (wrap) { // wrap such that min <= x < max
121 double min_val = min_node->getDoubleValue();
122 double max_val = max_node->getDoubleValue();
123 double resolution = arg->getDoubleValue("resolution");
124 if (resolution > 0.0) {
125 // snap to (min + N*resolution), taking special care to handle imprecision
126 int n = (int)floor((*value - min_val) / resolution + 0.5);
127 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
128 SG_NORMALIZE_RANGE(n, 0, steps);
129 *value = min_val + resolution * n;
131 // plain circular wrapping
132 SG_NORMALIZE_RANGE(*value, min_val, max_val);
134 } else { // clamp such that min <= x <= max
135 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
136 *value = min_node->getDoubleValue();
137 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
138 *value = max_node->getDoubleValue();
143 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
145 switch (value1->getType()) {
146 case simgear::props::BOOL:
147 return (value1->getBoolValue() == value2->getBoolValue());
148 case simgear::props::INT:
149 return (value1->getIntValue() == value2->getIntValue());
150 case simgear::props::LONG:
151 return (value1->getLongValue() == value2->getLongValue());
152 case simgear::props::FLOAT:
153 return (value1->getFloatValue() == value2->getFloatValue());
154 case simgear::props::DOUBLE:
155 return (value1->getDoubleValue() == value2->getDoubleValue());
157 return !strcmp(value1->getStringValue(), value2->getStringValue());
163 ////////////////////////////////////////////////////////////////////////
164 // Command implementations.
165 ////////////////////////////////////////////////////////////////////////
169 * Built-in command: do nothing.
172 do_null (const SGPropertyNode * arg)
178 * Built-in command: run a Nasal script.
181 do_nasal (const SGPropertyNode * arg)
183 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
187 * Built-in command: exit FlightGear.
189 * status: the exit status to return to the operating system (defaults to 0)
192 do_exit (const SGPropertyNode * arg)
194 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
195 fgSetBool("/sim/signals/exit", true);
196 globals->saveUserSettings();
197 fgOSExit(arg->getIntValue("status", 0));
203 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
206 do_reset (const SGPropertyNode * arg)
208 fgReInitSubsystems();
213 * Built-in command: replay the FDR buffer
216 do_replay (const SGPropertyNode * arg)
218 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
223 * Built-in command: pause/unpause the sim
226 do_pause (const SGPropertyNode * arg)
228 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
229 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
235 fgSetBool("/sim/freeze/master",!paused);
236 fgSetBool("/sim/freeze/clock",!paused);
239 SGPropertyNode_ptr args(new SGPropertyNode);
240 args->setStringValue("id", "sim-pause");
242 args->setStringValue("label", "Simulation is paused");
243 globals->get_commands()->execute("show-message", args);
245 globals->get_commands()->execute("clear-message", args);
252 * Built-in command: load flight.
254 * file (optional): the name of the file to load (relative to current
255 * directory). Defaults to "fgfs.sav"
258 do_load (const SGPropertyNode * arg)
260 string file = arg->getStringValue("file", "fgfs.sav");
261 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
264 if (!fgValidatePath(file.c_str(), false)) {
265 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
266 "(unauthorized access)");
270 ifstream input(file.c_str());
271 if (input.good() && fgLoadFlight(input)) {
273 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
276 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
283 * Built-in command: save flight.
285 * file (optional): the name of the file to save (relative to the
286 * current directory). Defaults to "fgfs.sav".
289 do_save (const SGPropertyNode * arg)
291 string file = arg->getStringValue("file", "fgfs.sav");
292 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
295 if (!fgValidatePath(file.c_str(), false)) {
296 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
297 "(unauthorized access)");
301 bool write_all = arg->getBoolValue("write-all", false);
302 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
303 ofstream output(file.c_str());
304 if (output.good() && fgSaveFlight(output, write_all)) {
306 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
309 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
315 * Built-in command: save flight recorder tape.
319 do_save_tape (const SGPropertyNode * arg)
321 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
322 replay->saveTape(arg);
327 * Built-in command: load flight recorder tape.
331 do_load_tape (const SGPropertyNode * arg)
333 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
334 replay->loadTape(arg);
340 * Built-in command: (re)load the panel.
342 * path (optional): the file name to load the panel from
343 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
344 * and if that's unspecified, to "Panels/Default/default.xml".
347 do_panel_load (const SGPropertyNode * arg)
349 string panel_path = arg->getStringValue("path");
350 if (!panel_path.empty()) {
351 // write to the standard property, which will force a load
352 fgSetString("/sim/panel/path", panel_path.c_str());
359 * Built-in command: (re)load preferences.
361 * path (optional): the file name to load the panel from (relative
362 * to FG_ROOT). Defaults to "preferences.xml".
365 do_preferences_load (const SGPropertyNode * arg)
368 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
369 globals->get_props());
370 } catch (const sg_exception &e) {
371 guiErrorMessage("Error reading global preferences: ", e);
374 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
381 globals->get_current_view()->setHeadingOffset_deg(0.0);
382 globals->get_viewmgr()->next_view();
388 globals->get_current_view()->setHeadingOffset_deg(0.0);
389 globals->get_viewmgr()->prev_view();
393 * An fgcommand to toggle fullscreen mode.
397 do_toggle_fullscreen(const SGPropertyNode *arg)
404 * Built-in command: cycle view.
407 do_view_cycle (const SGPropertyNode * arg)
409 globals->get_current_view()->setHeadingOffset_deg(0.0);
410 globals->get_viewmgr()->next_view();
415 * Built-in command: capture screen.
418 do_screen_capture (const SGPropertyNode * arg)
420 return fgDumpSnapShot();
424 do_reload_shaders (const SGPropertyNode*)
426 simgear::reload_shaders();
431 do_dump_scene_graph (const SGPropertyNode*)
438 do_dump_terrain_branch (const SGPropertyNode*)
440 fgDumpTerrainBranch();
442 double lon_deg = fgGetDouble("/position/longitude-deg");
443 double lat_deg = fgGetDouble("/position/latitude-deg");
444 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
445 SGVec3d zero = SGVec3d::fromGeod(geodPos);
447 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
448 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
449 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
455 do_print_visible_scene_info(const SGPropertyNode*)
457 fgPrintVisibleSceneInfoCommand();
462 * Built-in command: hires capture screen.
465 do_hires_screen_capture (const SGPropertyNode * arg)
473 * Reload the tile cache.
476 do_tile_cache_reload (const SGPropertyNode * arg)
478 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
479 bool freeze = master_freeze->getBoolValue();
480 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
482 master_freeze->setBoolValue(true);
485 globals->get_subsystem("tile-manager")->reinit();
488 master_freeze->setBoolValue(false);
494 * Reload the materials definition
497 do_materials_reload (const SGPropertyNode * arg)
499 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
500 SGMaterialLib* new_matlib = new SGMaterialLib;
501 SGPath mpath( globals->get_fg_root() );
502 mpath.append( fgGetString("/sim/rendering/materials-file") );
503 bool loaded = new_matlib->load(globals->get_fg_root(),
505 globals->get_props());
508 SG_LOG( SG_GENERAL, SG_ALERT,
509 "Error loading materials file " << mpath.str() );
513 globals->set_matlib(new_matlib);
519 These do_set_(some-environment-parameters) are deprecated and no longer
520 useful/functional - Torsten Dreyer, January 2011
522 * Set the sea level outside air temperature and assigning that to all
523 * boundary and aloft environment layers.
526 do_set_sea_level_degc ( double temp_sea_level_degc)
528 SGPropertyNode *node, *child;
531 node = fgGetNode( "/environment/config/boundary" );
532 if ( node != NULL ) {
534 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
535 child->setDoubleValue( "temperature-sea-level-degc",
536 temp_sea_level_degc );
542 node = fgGetNode( "/environment/config/aloft" );
543 if ( node != NULL ) {
545 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
546 child->setDoubleValue( "temperature-sea-level-degc",
547 temp_sea_level_degc );
556 do_set_sea_level_degc (const SGPropertyNode * arg)
558 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
563 * Set the outside air temperature at the "current" altitude by first
564 * calculating the corresponding sea level temp, and assigning that to
565 * all boundary and aloft environment layers.
568 do_set_oat_degc (const SGPropertyNode * arg)
570 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
571 // check for an altitude specified in the arguments, otherwise use
572 // current aircraft altitude.
573 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
574 if ( altitude_ft == NULL ) {
575 altitude_ft = fgGetNode("/position/altitude-ft");
578 FGEnvironment dummy; // instantiate a dummy so we can leech a method
579 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
580 dummy.set_temperature_degc( oat_degc );
581 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
585 * Set the sea level outside air dewpoint and assigning that to all
586 * boundary and aloft environment layers.
589 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
592 SGPropertyNode *node, *child;
595 node = fgGetNode( "/environment/config/boundary" );
596 if ( node != NULL ) {
598 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
599 child->setDoubleValue( "dewpoint-sea-level-degc",
600 dewpoint_sea_level_degc );
606 node = fgGetNode( "/environment/config/aloft" );
607 if ( node != NULL ) {
609 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
610 child->setDoubleValue( "dewpoint-sea-level-degc",
611 dewpoint_sea_level_degc );
620 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
622 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
626 * Set the outside air dewpoint at the "current" altitude by first
627 * calculating the corresponding sea level dewpoint, and assigning
628 * that to all boundary and aloft environment layers.
631 do_set_dewpoint_degc (const SGPropertyNode * arg)
633 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
635 // check for an altitude specified in the arguments, otherwise use
636 // current aircraft altitude.
637 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
638 if ( altitude_ft == NULL ) {
639 altitude_ft = fgGetNode("/position/altitude-ft");
642 FGEnvironment dummy; // instantiate a dummy so we can leech a method
643 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
644 dummy.set_dewpoint_degc( dewpoint_degc );
645 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
650 * Built-in command: toggle a bool property value.
652 * property: The name of the property to toggle.
655 do_property_toggle (const SGPropertyNode * arg)
657 SGPropertyNode * prop = get_prop(arg);
658 return prop->setBoolValue(!prop->getBoolValue());
663 * Built-in command: assign a value to a property.
665 * property: the name of the property to assign.
666 * value: the value to assign; or
667 * property[1]: the property to copy from.
670 do_property_assign (const SGPropertyNode * arg)
672 SGPropertyNode * prop = get_prop(arg);
673 const SGPropertyNode * value = arg->getNode("value");
676 return prop->setUnspecifiedValue(value->getStringValue());
679 const SGPropertyNode * prop2 = get_prop2(arg);
681 return prop->setUnspecifiedValue(prop2->getStringValue());
689 * Built-in command: increment or decrement a property value.
691 * If the 'step' argument is present, it will be used; otherwise,
692 * the command uses 'offset' and 'factor', usually from the mouse.
694 * property: the name of the property to increment or decrement.
695 * step: the amount of the increment or decrement (default: 0).
696 * offset: offset from the current setting (used for the mouse; multiplied
698 * factor: scaling amount for the offset (defaults to 1).
699 * min: the minimum allowed value (default: no minimum).
700 * max: the maximum allowed value (default: no maximum).
701 * mask: 'integer' to apply only to the left of the decimal point,
702 * 'decimal' to apply only to the right of the decimal point,
703 * or 'all' to apply to the whole number (the default).
704 * wrap: true if the value should be wrapped when it passes min or max;
705 * both min and max must be present for this to work (default:
709 do_property_adjust (const SGPropertyNode * arg)
711 SGPropertyNode * prop = get_prop(arg);
714 if (arg->hasValue("step"))
715 amount = arg->getDoubleValue("step");
717 amount = (arg->getDoubleValue("factor", 1)
718 * arg->getDoubleValue("offset"));
720 double unmodifiable, modifiable;
721 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
722 &unmodifiable, &modifiable);
723 modifiable += amount;
724 limit_value(&modifiable, arg);
726 prop->setDoubleValue(unmodifiable + modifiable);
733 * Built-in command: multiply a property value.
735 * property: the name of the property to multiply.
736 * factor: the amount by which to multiply.
737 * min: the minimum allowed value (default: no minimum).
738 * max: the maximum allowed value (default: no maximum).
739 * mask: 'integer' to apply only to the left of the decimal point,
740 * 'decimal' to apply only to the right of the decimal point,
741 * or 'all' to apply to the whole number (the default).
742 * wrap: true if the value should be wrapped when it passes min or max;
743 * both min and max must be present for this to work (default:
747 do_property_multiply (const SGPropertyNode * arg)
749 SGPropertyNode * prop = get_prop(arg);
750 double factor = arg->getDoubleValue("factor", 1);
752 double unmodifiable, modifiable;
753 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
754 &unmodifiable, &modifiable);
755 modifiable *= factor;
756 limit_value(&modifiable, arg);
758 prop->setDoubleValue(unmodifiable + modifiable);
765 * Built-in command: swap two property values.
767 * property[0]: the name of the first property.
768 * property[1]: the name of the second property.
771 do_property_swap (const SGPropertyNode * arg)
773 SGPropertyNode * prop1 = get_prop(arg);
774 SGPropertyNode * prop2 = get_prop2(arg);
776 // FIXME: inefficient
777 const string & tmp = prop1->getStringValue();
778 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
779 prop2->setUnspecifiedValue(tmp.c_str()));
784 * Built-in command: Set a property to an axis or other moving input.
786 * property: the name of the property to set.
787 * setting: the current input setting, usually between -1.0 and 1.0.
788 * offset: the offset to shift by, before applying the factor.
789 * factor: the factor to multiply by (use negative to reverse).
792 do_property_scale (const SGPropertyNode * arg)
794 SGPropertyNode * prop = get_prop(arg);
795 double setting = arg->getDoubleValue("setting");
796 double offset = arg->getDoubleValue("offset", 0.0);
797 double factor = arg->getDoubleValue("factor", 1.0);
798 bool squared = arg->getBoolValue("squared", false);
799 int power = arg->getIntValue("power", (squared ? 2 : 1));
801 int sign = (setting < 0 ? -1 : 1);
807 setting = setting * setting * sign;
810 setting = setting * setting * setting;
813 setting = setting * setting * setting * setting * sign;
816 setting = pow(setting, power);
817 if ((power % 2) == 0)
822 return prop->setDoubleValue((setting + offset) * factor);
827 * Built-in command: cycle a property through a set of values.
829 * If the current value isn't in the list, the cycle will
830 * (re)start from the beginning.
832 * property: the name of the property to cycle.
833 * value[*]: the list of values to cycle through.
836 do_property_cycle (const SGPropertyNode * arg)
838 SGPropertyNode * prop = get_prop(arg);
839 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
841 int nSelections = values.size();
843 if (nSelections < 1) {
844 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
848 // Try to find the current selection
849 for (int i = 0; i < nSelections; i++) {
850 if (compare_values(prop, values[i])) {
856 // Default or wrap to the first selection
857 if (selection < 0 || selection >= nSelections)
860 prop->setUnspecifiedValue(values[selection]->getStringValue());
866 * Built-in command: randomize a numeric property value.
868 * property: the name of the property value to randomize.
869 * min: the minimum allowed value.
870 * max: the maximum allowed value.
873 do_property_randomize (const SGPropertyNode * arg)
875 SGPropertyNode * prop = get_prop(arg);
876 double min = arg->getDoubleValue("min", DBL_MIN);
877 double max = arg->getDoubleValue("max", DBL_MAX);
878 prop->setDoubleValue(sg_random() * (max - min) + min);
883 * Built-in command: interpolate a property value over time
885 * property: the name of the property value to interpolate.
886 * value[0..n] any number of constant values to interpolate
887 * time/rate[0..n] time between each value, number of time elements must
888 * match those of value elements. Instead of time also rate can
889 * be used which automatically calculates the time to change
890 * the property value at the given speed.
892 * property[1..n] any number of target values taken from named properties
893 * time/rate[0..n] time between each value, number of time elements must
894 * match those of value elements. Instead of time also rate can
895 * be used which automatically calculates the time to change
896 * the property value at the given speed.
899 do_property_interpolate (const SGPropertyNode * arg)
901 SGPropertyNode * prop = get_prop(arg);
903 simgear::PropertyList valueNodes = arg->getChildren( "value" );
904 simgear::PropertyList timeNodes = arg->getChildren( "time" );
905 simgear::PropertyList rateNodes = arg->getChildren( "rate" );
907 if( !timeNodes.empty() && !rateNodes.empty() )
908 // mustn't specify time and rate
911 simgear::PropertyList::size_type num_times = timeNodes.empty()
915 boost::scoped_array<double> value;
916 boost::scoped_array<double> time;
918 if( valueNodes.size() > 0 ) {
920 if( num_times != valueNodes.size() )
923 value.reset( new double[valueNodes.size()] );
924 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
925 value[n] = valueNodes[n]->getDoubleValue();
928 valueNodes = arg->getChildren("property");
929 // must have one more property node
930 if( valueNodes.size() - 1 != num_times )
933 value.reset( new double[valueNodes.size()-1] );
934 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
935 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
940 time.reset( new double[num_times] );
941 if( !timeNodes.empty() ) {
942 for( simgear::PropertyList::size_type n = 0; n < num_times; n++ ) {
943 time[n] = timeNodes[n]->getDoubleValue();
946 for( simgear::PropertyList::size_type n = 0; n < num_times; n++ ) {
947 double delta = value[n]
948 - (n > 0 ? value[n - 1] : prop->getDoubleValue());
949 time[n] = fabs(delta / rateNodes[n]->getDoubleValue());
953 ((SGInterpolator*)globals->get_subsystem_mgr()
954 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
955 ->interpolate(prop, num_times, value.get(), time.get() );
961 * Built-in command: reinit the data logging system based on the
962 * current contents of the /logger tree.
965 do_data_logging_commit (const SGPropertyNode * arg)
967 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
973 * Built-in command: Add a dialog to the GUI system. Does *not*
974 * display the dialog. The property node should have the same format
975 * as a dialog XML configuration. It must include:
977 * name: the name of the GUI dialog for future reference.
980 do_dialog_new (const SGPropertyNode * arg)
982 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
987 // Note the casting away of const: this is *real*. Doing a
988 // "dialog-apply" command later on will mutate this property node.
989 // I'm not convinced that this isn't the Right Thing though; it
990 // allows client to create a node, pass it to dialog-new, and get
991 // the values back from the dialog by reading the same node.
992 // Perhaps command arguments are not as "const" as they would
994 gui->newDialog((SGPropertyNode*)arg);
999 * Built-in command: Show an XML-configured dialog.
1001 * dialog-name: the name of the GUI dialog to display.
1004 do_dialog_show (const SGPropertyNode * arg)
1006 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1007 gui->showDialog(arg->getStringValue("dialog-name"));
1013 * Built-in Command: Hide the active XML-configured dialog.
1016 do_dialog_close (const SGPropertyNode * arg)
1018 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1019 if(arg->hasValue("dialog-name"))
1020 return gui->closeDialog(arg->getStringValue("dialog-name"));
1021 return gui->closeActiveDialog();
1026 * Update a value in the active XML-configured dialog.
1028 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1031 do_dialog_update (const SGPropertyNode * arg)
1033 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1035 if (arg->hasValue("dialog-name"))
1036 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1038 dialog = gui->getActiveDialog();
1041 dialog->updateValues(arg->getStringValue("object-name"));
1049 do_open_browser (const SGPropertyNode * arg)
1052 if (arg->hasValue("path"))
1053 path = arg->getStringValue("path");
1055 if (arg->hasValue("url"))
1056 path = arg->getStringValue("url");
1060 return openBrowser(path);
1064 * Apply a value in the active XML-configured dialog.
1066 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1069 do_dialog_apply (const SGPropertyNode * arg)
1071 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1073 if (arg->hasValue("dialog-name"))
1074 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1076 dialog = gui->getActiveDialog();
1079 dialog->applyValues(arg->getStringValue("object-name"));
1088 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1092 do_gui_redraw (const SGPropertyNode * arg)
1094 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1101 * Adds model to the scenery. The path to the added branch (/models/model[*])
1102 * is returned in property "property".
1105 do_add_model (const SGPropertyNode * arg)
1107 SGPropertyNode * model = fgGetNode("models", true);
1109 for (i = 0; model->hasChild("model",i); i++);
1110 model = model->getChild("model", i, true);
1111 copyProperties(arg, model);
1112 if (model->hasValue("elevation-m"))
1113 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1114 * SG_METER_TO_FEET);
1115 model->getNode("load", true);
1116 model->removeChildren("load");
1117 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1122 * Built-in command: play an audio message (i.e. a wav file) This is
1123 * fire and forget. Call this once per message and it will get dumped
1124 * into a queue. Messages are played sequentially so they do not
1128 do_play_audio_sample (const SGPropertyNode * arg)
1130 SGSoundMgr *smgr = globals->get_soundmgr();
1132 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1136 string path = arg->getStringValue("path");
1137 string file = arg->getStringValue("file");
1138 float volume = arg->getFloatValue("volume");
1139 // cout << "playing " << path << " / " << file << endl;
1141 static FGSampleQueue *queue = 0;
1143 queue = new FGSampleQueue(smgr, "chatter");
1144 queue->tie_to_listener();
1147 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1148 msg->set_volume( volume );
1153 } catch (const sg_io_exception&) {
1154 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1155 "failed to load" << path << '/' << file);
1161 * Built-in command: commit presets (read from in /sim/presets/)
1164 do_presets_commit (const SGPropertyNode * arg)
1166 if (fgGetBool("/sim/initialized", false)) {
1167 fgReInitSubsystems();
1169 // Nasal can trigger this during initial init, which confuses
1170 // the logic in ReInitSubsystems, since initial state has not been
1171 // saved at that time. Short-circuit everything here.
1172 flightgear::initPosition();
1179 * Built-in command: set log level (0 ... 7)
1182 do_log_level (const SGPropertyNode * arg)
1184 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1191 do_decrease_visibility (const SGPropertyNode * arg)
1193 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1198 do_increase_visibility (const SGPropertyNode * arg)
1200 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1205 * An fgcommand to allow loading of xml files via nasal,
1206 * the xml file's structure will be made available within
1207 * a property tree node defined under argument "targetnode",
1208 * or in the given argument tree under "data" otherwise.
1210 * @param filename a string to hold the complete path & filename of an XML file
1211 * @param targetnode a string pointing to a location within the property tree
1212 * where to store the parsed XML file. If <targetnode> is undefined, then the
1213 * file contents are stored under a node <data> in the argument tree.
1217 do_load_xml_to_proptree(const SGPropertyNode * arg)
1219 SGPath file(arg->getStringValue("filename"));
1220 if (file.str().empty())
1223 if (file.extension() != "xml")
1224 file.concat(".xml");
1226 std::string icao = arg->getStringValue("icao");
1228 if (file.isRelative()) {
1229 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1230 if (!absPath.isNull())
1234 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1235 << file.str() << "'.");
1240 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1241 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1242 << file.str() << " at ICAO:" << icao);
1247 if (!fgValidatePath(file.c_str(), false)) {
1248 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1249 "(unauthorized access)");
1253 SGPropertyNode *targetnode;
1254 if (arg->hasValue("targetnode"))
1255 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1257 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1260 readProperties(file.c_str(), targetnode, true);
1261 } catch (const sg_exception &e) {
1262 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1269 class RemoteXMLRequest : public simgear::HTTP::Request
1272 SGPropertyNode_ptr _complete;
1273 SGPropertyNode_ptr _status;
1274 SGPropertyNode_ptr _failed;
1275 SGPropertyNode_ptr _target;
1277 mutable string _requestBody;
1278 int _requestBodyLength;
1281 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1282 simgear::HTTP::Request(url),
1283 _target(targetNode),
1284 _requestBodyLength(-1),
1289 void setCompletionProp(SGPropertyNode_ptr p)
1294 void setStatusProp(SGPropertyNode_ptr p)
1299 void setFailedProp(SGPropertyNode_ptr p)
1304 void setRequestData(const SGPropertyNode* body)
1307 std::stringstream buf;
1308 writeProperties(buf, body, true);
1309 _requestBody = buf.str();
1310 _requestBodyLength = _requestBody.size();
1313 virtual std::string method() const
1318 virtual int requestBodyLength() const
1320 return _requestBodyLength;
1323 virtual void getBodyData(char* s, int& count) const
1325 int toRead = std::min(count, (int) _requestBody.size());
1326 memcpy(s, _requestBody.c_str(), toRead);
1328 _requestBody = _requestBody.substr(count);
1331 virtual std::string requestBodyType() const
1333 return "application/xml";
1336 virtual void gotBodyData(const char* s, int n)
1338 propsData += string(s, n);
1341 virtual void failed()
1343 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1345 _failed->setBoolValue(true);
1349 virtual void responseComplete()
1351 simgear::HTTP::Request::responseComplete();
1353 int response = responseCode();
1354 bool failed = false;
1355 if (response == 200) {
1357 const char* buffer = propsData.c_str();
1358 readProperties(buffer, propsData.size(), _target, true);
1359 } catch (const sg_exception &e) {
1360 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1362 response = 406; // 'not acceptable', anything better?
1367 // now the response data is output, signal Nasal / listeners
1368 if (_complete) _complete->setBoolValue(true);
1369 if (_status) _status->setIntValue(response);
1370 if (_failed && failed) _failed->setBoolValue(true);
1376 do_load_xml_from_url(const SGPropertyNode * arg)
1378 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1380 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1384 std::string url(arg->getStringValue("url"));
1388 SGPropertyNode *targetnode;
1389 if (arg->hasValue("targetnode"))
1390 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1392 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1394 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1396 if (arg->hasChild("body"))
1397 req->setRequestData(arg->getChild("body"));
1399 // connect up optional reporting properties
1400 if (arg->hasValue("complete"))
1401 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1402 if (arg->hasValue("failure"))
1403 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1404 if (arg->hasValue("status"))
1405 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1407 http->makeRequest(req);
1413 * An fgcommand to allow saving of xml files via nasal,
1414 * the file's structure will be determined based on what's
1415 * encountered in the passed (source) property tree node
1417 * @param filename a string to hold the complete path & filename of the (new)
1419 * @param sourcenode a string pointing to a location within the property tree
1420 * where to find the nodes that should be written recursively into an XML file
1421 * @param data if no sourcenode is given, then the file contents are taken from
1422 * the argument tree's "data" node.
1426 do_save_xml_from_proptree(const SGPropertyNode * arg)
1428 SGPath file(arg->getStringValue("filename"));
1429 if (file.str().empty())
1432 if (file.extension() != "xml")
1433 file.concat(".xml");
1435 if (!fgValidatePath(file.c_str(), true)) {
1436 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1437 "(unauthorized access)");
1441 SGPropertyNode *sourcenode;
1442 if (arg->hasValue("sourcenode"))
1443 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1444 else if (arg->getNode("data", false))
1445 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1450 writeProperties (file.c_str(), sourcenode, true);
1451 } catch (const sg_exception &e) {
1452 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1460 do_press_cockpit_button (const SGPropertyNode *arg)
1462 const char *prefix = arg->getStringValue("prefix");
1464 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1467 string prop = string(prefix) + "-button";
1470 if (arg->getBoolValue("latching"))
1471 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1475 fgSetDouble(prop.c_str(), value);
1476 fgSetBool(arg->getStringValue("discrete"), value > 0);
1482 do_release_cockpit_button (const SGPropertyNode *arg)
1484 const char *prefix = arg->getStringValue("prefix");
1486 if (arg->getBoolValue("guarded")) {
1487 string prop = string(prefix) + "-guard";
1488 if (fgGetDouble(prop.c_str()) < 1) {
1489 fgSetDouble(prop.c_str(), 1);
1494 if (! arg->getBoolValue("latching")) {
1495 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1496 fgSetBool(arg->getStringValue("discrete"), false);
1502 // Optional profiling commands using gperftools:
1503 // http://code.google.com/p/gperftools/
1505 #ifndef FG_HAVE_GPERFTOOLS
1507 no_profiling_support()
1513 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1519 do_profiler_start(const SGPropertyNode *arg)
1521 #ifdef FG_HAVE_GPERFTOOLS
1522 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1523 ProfilerStart(filename);
1526 no_profiling_support();
1532 do_profiler_stop(const SGPropertyNode *arg)
1534 #ifdef FG_HAVE_GPERFTOOLS
1538 no_profiling_support();
1544 ////////////////////////////////////////////////////////////////////////
1546 ////////////////////////////////////////////////////////////////////////
1550 * Table of built-in commands.
1552 * New commands do not have to be added here; any module in the application
1553 * can add a new command using globals->get_commands()->addCommand(...).
1557 SGCommandMgr::command_t command;
1559 { "null", do_null },
1560 { "nasal", do_nasal },
1561 { "exit", do_exit },
1562 { "reset", do_reset },
1563 { "pause", do_pause },
1564 { "load", do_load },
1565 { "save", do_save },
1566 { "save-tape", do_save_tape },
1567 { "load-tape", do_load_tape },
1568 { "panel-load", do_panel_load },
1569 { "preferences-load", do_preferences_load },
1570 { "toggle-fullscreen", do_toggle_fullscreen },
1571 { "view-cycle", do_view_cycle },
1572 { "screen-capture", do_screen_capture },
1573 { "hires-screen-capture", do_hires_screen_capture },
1574 { "tile-cache-reload", do_tile_cache_reload },
1576 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1577 { "set-outside-air-temp-degc", do_set_oat_degc },
1578 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1579 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1581 { "property-toggle", do_property_toggle },
1582 { "property-assign", do_property_assign },
1583 { "property-adjust", do_property_adjust },
1584 { "property-multiply", do_property_multiply },
1585 { "property-swap", do_property_swap },
1586 { "property-scale", do_property_scale },
1587 { "property-cycle", do_property_cycle },
1588 { "property-randomize", do_property_randomize },
1589 { "property-interpolate", do_property_interpolate },
1590 { "data-logging-commit", do_data_logging_commit },
1591 { "dialog-new", do_dialog_new },
1592 { "dialog-show", do_dialog_show },
1593 { "dialog-close", do_dialog_close },
1594 { "dialog-update", do_dialog_update },
1595 { "dialog-apply", do_dialog_apply },
1596 { "open-browser", do_open_browser },
1597 { "gui-redraw", do_gui_redraw },
1598 { "add-model", do_add_model },
1599 { "play-audio-sample", do_play_audio_sample },
1600 { "presets-commit", do_presets_commit },
1601 { "log-level", do_log_level },
1602 { "replay", do_replay },
1604 { "decrease-visibility", do_decrease_visibility },
1605 { "increase-visibility", do_increase_visibility },
1607 { "loadxml", do_load_xml_to_proptree},
1608 { "savexml", do_save_xml_from_proptree },
1609 { "xmlhttprequest", do_load_xml_from_url },
1610 { "press-cockpit-button", do_press_cockpit_button },
1611 { "release-cockpit-button", do_release_cockpit_button },
1612 { "dump-scenegraph", do_dump_scene_graph },
1613 { "dump-terrainbranch", do_dump_terrain_branch },
1614 { "print-visible-scene", do_print_visible_scene_info },
1615 { "reload-shaders", do_reload_shaders },
1616 { "reload-materials", do_materials_reload },
1618 { "profiler-start", do_profiler_start },
1619 { "profiler-stop", do_profiler_stop },
1621 { 0, 0 } // zero-terminated
1626 * Initialize the default built-in commands.
1628 * Other commands may be added by other parts of the application.
1633 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1634 for (int i = 0; built_ins[i].name != 0; i++) {
1635 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1636 globals->get_commands()->addCommand(built_ins[i].name,
1637 built_ins[i].command);
1640 typedef bool (*dummy)();
1641 fgTie( "/command/view/next", dummy(0), do_view_next );
1642 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1644 SGPropertyNode* profiler_available =
1645 globals->get_props()->getNode("/sim/debug/profiler-available", true);
1646 #ifdef FG_HAVE_GPERFTOOLS
1647 profiler_available->setBoolValue(true);
1649 profiler_available->setBoolValue(false);
1651 profiler_available->setAttributes(SGPropertyNode::READ);
1654 // end of fg_commands.cxx