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 <Cockpit/panel.hxx>
30 #include <Cockpit/panel_io.hxx>
31 #include <FDM/flight.hxx>
33 #include <GUI/new_gui.hxx>
34 #include <GUI/dialog.hxx>
35 #include <Aircraft/replay.hxx>
36 #include <Scenery/scenery.hxx>
37 #include <Scripting/NasalSys.hxx>
38 #include <Sound/sample_queue.hxx>
39 #include <Airports/xmlloader.hxx>
40 #include <Network/HTTPClient.hxx>
41 #include <Viewer/viewmgr.hxx>
42 #include <Viewer/viewer.hxx>
43 #include <Environment/presets.hxx>
45 #include "fg_init.hxx"
48 #include "fg_commands.hxx"
49 #include "fg_props.hxx"
50 #include "globals.hxx"
55 #include <boost/scoped_array.hpp>
63 ////////////////////////////////////////////////////////////////////////
64 // Static helper functions.
65 ////////////////////////////////////////////////////////////////////////
68 static inline SGPropertyNode *
69 get_prop (const SGPropertyNode * arg)
71 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
74 static inline SGPropertyNode *
75 get_prop2 (const SGPropertyNode * arg)
77 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
82 * Get a double value and split it as required.
85 split_value (double full_value, const char * mask,
86 double * unmodifiable, double * modifiable)
88 if (!strcmp("integer", mask)) {
89 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
90 *unmodifiable = full_value - *modifiable;
91 } else if (!strcmp("decimal", mask)) {
92 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
93 *modifiable = full_value - *unmodifiable;
95 if (strcmp("all", mask))
96 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
97 << " assuming 'all'");
99 *modifiable = full_value;
105 * Clamp or wrap a value as specified.
108 limit_value (double * value, const SGPropertyNode * arg)
110 const SGPropertyNode * min_node = arg->getChild("min");
111 const SGPropertyNode * max_node = arg->getChild("max");
113 bool wrap = arg->getBoolValue("wrap");
115 if (min_node == 0 || max_node == 0)
118 if (wrap) { // wrap such that min <= x < max
119 double min_val = min_node->getDoubleValue();
120 double max_val = max_node->getDoubleValue();
121 double resolution = arg->getDoubleValue("resolution");
122 if (resolution > 0.0) {
123 // snap to (min + N*resolution), taking special care to handle imprecision
124 int n = (int)floor((*value - min_val) / resolution + 0.5);
125 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
126 SG_NORMALIZE_RANGE(n, 0, steps);
127 *value = min_val + resolution * n;
129 // plain circular wrapping
130 SG_NORMALIZE_RANGE(*value, min_val, max_val);
132 } else { // clamp such that min <= x <= max
133 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
134 *value = min_node->getDoubleValue();
135 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
136 *value = max_node->getDoubleValue();
141 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
143 switch (value1->getType()) {
144 case simgear::props::BOOL:
145 return (value1->getBoolValue() == value2->getBoolValue());
146 case simgear::props::INT:
147 return (value1->getIntValue() == value2->getIntValue());
148 case simgear::props::LONG:
149 return (value1->getLongValue() == value2->getLongValue());
150 case simgear::props::FLOAT:
151 return (value1->getFloatValue() == value2->getFloatValue());
152 case simgear::props::DOUBLE:
153 return (value1->getDoubleValue() == value2->getDoubleValue());
155 return !strcmp(value1->getStringValue(), value2->getStringValue());
161 ////////////////////////////////////////////////////////////////////////
162 // Command implementations.
163 ////////////////////////////////////////////////////////////////////////
167 * Built-in command: do nothing.
170 do_null (const SGPropertyNode * arg)
176 * Built-in command: run a Nasal script.
179 do_nasal (const SGPropertyNode * arg)
181 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
185 * Built-in command: exit FlightGear.
187 * status: the exit status to return to the operating system (defaults to 0)
190 do_exit (const SGPropertyNode * arg)
192 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
193 fgSetBool("/sim/signals/exit", true);
194 globals->saveUserSettings();
195 fgOSExit(arg->getIntValue("status", 0));
201 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
204 do_reset (const SGPropertyNode * arg)
206 fgReInitSubsystems();
212 * Built-in command: reinitialize one or more subsystems.
214 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
215 * none is specified, reinitialize all of them.
218 do_reinit (const SGPropertyNode * arg)
222 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
223 if (subsystems.size() == 0) {
224 globals->get_subsystem_mgr()->reinit();
226 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
227 const char * name = subsystems[i]->getStringValue();
228 SGSubsystem * subsystem = globals->get_subsystem(name);
229 if (subsystem == 0) {
231 SG_LOG( SG_GENERAL, SG_ALERT,
232 "Subsystem " << name << " not found" );
239 globals->get_event_mgr()->reinit();
246 // these routines look useful ??? but are never used in the code ???
250 * Built-in command: suspend one or more subsystems.
252 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
255 do_suspend (const SGPropertyNode * arg)
259 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
260 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
261 const char * name = subsystems[i]->getStringValue();
262 SGSubsystem * subsystem = globals->get_subsystem(name);
263 if (subsystem == 0) {
265 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
267 subsystem->suspend();
274 * Built-in command: suspend one or more subsystems.
276 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
279 do_resume (const SGPropertyNode * arg)
283 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
284 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
285 const char * name = subsystems[i]->getStringValue();
286 SGSubsystem * subsystem = globals->get_subsystem(name);
287 if (subsystem == 0) {
289 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
300 * Built-in command: replay the FDR buffer
303 do_replay (const SGPropertyNode * arg)
305 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
310 * Built-in command: pause/unpause the sim
313 do_pause (const SGPropertyNode * arg)
315 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
316 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
322 fgSetBool("/sim/freeze/master",!paused);
323 fgSetBool("/sim/freeze/clock",!paused);
329 * Built-in command: load flight.
331 * file (optional): the name of the file to load (relative to current
332 * directory). Defaults to "fgfs.sav"
335 do_load (const SGPropertyNode * arg)
337 string file = arg->getStringValue("file", "fgfs.sav");
338 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
341 if (!fgValidatePath(file.c_str(), false)) {
342 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
343 "(unauthorized access)");
347 ifstream input(file.c_str());
348 if (input.good() && fgLoadFlight(input)) {
350 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
353 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
360 * Built-in command: save flight.
362 * file (optional): the name of the file to save (relative to the
363 * current directory). Defaults to "fgfs.sav".
366 do_save (const SGPropertyNode * arg)
368 string file = arg->getStringValue("file", "fgfs.sav");
369 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
372 if (!fgValidatePath(file.c_str(), false)) {
373 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
374 "(unauthorized access)");
378 bool write_all = arg->getBoolValue("write-all", false);
379 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
380 ofstream output(file.c_str());
381 if (output.good() && fgSaveFlight(output, write_all)) {
383 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
386 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
393 * Built-in command: (re)load the panel.
395 * path (optional): the file name to load the panel from
396 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
397 * and if that's unspecified, to "Panels/Default/default.xml".
400 do_panel_load (const SGPropertyNode * arg)
403 arg->getStringValue("path", fgGetString("/sim/panel/path"));
404 if (panel_path.empty()) {
408 FGPanel * new_panel = fgReadPanel(panel_path);
409 if (new_panel == 0) {
410 SG_LOG(SG_INPUT, SG_ALERT,
411 "Error reading new panel from " << panel_path);
414 SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
415 globals->get_current_panel()->unbind();
416 globals->set_current_panel( new_panel );
417 globals->get_current_panel()->bind();
423 * Built-in command: pass a mouse click to the panel.
425 * button: the mouse button number, zero-based.
426 * is-down: true if the button is down, false if it is up.
427 * x-pos: the x position of the mouse click.
428 * y-pos: the y position of the mouse click.
431 do_panel_mouse_click (const SGPropertyNode * arg)
433 if (globals->get_current_panel() != 0)
434 return globals->get_current_panel()
435 ->doMouseAction(arg->getIntValue("button"),
436 arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
437 arg->getIntValue("x-pos"),
438 arg->getIntValue("y-pos"));
445 * Built-in command: (re)load preferences.
447 * path (optional): the file name to load the panel from (relative
448 * to FG_ROOT). Defaults to "preferences.xml".
451 do_preferences_load (const SGPropertyNode * arg)
454 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
455 globals->get_props());
456 } catch (const sg_exception &e) {
457 guiErrorMessage("Error reading global preferences: ", e);
460 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
467 globals->get_current_view()->setHeadingOffset_deg(0.0);
468 globals->get_viewmgr()->next_view();
474 globals->get_current_view()->setHeadingOffset_deg(0.0);
475 globals->get_viewmgr()->prev_view();
479 * Built-in command: cycle view.
482 do_view_cycle (const SGPropertyNode * arg)
484 globals->get_current_view()->setHeadingOffset_deg(0.0);
485 globals->get_viewmgr()->next_view();
490 * Built-in command: capture screen.
493 do_screen_capture (const SGPropertyNode * arg)
495 return fgDumpSnapShot();
499 do_reload_shaders (const SGPropertyNode*)
501 simgear::reload_shaders();
506 do_dump_scene_graph (const SGPropertyNode*)
513 do_dump_terrain_branch (const SGPropertyNode*)
515 fgDumpTerrainBranch();
517 double lon_deg = fgGetDouble("/position/longitude-deg");
518 double lat_deg = fgGetDouble("/position/latitude-deg");
519 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
520 SGVec3d zero = SGVec3d::fromGeod(geodPos);
522 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
523 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
524 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
530 do_print_visible_scene_info(const SGPropertyNode*)
532 fgPrintVisibleSceneInfoCommand();
537 * Built-in command: hires capture screen.
540 do_hires_screen_capture (const SGPropertyNode * arg)
548 * Reload the tile cache.
551 do_tile_cache_reload (const SGPropertyNode * arg)
553 static const SGPropertyNode *master_freeze
554 = fgGetNode("/sim/freeze/master");
555 bool freeze = master_freeze->getBoolValue();
556 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
558 fgSetBool("/sim/freeze/master", true);
561 globals->get_subsystem("tile-manager")->reinit();
564 fgSetBool("/sim/freeze/master", false);
571 These do_set_(some-environment-parameters) are deprecated and no longer
572 useful/functional - Torsten Dreyer, January 2011
574 * Set the sea level outside air temperature and assigning that to all
575 * boundary and aloft environment layers.
578 do_set_sea_level_degc ( double temp_sea_level_degc)
580 SGPropertyNode *node, *child;
583 node = fgGetNode( "/environment/config/boundary" );
584 if ( node != NULL ) {
586 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
587 child->setDoubleValue( "temperature-sea-level-degc",
588 temp_sea_level_degc );
594 node = fgGetNode( "/environment/config/aloft" );
595 if ( node != NULL ) {
597 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
598 child->setDoubleValue( "temperature-sea-level-degc",
599 temp_sea_level_degc );
608 do_set_sea_level_degc (const SGPropertyNode * arg)
610 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
615 * Set the outside air temperature at the "current" altitude by first
616 * calculating the corresponding sea level temp, and assigning that to
617 * all boundary and aloft environment layers.
620 do_set_oat_degc (const SGPropertyNode * arg)
622 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
623 // check for an altitude specified in the arguments, otherwise use
624 // current aircraft altitude.
625 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
626 if ( altitude_ft == NULL ) {
627 altitude_ft = fgGetNode("/position/altitude-ft");
630 FGEnvironment dummy; // instantiate a dummy so we can leech a method
631 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
632 dummy.set_temperature_degc( oat_degc );
633 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
637 * Set the sea level outside air dewpoint and assigning that to all
638 * boundary and aloft environment layers.
641 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
644 SGPropertyNode *node, *child;
647 node = fgGetNode( "/environment/config/boundary" );
648 if ( node != NULL ) {
650 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
651 child->setDoubleValue( "dewpoint-sea-level-degc",
652 dewpoint_sea_level_degc );
658 node = fgGetNode( "/environment/config/aloft" );
659 if ( node != NULL ) {
661 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
662 child->setDoubleValue( "dewpoint-sea-level-degc",
663 dewpoint_sea_level_degc );
672 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
674 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
678 * Set the outside air dewpoint at the "current" altitude by first
679 * calculating the corresponding sea level dewpoint, and assigning
680 * that to all boundary and aloft environment layers.
683 do_set_dewpoint_degc (const SGPropertyNode * arg)
685 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
687 // check for an altitude specified in the arguments, otherwise use
688 // current aircraft altitude.
689 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
690 if ( altitude_ft == NULL ) {
691 altitude_ft = fgGetNode("/position/altitude-ft");
694 FGEnvironment dummy; // instantiate a dummy so we can leech a method
695 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
696 dummy.set_dewpoint_degc( dewpoint_degc );
697 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
702 * Built-in command: toggle a bool property value.
704 * property: The name of the property to toggle.
707 do_property_toggle (const SGPropertyNode * arg)
709 SGPropertyNode * prop = get_prop(arg);
710 return prop->setBoolValue(!prop->getBoolValue());
715 * Built-in command: assign a value to a property.
717 * property: the name of the property to assign.
718 * value: the value to assign; or
719 * property[1]: the property to copy from.
722 do_property_assign (const SGPropertyNode * arg)
724 SGPropertyNode * prop = get_prop(arg);
725 const SGPropertyNode * value = arg->getNode("value");
728 return prop->setUnspecifiedValue(value->getStringValue());
731 const SGPropertyNode * prop2 = get_prop2(arg);
733 return prop->setUnspecifiedValue(prop2->getStringValue());
741 * Built-in command: increment or decrement a property value.
743 * If the 'step' argument is present, it will be used; otherwise,
744 * the command uses 'offset' and 'factor', usually from the mouse.
746 * property: the name of the property to increment or decrement.
747 * step: the amount of the increment or decrement (default: 0).
748 * offset: offset from the current setting (used for the mouse; multiplied
750 * factor: scaling amount for the offset (defaults to 1).
751 * min: the minimum allowed value (default: no minimum).
752 * max: the maximum allowed value (default: no maximum).
753 * mask: 'integer' to apply only to the left of the decimal point,
754 * 'decimal' to apply only to the right of the decimal point,
755 * or 'all' to apply to the whole number (the default).
756 * wrap: true if the value should be wrapped when it passes min or max;
757 * both min and max must be present for this to work (default:
761 do_property_adjust (const SGPropertyNode * arg)
763 SGPropertyNode * prop = get_prop(arg);
766 if (arg->hasValue("step"))
767 amount = arg->getDoubleValue("step");
769 amount = (arg->getDoubleValue("factor", 1)
770 * arg->getDoubleValue("offset"));
772 double unmodifiable, modifiable;
773 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
774 &unmodifiable, &modifiable);
775 modifiable += amount;
776 limit_value(&modifiable, arg);
778 prop->setDoubleValue(unmodifiable + modifiable);
785 * Built-in command: multiply a property value.
787 * property: the name of the property to multiply.
788 * factor: the amount by which to multiply.
789 * min: the minimum allowed value (default: no minimum).
790 * max: the maximum allowed value (default: no maximum).
791 * mask: 'integer' to apply only to the left of the decimal point,
792 * 'decimal' to apply only to the right of the decimal point,
793 * or 'all' to apply to the whole number (the default).
794 * wrap: true if the value should be wrapped when it passes min or max;
795 * both min and max must be present for this to work (default:
799 do_property_multiply (const SGPropertyNode * arg)
801 SGPropertyNode * prop = get_prop(arg);
802 double factor = arg->getDoubleValue("factor", 1);
804 double unmodifiable, modifiable;
805 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
806 &unmodifiable, &modifiable);
807 modifiable *= factor;
808 limit_value(&modifiable, arg);
810 prop->setDoubleValue(unmodifiable + modifiable);
817 * Built-in command: swap two property values.
819 * property[0]: the name of the first property.
820 * property[1]: the name of the second property.
823 do_property_swap (const SGPropertyNode * arg)
825 SGPropertyNode * prop1 = get_prop(arg);
826 SGPropertyNode * prop2 = get_prop2(arg);
828 // FIXME: inefficient
829 const string & tmp = prop1->getStringValue();
830 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
831 prop2->setUnspecifiedValue(tmp.c_str()));
836 * Built-in command: Set a property to an axis or other moving input.
838 * property: the name of the property to set.
839 * setting: the current input setting, usually between -1.0 and 1.0.
840 * offset: the offset to shift by, before applying the factor.
841 * factor: the factor to multiply by (use negative to reverse).
844 do_property_scale (const SGPropertyNode * arg)
846 SGPropertyNode * prop = get_prop(arg);
847 double setting = arg->getDoubleValue("setting");
848 double offset = arg->getDoubleValue("offset", 0.0);
849 double factor = arg->getDoubleValue("factor", 1.0);
850 bool squared = arg->getBoolValue("squared", false);
851 int power = arg->getIntValue("power", (squared ? 2 : 1));
853 int sign = (setting < 0 ? -1 : 1);
859 setting = setting * setting * sign;
862 setting = setting * setting * setting;
865 setting = setting * setting * setting * setting * sign;
868 setting = pow(setting, power);
869 if ((power % 2) == 0)
874 return prop->setDoubleValue((setting + offset) * factor);
879 * Built-in command: cycle a property through a set of values.
881 * If the current value isn't in the list, the cycle will
882 * (re)start from the beginning.
884 * property: the name of the property to cycle.
885 * value[*]: the list of values to cycle through.
888 do_property_cycle (const SGPropertyNode * arg)
890 SGPropertyNode * prop = get_prop(arg);
891 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
893 int nSelections = values.size();
895 if (nSelections < 1) {
896 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
900 // Try to find the current selection
901 for (int i = 0; i < nSelections; i++) {
902 if (compare_values(prop, values[i])) {
908 // Default or wrap to the first selection
909 if (selection < 0 || selection >= nSelections)
912 prop->setUnspecifiedValue(values[selection]->getStringValue());
918 * Built-in command: randomize a numeric property value.
920 * property: the name of the property value to randomize.
921 * min: the minimum allowed value.
922 * max: the maximum allowed value.
925 do_property_randomize (const SGPropertyNode * arg)
927 SGPropertyNode * prop = get_prop(arg);
928 double min = arg->getDoubleValue("min", DBL_MIN);
929 double max = arg->getDoubleValue("max", DBL_MAX);
930 prop->setDoubleValue(sg_random() * (max - min) + min);
935 * Built-in command: interpolate a property value over time
937 * property: the name of the property value to interpolate.
938 * value[0..n] any number of constant values to interpolate
939 * time[0..n] time between each value, number of time elements must
940 * match those of value elements
942 * property[1..n] any number of target values taken from named properties
943 * time[0..n] time between each value, number of time elements must
944 * match those of property elements minus one
947 do_property_interpolate (const SGPropertyNode * arg)
949 SGPropertyNode * prop = get_prop(arg);
951 simgear::PropertyList valueNodes = arg->getChildren( "value" );
952 simgear::PropertyList timeNodes = arg->getChildren( "time" );
954 boost::scoped_array<double> value;
955 boost::scoped_array<double> time;
957 if( valueNodes.size() > 0 ) {
959 if( timeNodes.size() != valueNodes.size() )
962 value.reset( new double[valueNodes.size()] );
963 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
964 value[n] = valueNodes[n]->getDoubleValue();
967 valueNodes = arg->getChildren("property");
968 // must have one more property node
969 if( valueNodes.size() - 1 != timeNodes.size() )
972 value.reset( new double[valueNodes.size()-1] );
973 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
974 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
979 time.reset( new double[timeNodes.size()] );
980 for( simgear::PropertyList::size_type n = 0; n < timeNodes.size(); n++ ) {
981 time[n] = timeNodes[n]->getDoubleValue();
984 ((SGInterpolator*)globals->get_subsystem_mgr()
985 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
986 ->interpolate(prop, timeNodes.size(), value.get(), time.get() );
992 * Built-in command: reinit the data logging system based on the
993 * current contents of the /logger tree.
996 do_data_logging_commit (const SGPropertyNode * arg)
998 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1004 * Built-in command: Add a dialog to the GUI system. Does *not*
1005 * display the dialog. The property node should have the same format
1006 * as a dialog XML configuration. It must include:
1008 * name: the name of the GUI dialog for future reference.
1011 do_dialog_new (const SGPropertyNode * arg)
1013 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1015 // Note the casting away of const: this is *real*. Doing a
1016 // "dialog-apply" command later on will mutate this property node.
1017 // I'm not convinced that this isn't the Right Thing though; it
1018 // allows client to create a node, pass it to dialog-new, and get
1019 // the values back from the dialog by reading the same node.
1020 // Perhaps command arguments are not as "const" as they would
1022 gui->newDialog((SGPropertyNode*)arg);
1027 * Built-in command: Show an XML-configured dialog.
1029 * dialog-name: the name of the GUI dialog to display.
1032 do_dialog_show (const SGPropertyNode * arg)
1034 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1035 gui->showDialog(arg->getStringValue("dialog-name"));
1041 * Built-in Command: Hide the active XML-configured dialog.
1044 do_dialog_close (const SGPropertyNode * arg)
1046 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1047 if(arg->hasValue("dialog-name"))
1048 return gui->closeDialog(arg->getStringValue("dialog-name"));
1049 return gui->closeActiveDialog();
1054 * Update a value in the active XML-configured dialog.
1056 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1059 do_dialog_update (const SGPropertyNode * arg)
1061 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1063 if (arg->hasValue("dialog-name"))
1064 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1066 dialog = gui->getActiveDialog();
1069 dialog->updateValues(arg->getStringValue("object-name"));
1077 do_open_browser (const SGPropertyNode * arg)
1080 if (arg->hasValue("path"))
1081 path = arg->getStringValue("path");
1083 if (arg->hasValue("url"))
1084 path = arg->getStringValue("url");
1088 return openBrowser(path);
1092 * Apply a value in the active XML-configured dialog.
1094 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1097 do_dialog_apply (const SGPropertyNode * arg)
1099 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1101 if (arg->hasValue("dialog-name"))
1102 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1104 dialog = gui->getActiveDialog();
1107 dialog->applyValues(arg->getStringValue("object-name"));
1116 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1120 do_gui_redraw (const SGPropertyNode * arg)
1122 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1129 * Adds model to the scenery. The path to the added branch (/models/model[*])
1130 * is returned in property "property".
1133 do_add_model (const SGPropertyNode * arg)
1135 SGPropertyNode * model = fgGetNode("models", true);
1137 for (i = 0; model->hasChild("model",i); i++);
1138 model = model->getChild("model", i, true);
1139 copyProperties(arg, model);
1140 if (model->hasValue("elevation-m"))
1141 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1142 * SG_METER_TO_FEET);
1143 model->getNode("load", true);
1144 model->removeChildren("load");
1145 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1151 * Set mouse cursor coordinates and cursor shape.
1154 do_set_cursor (const SGPropertyNode * arg)
1156 if (arg->hasValue("x") || arg->hasValue("y")) {
1157 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1158 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1159 int x = arg->getIntValue("x", mx->getIntValue());
1160 int y = arg->getIntValue("y", my->getIntValue());
1166 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1167 if (cursor->getType() != simgear::props::NONE)
1168 fgSetMouseCursor(cursor->getIntValue());
1170 cursor->setIntValue(fgGetMouseCursor());
1176 * Built-in command: play an audio message (i.e. a wav file) This is
1177 * fire and forget. Call this once per message and it will get dumped
1178 * into a queue. Messages are played sequentially so they do not
1182 do_play_audio_sample (const SGPropertyNode * arg)
1184 string path = arg->getStringValue("path");
1185 string file = arg->getStringValue("file");
1186 float volume = arg->getFloatValue("volume");
1187 // cout << "playing " << path << " / " << file << endl;
1189 static FGSampleQueue *queue = 0;
1191 SGSoundMgr *smgr = globals->get_soundmgr();
1192 queue = new FGSampleQueue(smgr, "chatter");
1193 queue->tie_to_listener();
1196 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1197 msg->set_volume( volume );
1202 } catch (const sg_io_exception&) {
1203 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1204 "failed to load" << path << '/' << file);
1210 * Built-in command: commit presets (read from in /sim/presets/)
1213 do_presets_commit (const SGPropertyNode * arg)
1215 if (fgGetBool("/sim/initialized", false)) {
1216 fgReInitSubsystems();
1218 // Nasal can trigger this during initial init, which confuses
1219 // the logic in ReInitSubsystems, since initial state has not been
1220 // saved at that time. Short-circuit everything here.
1228 * Built-in command: set log level (0 ... 7)
1231 do_log_level (const SGPropertyNode * arg)
1233 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1240 do_decrease_visibility (const SGPropertyNode * arg)
1242 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1247 do_increase_visibility (const SGPropertyNode * arg)
1249 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1254 * An fgcommand to allow loading of xml files via nasal,
1255 * the xml file's structure will be made available within
1256 * a property tree node defined under argument "targetnode",
1257 * or in the given argument tree under "data" otherwise.
1259 * @param filename a string to hold the complete path & filename of an XML file
1260 * @param targetnode a string pointing to a location within the property tree
1261 * where to store the parsed XML file. If <targetnode> is undefined, then the
1262 * file contents are stored under a node <data> in the argument tree.
1266 do_load_xml_to_proptree(const SGPropertyNode * arg)
1268 SGPath file(arg->getStringValue("filename"));
1269 if (file.str().empty())
1272 if (file.extension() != "xml")
1273 file.concat(".xml");
1275 std::string icao = arg->getStringValue("icao");
1277 if (file.isRelative()) {
1278 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1279 if (!absPath.isNull())
1283 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1284 << file.str() << "'.");
1289 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1290 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1291 << file.str() << " at ICAO:" << icao);
1296 if (!fgValidatePath(file.c_str(), false)) {
1297 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1298 "(unauthorized access)");
1302 SGPropertyNode *targetnode;
1303 if (arg->hasValue("targetnode"))
1304 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1306 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1309 readProperties(file.c_str(), targetnode, true);
1310 } catch (const sg_exception &e) {
1311 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1318 class RemoteXMLRequest : public simgear::HTTP::Request
1321 SGPropertyNode_ptr _complete;
1322 SGPropertyNode_ptr _status;
1323 SGPropertyNode_ptr _failed;
1324 SGPropertyNode_ptr _target;
1327 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1328 simgear::HTTP::Request(url),
1333 void setCompletionProp(SGPropertyNode_ptr p)
1338 void setStatusProp(SGPropertyNode_ptr p)
1343 void setFailedProp(SGPropertyNode_ptr p)
1348 virtual void gotBodyData(const char* s, int n)
1350 propsData += string(s, n);
1353 virtual void responseComplete()
1355 int response = responseCode();
1356 bool failed = false;
1357 if (response == 200) {
1359 const char* buffer = propsData.c_str();
1360 readProperties(buffer, propsData.size(), _target, true);
1361 } catch (const sg_exception &e) {
1362 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1364 response = 406; // 'not acceptable', anything better?
1369 // now the response data is output, signal Nasal / listeners
1370 if (_complete) _complete->setBoolValue(true);
1371 if (_status) _status->setIntValue(response);
1372 if (_failed) _failed->setBoolValue(failed);
1378 do_load_xml_from_url(const SGPropertyNode * arg)
1380 std::string url(arg->getStringValue("url"));
1384 SGPropertyNode *targetnode;
1385 if (arg->hasValue("targetnode"))
1386 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1388 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1390 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1392 // connect up optional reporting properties
1393 if (arg->hasValue("complete"))
1394 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1395 if (arg->hasValue("failure"))
1396 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1397 if (arg->hasValue("status"))
1398 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1400 FGHTTPClient::instance()->makeRequest(req);
1407 * An fgcommand to allow saving of xml files via nasal,
1408 * the file's structure will be determined based on what's
1409 * encountered in the passed (source) property tree node
1411 * @param filename a string to hold the complete path & filename of the (new)
1413 * @param sourcenode a string pointing to a location within the property tree
1414 * where to find the nodes that should be written recursively into an XML file
1415 * @param data if no sourcenode is given, then the file contents are taken from
1416 * the argument tree's "data" node.
1420 do_save_xml_from_proptree(const SGPropertyNode * arg)
1422 SGPath file(arg->getStringValue("filename"));
1423 if (file.str().empty())
1426 if (file.extension() != "xml")
1427 file.concat(".xml");
1429 if (!fgValidatePath(file.c_str(), true)) {
1430 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1431 "(unauthorized access)");
1435 SGPropertyNode *sourcenode;
1436 if (arg->hasValue("sourcenode"))
1437 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1438 else if (arg->getNode("data", false))
1439 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1444 writeProperties (file.c_str(), sourcenode, true);
1445 } catch (const sg_exception &e) {
1446 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1454 do_press_cockpit_button (const SGPropertyNode *arg)
1456 const char *prefix = arg->getStringValue("prefix");
1458 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1461 string prop = string(prefix) + "-button";
1464 if (arg->getBoolValue("latching"))
1465 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1469 fgSetDouble(prop.c_str(), value);
1470 fgSetBool(arg->getStringValue("discrete"), value > 0);
1476 do_release_cockpit_button (const SGPropertyNode *arg)
1478 const char *prefix = arg->getStringValue("prefix");
1480 if (arg->getBoolValue("guarded")) {
1481 string prop = string(prefix) + "-guard";
1482 if (fgGetDouble(prop.c_str()) < 1) {
1483 fgSetDouble(prop.c_str(), 1);
1488 if (! arg->getBoolValue("latching")) {
1489 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1490 fgSetBool(arg->getStringValue("discrete"), false);
1496 ////////////////////////////////////////////////////////////////////////
1498 ////////////////////////////////////////////////////////////////////////
1502 * Table of built-in commands.
1504 * New commands do not have to be added here; any module in the application
1505 * can add a new command using globals->get_commands()->addCommand(...).
1509 SGCommandMgr::command_t command;
1511 { "null", do_null },
1512 { "nasal", do_nasal },
1513 { "exit", do_exit },
1514 { "reset", do_reset },
1515 { "reinit", do_reinit },
1516 { "suspend", do_reinit },
1517 { "resume", do_reinit },
1518 { "pause", do_pause },
1519 { "load", do_load },
1520 { "save", do_save },
1521 { "panel-load", do_panel_load },
1522 { "panel-mouse-click", do_panel_mouse_click },
1523 { "preferences-load", do_preferences_load },
1524 { "view-cycle", do_view_cycle },
1525 { "screen-capture", do_screen_capture },
1526 { "hires-screen-capture", do_hires_screen_capture },
1527 { "tile-cache-reload", do_tile_cache_reload },
1529 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1530 { "set-outside-air-temp-degc", do_set_oat_degc },
1531 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1532 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1534 { "property-toggle", do_property_toggle },
1535 { "property-assign", do_property_assign },
1536 { "property-adjust", do_property_adjust },
1537 { "property-multiply", do_property_multiply },
1538 { "property-swap", do_property_swap },
1539 { "property-scale", do_property_scale },
1540 { "property-cycle", do_property_cycle },
1541 { "property-randomize", do_property_randomize },
1542 { "property-interpolate", do_property_interpolate },
1543 { "data-logging-commit", do_data_logging_commit },
1544 { "dialog-new", do_dialog_new },
1545 { "dialog-show", do_dialog_show },
1546 { "dialog-close", do_dialog_close },
1547 { "dialog-update", do_dialog_update },
1548 { "dialog-apply", do_dialog_apply },
1549 { "open-browser", do_open_browser },
1550 { "gui-redraw", do_gui_redraw },
1551 { "add-model", do_add_model },
1552 { "set-cursor", do_set_cursor },
1553 { "play-audio-sample", do_play_audio_sample },
1554 { "presets-commit", do_presets_commit },
1555 { "log-level", do_log_level },
1556 { "replay", do_replay },
1558 { "decrease-visibility", do_decrease_visibility },
1559 { "increase-visibility", do_increase_visibility },
1561 { "loadxml", do_load_xml_to_proptree},
1562 { "savexml", do_save_xml_from_proptree },
1563 { "xmlhttprequest", do_load_xml_from_url },
1564 { "press-cockpit-button", do_press_cockpit_button },
1565 { "release-cockpit-button", do_release_cockpit_button },
1566 { "dump-scenegraph", do_dump_scene_graph },
1567 { "dump-terrainbranch", do_dump_terrain_branch },
1568 { "print-visible-scene", do_print_visible_scene_info },
1569 { "reload-shaders", do_reload_shaders },
1571 { 0, 0 } // zero-terminated
1576 * Initialize the default built-in commands.
1578 * Other commands may be added by other parts of the application.
1583 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1584 for (int i = 0; built_ins[i].name != 0; i++) {
1585 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1586 globals->get_commands()->addCommand(built_ins[i].name,
1587 built_ins[i].command);
1590 typedef bool (*dummy)();
1591 fgTie( "/command/view/next", dummy(0), do_view_next );
1592 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1595 // end of fg_commands.cxx