1 // fg_commands.cxx - internal FGFS commands.
7 #include <string.h> // strcmp()
9 #include <simgear/compiler.h>
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/misc/interpolator.hxx>
27 #include <simgear/io/HTTPRequest.hxx>
29 #include <FDM/flight.hxx>
31 #include <GUI/new_gui.hxx>
32 #include <GUI/dialog.hxx>
33 #include <Aircraft/replay.hxx>
34 #include <Scenery/scenery.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/sample_queue.hxx>
37 #include <Airports/xmlloader.hxx>
38 #include <Network/HTTPClient.hxx>
39 #include <Viewer/viewmgr.hxx>
40 #include <Viewer/viewer.hxx>
41 #include <Environment/presets.hxx>
43 #include "fg_init.hxx"
46 #include "fg_commands.hxx"
47 #include "fg_props.hxx"
48 #include "globals.hxx"
53 #include <boost/scoped_array.hpp>
61 ////////////////////////////////////////////////////////////////////////
62 // Static helper functions.
63 ////////////////////////////////////////////////////////////////////////
66 static inline SGPropertyNode *
67 get_prop (const SGPropertyNode * arg)
69 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
72 static inline SGPropertyNode *
73 get_prop2 (const SGPropertyNode * arg)
75 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
80 * Get a double value and split it as required.
83 split_value (double full_value, const char * mask,
84 double * unmodifiable, double * modifiable)
86 if (!strcmp("integer", mask)) {
87 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
88 *unmodifiable = full_value - *modifiable;
89 } else if (!strcmp("decimal", mask)) {
90 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
91 *modifiable = full_value - *unmodifiable;
93 if (strcmp("all", mask))
94 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
95 << " assuming 'all'");
97 *modifiable = full_value;
103 * Clamp or wrap a value as specified.
106 limit_value (double * value, const SGPropertyNode * arg)
108 const SGPropertyNode * min_node = arg->getChild("min");
109 const SGPropertyNode * max_node = arg->getChild("max");
111 bool wrap = arg->getBoolValue("wrap");
113 if (min_node == 0 || max_node == 0)
116 if (wrap) { // wrap such that min <= x < max
117 double min_val = min_node->getDoubleValue();
118 double max_val = max_node->getDoubleValue();
119 double resolution = arg->getDoubleValue("resolution");
120 if (resolution > 0.0) {
121 // snap to (min + N*resolution), taking special care to handle imprecision
122 int n = (int)floor((*value - min_val) / resolution + 0.5);
123 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
124 SG_NORMALIZE_RANGE(n, 0, steps);
125 *value = min_val + resolution * n;
127 // plain circular wrapping
128 SG_NORMALIZE_RANGE(*value, min_val, max_val);
130 } else { // clamp such that min <= x <= max
131 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
132 *value = min_node->getDoubleValue();
133 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
134 *value = max_node->getDoubleValue();
139 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
141 switch (value1->getType()) {
142 case simgear::props::BOOL:
143 return (value1->getBoolValue() == value2->getBoolValue());
144 case simgear::props::INT:
145 return (value1->getIntValue() == value2->getIntValue());
146 case simgear::props::LONG:
147 return (value1->getLongValue() == value2->getLongValue());
148 case simgear::props::FLOAT:
149 return (value1->getFloatValue() == value2->getFloatValue());
150 case simgear::props::DOUBLE:
151 return (value1->getDoubleValue() == value2->getDoubleValue());
153 return !strcmp(value1->getStringValue(), value2->getStringValue());
159 ////////////////////////////////////////////////////////////////////////
160 // Command implementations.
161 ////////////////////////////////////////////////////////////////////////
165 * Built-in command: do nothing.
168 do_null (const SGPropertyNode * arg)
174 * Built-in command: run a Nasal script.
177 do_nasal (const SGPropertyNode * arg)
179 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
183 * Built-in command: exit FlightGear.
185 * status: the exit status to return to the operating system (defaults to 0)
188 do_exit (const SGPropertyNode * arg)
190 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
191 fgSetBool("/sim/signals/exit", true);
192 globals->saveUserSettings();
193 fgOSExit(arg->getIntValue("status", 0));
199 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
202 do_reset (const SGPropertyNode * arg)
204 fgReInitSubsystems();
210 * Built-in command: reinitialize one or more subsystems.
212 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
213 * none is specified, reinitialize all of them.
216 do_reinit (const SGPropertyNode * arg)
220 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
221 if (subsystems.size() == 0) {
222 globals->get_subsystem_mgr()->reinit();
224 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
225 const char * name = subsystems[i]->getStringValue();
226 SGSubsystem * subsystem = globals->get_subsystem(name);
227 if (subsystem == 0) {
229 SG_LOG( SG_GENERAL, SG_ALERT,
230 "Subsystem " << name << " not found" );
237 globals->get_event_mgr()->reinit();
244 // these routines look useful ??? but are never used in the code ???
248 * Built-in command: suspend one or more subsystems.
250 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
253 do_suspend (const SGPropertyNode * arg)
257 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
258 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
259 const char * name = subsystems[i]->getStringValue();
260 SGSubsystem * subsystem = globals->get_subsystem(name);
261 if (subsystem == 0) {
263 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
265 subsystem->suspend();
272 * Built-in command: suspend one or more subsystems.
274 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
277 do_resume (const SGPropertyNode * arg)
281 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
282 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
283 const char * name = subsystems[i]->getStringValue();
284 SGSubsystem * subsystem = globals->get_subsystem(name);
285 if (subsystem == 0) {
287 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
298 * Built-in command: replay the FDR buffer
301 do_replay (const SGPropertyNode * arg)
303 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
308 * Built-in command: pause/unpause the sim
311 do_pause (const SGPropertyNode * arg)
313 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
314 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
320 fgSetBool("/sim/freeze/master",!paused);
321 fgSetBool("/sim/freeze/clock",!paused);
327 * Built-in command: load flight.
329 * file (optional): the name of the file to load (relative to current
330 * directory). Defaults to "fgfs.sav"
333 do_load (const SGPropertyNode * arg)
335 string file = arg->getStringValue("file", "fgfs.sav");
336 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
339 if (!fgValidatePath(file.c_str(), false)) {
340 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
341 "(unauthorized access)");
345 ifstream input(file.c_str());
346 if (input.good() && fgLoadFlight(input)) {
348 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
351 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
358 * Built-in command: save flight.
360 * file (optional): the name of the file to save (relative to the
361 * current directory). Defaults to "fgfs.sav".
364 do_save (const SGPropertyNode * arg)
366 string file = arg->getStringValue("file", "fgfs.sav");
367 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
370 if (!fgValidatePath(file.c_str(), false)) {
371 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
372 "(unauthorized access)");
376 bool write_all = arg->getBoolValue("write-all", false);
377 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
378 ofstream output(file.c_str());
379 if (output.good() && fgSaveFlight(output, write_all)) {
381 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
384 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
391 * Built-in command: (re)load the panel.
393 * path (optional): the file name to load the panel from
394 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
395 * and if that's unspecified, to "Panels/Default/default.xml".
398 do_panel_load (const SGPropertyNode * arg)
400 string panel_path = arg->getStringValue("path");
401 if (!panel_path.empty()) {
402 // write to the standard property, which will force a load
403 fgSetString("/sim/panel/path", panel_path.c_str());
410 * Built-in command: (re)load preferences.
412 * path (optional): the file name to load the panel from (relative
413 * to FG_ROOT). Defaults to "preferences.xml".
416 do_preferences_load (const SGPropertyNode * arg)
419 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
420 globals->get_props());
421 } catch (const sg_exception &e) {
422 guiErrorMessage("Error reading global preferences: ", e);
425 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
432 globals->get_current_view()->setHeadingOffset_deg(0.0);
433 globals->get_viewmgr()->next_view();
439 globals->get_current_view()->setHeadingOffset_deg(0.0);
440 globals->get_viewmgr()->prev_view();
444 * Built-in command: cycle view.
447 do_view_cycle (const SGPropertyNode * arg)
449 globals->get_current_view()->setHeadingOffset_deg(0.0);
450 globals->get_viewmgr()->next_view();
455 * Built-in command: capture screen.
458 do_screen_capture (const SGPropertyNode * arg)
460 return fgDumpSnapShot();
464 do_reload_shaders (const SGPropertyNode*)
466 simgear::reload_shaders();
471 do_dump_scene_graph (const SGPropertyNode*)
478 do_dump_terrain_branch (const SGPropertyNode*)
480 fgDumpTerrainBranch();
482 double lon_deg = fgGetDouble("/position/longitude-deg");
483 double lat_deg = fgGetDouble("/position/latitude-deg");
484 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
485 SGVec3d zero = SGVec3d::fromGeod(geodPos);
487 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
488 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
489 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
495 do_print_visible_scene_info(const SGPropertyNode*)
497 fgPrintVisibleSceneInfoCommand();
502 * Built-in command: hires capture screen.
505 do_hires_screen_capture (const SGPropertyNode * arg)
513 * Reload the tile cache.
516 do_tile_cache_reload (const SGPropertyNode * arg)
518 static const SGPropertyNode *master_freeze
519 = fgGetNode("/sim/freeze/master");
520 bool freeze = master_freeze->getBoolValue();
521 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
523 fgSetBool("/sim/freeze/master", true);
526 globals->get_subsystem("tile-manager")->reinit();
529 fgSetBool("/sim/freeze/master", false);
535 * Reload the materials definition
538 do_materials_reload (const SGPropertyNode * arg)
540 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
541 SGMaterialLib* new_matlib = new SGMaterialLib;
542 SGPath mpath( globals->get_fg_root() );
543 mpath.append( fgGetString("/sim/rendering/materials-file") );
544 bool loaded = new_matlib->load(globals->get_fg_root(),
546 globals->get_props());
549 SG_LOG( SG_GENERAL, SG_ALERT,
550 "Error loading materials file " << mpath.str() );
554 globals->set_matlib(new_matlib);
560 These do_set_(some-environment-parameters) are deprecated and no longer
561 useful/functional - Torsten Dreyer, January 2011
563 * Set the sea level outside air temperature and assigning that to all
564 * boundary and aloft environment layers.
567 do_set_sea_level_degc ( double temp_sea_level_degc)
569 SGPropertyNode *node, *child;
572 node = fgGetNode( "/environment/config/boundary" );
573 if ( node != NULL ) {
575 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
576 child->setDoubleValue( "temperature-sea-level-degc",
577 temp_sea_level_degc );
583 node = fgGetNode( "/environment/config/aloft" );
584 if ( node != NULL ) {
586 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
587 child->setDoubleValue( "temperature-sea-level-degc",
588 temp_sea_level_degc );
597 do_set_sea_level_degc (const SGPropertyNode * arg)
599 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
604 * Set the outside air temperature at the "current" altitude by first
605 * calculating the corresponding sea level temp, and assigning that to
606 * all boundary and aloft environment layers.
609 do_set_oat_degc (const SGPropertyNode * arg)
611 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
612 // check for an altitude specified in the arguments, otherwise use
613 // current aircraft altitude.
614 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
615 if ( altitude_ft == NULL ) {
616 altitude_ft = fgGetNode("/position/altitude-ft");
619 FGEnvironment dummy; // instantiate a dummy so we can leech a method
620 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
621 dummy.set_temperature_degc( oat_degc );
622 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
626 * Set the sea level outside air dewpoint and assigning that to all
627 * boundary and aloft environment layers.
630 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
633 SGPropertyNode *node, *child;
636 node = fgGetNode( "/environment/config/boundary" );
637 if ( node != NULL ) {
639 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
640 child->setDoubleValue( "dewpoint-sea-level-degc",
641 dewpoint_sea_level_degc );
647 node = fgGetNode( "/environment/config/aloft" );
648 if ( node != NULL ) {
650 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
651 child->setDoubleValue( "dewpoint-sea-level-degc",
652 dewpoint_sea_level_degc );
661 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
663 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
667 * Set the outside air dewpoint at the "current" altitude by first
668 * calculating the corresponding sea level dewpoint, and assigning
669 * that to all boundary and aloft environment layers.
672 do_set_dewpoint_degc (const SGPropertyNode * arg)
674 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
676 // check for an altitude specified in the arguments, otherwise use
677 // current aircraft altitude.
678 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
679 if ( altitude_ft == NULL ) {
680 altitude_ft = fgGetNode("/position/altitude-ft");
683 FGEnvironment dummy; // instantiate a dummy so we can leech a method
684 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
685 dummy.set_dewpoint_degc( dewpoint_degc );
686 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
691 * Built-in command: toggle a bool property value.
693 * property: The name of the property to toggle.
696 do_property_toggle (const SGPropertyNode * arg)
698 SGPropertyNode * prop = get_prop(arg);
699 return prop->setBoolValue(!prop->getBoolValue());
704 * Built-in command: assign a value to a property.
706 * property: the name of the property to assign.
707 * value: the value to assign; or
708 * property[1]: the property to copy from.
711 do_property_assign (const SGPropertyNode * arg)
713 SGPropertyNode * prop = get_prop(arg);
714 const SGPropertyNode * value = arg->getNode("value");
717 return prop->setUnspecifiedValue(value->getStringValue());
720 const SGPropertyNode * prop2 = get_prop2(arg);
722 return prop->setUnspecifiedValue(prop2->getStringValue());
730 * Built-in command: increment or decrement a property value.
732 * If the 'step' argument is present, it will be used; otherwise,
733 * the command uses 'offset' and 'factor', usually from the mouse.
735 * property: the name of the property to increment or decrement.
736 * step: the amount of the increment or decrement (default: 0).
737 * offset: offset from the current setting (used for the mouse; multiplied
739 * factor: scaling amount for the offset (defaults to 1).
740 * min: the minimum allowed value (default: no minimum).
741 * max: the maximum allowed value (default: no maximum).
742 * mask: 'integer' to apply only to the left of the decimal point,
743 * 'decimal' to apply only to the right of the decimal point,
744 * or 'all' to apply to the whole number (the default).
745 * wrap: true if the value should be wrapped when it passes min or max;
746 * both min and max must be present for this to work (default:
750 do_property_adjust (const SGPropertyNode * arg)
752 SGPropertyNode * prop = get_prop(arg);
755 if (arg->hasValue("step"))
756 amount = arg->getDoubleValue("step");
758 amount = (arg->getDoubleValue("factor", 1)
759 * arg->getDoubleValue("offset"));
761 double unmodifiable, modifiable;
762 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
763 &unmodifiable, &modifiable);
764 modifiable += amount;
765 limit_value(&modifiable, arg);
767 prop->setDoubleValue(unmodifiable + modifiable);
774 * Built-in command: multiply a property value.
776 * property: the name of the property to multiply.
777 * factor: the amount by which to multiply.
778 * min: the minimum allowed value (default: no minimum).
779 * max: the maximum allowed value (default: no maximum).
780 * mask: 'integer' to apply only to the left of the decimal point,
781 * 'decimal' to apply only to the right of the decimal point,
782 * or 'all' to apply to the whole number (the default).
783 * wrap: true if the value should be wrapped when it passes min or max;
784 * both min and max must be present for this to work (default:
788 do_property_multiply (const SGPropertyNode * arg)
790 SGPropertyNode * prop = get_prop(arg);
791 double factor = arg->getDoubleValue("factor", 1);
793 double unmodifiable, modifiable;
794 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
795 &unmodifiable, &modifiable);
796 modifiable *= factor;
797 limit_value(&modifiable, arg);
799 prop->setDoubleValue(unmodifiable + modifiable);
806 * Built-in command: swap two property values.
808 * property[0]: the name of the first property.
809 * property[1]: the name of the second property.
812 do_property_swap (const SGPropertyNode * arg)
814 SGPropertyNode * prop1 = get_prop(arg);
815 SGPropertyNode * prop2 = get_prop2(arg);
817 // FIXME: inefficient
818 const string & tmp = prop1->getStringValue();
819 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
820 prop2->setUnspecifiedValue(tmp.c_str()));
825 * Built-in command: Set a property to an axis or other moving input.
827 * property: the name of the property to set.
828 * setting: the current input setting, usually between -1.0 and 1.0.
829 * offset: the offset to shift by, before applying the factor.
830 * factor: the factor to multiply by (use negative to reverse).
833 do_property_scale (const SGPropertyNode * arg)
835 SGPropertyNode * prop = get_prop(arg);
836 double setting = arg->getDoubleValue("setting");
837 double offset = arg->getDoubleValue("offset", 0.0);
838 double factor = arg->getDoubleValue("factor", 1.0);
839 bool squared = arg->getBoolValue("squared", false);
840 int power = arg->getIntValue("power", (squared ? 2 : 1));
842 int sign = (setting < 0 ? -1 : 1);
848 setting = setting * setting * sign;
851 setting = setting * setting * setting;
854 setting = setting * setting * setting * setting * sign;
857 setting = pow(setting, power);
858 if ((power % 2) == 0)
863 return prop->setDoubleValue((setting + offset) * factor);
868 * Built-in command: cycle a property through a set of values.
870 * If the current value isn't in the list, the cycle will
871 * (re)start from the beginning.
873 * property: the name of the property to cycle.
874 * value[*]: the list of values to cycle through.
877 do_property_cycle (const SGPropertyNode * arg)
879 SGPropertyNode * prop = get_prop(arg);
880 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
882 int nSelections = values.size();
884 if (nSelections < 1) {
885 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
889 // Try to find the current selection
890 for (int i = 0; i < nSelections; i++) {
891 if (compare_values(prop, values[i])) {
897 // Default or wrap to the first selection
898 if (selection < 0 || selection >= nSelections)
901 prop->setUnspecifiedValue(values[selection]->getStringValue());
907 * Built-in command: randomize a numeric property value.
909 * property: the name of the property value to randomize.
910 * min: the minimum allowed value.
911 * max: the maximum allowed value.
914 do_property_randomize (const SGPropertyNode * arg)
916 SGPropertyNode * prop = get_prop(arg);
917 double min = arg->getDoubleValue("min", DBL_MIN);
918 double max = arg->getDoubleValue("max", DBL_MAX);
919 prop->setDoubleValue(sg_random() * (max - min) + min);
924 * Built-in command: interpolate a property value over time
926 * property: the name of the property value to interpolate.
927 * value[0..n] any number of constant values to interpolate
928 * time/rate[0..n] time between each value, number of time elements must
929 * match those of value elements. Instead of time also rate can
930 * be used which automatically calculates the time to change
931 * the property value at the given speed.
933 * property[1..n] any number of target values taken from named properties
934 * time/rate[0..n] time between each value, number of time elements must
935 * match those of value elements. Instead of time also rate can
936 * be used which automatically calculates the time to change
937 * the property value at the given speed.
940 do_property_interpolate (const SGPropertyNode * arg)
942 SGPropertyNode * prop = get_prop(arg);
944 simgear::PropertyList valueNodes = arg->getChildren( "value" );
945 simgear::PropertyList timeNodes = arg->getChildren( "time" );
946 simgear::PropertyList rateNodes = arg->getChildren( "rate" );
948 if( !timeNodes.empty() && !rateNodes.empty() )
949 // mustn't specify time and rate
952 simgear::PropertyList::size_type num_times = timeNodes.empty()
956 boost::scoped_array<double> value;
957 boost::scoped_array<double> time;
959 if( valueNodes.size() > 0 ) {
961 if( num_times != valueNodes.size() )
964 value.reset( new double[valueNodes.size()] );
965 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
966 value[n] = valueNodes[n]->getDoubleValue();
969 valueNodes = arg->getChildren("property");
970 // must have one more property node
971 if( valueNodes.size() - 1 != num_times )
974 value.reset( new double[valueNodes.size()-1] );
975 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
976 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
981 time.reset( new double[num_times] );
982 if( !timeNodes.empty() ) {
983 for( simgear::PropertyList::size_type n = 0; n < num_times; n++ ) {
984 time[n] = timeNodes[n]->getDoubleValue();
987 for( simgear::PropertyList::size_type n = 0; n < num_times; n++ ) {
988 double delta = value[n]
989 - (n > 0 ? value[n - 1] : prop->getDoubleValue());
990 time[n] = fabs(delta / rateNodes[n]->getDoubleValue());
994 ((SGInterpolator*)globals->get_subsystem_mgr()
995 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
996 ->interpolate(prop, num_times, value.get(), time.get() );
1002 * Built-in command: reinit the data logging system based on the
1003 * current contents of the /logger tree.
1006 do_data_logging_commit (const SGPropertyNode * arg)
1008 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1014 * Built-in command: Add a dialog to the GUI system. Does *not*
1015 * display the dialog. The property node should have the same format
1016 * as a dialog XML configuration. It must include:
1018 * name: the name of the GUI dialog for future reference.
1021 do_dialog_new (const SGPropertyNode * arg)
1023 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1025 // Note the casting away of const: this is *real*. Doing a
1026 // "dialog-apply" command later on will mutate this property node.
1027 // I'm not convinced that this isn't the Right Thing though; it
1028 // allows client to create a node, pass it to dialog-new, and get
1029 // the values back from the dialog by reading the same node.
1030 // Perhaps command arguments are not as "const" as they would
1032 gui->newDialog((SGPropertyNode*)arg);
1037 * Built-in command: Show an XML-configured dialog.
1039 * dialog-name: the name of the GUI dialog to display.
1042 do_dialog_show (const SGPropertyNode * arg)
1044 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1045 gui->showDialog(arg->getStringValue("dialog-name"));
1051 * Built-in Command: Hide the active XML-configured dialog.
1054 do_dialog_close (const SGPropertyNode * arg)
1056 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1057 if(arg->hasValue("dialog-name"))
1058 return gui->closeDialog(arg->getStringValue("dialog-name"));
1059 return gui->closeActiveDialog();
1064 * Update a value in the active XML-configured dialog.
1066 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1069 do_dialog_update (const SGPropertyNode * arg)
1071 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1073 if (arg->hasValue("dialog-name"))
1074 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1076 dialog = gui->getActiveDialog();
1079 dialog->updateValues(arg->getStringValue("object-name"));
1087 do_open_browser (const SGPropertyNode * arg)
1090 if (arg->hasValue("path"))
1091 path = arg->getStringValue("path");
1093 if (arg->hasValue("url"))
1094 path = arg->getStringValue("url");
1098 return openBrowser(path);
1102 * Apply a value in the active XML-configured dialog.
1104 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1107 do_dialog_apply (const SGPropertyNode * arg)
1109 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1111 if (arg->hasValue("dialog-name"))
1112 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1114 dialog = gui->getActiveDialog();
1117 dialog->applyValues(arg->getStringValue("object-name"));
1126 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1130 do_gui_redraw (const SGPropertyNode * arg)
1132 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1139 * Adds model to the scenery. The path to the added branch (/models/model[*])
1140 * is returned in property "property".
1143 do_add_model (const SGPropertyNode * arg)
1145 SGPropertyNode * model = fgGetNode("models", true);
1147 for (i = 0; model->hasChild("model",i); i++);
1148 model = model->getChild("model", i, true);
1149 copyProperties(arg, model);
1150 if (model->hasValue("elevation-m"))
1151 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1152 * SG_METER_TO_FEET);
1153 model->getNode("load", true);
1154 model->removeChildren("load");
1155 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1161 * Set mouse cursor coordinates and cursor shape.
1164 do_set_cursor (const SGPropertyNode * arg)
1166 if (arg->hasValue("x") || arg->hasValue("y")) {
1167 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1168 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1169 int x = arg->getIntValue("x", mx->getIntValue());
1170 int y = arg->getIntValue("y", my->getIntValue());
1176 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1177 if (cursor->getType() != simgear::props::NONE)
1178 fgSetMouseCursor(cursor->getIntValue());
1180 cursor->setIntValue(fgGetMouseCursor());
1186 * Built-in command: play an audio message (i.e. a wav file) This is
1187 * fire and forget. Call this once per message and it will get dumped
1188 * into a queue. Messages are played sequentially so they do not
1192 do_play_audio_sample (const SGPropertyNode * arg)
1194 string path = arg->getStringValue("path");
1195 string file = arg->getStringValue("file");
1196 float volume = arg->getFloatValue("volume");
1197 // cout << "playing " << path << " / " << file << endl;
1199 static FGSampleQueue *queue = 0;
1201 SGSoundMgr *smgr = globals->get_soundmgr();
1202 queue = new FGSampleQueue(smgr, "chatter");
1203 queue->tie_to_listener();
1206 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1207 msg->set_volume( volume );
1212 } catch (const sg_io_exception&) {
1213 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1214 "failed to load" << path << '/' << file);
1220 * Built-in command: commit presets (read from in /sim/presets/)
1223 do_presets_commit (const SGPropertyNode * arg)
1225 if (fgGetBool("/sim/initialized", false)) {
1226 fgReInitSubsystems();
1228 // Nasal can trigger this during initial init, which confuses
1229 // the logic in ReInitSubsystems, since initial state has not been
1230 // saved at that time. Short-circuit everything here.
1238 * Built-in command: set log level (0 ... 7)
1241 do_log_level (const SGPropertyNode * arg)
1243 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1250 do_decrease_visibility (const SGPropertyNode * arg)
1252 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1257 do_increase_visibility (const SGPropertyNode * arg)
1259 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1264 * An fgcommand to allow loading of xml files via nasal,
1265 * the xml file's structure will be made available within
1266 * a property tree node defined under argument "targetnode",
1267 * or in the given argument tree under "data" otherwise.
1269 * @param filename a string to hold the complete path & filename of an XML file
1270 * @param targetnode a string pointing to a location within the property tree
1271 * where to store the parsed XML file. If <targetnode> is undefined, then the
1272 * file contents are stored under a node <data> in the argument tree.
1276 do_load_xml_to_proptree(const SGPropertyNode * arg)
1278 SGPath file(arg->getStringValue("filename"));
1279 if (file.str().empty())
1282 if (file.extension() != "xml")
1283 file.concat(".xml");
1285 std::string icao = arg->getStringValue("icao");
1287 if (file.isRelative()) {
1288 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1289 if (!absPath.isNull())
1293 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1294 << file.str() << "'.");
1299 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1300 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1301 << file.str() << " at ICAO:" << icao);
1306 if (!fgValidatePath(file.c_str(), false)) {
1307 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1308 "(unauthorized access)");
1312 SGPropertyNode *targetnode;
1313 if (arg->hasValue("targetnode"))
1314 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1316 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1319 readProperties(file.c_str(), targetnode, true);
1320 } catch (const sg_exception &e) {
1321 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1328 class RemoteXMLRequest : public simgear::HTTP::Request
1331 SGPropertyNode_ptr _complete;
1332 SGPropertyNode_ptr _status;
1333 SGPropertyNode_ptr _failed;
1334 SGPropertyNode_ptr _target;
1337 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1338 simgear::HTTP::Request(url),
1343 void setCompletionProp(SGPropertyNode_ptr p)
1348 void setStatusProp(SGPropertyNode_ptr p)
1353 void setFailedProp(SGPropertyNode_ptr p)
1358 virtual void gotBodyData(const char* s, int n)
1360 propsData += string(s, n);
1363 virtual void responseComplete()
1365 int response = responseCode();
1366 bool failed = false;
1367 if (response == 200) {
1369 const char* buffer = propsData.c_str();
1370 readProperties(buffer, propsData.size(), _target, true);
1371 } catch (const sg_exception &e) {
1372 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1374 response = 406; // 'not acceptable', anything better?
1379 // now the response data is output, signal Nasal / listeners
1380 if (_complete) _complete->setBoolValue(true);
1381 if (_status) _status->setIntValue(response);
1382 if (_failed) _failed->setBoolValue(failed);
1388 do_load_xml_from_url(const SGPropertyNode * arg)
1390 std::string url(arg->getStringValue("url"));
1394 SGPropertyNode *targetnode;
1395 if (arg->hasValue("targetnode"))
1396 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1398 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1400 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1402 // connect up optional reporting properties
1403 if (arg->hasValue("complete"))
1404 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1405 if (arg->hasValue("failure"))
1406 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1407 if (arg->hasValue("status"))
1408 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1410 FGHTTPClient::instance()->makeRequest(req);
1417 * An fgcommand to allow saving of xml files via nasal,
1418 * the file's structure will be determined based on what's
1419 * encountered in the passed (source) property tree node
1421 * @param filename a string to hold the complete path & filename of the (new)
1423 * @param sourcenode a string pointing to a location within the property tree
1424 * where to find the nodes that should be written recursively into an XML file
1425 * @param data if no sourcenode is given, then the file contents are taken from
1426 * the argument tree's "data" node.
1430 do_save_xml_from_proptree(const SGPropertyNode * arg)
1432 SGPath file(arg->getStringValue("filename"));
1433 if (file.str().empty())
1436 if (file.extension() != "xml")
1437 file.concat(".xml");
1439 if (!fgValidatePath(file.c_str(), true)) {
1440 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1441 "(unauthorized access)");
1445 SGPropertyNode *sourcenode;
1446 if (arg->hasValue("sourcenode"))
1447 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1448 else if (arg->getNode("data", false))
1449 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1454 writeProperties (file.c_str(), sourcenode, true);
1455 } catch (const sg_exception &e) {
1456 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1464 do_press_cockpit_button (const SGPropertyNode *arg)
1466 const char *prefix = arg->getStringValue("prefix");
1468 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1471 string prop = string(prefix) + "-button";
1474 if (arg->getBoolValue("latching"))
1475 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1479 fgSetDouble(prop.c_str(), value);
1480 fgSetBool(arg->getStringValue("discrete"), value > 0);
1486 do_release_cockpit_button (const SGPropertyNode *arg)
1488 const char *prefix = arg->getStringValue("prefix");
1490 if (arg->getBoolValue("guarded")) {
1491 string prop = string(prefix) + "-guard";
1492 if (fgGetDouble(prop.c_str()) < 1) {
1493 fgSetDouble(prop.c_str(), 1);
1498 if (! arg->getBoolValue("latching")) {
1499 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1500 fgSetBool(arg->getStringValue("discrete"), false);
1506 ////////////////////////////////////////////////////////////////////////
1508 ////////////////////////////////////////////////////////////////////////
1512 * Table of built-in commands.
1514 * New commands do not have to be added here; any module in the application
1515 * can add a new command using globals->get_commands()->addCommand(...).
1519 SGCommandMgr::command_t command;
1521 { "null", do_null },
1522 { "nasal", do_nasal },
1523 { "exit", do_exit },
1524 { "reset", do_reset },
1525 { "reinit", do_reinit },
1526 { "suspend", do_reinit },
1527 { "resume", do_reinit },
1528 { "pause", do_pause },
1529 { "load", do_load },
1530 { "save", do_save },
1531 { "panel-load", do_panel_load },
1532 { "preferences-load", do_preferences_load },
1533 { "view-cycle", do_view_cycle },
1534 { "screen-capture", do_screen_capture },
1535 { "hires-screen-capture", do_hires_screen_capture },
1536 { "tile-cache-reload", do_tile_cache_reload },
1538 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1539 { "set-outside-air-temp-degc", do_set_oat_degc },
1540 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1541 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1543 { "property-toggle", do_property_toggle },
1544 { "property-assign", do_property_assign },
1545 { "property-adjust", do_property_adjust },
1546 { "property-multiply", do_property_multiply },
1547 { "property-swap", do_property_swap },
1548 { "property-scale", do_property_scale },
1549 { "property-cycle", do_property_cycle },
1550 { "property-randomize", do_property_randomize },
1551 { "property-interpolate", do_property_interpolate },
1552 { "data-logging-commit", do_data_logging_commit },
1553 { "dialog-new", do_dialog_new },
1554 { "dialog-show", do_dialog_show },
1555 { "dialog-close", do_dialog_close },
1556 { "dialog-update", do_dialog_update },
1557 { "dialog-apply", do_dialog_apply },
1558 { "open-browser", do_open_browser },
1559 { "gui-redraw", do_gui_redraw },
1560 { "add-model", do_add_model },
1561 { "set-cursor", do_set_cursor },
1562 { "play-audio-sample", do_play_audio_sample },
1563 { "presets-commit", do_presets_commit },
1564 { "log-level", do_log_level },
1565 { "replay", do_replay },
1567 { "decrease-visibility", do_decrease_visibility },
1568 { "increase-visibility", do_increase_visibility },
1570 { "loadxml", do_load_xml_to_proptree},
1571 { "savexml", do_save_xml_from_proptree },
1572 { "xmlhttprequest", do_load_xml_from_url },
1573 { "press-cockpit-button", do_press_cockpit_button },
1574 { "release-cockpit-button", do_release_cockpit_button },
1575 { "dump-scenegraph", do_dump_scene_graph },
1576 { "dump-terrainbranch", do_dump_terrain_branch },
1577 { "print-visible-scene", do_print_visible_scene_info },
1578 { "reload-shaders", do_reload_shaders },
1579 { "reload-materials", do_materials_reload },
1581 { 0, 0 } // zero-terminated
1586 * Initialize the default built-in commands.
1588 * Other commands may be added by other parts of the application.
1593 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1594 for (int i = 0; built_ins[i].name != 0; i++) {
1595 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1596 globals->get_commands()->addCommand(built_ins[i].name,
1597 built_ins[i].command);
1600 typedef bool (*dummy)();
1601 fgTie( "/command/view/next", dummy(0), do_view_next );
1602 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1605 // end of fg_commands.cxx