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 <ATC/CommStation.hxx>
41 #include <Navaids/navrecord.hxx>
42 #include <Navaids/navlist.hxx>
43 #include <Network/HTTPClient.hxx>
45 #include "fg_init.hxx"
48 #include "fg_commands.hxx"
49 #include "fg_props.hxx"
50 #include "globals.hxx"
53 #include "viewmgr.hxx"
55 #include <Main/viewer.hxx>
56 #include <Environment/presets.hxx>
58 #include <boost/scoped_array.hpp>
66 ////////////////////////////////////////////////////////////////////////
67 // Static helper functions.
68 ////////////////////////////////////////////////////////////////////////
71 static inline SGPropertyNode *
72 get_prop (const SGPropertyNode * arg)
74 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
77 static inline SGPropertyNode *
78 get_prop2 (const SGPropertyNode * arg)
80 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
85 * Get a double value and split it as required.
88 split_value (double full_value, const char * mask,
89 double * unmodifiable, double * modifiable)
91 if (!strcmp("integer", mask)) {
92 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
93 *unmodifiable = full_value - *modifiable;
94 } else if (!strcmp("decimal", mask)) {
95 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
96 *modifiable = full_value - *unmodifiable;
98 if (strcmp("all", mask))
99 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
100 << " assuming 'all'");
102 *modifiable = full_value;
108 * Clamp or wrap a value as specified.
111 limit_value (double * value, const SGPropertyNode * arg)
113 const SGPropertyNode * min_node = arg->getChild("min");
114 const SGPropertyNode * max_node = arg->getChild("max");
116 bool wrap = arg->getBoolValue("wrap");
118 if (min_node == 0 || max_node == 0)
121 if (wrap) { // wrap such that min <= x < max
122 double min_val = min_node->getDoubleValue();
123 double max_val = max_node->getDoubleValue();
124 double resolution = arg->getDoubleValue("resolution");
125 if (resolution > 0.0) {
126 // snap to (min + N*resolution), taking special care to handle imprecision
127 int n = (int)floor((*value - min_val) / resolution + 0.5);
128 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
129 SG_NORMALIZE_RANGE(n, 0, steps);
130 *value = min_val + resolution * n;
132 // plain circular wrapping
133 SG_NORMALIZE_RANGE(*value, min_val, max_val);
135 } else { // clamp such that min <= x <= max
136 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
137 *value = min_node->getDoubleValue();
138 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
139 *value = max_node->getDoubleValue();
144 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
146 switch (value1->getType()) {
147 case simgear::props::BOOL:
148 return (value1->getBoolValue() == value2->getBoolValue());
149 case simgear::props::INT:
150 return (value1->getIntValue() == value2->getIntValue());
151 case simgear::props::LONG:
152 return (value1->getLongValue() == value2->getLongValue());
153 case simgear::props::FLOAT:
154 return (value1->getFloatValue() == value2->getFloatValue());
155 case simgear::props::DOUBLE:
156 return (value1->getDoubleValue() == value2->getDoubleValue());
158 return !strcmp(value1->getStringValue(), value2->getStringValue());
164 ////////////////////////////////////////////////////////////////////////
165 // Command implementations.
166 ////////////////////////////////////////////////////////////////////////
170 * Built-in command: do nothing.
173 do_null (const SGPropertyNode * arg)
179 * Built-in command: run a Nasal script.
182 do_nasal (const SGPropertyNode * arg)
184 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
188 * Built-in command: exit FlightGear.
190 * status: the exit status to return to the operating system (defaults to 0)
193 do_exit (const SGPropertyNode * arg)
195 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
196 fgSetBool("/sim/signals/exit", true);
197 globals->saveUserSettings();
198 fgOSExit(arg->getIntValue("status", 0));
204 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
207 do_reset (const SGPropertyNode * arg)
209 fgReInitSubsystems();
215 * Built-in command: reinitialize one or more subsystems.
217 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
218 * none is specified, reinitialize all of them.
221 do_reinit (const SGPropertyNode * arg)
225 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
226 if (subsystems.size() == 0) {
227 globals->get_subsystem_mgr()->reinit();
229 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
230 const char * name = subsystems[i]->getStringValue();
231 SGSubsystem * subsystem = globals->get_subsystem(name);
232 if (subsystem == 0) {
234 SG_LOG( SG_GENERAL, SG_ALERT,
235 "Subsystem " << name << " not found" );
242 globals->get_event_mgr()->reinit();
249 // these routines look useful ??? but are never used in the code ???
253 * Built-in command: suspend one or more subsystems.
255 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
258 do_suspend (const SGPropertyNode * arg)
262 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
263 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
264 const char * name = subsystems[i]->getStringValue();
265 SGSubsystem * subsystem = globals->get_subsystem(name);
266 if (subsystem == 0) {
268 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
270 subsystem->suspend();
277 * Built-in command: suspend one or more subsystems.
279 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
282 do_resume (const SGPropertyNode * arg)
286 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
287 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
288 const char * name = subsystems[i]->getStringValue();
289 SGSubsystem * subsystem = globals->get_subsystem(name);
290 if (subsystem == 0) {
292 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << " not found");
303 * Built-in command: replay the FDR buffer
306 do_replay (const SGPropertyNode * arg)
308 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
313 * Built-in command: pause/unpause the sim
316 do_pause (const SGPropertyNode * arg)
318 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
319 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
325 fgSetBool("/sim/freeze/master",!paused);
326 fgSetBool("/sim/freeze/clock",!paused);
332 * Built-in command: load flight.
334 * file (optional): the name of the file to load (relative to current
335 * directory). Defaults to "fgfs.sav"
338 do_load (const SGPropertyNode * arg)
340 string file = arg->getStringValue("file", "fgfs.sav");
341 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
344 if (!fgValidatePath(file.c_str(), false)) {
345 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
346 "(unauthorized access)");
350 ifstream input(file.c_str());
351 if (input.good() && fgLoadFlight(input)) {
353 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
356 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
363 * Built-in command: save flight.
365 * file (optional): the name of the file to save (relative to the
366 * current directory). Defaults to "fgfs.sav".
369 do_save (const SGPropertyNode * arg)
371 string file = arg->getStringValue("file", "fgfs.sav");
372 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
375 if (!fgValidatePath(file.c_str(), false)) {
376 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
377 "(unauthorized access)");
381 bool write_all = arg->getBoolValue("write-all", false);
382 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
383 ofstream output(file.c_str());
384 if (output.good() && fgSaveFlight(output, write_all)) {
386 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
389 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
396 * Built-in command: (re)load the panel.
398 * path (optional): the file name to load the panel from
399 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
400 * and if that's unspecified, to "Panels/Default/default.xml".
403 do_panel_load (const SGPropertyNode * arg)
406 arg->getStringValue("path", fgGetString("/sim/panel/path"));
407 if (panel_path.empty()) {
411 FGPanel * new_panel = fgReadPanel(panel_path);
412 if (new_panel == 0) {
413 SG_LOG(SG_INPUT, SG_ALERT,
414 "Error reading new panel from " << panel_path);
417 SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
418 globals->get_current_panel()->unbind();
419 globals->set_current_panel( new_panel );
420 globals->get_current_panel()->bind();
426 * Built-in command: pass a mouse click to the panel.
428 * button: the mouse button number, zero-based.
429 * is-down: true if the button is down, false if it is up.
430 * x-pos: the x position of the mouse click.
431 * y-pos: the y position of the mouse click.
434 do_panel_mouse_click (const SGPropertyNode * arg)
436 if (globals->get_current_panel() != 0)
437 return globals->get_current_panel()
438 ->doMouseAction(arg->getIntValue("button"),
439 arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
440 arg->getIntValue("x-pos"),
441 arg->getIntValue("y-pos"));
448 * Built-in command: (re)load preferences.
450 * path (optional): the file name to load the panel from (relative
451 * to FG_ROOT). Defaults to "preferences.xml".
454 do_preferences_load (const SGPropertyNode * arg)
457 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
458 globals->get_props());
459 } catch (const sg_exception &e) {
460 guiErrorMessage("Error reading global preferences: ", e);
463 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
470 globals->get_current_view()->setHeadingOffset_deg(0.0);
471 globals->get_viewmgr()->next_view();
477 globals->get_current_view()->setHeadingOffset_deg(0.0);
478 globals->get_viewmgr()->prev_view();
482 * Built-in command: cycle view.
485 do_view_cycle (const SGPropertyNode * arg)
487 globals->get_current_view()->setHeadingOffset_deg(0.0);
488 globals->get_viewmgr()->next_view();
493 * Built-in command: capture screen.
496 do_screen_capture (const SGPropertyNode * arg)
498 return fgDumpSnapShot();
502 do_reload_shaders (const SGPropertyNode*)
504 simgear::reload_shaders();
509 do_dump_scene_graph (const SGPropertyNode*)
516 do_dump_terrain_branch (const SGPropertyNode*)
518 fgDumpTerrainBranch();
520 double lon_deg = fgGetDouble("/position/longitude-deg");
521 double lat_deg = fgGetDouble("/position/latitude-deg");
522 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
523 SGVec3d zero = SGVec3d::fromGeod(geodPos);
525 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
526 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
527 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
533 do_print_visible_scene_info(const SGPropertyNode*)
535 fgPrintVisibleSceneInfoCommand();
540 * Built-in command: hires capture screen.
543 do_hires_screen_capture (const SGPropertyNode * arg)
551 * Reload the tile cache.
554 do_tile_cache_reload (const SGPropertyNode * arg)
556 static const SGPropertyNode *master_freeze
557 = fgGetNode("/sim/freeze/master");
558 bool freeze = master_freeze->getBoolValue();
559 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
561 fgSetBool("/sim/freeze/master", true);
564 globals->get_subsystem("tile-manager")->reinit();
567 fgSetBool("/sim/freeze/master", false);
574 These do_set_(some-environment-parameters) are deprecated and no longer
575 useful/functional - Torsten Dreyer, January 2011
577 * Set the sea level outside air temperature and assigning that to all
578 * boundary and aloft environment layers.
581 do_set_sea_level_degc ( double temp_sea_level_degc)
583 SGPropertyNode *node, *child;
586 node = fgGetNode( "/environment/config/boundary" );
587 if ( node != NULL ) {
589 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
590 child->setDoubleValue( "temperature-sea-level-degc",
591 temp_sea_level_degc );
597 node = fgGetNode( "/environment/config/aloft" );
598 if ( node != NULL ) {
600 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
601 child->setDoubleValue( "temperature-sea-level-degc",
602 temp_sea_level_degc );
611 do_set_sea_level_degc (const SGPropertyNode * arg)
613 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
618 * Set the outside air temperature at the "current" altitude by first
619 * calculating the corresponding sea level temp, and assigning that to
620 * all boundary and aloft environment layers.
623 do_set_oat_degc (const SGPropertyNode * arg)
625 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
626 // check for an altitude specified in the arguments, otherwise use
627 // current aircraft altitude.
628 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
629 if ( altitude_ft == NULL ) {
630 altitude_ft = fgGetNode("/position/altitude-ft");
633 FGEnvironment dummy; // instantiate a dummy so we can leech a method
634 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
635 dummy.set_temperature_degc( oat_degc );
636 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
640 * Set the sea level outside air dewpoint and assigning that to all
641 * boundary and aloft environment layers.
644 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
647 SGPropertyNode *node, *child;
650 node = fgGetNode( "/environment/config/boundary" );
651 if ( node != NULL ) {
653 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
654 child->setDoubleValue( "dewpoint-sea-level-degc",
655 dewpoint_sea_level_degc );
661 node = fgGetNode( "/environment/config/aloft" );
662 if ( node != NULL ) {
664 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
665 child->setDoubleValue( "dewpoint-sea-level-degc",
666 dewpoint_sea_level_degc );
675 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
677 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
681 * Set the outside air dewpoint at the "current" altitude by first
682 * calculating the corresponding sea level dewpoint, and assigning
683 * that to all boundary and aloft environment layers.
686 do_set_dewpoint_degc (const SGPropertyNode * arg)
688 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
690 // check for an altitude specified in the arguments, otherwise use
691 // current aircraft altitude.
692 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
693 if ( altitude_ft == NULL ) {
694 altitude_ft = fgGetNode("/position/altitude-ft");
697 FGEnvironment dummy; // instantiate a dummy so we can leech a method
698 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
699 dummy.set_dewpoint_degc( dewpoint_degc );
700 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
705 * Built-in command: toggle a bool property value.
707 * property: The name of the property to toggle.
710 do_property_toggle (const SGPropertyNode * arg)
712 SGPropertyNode * prop = get_prop(arg);
713 return prop->setBoolValue(!prop->getBoolValue());
718 * Built-in command: assign a value to a property.
720 * property: the name of the property to assign.
721 * value: the value to assign; or
722 * property[1]: the property to copy from.
725 do_property_assign (const SGPropertyNode * arg)
727 SGPropertyNode * prop = get_prop(arg);
728 const SGPropertyNode * value = arg->getNode("value");
731 return prop->setUnspecifiedValue(value->getStringValue());
734 const SGPropertyNode * prop2 = get_prop2(arg);
736 return prop->setUnspecifiedValue(prop2->getStringValue());
744 * Built-in command: increment or decrement a property value.
746 * If the 'step' argument is present, it will be used; otherwise,
747 * the command uses 'offset' and 'factor', usually from the mouse.
749 * property: the name of the property to increment or decrement.
750 * step: the amount of the increment or decrement (default: 0).
751 * offset: offset from the current setting (used for the mouse; multiplied
753 * factor: scaling amount for the offset (defaults to 1).
754 * min: the minimum allowed value (default: no minimum).
755 * max: the maximum allowed value (default: no maximum).
756 * mask: 'integer' to apply only to the left of the decimal point,
757 * 'decimal' to apply only to the right of the decimal point,
758 * or 'all' to apply to the whole number (the default).
759 * wrap: true if the value should be wrapped when it passes min or max;
760 * both min and max must be present for this to work (default:
764 do_property_adjust (const SGPropertyNode * arg)
766 SGPropertyNode * prop = get_prop(arg);
769 if (arg->hasValue("step"))
770 amount = arg->getDoubleValue("step");
772 amount = (arg->getDoubleValue("factor", 1)
773 * arg->getDoubleValue("offset"));
775 double unmodifiable, modifiable;
776 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
777 &unmodifiable, &modifiable);
778 modifiable += amount;
779 limit_value(&modifiable, arg);
781 prop->setDoubleValue(unmodifiable + modifiable);
788 * Built-in command: multiply a property value.
790 * property: the name of the property to multiply.
791 * factor: the amount by which to multiply.
792 * min: the minimum allowed value (default: no minimum).
793 * max: the maximum allowed value (default: no maximum).
794 * mask: 'integer' to apply only to the left of the decimal point,
795 * 'decimal' to apply only to the right of the decimal point,
796 * or 'all' to apply to the whole number (the default).
797 * wrap: true if the value should be wrapped when it passes min or max;
798 * both min and max must be present for this to work (default:
802 do_property_multiply (const SGPropertyNode * arg)
804 SGPropertyNode * prop = get_prop(arg);
805 double factor = arg->getDoubleValue("factor", 1);
807 double unmodifiable, modifiable;
808 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
809 &unmodifiable, &modifiable);
810 modifiable *= factor;
811 limit_value(&modifiable, arg);
813 prop->setDoubleValue(unmodifiable + modifiable);
820 * Built-in command: swap two property values.
822 * property[0]: the name of the first property.
823 * property[1]: the name of the second property.
826 do_property_swap (const SGPropertyNode * arg)
828 SGPropertyNode * prop1 = get_prop(arg);
829 SGPropertyNode * prop2 = get_prop2(arg);
831 // FIXME: inefficient
832 const string & tmp = prop1->getStringValue();
833 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
834 prop2->setUnspecifiedValue(tmp.c_str()));
839 * Built-in command: Set a property to an axis or other moving input.
841 * property: the name of the property to set.
842 * setting: the current input setting, usually between -1.0 and 1.0.
843 * offset: the offset to shift by, before applying the factor.
844 * factor: the factor to multiply by (use negative to reverse).
847 do_property_scale (const SGPropertyNode * arg)
849 SGPropertyNode * prop = get_prop(arg);
850 double setting = arg->getDoubleValue("setting");
851 double offset = arg->getDoubleValue("offset", 0.0);
852 double factor = arg->getDoubleValue("factor", 1.0);
853 bool squared = arg->getBoolValue("squared", false);
854 int power = arg->getIntValue("power", (squared ? 2 : 1));
856 int sign = (setting < 0 ? -1 : 1);
862 setting = setting * setting * sign;
865 setting = setting * setting * setting;
868 setting = setting * setting * setting * setting * sign;
871 setting = pow(setting, power);
872 if ((power % 2) == 0)
877 return prop->setDoubleValue((setting + offset) * factor);
882 * Built-in command: cycle a property through a set of values.
884 * If the current value isn't in the list, the cycle will
885 * (re)start from the beginning.
887 * property: the name of the property to cycle.
888 * value[*]: the list of values to cycle through.
891 do_property_cycle (const SGPropertyNode * arg)
893 SGPropertyNode * prop = get_prop(arg);
894 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
896 int nSelections = values.size();
898 if (nSelections < 1) {
899 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
903 // Try to find the current selection
904 for (int i = 0; i < nSelections; i++) {
905 if (compare_values(prop, values[i])) {
911 // Default or wrap to the first selection
912 if (selection < 0 || selection >= nSelections)
915 prop->setUnspecifiedValue(values[selection]->getStringValue());
921 * Built-in command: randomize a numeric property value.
923 * property: the name of the property value to randomize.
924 * min: the minimum allowed value.
925 * max: the maximum allowed value.
928 do_property_randomize (const SGPropertyNode * arg)
930 SGPropertyNode * prop = get_prop(arg);
931 double min = arg->getDoubleValue("min", DBL_MIN);
932 double max = arg->getDoubleValue("max", DBL_MAX);
933 prop->setDoubleValue(sg_random() * (max - min) + min);
938 * Built-in command: interpolate a property value over time
940 * property: the name of the property value to interpolate.
941 * value[0..n] any number of constant values to interpolate
942 * time[0..n] time between each value, number of time elements must
943 * match those of value elements
945 * property[1..n] any number of target values taken from named properties
946 * time[0..n] time between each value, number of time elements must
947 * match those of property elements minus one
950 do_property_interpolate (const SGPropertyNode * arg)
952 SGPropertyNode * prop = get_prop(arg);
954 simgear::PropertyList valueNodes = arg->getChildren( "value" );
955 simgear::PropertyList timeNodes = arg->getChildren( "time" );
957 boost::scoped_array<double> value;
958 boost::scoped_array<double> time;
960 if( valueNodes.size() > 0 ) {
962 if( timeNodes.size() != valueNodes.size() )
965 value.reset( new double[valueNodes.size()] );
966 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size(); n++ ) {
967 value[n] = valueNodes[n]->getDoubleValue();
970 valueNodes = arg->getChildren("property");
971 // must have one more property node
972 if( valueNodes.size() - 1 != timeNodes.size() )
975 value.reset( new double[valueNodes.size()-1] );
976 for( simgear::PropertyList::size_type n = 0; n < valueNodes.size()-1; n++ ) {
977 value[n] = fgGetNode(valueNodes[n+1]->getStringValue(), "/null")->getDoubleValue();
982 time.reset( new double[timeNodes.size()] );
983 for( simgear::PropertyList::size_type n = 0; n < timeNodes.size(); n++ ) {
984 time[n] = timeNodes[n]->getDoubleValue();
987 ((SGInterpolator*)globals->get_subsystem_mgr()
988 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
989 ->interpolate(prop, timeNodes.size(), value.get(), time.get() );
995 * Built-in command: reinit the data logging system based on the
996 * current contents of the /logger tree.
999 do_data_logging_commit (const SGPropertyNode * arg)
1001 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1007 * Built-in command: Add a dialog to the GUI system. Does *not*
1008 * display the dialog. The property node should have the same format
1009 * as a dialog XML configuration. It must include:
1011 * name: the name of the GUI dialog for future reference.
1014 do_dialog_new (const SGPropertyNode * arg)
1016 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1018 // Note the casting away of const: this is *real*. Doing a
1019 // "dialog-apply" command later on will mutate this property node.
1020 // I'm not convinced that this isn't the Right Thing though; it
1021 // allows client to create a node, pass it to dialog-new, and get
1022 // the values back from the dialog by reading the same node.
1023 // Perhaps command arguments are not as "const" as they would
1025 gui->newDialog((SGPropertyNode*)arg);
1030 * Built-in command: Show an XML-configured dialog.
1032 * dialog-name: the name of the GUI dialog to display.
1035 do_dialog_show (const SGPropertyNode * arg)
1037 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1038 gui->showDialog(arg->getStringValue("dialog-name"));
1044 * Built-in Command: Hide the active XML-configured dialog.
1047 do_dialog_close (const SGPropertyNode * arg)
1049 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1050 if(arg->hasValue("dialog-name"))
1051 return gui->closeDialog(arg->getStringValue("dialog-name"));
1052 return gui->closeActiveDialog();
1057 * Update a value in the active XML-configured dialog.
1059 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1062 do_dialog_update (const SGPropertyNode * arg)
1064 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1066 if (arg->hasValue("dialog-name"))
1067 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1069 dialog = gui->getActiveDialog();
1072 dialog->updateValues(arg->getStringValue("object-name"));
1080 do_open_browser (const SGPropertyNode * arg)
1083 if (arg->hasValue("path"))
1084 path = arg->getStringValue("path");
1086 if (arg->hasValue("url"))
1087 path = arg->getStringValue("url");
1091 return openBrowser(path);
1095 * Apply a value in the active XML-configured dialog.
1097 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1100 do_dialog_apply (const SGPropertyNode * arg)
1102 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1104 if (arg->hasValue("dialog-name"))
1105 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1107 dialog = gui->getActiveDialog();
1110 dialog->applyValues(arg->getStringValue("object-name"));
1119 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1123 do_gui_redraw (const SGPropertyNode * arg)
1125 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1132 * Adds model to the scenery. The path to the added branch (/models/model[*])
1133 * is returned in property "property".
1136 do_add_model (const SGPropertyNode * arg)
1138 SGPropertyNode * model = fgGetNode("models", true);
1140 for (i = 0; model->hasChild("model",i); i++);
1141 model = model->getChild("model", i, true);
1142 copyProperties(arg, model);
1143 if (model->hasValue("elevation-m"))
1144 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1145 * SG_METER_TO_FEET);
1146 model->getNode("load", true);
1147 model->removeChildren("load");
1148 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1154 * Set mouse cursor coordinates and cursor shape.
1157 do_set_cursor (const SGPropertyNode * arg)
1159 if (arg->hasValue("x") || arg->hasValue("y")) {
1160 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1161 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1162 int x = arg->getIntValue("x", mx->getIntValue());
1163 int y = arg->getIntValue("y", my->getIntValue());
1169 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1170 if (cursor->getType() != simgear::props::NONE)
1171 fgSetMouseCursor(cursor->getIntValue());
1173 cursor->setIntValue(fgGetMouseCursor());
1179 * Built-in command: play an audio message (i.e. a wav file) This is
1180 * fire and forget. Call this once per message and it will get dumped
1181 * into a queue. Messages are played sequentially so they do not
1185 do_play_audio_sample (const SGPropertyNode * arg)
1187 string path = arg->getStringValue("path");
1188 string file = arg->getStringValue("file");
1189 float volume = arg->getFloatValue("volume");
1190 // cout << "playing " << path << " / " << file << endl;
1192 static FGSampleQueue *queue = 0;
1194 SGSoundMgr *smgr = globals->get_soundmgr();
1195 queue = new FGSampleQueue(smgr, "chatter");
1196 queue->tie_to_listener();
1199 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1200 msg->set_volume( volume );
1205 } catch (const sg_io_exception&) {
1206 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1207 "failed to load" << path << '/' << file);
1213 * Built-in command: commit presets (read from in /sim/presets/)
1216 do_presets_commit (const SGPropertyNode * arg)
1218 if (fgGetBool("/sim/initialized", false)) {
1219 fgReInitSubsystems();
1221 // Nasal can trigger this during initial init, which confuses
1222 // the logic in ReInitSubsystems, since initial state has not been
1223 // saved at that time. Short-circuit everything here.
1231 * Built-in command: set log level (0 ... 7)
1234 do_log_level (const SGPropertyNode * arg)
1236 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1243 do_decrease_visibility (const SGPropertyNode * arg)
1245 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1250 do_increase_visibility (const SGPropertyNode * arg)
1252 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1257 * An fgcommand to allow loading of xml files via nasal,
1258 * the xml file's structure will be made available within
1259 * a property tree node defined under argument "targetnode",
1260 * or in the given argument tree under "data" otherwise.
1262 * @param filename a string to hold the complete path & filename of an XML file
1263 * @param targetnode a string pointing to a location within the property tree
1264 * where to store the parsed XML file. If <targetnode> is undefined, then the
1265 * file contents are stored under a node <data> in the argument tree.
1269 do_load_xml_to_proptree(const SGPropertyNode * arg)
1271 SGPath file(arg->getStringValue("filename"));
1272 if (file.str().empty())
1275 if (file.extension() != "xml")
1276 file.concat(".xml");
1278 std::string icao = arg->getStringValue("icao");
1280 if (file.isRelative()) {
1281 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1282 if (!absPath.isNull())
1286 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1287 << file.str() << "'.");
1292 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1293 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1294 << file.str() << " at ICAO:" << icao);
1299 if (!fgValidatePath(file.c_str(), false)) {
1300 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1301 "(unauthorized access)");
1305 SGPropertyNode *targetnode;
1306 if (arg->hasValue("targetnode"))
1307 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1309 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1312 readProperties(file.c_str(), targetnode, true);
1313 } catch (const sg_exception &e) {
1314 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1321 class RemoteXMLRequest : public simgear::HTTP::Request
1324 SGPropertyNode_ptr _complete;
1325 SGPropertyNode_ptr _status;
1326 SGPropertyNode_ptr _failed;
1327 SGPropertyNode_ptr _target;
1330 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1331 simgear::HTTP::Request(url),
1336 void setCompletionProp(SGPropertyNode_ptr p)
1341 void setStatusProp(SGPropertyNode_ptr p)
1346 void setFailedProp(SGPropertyNode_ptr p)
1351 virtual void gotBodyData(const char* s, int n)
1353 propsData += string(s, n);
1356 virtual void responseComplete()
1358 int response = responseCode();
1359 bool failed = false;
1360 if (response == 200) {
1362 const char* buffer = propsData.c_str();
1363 readProperties(buffer, propsData.size(), _target, true);
1364 } catch (const sg_exception &e) {
1365 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1367 response = 406; // 'not acceptable', anything better?
1372 // now the response data is output, signal Nasal / listeners
1373 if (_complete) _complete->setBoolValue(true);
1374 if (_status) _status->setIntValue(response);
1375 if (_failed) _failed->setBoolValue(failed);
1381 do_load_xml_from_url(const SGPropertyNode * arg)
1383 std::string url(arg->getStringValue("url"));
1387 SGPropertyNode *targetnode;
1388 if (arg->hasValue("targetnode"))
1389 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1391 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1393 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1395 // connect up optional reporting properties
1396 if (arg->hasValue("complete"))
1397 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1398 if (arg->hasValue("failure"))
1399 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1400 if (arg->hasValue("status"))
1401 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1403 FGHTTPClient::instance()->makeRequest(req);
1410 * An fgcommand to allow saving of xml files via nasal,
1411 * the file's structure will be determined based on what's
1412 * encountered in the passed (source) property tree node
1414 * @param filename a string to hold the complete path & filename of the (new)
1416 * @param sourcenode a string pointing to a location within the property tree
1417 * where to find the nodes that should be written recursively into an XML file
1418 * @param data if no sourcenode is given, then the file contents are taken from
1419 * the argument tree's "data" node.
1423 do_save_xml_from_proptree(const SGPropertyNode * arg)
1425 SGPath file(arg->getStringValue("filename"));
1426 if (file.str().empty())
1429 if (file.extension() != "xml")
1430 file.concat(".xml");
1432 if (!fgValidatePath(file.c_str(), true)) {
1433 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1434 "(unauthorized access)");
1438 SGPropertyNode *sourcenode;
1439 if (arg->hasValue("sourcenode"))
1440 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1441 else if (arg->getNode("data", false))
1442 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1447 writeProperties (file.c_str(), sourcenode, true);
1448 } catch (const sg_exception &e) {
1449 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1457 do_press_cockpit_button (const SGPropertyNode *arg)
1459 const char *prefix = arg->getStringValue("prefix");
1461 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1464 string prop = string(prefix) + "-button";
1467 if (arg->getBoolValue("latching"))
1468 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1472 fgSetDouble(prop.c_str(), value);
1473 fgSetBool(arg->getStringValue("discrete"), value > 0);
1479 do_release_cockpit_button (const SGPropertyNode *arg)
1481 const char *prefix = arg->getStringValue("prefix");
1483 if (arg->getBoolValue("guarded")) {
1484 string prop = string(prefix) + "-guard";
1485 if (fgGetDouble(prop.c_str()) < 1) {
1486 fgSetDouble(prop.c_str(), 1);
1491 if (! arg->getBoolValue("latching")) {
1492 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1493 fgSetBool(arg->getStringValue("discrete"), false);
1499 static SGGeod commandSearchPos(const SGPropertyNode* arg)
1501 if (arg->hasChild("longitude-deg") && arg->hasChild("latitude-deg")) {
1502 return SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1503 arg->getDoubleValue("latitude-deg"));
1506 // use current viewer/aircraft position
1507 return SGGeod::fromDeg(fgGetDouble("/position/longitude-deg"),
1508 fgGetDouble("/position/latitude-deg"));
1512 do_comm_search(const SGPropertyNode* arg)
1514 SGGeod pos = commandSearchPos(arg);
1515 int khz = static_cast<int>(arg->getDoubleValue("frequency-mhz") * 100.0 + 0.25);
1517 flightgear::CommStation* sta = flightgear::CommStation::findByFreq(khz, pos, NULL);
1522 SGPropertyNode* result = fgGetNode(arg->getStringValue("result"));
1523 sta->createBinding(result);
1528 do_nav_search(const SGPropertyNode* arg)
1530 SGGeod pos = commandSearchPos(arg);
1531 double mhz = arg->getDoubleValue("frequency-mhz");
1533 FGNavList* navList = globals->get_navlist();
1534 string type(arg->getStringValue("type", "vor"));
1535 if (type == "dme") {
1536 navList = globals->get_dmelist();
1537 } else if (type == "tacan") {
1538 navList = globals->get_tacanlist();
1541 FGNavRecord* nav = navList->findByFreq(mhz, pos);
1542 if (!nav && (type == "vor")) {
1543 // if we're searching VORs, look for localizers too
1544 nav = globals->get_loclist()->findByFreq(mhz, pos);
1551 SGPropertyNode* result = fgGetNode(arg->getStringValue("result"));
1552 nav->createBinding(result);
1556 ////////////////////////////////////////////////////////////////////////
1558 ////////////////////////////////////////////////////////////////////////
1562 * Table of built-in commands.
1564 * New commands do not have to be added here; any module in the application
1565 * can add a new command using globals->get_commands()->addCommand(...).
1569 SGCommandMgr::command_t command;
1571 { "null", do_null },
1572 { "nasal", do_nasal },
1573 { "exit", do_exit },
1574 { "reset", do_reset },
1575 { "reinit", do_reinit },
1576 { "suspend", do_reinit },
1577 { "resume", do_reinit },
1578 { "pause", do_pause },
1579 { "load", do_load },
1580 { "save", do_save },
1581 { "panel-load", do_panel_load },
1582 { "panel-mouse-click", do_panel_mouse_click },
1583 { "preferences-load", do_preferences_load },
1584 { "view-cycle", do_view_cycle },
1585 { "screen-capture", do_screen_capture },
1586 { "hires-screen-capture", do_hires_screen_capture },
1587 { "tile-cache-reload", do_tile_cache_reload },
1589 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1590 { "set-outside-air-temp-degc", do_set_oat_degc },
1591 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1592 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1594 { "property-toggle", do_property_toggle },
1595 { "property-assign", do_property_assign },
1596 { "property-adjust", do_property_adjust },
1597 { "property-multiply", do_property_multiply },
1598 { "property-swap", do_property_swap },
1599 { "property-scale", do_property_scale },
1600 { "property-cycle", do_property_cycle },
1601 { "property-randomize", do_property_randomize },
1602 { "property-interpolate", do_property_interpolate },
1603 { "data-logging-commit", do_data_logging_commit },
1604 { "dialog-new", do_dialog_new },
1605 { "dialog-show", do_dialog_show },
1606 { "dialog-close", do_dialog_close },
1607 { "dialog-update", do_dialog_update },
1608 { "dialog-apply", do_dialog_apply },
1609 { "open-browser", do_open_browser },
1610 { "gui-redraw", do_gui_redraw },
1611 { "add-model", do_add_model },
1612 { "set-cursor", do_set_cursor },
1613 { "play-audio-sample", do_play_audio_sample },
1614 { "presets-commit", do_presets_commit },
1615 { "log-level", do_log_level },
1616 { "replay", do_replay },
1618 { "decrease-visibility", do_decrease_visibility },
1619 { "increase-visibility", do_increase_visibility },
1621 { "loadxml", do_load_xml_to_proptree},
1622 { "savexml", do_save_xml_from_proptree },
1623 { "xmlhttprequest", do_load_xml_from_url },
1624 { "press-cockpit-button", do_press_cockpit_button },
1625 { "release-cockpit-button", do_release_cockpit_button },
1626 { "dump-scenegraph", do_dump_scene_graph },
1627 { "dump-terrainbranch", do_dump_terrain_branch },
1628 { "print-visible-scene", do_print_visible_scene_info },
1629 { "reload-shaders", do_reload_shaders },
1631 { "find-navaid", do_nav_search },
1632 { "find-comm", do_comm_search },
1634 { 0, 0 } // zero-terminated
1639 * Initialize the default built-in commands.
1641 * Other commands may be added by other parts of the application.
1646 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1647 for (int i = 0; built_ins[i].name != 0; i++) {
1648 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1649 globals->get_commands()->addCommand(built_ins[i].name,
1650 built_ins[i].command);
1653 typedef bool (*dummy)();
1654 fgTie( "/command/view/next", dummy(0), do_view_next );
1655 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1658 // end of fg_commands.cxx