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/HTTPMemoryRequest.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 <Scenery/tilemgr.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 #if 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();
215 do_reposition (const SGPropertyNode * arg)
222 * Built-in command: replay the FDR buffer
225 do_replay (const SGPropertyNode * arg)
227 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
232 * Built-in command: pause/unpause the sim
235 do_pause (const SGPropertyNode * arg)
237 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
238 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
244 fgSetBool("/sim/freeze/master",!paused);
245 fgSetBool("/sim/freeze/clock",!paused);
248 SGPropertyNode_ptr args(new SGPropertyNode);
249 args->setStringValue("id", "sim-pause");
250 if (!paused && fgGetBool("/sim/view-name-popup")) {
251 args->setStringValue("label", "Simulation is paused");
252 globals->get_commands()->execute("show-message", args);
254 globals->get_commands()->execute("clear-message", args);
261 * Built-in command: load flight.
263 * file (optional): the name of the file to load (relative to current
264 * directory). Defaults to "fgfs.sav"
267 do_load (const SGPropertyNode * arg)
269 string file = arg->getStringValue("file", "fgfs.sav");
270 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
273 if (!fgValidatePath(file.c_str(), false)) {
274 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
275 "(unauthorized access)");
279 ifstream input(file.c_str());
280 if (input.good() && fgLoadFlight(input)) {
282 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
285 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
292 * Built-in command: save flight.
294 * file (optional): the name of the file to save (relative to the
295 * current directory). Defaults to "fgfs.sav".
298 do_save (const SGPropertyNode * arg)
300 string file = arg->getStringValue("file", "fgfs.sav");
301 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
304 if (!fgValidatePath(file.c_str(), false)) {
305 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
306 "(unauthorized access)");
310 bool write_all = arg->getBoolValue("write-all", false);
311 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
312 ofstream output(file.c_str());
313 if (output.good() && fgSaveFlight(output, write_all)) {
315 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
318 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
324 * Built-in command: save flight recorder tape.
328 do_save_tape (const SGPropertyNode * arg)
330 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
331 replay->saveTape(arg);
336 * Built-in command: load flight recorder tape.
340 do_load_tape (const SGPropertyNode * arg)
342 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
343 replay->loadTape(arg);
349 * Built-in command: (re)load the panel.
351 * path (optional): the file name to load the panel from
352 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
353 * and if that's unspecified, to "Panels/Default/default.xml".
356 do_panel_load (const SGPropertyNode * arg)
358 string panel_path = arg->getStringValue("path");
359 if (!panel_path.empty()) {
360 // write to the standard property, which will force a load
361 fgSetString("/sim/panel/path", panel_path.c_str());
368 * Built-in command: (re)load preferences.
370 * path (optional): the file name to load the panel from (relative
371 * to FG_ROOT). Defaults to "preferences.xml".
374 do_preferences_load (const SGPropertyNode * arg)
377 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
378 globals->get_props());
379 } catch (const sg_exception &e) {
380 guiErrorMessage("Error reading global preferences: ", e);
383 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
388 do_view_next(bool do_it)
390 // Only switch view if really requested to do so (and not for example while
391 // reset/reposition where /command/view/next is set to false)
394 globals->get_current_view()->setHeadingOffset_deg(0.0);
395 globals->get_viewmgr()->next_view();
400 do_view_prev(bool do_it)
404 globals->get_current_view()->setHeadingOffset_deg(0.0);
405 globals->get_viewmgr()->prev_view();
410 * An fgcommand to toggle fullscreen mode.
414 do_toggle_fullscreen(const SGPropertyNode *arg)
421 * Built-in command: cycle view.
424 do_view_cycle (const SGPropertyNode * arg)
426 globals->get_current_view()->setHeadingOffset_deg(0.0);
427 globals->get_viewmgr()->next_view();
432 * Built-in command: capture screen.
435 do_screen_capture (const SGPropertyNode * arg)
437 return fgDumpSnapShot();
441 do_reload_shaders (const SGPropertyNode*)
443 simgear::reload_shaders();
448 do_dump_scene_graph (const SGPropertyNode*)
455 do_dump_terrain_branch (const SGPropertyNode*)
457 fgDumpTerrainBranch();
459 double lon_deg = fgGetDouble("/position/longitude-deg");
460 double lat_deg = fgGetDouble("/position/latitude-deg");
461 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
462 SGVec3d zero = SGVec3d::fromGeod(geodPos);
464 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
465 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
466 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
472 do_print_visible_scene_info(const SGPropertyNode*)
474 fgPrintVisibleSceneInfoCommand();
479 * Built-in command: hires capture screen.
482 do_hires_screen_capture (const SGPropertyNode * arg)
490 * Reload the tile cache.
493 do_tile_cache_reload (const SGPropertyNode * arg)
495 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
496 bool freeze = master_freeze->getBoolValue();
497 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
499 master_freeze->setBoolValue(true);
502 globals->get_subsystem("tile-manager")->reinit();
505 master_freeze->setBoolValue(false);
511 * Reload the materials definition
514 do_materials_reload (const SGPropertyNode * arg)
516 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
517 SGMaterialLib* new_matlib = new SGMaterialLib;
518 SGPath mpath( globals->get_fg_root() );
519 mpath.append( fgGetString("/sim/rendering/materials-file") );
520 bool loaded = new_matlib->load(globals->get_fg_root(),
522 globals->get_props());
525 SG_LOG( SG_GENERAL, SG_ALERT,
526 "Error loading materials file " << mpath.str() );
530 globals->set_matlib(new_matlib);
531 FGTileMgr* tileManager = static_cast<FGTileMgr*>(globals->get_subsystem("tile-manager"));
532 tileManager->materialLibChanged();
539 These do_set_(some-environment-parameters) are deprecated and no longer
540 useful/functional - Torsten Dreyer, January 2011
542 * Set the sea level outside air temperature and assigning that to all
543 * boundary and aloft environment layers.
546 do_set_sea_level_degc ( double temp_sea_level_degc)
548 SGPropertyNode *node, *child;
551 node = fgGetNode( "/environment/config/boundary" );
552 if ( node != NULL ) {
554 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
555 child->setDoubleValue( "temperature-sea-level-degc",
556 temp_sea_level_degc );
562 node = fgGetNode( "/environment/config/aloft" );
563 if ( node != NULL ) {
565 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
566 child->setDoubleValue( "temperature-sea-level-degc",
567 temp_sea_level_degc );
576 do_set_sea_level_degc (const SGPropertyNode * arg)
578 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
583 * Set the outside air temperature at the "current" altitude by first
584 * calculating the corresponding sea level temp, and assigning that to
585 * all boundary and aloft environment layers.
588 do_set_oat_degc (const SGPropertyNode * arg)
590 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
591 // check for an altitude specified in the arguments, otherwise use
592 // current aircraft altitude.
593 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
594 if ( altitude_ft == NULL ) {
595 altitude_ft = fgGetNode("/position/altitude-ft");
598 FGEnvironment dummy; // instantiate a dummy so we can leech a method
599 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
600 dummy.set_temperature_degc( oat_degc );
601 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
605 * Set the sea level outside air dewpoint and assigning that to all
606 * boundary and aloft environment layers.
609 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
612 SGPropertyNode *node, *child;
615 node = fgGetNode( "/environment/config/boundary" );
616 if ( node != NULL ) {
618 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
619 child->setDoubleValue( "dewpoint-sea-level-degc",
620 dewpoint_sea_level_degc );
626 node = fgGetNode( "/environment/config/aloft" );
627 if ( node != NULL ) {
629 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
630 child->setDoubleValue( "dewpoint-sea-level-degc",
631 dewpoint_sea_level_degc );
640 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
642 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
646 * Set the outside air dewpoint at the "current" altitude by first
647 * calculating the corresponding sea level dewpoint, and assigning
648 * that to all boundary and aloft environment layers.
651 do_set_dewpoint_degc (const SGPropertyNode * arg)
653 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
655 // check for an altitude specified in the arguments, otherwise use
656 // current aircraft altitude.
657 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
658 if ( altitude_ft == NULL ) {
659 altitude_ft = fgGetNode("/position/altitude-ft");
662 FGEnvironment dummy; // instantiate a dummy so we can leech a method
663 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
664 dummy.set_dewpoint_degc( dewpoint_degc );
665 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
670 * Built-in command: toggle a bool property value.
672 * property: The name of the property to toggle.
675 do_property_toggle (const SGPropertyNode * arg)
677 SGPropertyNode * prop = get_prop(arg);
678 return prop->setBoolValue(!prop->getBoolValue());
683 * Built-in command: assign a value to a property.
685 * property: the name of the property to assign.
686 * value: the value to assign; or
687 * property[1]: the property to copy from.
690 do_property_assign (const SGPropertyNode * arg)
692 SGPropertyNode * prop = get_prop(arg);
693 const SGPropertyNode * value = arg->getNode("value");
696 return prop->setUnspecifiedValue(value->getStringValue());
699 const SGPropertyNode * prop2 = get_prop2(arg);
701 return prop->setUnspecifiedValue(prop2->getStringValue());
709 * Built-in command: increment or decrement a property value.
711 * If the 'step' argument is present, it will be used; otherwise,
712 * the command uses 'offset' and 'factor', usually from the mouse.
714 * property: the name of the property to increment or decrement.
715 * step: the amount of the increment or decrement (default: 0).
716 * offset: offset from the current setting (used for the mouse; multiplied
718 * factor: scaling amount for the offset (defaults to 1).
719 * min: the minimum allowed value (default: no minimum).
720 * max: the maximum allowed value (default: no maximum).
721 * mask: 'integer' to apply only to the left of the decimal point,
722 * 'decimal' to apply only to the right of the decimal point,
723 * or 'all' to apply to the whole number (the default).
724 * wrap: true if the value should be wrapped when it passes min or max;
725 * both min and max must be present for this to work (default:
729 do_property_adjust (const SGPropertyNode * arg)
731 SGPropertyNode * prop = get_prop(arg);
734 if (arg->hasValue("step"))
735 amount = arg->getDoubleValue("step");
737 amount = (arg->getDoubleValue("factor", 1)
738 * arg->getDoubleValue("offset"));
740 double unmodifiable, modifiable;
741 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
742 &unmodifiable, &modifiable);
743 modifiable += amount;
744 limit_value(&modifiable, arg);
746 prop->setDoubleValue(unmodifiable + modifiable);
753 * Built-in command: multiply a property value.
755 * property: the name of the property to multiply.
756 * factor: the amount by which to multiply.
757 * min: the minimum allowed value (default: no minimum).
758 * max: the maximum allowed value (default: no maximum).
759 * mask: 'integer' to apply only to the left of the decimal point,
760 * 'decimal' to apply only to the right of the decimal point,
761 * or 'all' to apply to the whole number (the default).
762 * wrap: true if the value should be wrapped when it passes min or max;
763 * both min and max must be present for this to work (default:
767 do_property_multiply (const SGPropertyNode * arg)
769 SGPropertyNode * prop = get_prop(arg);
770 double factor = arg->getDoubleValue("factor", 1);
772 double unmodifiable, modifiable;
773 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
774 &unmodifiable, &modifiable);
775 modifiable *= factor;
776 limit_value(&modifiable, arg);
778 prop->setDoubleValue(unmodifiable + modifiable);
785 * Built-in command: swap two property values.
787 * property[0]: the name of the first property.
788 * property[1]: the name of the second property.
791 do_property_swap (const SGPropertyNode * arg)
793 SGPropertyNode * prop1 = get_prop(arg);
794 SGPropertyNode * prop2 = get_prop2(arg);
796 // FIXME: inefficient
797 const string & tmp = prop1->getStringValue();
798 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
799 prop2->setUnspecifiedValue(tmp.c_str()));
804 * Built-in command: Set a property to an axis or other moving input.
806 * property: the name of the property to set.
807 * setting: the current input setting, usually between -1.0 and 1.0.
808 * offset: the offset to shift by, before applying the factor.
809 * factor: the factor to multiply by (use negative to reverse).
812 do_property_scale (const SGPropertyNode * arg)
814 SGPropertyNode * prop = get_prop(arg);
815 double setting = arg->getDoubleValue("setting");
816 double offset = arg->getDoubleValue("offset", 0.0);
817 double factor = arg->getDoubleValue("factor", 1.0);
818 bool squared = arg->getBoolValue("squared", false);
819 int power = arg->getIntValue("power", (squared ? 2 : 1));
821 int sign = (setting < 0 ? -1 : 1);
827 setting = setting * setting * sign;
830 setting = setting * setting * setting;
833 setting = setting * setting * setting * setting * sign;
836 setting = pow(setting, power);
837 if ((power % 2) == 0)
842 return prop->setDoubleValue((setting + offset) * factor);
847 * Built-in command: cycle a property through a set of values.
849 * If the current value isn't in the list, the cycle will
850 * (re)start from the beginning.
852 * property: the name of the property to cycle.
853 * value[*]: the list of values to cycle through.
856 do_property_cycle (const SGPropertyNode * arg)
858 SGPropertyNode * prop = get_prop(arg);
859 std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
861 bool wrap = arg->getBoolValue("wrap", true);
862 // compatible with knob/pick animations
863 int offset = arg->getIntValue("offset", 1);
866 int nSelections = values.size();
868 if (nSelections < 1) {
869 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
873 // Try to find the current selection
874 for (int i = 0; i < nSelections; i++) {
875 if (compare_values(prop, values[i])) {
881 if (selection < 0) { // default to first selection
886 selection = (selection + nSelections) % nSelections;
888 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
892 prop->setUnspecifiedValue(values[selection]->getStringValue());
898 * Built-in command: randomize a numeric property value.
900 * property: the name of the property value to randomize.
901 * min: the minimum allowed value.
902 * max: the maximum allowed value.
905 do_property_randomize (const SGPropertyNode * arg)
907 SGPropertyNode * prop = get_prop(arg);
908 double min = arg->getDoubleValue("min", DBL_MIN);
909 double max = arg->getDoubleValue("max", DBL_MAX);
910 prop->setDoubleValue(sg_random() * (max - min) + min);
915 * Built-in command: interpolate a property value over time
917 * property: the name of the property value to interpolate.
918 * type: the interpolation type ("numeric", "color", etc.)
919 * easing: name of easing function (see http://easings.net/)
920 * value[0..n] any number of constant values to interpolate
921 * time/rate[0..n] time between each value, number of time elements must
922 * match those of value elements. Instead of time also rate can
923 * be used which automatically calculates the time to change
924 * the property value at the given speed.
926 * property[1..n+1] any number of target values taken from named properties
927 * time/rate[0..n] time between each value, number of time elements must
928 * match those of value elements. Instead of time also rate can
929 * be used which automatically calculates the time to change
930 * the property value at the given speed.
933 do_property_interpolate (const SGPropertyNode * arg)
935 SGPropertyNode * prop = get_prop(arg);
939 simgear::PropertyList time_nodes = arg->getChildren("time");
940 simgear::PropertyList rate_nodes = arg->getChildren("rate");
942 if( !time_nodes.empty() && !rate_nodes.empty() )
943 // mustn't specify time and rate
946 simgear::PropertyList::size_type num_times = time_nodes.empty()
950 simgear::PropertyList value_nodes = arg->getChildren("value");
951 if( value_nodes.empty() )
953 simgear::PropertyList prop_nodes = arg->getChildren("property");
955 // must have one more property node
956 if( prop_nodes.size() != num_times + 1 )
959 value_nodes.reserve(num_times);
960 for( size_t i = 1; i < prop_nodes.size(); ++i )
961 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
965 if( value_nodes.size() != num_times )
969 deltas.reserve(num_times);
971 if( !time_nodes.empty() )
973 for( size_t i = 0; i < num_times; ++i )
974 deltas.push_back( time_nodes[i]->getDoubleValue() );
978 for( size_t i = 0; i < num_times; ++i )
980 // TODO calculate delta based on property type
981 double delta = value_nodes[i]->getDoubleValue()
983 ? value_nodes[i - 1]->getDoubleValue()
984 : prop->getDoubleValue()
986 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
990 return prop->interpolate
992 arg->getStringValue("type", "numeric"),
995 arg->getStringValue("easing", "linear")
1000 * Built-in command: reinit the data logging system based on the
1001 * current contents of the /logger tree.
1004 do_data_logging_commit (const SGPropertyNode * arg)
1006 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1012 * Built-in command: Add a dialog to the GUI system. Does *not*
1013 * display the dialog. The property node should have the same format
1014 * as a dialog XML configuration. It must include:
1016 * name: the name of the GUI dialog for future reference.
1019 do_dialog_new (const SGPropertyNode * arg)
1021 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1026 // Note the casting away of const: this is *real*. Doing a
1027 // "dialog-apply" command later on will mutate this property node.
1028 // I'm not convinced that this isn't the Right Thing though; it
1029 // allows client to create a node, pass it to dialog-new, and get
1030 // the values back from the dialog by reading the same node.
1031 // Perhaps command arguments are not as "const" as they would
1033 gui->newDialog((SGPropertyNode*)arg);
1038 * Built-in command: Show an XML-configured dialog.
1040 * dialog-name: the name of the GUI dialog to display.
1043 do_dialog_show (const SGPropertyNode * arg)
1045 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1046 gui->showDialog(arg->getStringValue("dialog-name"));
1052 * Built-in Command: Hide the active XML-configured dialog.
1055 do_dialog_close (const SGPropertyNode * arg)
1057 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1058 if(arg->hasValue("dialog-name"))
1059 return gui->closeDialog(arg->getStringValue("dialog-name"));
1060 return gui->closeActiveDialog();
1065 * Update a value in the active XML-configured dialog.
1067 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1070 do_dialog_update (const SGPropertyNode * arg)
1072 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1074 if (arg->hasValue("dialog-name"))
1075 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1077 dialog = gui->getActiveDialog();
1080 dialog->updateValues(arg->getStringValue("object-name"));
1088 do_open_browser (const SGPropertyNode * arg)
1091 if (arg->hasValue("path"))
1092 path = arg->getStringValue("path");
1094 if (arg->hasValue("url"))
1095 path = arg->getStringValue("url");
1099 return openBrowser(path);
1103 * Apply a value in the active XML-configured dialog.
1105 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1108 do_dialog_apply (const SGPropertyNode * arg)
1110 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1112 if (arg->hasValue("dialog-name"))
1113 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1115 dialog = gui->getActiveDialog();
1118 dialog->applyValues(arg->getStringValue("object-name"));
1127 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1131 do_gui_redraw (const SGPropertyNode * arg)
1133 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1140 * Adds model to the scenery. The path to the added branch (/models/model[*])
1141 * is returned in property "property".
1144 do_add_model (const SGPropertyNode * arg)
1146 SGPropertyNode * model = fgGetNode("models", true);
1148 for (i = 0; model->hasChild("model",i); i++);
1149 model = model->getChild("model", i, true);
1150 copyProperties(arg, model);
1151 if (model->hasValue("elevation-m"))
1152 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1153 * SG_METER_TO_FEET);
1154 model->getNode("load", true);
1155 model->removeChildren("load");
1156 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1161 * Built-in command: play an audio message (i.e. a wav file) This is
1162 * fire and forget. Call this once per message and it will get dumped
1163 * into a queue. Messages are played sequentially so they do not
1167 do_play_audio_sample (const SGPropertyNode * arg)
1169 SGSoundMgr *smgr = globals->get_soundmgr();
1171 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1175 string path = arg->getStringValue("path");
1176 string file = arg->getStringValue("file");
1177 float volume = arg->getFloatValue("volume");
1178 // cout << "playing " << path << " / " << file << endl;
1180 FGSampleQueue *queue = globals->get_chatter_queue();
1182 queue = new FGSampleQueue(smgr, "chatter");
1183 queue->tie_to_listener();
1184 globals->set_chatter_queue(queue);
1187 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1188 msg->set_volume( volume );
1193 } catch (const sg_io_exception&) {
1194 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1195 "failed to load" << path << '/' << file);
1201 * Built-in command: commit presets (read from in /sim/presets/)
1204 do_presets_commit (const SGPropertyNode * arg)
1206 if (fgGetBool("/sim/initialized", false)) {
1207 fgReInitSubsystems();
1209 // Nasal can trigger this during initial init, which confuses
1210 // the logic in ReInitSubsystems, since initial state has not been
1211 // saved at that time. Short-circuit everything here.
1212 flightgear::initPosition();
1219 * Built-in command: set log level (0 ... 7)
1222 do_log_level (const SGPropertyNode * arg)
1224 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1231 do_decrease_visibility (const SGPropertyNode * arg)
1233 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1238 do_increase_visibility (const SGPropertyNode * arg)
1240 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1245 * An fgcommand to allow loading of xml files via nasal,
1246 * the xml file's structure will be made available within
1247 * a property tree node defined under argument "targetnode",
1248 * or in the given argument tree under "data" otherwise.
1250 * @param filename a string to hold the complete path & filename of an XML file
1251 * @param targetnode a string pointing to a location within the property tree
1252 * where to store the parsed XML file. If <targetnode> is undefined, then the
1253 * file contents are stored under a node <data> in the argument tree.
1257 do_load_xml_to_proptree(const SGPropertyNode * arg)
1259 SGPath file(arg->getStringValue("filename"));
1260 if (file.str().empty())
1263 if (file.extension() != "xml")
1264 file.concat(".xml");
1266 std::string icao = arg->getStringValue("icao");
1268 if (file.isRelative()) {
1269 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1270 if (!absPath.isNull())
1274 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1275 << file.str() << "'.");
1280 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1281 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1282 << file.str() << " at ICAO:" << icao);
1287 if (!fgValidatePath(file.c_str(), false)) {
1288 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1289 "(unauthorized access)");
1293 SGPropertyNode *targetnode;
1294 if (arg->hasValue("targetnode"))
1295 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1297 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1300 readProperties(file.c_str(), targetnode, true);
1301 } catch (const sg_exception &e) {
1302 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1309 class RemoteXMLRequest:
1310 public simgear::HTTP::MemoryRequest
1313 SGPropertyNode_ptr _complete;
1314 SGPropertyNode_ptr _status;
1315 SGPropertyNode_ptr _failed;
1316 SGPropertyNode_ptr _target;
1318 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1319 simgear::HTTP::MemoryRequest(url),
1324 void setCompletionProp(SGPropertyNode_ptr p)
1329 void setStatusProp(SGPropertyNode_ptr p)
1334 void setFailedProp(SGPropertyNode_ptr p)
1341 virtual void onFail()
1343 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1345 _failed->setBoolValue(true);
1349 virtual void onDone()
1351 int response = responseCode();
1352 bool failed = false;
1353 if (response == 200) {
1355 const char* buffer = responseBody().c_str();
1356 readProperties(buffer, responseBody().size(), _target, true);
1357 } catch (const sg_exception &e) {
1358 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1360 response = 406; // 'not acceptable', anything better?
1365 // now the response data is output, signal Nasal / listeners
1366 if (_complete) _complete->setBoolValue(true);
1367 if (_status) _status->setIntValue(response);
1368 if (_failed && failed) _failed->setBoolValue(true);
1374 do_load_xml_from_url(const SGPropertyNode * arg)
1376 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1378 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1382 std::string url(arg->getStringValue("url"));
1386 SGPropertyNode *targetnode;
1387 if (arg->hasValue("targetnode"))
1388 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1390 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1392 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1394 if (arg->hasChild("body"))
1395 req->setBodyData(arg->getChild("body"));
1397 // connect up optional reporting properties
1398 if (arg->hasValue("complete"))
1399 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1400 if (arg->hasValue("failure"))
1401 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1402 if (arg->hasValue("status"))
1403 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1405 http->makeRequest(req);
1411 * An fgcommand to allow saving of xml files via nasal,
1412 * the file's structure will be determined based on what's
1413 * encountered in the passed (source) property tree node
1415 * @param filename a string to hold the complete path & filename of the (new)
1417 * @param sourcenode a string pointing to a location within the property tree
1418 * where to find the nodes that should be written recursively into an XML file
1419 * @param data if no sourcenode is given, then the file contents are taken from
1420 * the argument tree's "data" node.
1424 do_save_xml_from_proptree(const SGPropertyNode * arg)
1426 SGPath file(arg->getStringValue("filename"));
1427 if (file.str().empty())
1430 if (file.extension() != "xml")
1431 file.concat(".xml");
1433 if (!fgValidatePath(file.c_str(), true)) {
1434 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1435 "(unauthorized access)");
1439 SGPropertyNode *sourcenode;
1440 if (arg->hasValue("sourcenode"))
1441 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1442 else if (arg->getNode("data", false))
1443 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1448 writeProperties (file.c_str(), sourcenode, true);
1449 } catch (const sg_exception &e) {
1450 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1458 do_press_cockpit_button (const SGPropertyNode *arg)
1460 const char *prefix = arg->getStringValue("prefix");
1462 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1465 string prop = string(prefix) + "-button";
1468 if (arg->getBoolValue("latching"))
1469 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1473 fgSetDouble(prop.c_str(), value);
1474 fgSetBool(arg->getStringValue("discrete"), value > 0);
1480 do_release_cockpit_button (const SGPropertyNode *arg)
1482 const char *prefix = arg->getStringValue("prefix");
1484 if (arg->getBoolValue("guarded")) {
1485 string prop = string(prefix) + "-guard";
1486 if (fgGetDouble(prop.c_str()) < 1) {
1487 fgSetDouble(prop.c_str(), 1);
1492 if (! arg->getBoolValue("latching")) {
1493 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1494 fgSetBool(arg->getStringValue("discrete"), false);
1500 // Optional profiling commands using gperftools:
1501 // http://code.google.com/p/gperftools/
1503 #if !FG_HAVE_GPERFTOOLS
1505 no_profiling_support()
1511 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1517 do_profiler_start(const SGPropertyNode *arg)
1519 #if FG_HAVE_GPERFTOOLS
1520 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1521 ProfilerStart(filename);
1524 no_profiling_support();
1530 do_profiler_stop(const SGPropertyNode *arg)
1532 #if FG_HAVE_GPERFTOOLS
1536 no_profiling_support();
1542 ////////////////////////////////////////////////////////////////////////
1544 ////////////////////////////////////////////////////////////////////////
1548 * Table of built-in commands.
1550 * New commands do not have to be added here; any module in the application
1551 * can add a new command using globals->get_commands()->addCommand(...).
1555 SGCommandMgr::command_t command;
1557 { "null", do_null },
1558 { "nasal", do_nasal },
1559 { "exit", do_exit },
1560 { "reset", do_reset },
1561 { "reposition", do_reposition },
1562 { "pause", do_pause },
1563 { "load", do_load },
1564 { "save", do_save },
1565 { "save-tape", do_save_tape },
1566 { "load-tape", do_load_tape },
1567 { "panel-load", do_panel_load },
1568 { "preferences-load", do_preferences_load },
1569 { "toggle-fullscreen", do_toggle_fullscreen },
1570 { "view-cycle", do_view_cycle },
1571 { "screen-capture", do_screen_capture },
1572 { "hires-screen-capture", do_hires_screen_capture },
1573 { "tile-cache-reload", do_tile_cache_reload },
1575 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1576 { "set-outside-air-temp-degc", do_set_oat_degc },
1577 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1578 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1580 { "property-toggle", do_property_toggle },
1581 { "property-assign", do_property_assign },
1582 { "property-adjust", do_property_adjust },
1583 { "property-multiply", do_property_multiply },
1584 { "property-swap", do_property_swap },
1585 { "property-scale", do_property_scale },
1586 { "property-cycle", do_property_cycle },
1587 { "property-randomize", do_property_randomize },
1588 { "property-interpolate", do_property_interpolate },
1589 { "data-logging-commit", do_data_logging_commit },
1590 { "dialog-new", do_dialog_new },
1591 { "dialog-show", do_dialog_show },
1592 { "dialog-close", do_dialog_close },
1593 { "dialog-update", do_dialog_update },
1594 { "dialog-apply", do_dialog_apply },
1595 { "open-browser", do_open_browser },
1596 { "gui-redraw", do_gui_redraw },
1597 { "add-model", do_add_model },
1598 { "play-audio-sample", do_play_audio_sample },
1599 { "presets-commit", do_presets_commit },
1600 { "log-level", do_log_level },
1601 { "replay", do_replay },
1603 { "decrease-visibility", do_decrease_visibility },
1604 { "increase-visibility", do_increase_visibility },
1606 { "loadxml", do_load_xml_to_proptree},
1607 { "savexml", do_save_xml_from_proptree },
1608 { "xmlhttprequest", do_load_xml_from_url },
1609 { "press-cockpit-button", do_press_cockpit_button },
1610 { "release-cockpit-button", do_release_cockpit_button },
1611 { "dump-scenegraph", do_dump_scene_graph },
1612 { "dump-terrainbranch", do_dump_terrain_branch },
1613 { "print-visible-scene", do_print_visible_scene_info },
1614 { "reload-shaders", do_reload_shaders },
1615 { "reload-materials", do_materials_reload },
1617 { "profiler-start", do_profiler_start },
1618 { "profiler-stop", do_profiler_stop },
1620 { 0, 0 } // zero-terminated
1625 * Initialize the default built-in commands.
1627 * Other commands may be added by other parts of the application.
1632 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1633 for (int i = 0; built_ins[i].name != 0; i++) {
1634 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1635 globals->get_commands()->addCommand(built_ins[i].name,
1636 built_ins[i].command);
1639 typedef bool (*dummy)();
1640 fgTie( "/command/view/next", dummy(0), do_view_next );
1641 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1643 globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1644 bool(FG_HAVE_GPERFTOOLS) );
1647 // end of fg_commands.cxx