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 bool wrap = arg->getBoolValue("wrap", true);
841 // compatible with knob/pick animations
842 int offset = arg->getIntValue("offset", 1);
845 int nSelections = values.size();
847 if (nSelections < 1) {
848 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
852 // Try to find the current selection
853 for (int i = 0; i < nSelections; i++) {
854 if (compare_values(prop, values[i])) {
860 if (selection < 0) { // default to first selection
865 selection = (selection + nSelections) % nSelections;
867 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
871 prop->setUnspecifiedValue(values[selection]->getStringValue());
877 * Built-in command: randomize a numeric property value.
879 * property: the name of the property value to randomize.
880 * min: the minimum allowed value.
881 * max: the maximum allowed value.
884 do_property_randomize (const SGPropertyNode * arg)
886 SGPropertyNode * prop = get_prop(arg);
887 double min = arg->getDoubleValue("min", DBL_MIN);
888 double max = arg->getDoubleValue("max", DBL_MAX);
889 prop->setDoubleValue(sg_random() * (max - min) + min);
894 * Built-in command: interpolate a property value over time
896 * property: the name of the property value to interpolate.
897 * type: the interpolation type ("numeric", "color", etc.)
898 * easing: name of easing function (see http://easings.net/)
899 * value[0..n] any number of constant values to interpolate
900 * time/rate[0..n] time between each value, number of time elements must
901 * match those of value elements. Instead of time also rate can
902 * be used which automatically calculates the time to change
903 * the property value at the given speed.
905 * property[1..n+1] any number of target values taken from named properties
906 * time/rate[0..n] time between each value, number of time elements must
907 * match those of value elements. Instead of time also rate can
908 * be used which automatically calculates the time to change
909 * the property value at the given speed.
912 do_property_interpolate (const SGPropertyNode * arg)
914 SGPropertyNode * prop = get_prop(arg);
918 simgear::PropertyList time_nodes = arg->getChildren("time");
919 simgear::PropertyList rate_nodes = arg->getChildren("rate");
921 if( !time_nodes.empty() && !rate_nodes.empty() )
922 // mustn't specify time and rate
925 simgear::PropertyList::size_type num_times = time_nodes.empty()
929 simgear::PropertyList value_nodes = arg->getChildren("value");
930 if( value_nodes.empty() )
932 simgear::PropertyList prop_nodes = arg->getChildren("property");
934 // must have one more property node
935 if( prop_nodes.size() != num_times + 1 )
938 value_nodes.reserve(num_times);
939 for( size_t i = 1; i < prop_nodes.size(); ++i )
940 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
944 if( value_nodes.size() != num_times )
948 deltas.reserve(num_times);
950 if( !time_nodes.empty() )
952 for( size_t i = 0; i < num_times; ++i )
953 deltas.push_back( time_nodes[i]->getDoubleValue() );
957 for( size_t i = 0; i < num_times; ++i )
959 // TODO calculate delta based on property type
960 double delta = value_nodes[i]->getDoubleValue()
962 ? value_nodes[i - 1]->getDoubleValue()
963 : prop->getDoubleValue()
965 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
969 return prop->interpolate
971 arg->getStringValue("type", "numeric"),
974 arg->getStringValue("easing", "linear")
979 * Built-in command: reinit the data logging system based on the
980 * current contents of the /logger tree.
983 do_data_logging_commit (const SGPropertyNode * arg)
985 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
991 * Built-in command: Add a dialog to the GUI system. Does *not*
992 * display the dialog. The property node should have the same format
993 * as a dialog XML configuration. It must include:
995 * name: the name of the GUI dialog for future reference.
998 do_dialog_new (const SGPropertyNode * arg)
1000 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1005 // Note the casting away of const: this is *real*. Doing a
1006 // "dialog-apply" command later on will mutate this property node.
1007 // I'm not convinced that this isn't the Right Thing though; it
1008 // allows client to create a node, pass it to dialog-new, and get
1009 // the values back from the dialog by reading the same node.
1010 // Perhaps command arguments are not as "const" as they would
1012 gui->newDialog((SGPropertyNode*)arg);
1017 * Built-in command: Show an XML-configured dialog.
1019 * dialog-name: the name of the GUI dialog to display.
1022 do_dialog_show (const SGPropertyNode * arg)
1024 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1025 gui->showDialog(arg->getStringValue("dialog-name"));
1031 * Built-in Command: Hide the active XML-configured dialog.
1034 do_dialog_close (const SGPropertyNode * arg)
1036 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1037 if(arg->hasValue("dialog-name"))
1038 return gui->closeDialog(arg->getStringValue("dialog-name"));
1039 return gui->closeActiveDialog();
1044 * Update a value in the active XML-configured dialog.
1046 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1049 do_dialog_update (const SGPropertyNode * arg)
1051 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1053 if (arg->hasValue("dialog-name"))
1054 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1056 dialog = gui->getActiveDialog();
1059 dialog->updateValues(arg->getStringValue("object-name"));
1067 do_open_browser (const SGPropertyNode * arg)
1070 if (arg->hasValue("path"))
1071 path = arg->getStringValue("path");
1073 if (arg->hasValue("url"))
1074 path = arg->getStringValue("url");
1078 return openBrowser(path);
1082 * Apply a value in the active XML-configured dialog.
1084 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1087 do_dialog_apply (const SGPropertyNode * arg)
1089 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1091 if (arg->hasValue("dialog-name"))
1092 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1094 dialog = gui->getActiveDialog();
1097 dialog->applyValues(arg->getStringValue("object-name"));
1106 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1110 do_gui_redraw (const SGPropertyNode * arg)
1112 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1119 * Adds model to the scenery. The path to the added branch (/models/model[*])
1120 * is returned in property "property".
1123 do_add_model (const SGPropertyNode * arg)
1125 SGPropertyNode * model = fgGetNode("models", true);
1127 for (i = 0; model->hasChild("model",i); i++);
1128 model = model->getChild("model", i, true);
1129 copyProperties(arg, model);
1130 if (model->hasValue("elevation-m"))
1131 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1132 * SG_METER_TO_FEET);
1133 model->getNode("load", true);
1134 model->removeChildren("load");
1135 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1140 * Built-in command: play an audio message (i.e. a wav file) This is
1141 * fire and forget. Call this once per message and it will get dumped
1142 * into a queue. Messages are played sequentially so they do not
1146 do_play_audio_sample (const SGPropertyNode * arg)
1148 SGSoundMgr *smgr = globals->get_soundmgr();
1150 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1154 string path = arg->getStringValue("path");
1155 string file = arg->getStringValue("file");
1156 float volume = arg->getFloatValue("volume");
1157 // cout << "playing " << path << " / " << file << endl;
1159 static FGSampleQueue *queue = 0;
1161 queue = new FGSampleQueue(smgr, "chatter");
1162 queue->tie_to_listener();
1165 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1166 msg->set_volume( volume );
1171 } catch (const sg_io_exception&) {
1172 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1173 "failed to load" << path << '/' << file);
1179 * Built-in command: commit presets (read from in /sim/presets/)
1182 do_presets_commit (const SGPropertyNode * arg)
1184 if (fgGetBool("/sim/initialized", false)) {
1185 fgReInitSubsystems();
1187 // Nasal can trigger this during initial init, which confuses
1188 // the logic in ReInitSubsystems, since initial state has not been
1189 // saved at that time. Short-circuit everything here.
1190 flightgear::initPosition();
1197 * Built-in command: set log level (0 ... 7)
1200 do_log_level (const SGPropertyNode * arg)
1202 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1209 do_decrease_visibility (const SGPropertyNode * arg)
1211 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1216 do_increase_visibility (const SGPropertyNode * arg)
1218 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1223 * An fgcommand to allow loading of xml files via nasal,
1224 * the xml file's structure will be made available within
1225 * a property tree node defined under argument "targetnode",
1226 * or in the given argument tree under "data" otherwise.
1228 * @param filename a string to hold the complete path & filename of an XML file
1229 * @param targetnode a string pointing to a location within the property tree
1230 * where to store the parsed XML file. If <targetnode> is undefined, then the
1231 * file contents are stored under a node <data> in the argument tree.
1235 do_load_xml_to_proptree(const SGPropertyNode * arg)
1237 SGPath file(arg->getStringValue("filename"));
1238 if (file.str().empty())
1241 if (file.extension() != "xml")
1242 file.concat(".xml");
1244 std::string icao = arg->getStringValue("icao");
1246 if (file.isRelative()) {
1247 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1248 if (!absPath.isNull())
1252 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1253 << file.str() << "'.");
1258 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1259 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1260 << file.str() << " at ICAO:" << icao);
1265 if (!fgValidatePath(file.c_str(), false)) {
1266 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1267 "(unauthorized access)");
1271 SGPropertyNode *targetnode;
1272 if (arg->hasValue("targetnode"))
1273 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1275 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1278 readProperties(file.c_str(), targetnode, true);
1279 } catch (const sg_exception &e) {
1280 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1287 class RemoteXMLRequest : public simgear::HTTP::Request
1290 SGPropertyNode_ptr _complete;
1291 SGPropertyNode_ptr _status;
1292 SGPropertyNode_ptr _failed;
1293 SGPropertyNode_ptr _target;
1295 mutable string _requestBody;
1296 int _requestBodyLength;
1299 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1300 simgear::HTTP::Request(url),
1301 _target(targetNode),
1302 _requestBodyLength(-1),
1307 void setCompletionProp(SGPropertyNode_ptr p)
1312 void setStatusProp(SGPropertyNode_ptr p)
1317 void setFailedProp(SGPropertyNode_ptr p)
1322 void setRequestData(const SGPropertyNode* body)
1325 std::stringstream buf;
1326 writeProperties(buf, body, true);
1327 _requestBody = buf.str();
1328 _requestBodyLength = _requestBody.size();
1331 virtual std::string method() const
1336 virtual int requestBodyLength() const
1338 return _requestBodyLength;
1341 virtual void getBodyData(char* s, int& count) const
1343 int toRead = std::min(count, (int) _requestBody.size());
1344 memcpy(s, _requestBody.c_str(), toRead);
1346 _requestBody = _requestBody.substr(count);
1349 virtual std::string requestBodyType() const
1351 return "application/xml";
1354 virtual void gotBodyData(const char* s, int n)
1356 propsData += string(s, n);
1359 virtual void failed()
1361 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1363 _failed->setBoolValue(true);
1367 virtual void responseComplete()
1369 simgear::HTTP::Request::responseComplete();
1371 int response = responseCode();
1372 bool failed = false;
1373 if (response == 200) {
1375 const char* buffer = propsData.c_str();
1376 readProperties(buffer, propsData.size(), _target, true);
1377 } catch (const sg_exception &e) {
1378 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1380 response = 406; // 'not acceptable', anything better?
1385 // now the response data is output, signal Nasal / listeners
1386 if (_complete) _complete->setBoolValue(true);
1387 if (_status) _status->setIntValue(response);
1388 if (_failed && failed) _failed->setBoolValue(true);
1394 do_load_xml_from_url(const SGPropertyNode * arg)
1396 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1398 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1402 std::string url(arg->getStringValue("url"));
1406 SGPropertyNode *targetnode;
1407 if (arg->hasValue("targetnode"))
1408 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1410 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1412 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1414 if (arg->hasChild("body"))
1415 req->setRequestData(arg->getChild("body"));
1417 // connect up optional reporting properties
1418 if (arg->hasValue("complete"))
1419 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1420 if (arg->hasValue("failure"))
1421 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1422 if (arg->hasValue("status"))
1423 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1425 http->makeRequest(req);
1431 * An fgcommand to allow saving of xml files via nasal,
1432 * the file's structure will be determined based on what's
1433 * encountered in the passed (source) property tree node
1435 * @param filename a string to hold the complete path & filename of the (new)
1437 * @param sourcenode a string pointing to a location within the property tree
1438 * where to find the nodes that should be written recursively into an XML file
1439 * @param data if no sourcenode is given, then the file contents are taken from
1440 * the argument tree's "data" node.
1444 do_save_xml_from_proptree(const SGPropertyNode * arg)
1446 SGPath file(arg->getStringValue("filename"));
1447 if (file.str().empty())
1450 if (file.extension() != "xml")
1451 file.concat(".xml");
1453 if (!fgValidatePath(file.c_str(), true)) {
1454 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1455 "(unauthorized access)");
1459 SGPropertyNode *sourcenode;
1460 if (arg->hasValue("sourcenode"))
1461 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1462 else if (arg->getNode("data", false))
1463 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1468 writeProperties (file.c_str(), sourcenode, true);
1469 } catch (const sg_exception &e) {
1470 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1478 do_press_cockpit_button (const SGPropertyNode *arg)
1480 const char *prefix = arg->getStringValue("prefix");
1482 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1485 string prop = string(prefix) + "-button";
1488 if (arg->getBoolValue("latching"))
1489 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1493 fgSetDouble(prop.c_str(), value);
1494 fgSetBool(arg->getStringValue("discrete"), value > 0);
1500 do_release_cockpit_button (const SGPropertyNode *arg)
1502 const char *prefix = arg->getStringValue("prefix");
1504 if (arg->getBoolValue("guarded")) {
1505 string prop = string(prefix) + "-guard";
1506 if (fgGetDouble(prop.c_str()) < 1) {
1507 fgSetDouble(prop.c_str(), 1);
1512 if (! arg->getBoolValue("latching")) {
1513 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1514 fgSetBool(arg->getStringValue("discrete"), false);
1520 // Optional profiling commands using gperftools:
1521 // http://code.google.com/p/gperftools/
1523 #ifndef FG_HAVE_GPERFTOOLS
1525 no_profiling_support()
1531 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1537 do_profiler_start(const SGPropertyNode *arg)
1539 #ifdef FG_HAVE_GPERFTOOLS
1540 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1541 ProfilerStart(filename);
1544 no_profiling_support();
1550 do_profiler_stop(const SGPropertyNode *arg)
1552 #ifdef FG_HAVE_GPERFTOOLS
1556 no_profiling_support();
1562 ////////////////////////////////////////////////////////////////////////
1564 ////////////////////////////////////////////////////////////////////////
1568 * Table of built-in commands.
1570 * New commands do not have to be added here; any module in the application
1571 * can add a new command using globals->get_commands()->addCommand(...).
1575 SGCommandMgr::command_t command;
1577 { "null", do_null },
1578 { "nasal", do_nasal },
1579 { "exit", do_exit },
1580 { "reset", do_reset },
1581 { "pause", do_pause },
1582 { "load", do_load },
1583 { "save", do_save },
1584 { "save-tape", do_save_tape },
1585 { "load-tape", do_load_tape },
1586 { "panel-load", do_panel_load },
1587 { "preferences-load", do_preferences_load },
1588 { "toggle-fullscreen", do_toggle_fullscreen },
1589 { "view-cycle", do_view_cycle },
1590 { "screen-capture", do_screen_capture },
1591 { "hires-screen-capture", do_hires_screen_capture },
1592 { "tile-cache-reload", do_tile_cache_reload },
1594 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1595 { "set-outside-air-temp-degc", do_set_oat_degc },
1596 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1597 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1599 { "property-toggle", do_property_toggle },
1600 { "property-assign", do_property_assign },
1601 { "property-adjust", do_property_adjust },
1602 { "property-multiply", do_property_multiply },
1603 { "property-swap", do_property_swap },
1604 { "property-scale", do_property_scale },
1605 { "property-cycle", do_property_cycle },
1606 { "property-randomize", do_property_randomize },
1607 { "property-interpolate", do_property_interpolate },
1608 { "data-logging-commit", do_data_logging_commit },
1609 { "dialog-new", do_dialog_new },
1610 { "dialog-show", do_dialog_show },
1611 { "dialog-close", do_dialog_close },
1612 { "dialog-update", do_dialog_update },
1613 { "dialog-apply", do_dialog_apply },
1614 { "open-browser", do_open_browser },
1615 { "gui-redraw", do_gui_redraw },
1616 { "add-model", do_add_model },
1617 { "play-audio-sample", do_play_audio_sample },
1618 { "presets-commit", do_presets_commit },
1619 { "log-level", do_log_level },
1620 { "replay", do_replay },
1622 { "decrease-visibility", do_decrease_visibility },
1623 { "increase-visibility", do_increase_visibility },
1625 { "loadxml", do_load_xml_to_proptree},
1626 { "savexml", do_save_xml_from_proptree },
1627 { "xmlhttprequest", do_load_xml_from_url },
1628 { "press-cockpit-button", do_press_cockpit_button },
1629 { "release-cockpit-button", do_release_cockpit_button },
1630 { "dump-scenegraph", do_dump_scene_graph },
1631 { "dump-terrainbranch", do_dump_terrain_branch },
1632 { "print-visible-scene", do_print_visible_scene_info },
1633 { "reload-shaders", do_reload_shaders },
1634 { "reload-materials", do_materials_reload },
1636 { "profiler-start", do_profiler_start },
1637 { "profiler-stop", do_profiler_stop },
1639 { 0, 0 } // zero-terminated
1644 * Initialize the default built-in commands.
1646 * Other commands may be added by other parts of the application.
1651 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1652 for (int i = 0; built_ins[i].name != 0; i++) {
1653 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1654 globals->get_commands()->addCommand(built_ins[i].name,
1655 built_ins[i].command);
1658 typedef bool (*dummy)();
1659 fgTie( "/command/view/next", dummy(0), do_view_next );
1660 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1662 SGPropertyNode* profiler_available =
1663 globals->get_props()->getNode("/sim/debug/profiler-available", true);
1664 #ifdef FG_HAVE_GPERFTOOLS
1665 profiler_available->setBoolValue(true);
1667 profiler_available->setBoolValue(false);
1669 profiler_available->setAttributes(SGPropertyNode::READ);
1672 // end of fg_commands.cxx