1 // fg_commands.cxx - internal FGFS commands.
7 #include <string.h> // strcmp()
9 #include <simgear/compiler.h>
14 #include <simgear/sg_inlines.h>
15 #include <simgear/debug/logstream.hxx>
16 #include <simgear/math/sg_random.h>
17 #include <simgear/scene/material/mat.hxx>
18 #include <simgear/scene/material/matlib.hxx>
19 #include <simgear/structure/exception.hxx>
20 #include <simgear/structure/commands.hxx>
21 #include <simgear/props/props.hxx>
22 #include <simgear/props/props_io.hxx>
23 #include <simgear/structure/event_mgr.hxx>
24 #include <simgear/sound/soundmgr_openal.hxx>
25 #include <simgear/timing/sg_time.hxx>
26 #include <simgear/io/HTTPMemoryRequest.hxx>
28 #include <FDM/flight.hxx>
30 #include <GUI/new_gui.hxx>
31 #include <GUI/dialog.hxx>
32 #include <Aircraft/replay.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scenery/tilemgr.hxx>
35 #include <Scripting/NasalSys.hxx>
36 #include <Sound/sample_queue.hxx>
37 #include <Airports/xmlloader.hxx>
38 #include <Network/HTTPClient.hxx>
39 #include <Viewer/viewmgr.hxx>
40 #include <Viewer/viewer.hxx>
41 #include <Environment/presets.hxx>
43 #include "fg_init.hxx"
46 #include "fg_commands.hxx"
47 #include "fg_props.hxx"
48 #include "globals.hxx"
52 #include "positioninit.hxx"
54 #include <boost/scoped_array.hpp>
56 #if FG_HAVE_GPERFTOOLS
57 # include <google/profiler.h>
65 ////////////////////////////////////////////////////////////////////////
66 // Static helper functions.
67 ////////////////////////////////////////////////////////////////////////
70 static inline SGPropertyNode *
71 get_prop (const SGPropertyNode * arg)
73 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
76 static inline SGPropertyNode *
77 get_prop2 (const SGPropertyNode * arg)
79 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
84 * Get a double value and split it as required.
87 split_value (double full_value, const char * mask,
88 double * unmodifiable, double * modifiable)
90 if (!strcmp("integer", mask)) {
91 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
92 *unmodifiable = full_value - *modifiable;
93 } else if (!strcmp("decimal", mask)) {
94 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
95 *modifiable = full_value - *unmodifiable;
97 if (strcmp("all", mask))
98 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
99 << " assuming 'all'");
101 *modifiable = full_value;
107 * Clamp or wrap a value as specified.
110 limit_value (double * value, const SGPropertyNode * arg)
112 const SGPropertyNode * min_node = arg->getChild("min");
113 const SGPropertyNode * max_node = arg->getChild("max");
115 bool wrap = arg->getBoolValue("wrap");
117 if (min_node == 0 || max_node == 0)
120 if (wrap) { // wrap such that min <= x < max
121 double min_val = min_node->getDoubleValue();
122 double max_val = max_node->getDoubleValue();
123 double resolution = arg->getDoubleValue("resolution");
124 if (resolution > 0.0) {
125 // snap to (min + N*resolution), taking special care to handle imprecision
126 int n = (int)floor((*value - min_val) / resolution + 0.5);
127 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
128 SG_NORMALIZE_RANGE(n, 0, steps);
129 *value = min_val + resolution * n;
131 // plain circular wrapping
132 SG_NORMALIZE_RANGE(*value, min_val, max_val);
134 } else { // clamp such that min <= x <= max
135 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
136 *value = min_node->getDoubleValue();
137 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
138 *value = max_node->getDoubleValue();
143 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
145 switch (value1->getType()) {
146 case simgear::props::BOOL:
147 return (value1->getBoolValue() == value2->getBoolValue());
148 case simgear::props::INT:
149 return (value1->getIntValue() == value2->getIntValue());
150 case simgear::props::LONG:
151 return (value1->getLongValue() == value2->getLongValue());
152 case simgear::props::FLOAT:
153 return (value1->getFloatValue() == value2->getFloatValue());
154 case simgear::props::DOUBLE:
155 return (value1->getDoubleValue() == value2->getDoubleValue());
157 return !strcmp(value1->getStringValue(), value2->getStringValue());
163 ////////////////////////////////////////////////////////////////////////
164 // Command implementations.
165 ////////////////////////////////////////////////////////////////////////
169 * Built-in command: do nothing.
172 do_null (const SGPropertyNode * arg)
178 * Built-in command: run a Nasal script.
181 do_nasal (const SGPropertyNode * arg)
183 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
187 * Built-in command: exit FlightGear.
189 * status: the exit status to return to the operating system (defaults to 0)
192 do_exit (const SGPropertyNode * arg)
194 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
195 fgSetBool("/sim/signals/exit", true);
196 globals->saveUserSettings();
197 fgOSExit(arg->getIntValue("status", 0));
203 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
206 do_reset (const SGPropertyNode * arg)
215 do_reposition (const SGPropertyNode * arg)
222 * Built-in command: replay the FDR buffer
225 do_replay (const SGPropertyNode * arg)
227 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
232 * Built-in command: pause/unpause the sim
235 do_pause (const SGPropertyNode * arg)
237 bool paused = fgGetBool("/sim/freeze/master",true) || fgGetBool("/sim/freeze/clock",true);
238 if (paused && (fgGetInt("/sim/freeze/replay-state",0)>0))
244 fgSetBool("/sim/freeze/master",!paused);
245 fgSetBool("/sim/freeze/clock",!paused);
248 SGPropertyNode_ptr args(new SGPropertyNode);
249 args->setStringValue("id", "sim-pause");
250 if (!paused && fgGetBool("/sim/view-name-popup")) {
251 args->setStringValue("label", "Simulation is paused");
252 globals->get_commands()->execute("show-message", args);
254 globals->get_commands()->execute("clear-message", args);
261 * Built-in command: load flight.
263 * file (optional): the name of the file to load (relative to current
264 * directory). Defaults to "fgfs.sav"
267 do_load (const SGPropertyNode * arg)
269 string file = arg->getStringValue("file", "fgfs.sav");
270 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
273 if (!fgValidatePath(file.c_str(), false)) {
274 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
275 "(unauthorized access)");
279 ifstream input(file.c_str());
280 if (input.good() && fgLoadFlight(input)) {
282 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
285 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
292 * Built-in command: save flight.
294 * file (optional): the name of the file to save (relative to the
295 * current directory). Defaults to "fgfs.sav".
298 do_save (const SGPropertyNode * arg)
300 string file = arg->getStringValue("file", "fgfs.sav");
301 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
304 if (!fgValidatePath(file.c_str(), false)) {
305 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
306 "(unauthorized access)");
310 bool write_all = arg->getBoolValue("write-all", false);
311 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
312 ofstream output(file.c_str());
313 if (output.good() && fgSaveFlight(output, write_all)) {
315 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
318 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
324 * Built-in command: save flight recorder tape.
328 do_save_tape (const SGPropertyNode * arg)
330 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
331 replay->saveTape(arg);
336 * Built-in command: load flight recorder tape.
340 do_load_tape (const SGPropertyNode * arg)
342 FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
343 replay->loadTape(arg);
349 * Built-in command: (re)load the panel.
351 * path (optional): the file name to load the panel from
352 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
353 * and if that's unspecified, to "Panels/Default/default.xml".
356 do_panel_load (const SGPropertyNode * arg)
358 string panel_path = arg->getStringValue("path");
359 if (!panel_path.empty()) {
360 // write to the standard property, which will force a load
361 fgSetString("/sim/panel/path", panel_path.c_str());
368 * Built-in command: (re)load preferences.
370 * path (optional): the file name to load the panel from (relative
371 * to FG_ROOT). Defaults to "preferences.xml".
374 do_preferences_load (const SGPropertyNode * arg)
377 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
378 globals->get_props());
379 } catch (const sg_exception &e) {
380 guiErrorMessage("Error reading global preferences: ", e);
383 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
388 do_view_next(bool do_it)
390 // Only switch view if really requested to do so (and not for example while
391 // reset/reposition where /command/view/next is set to false)
394 globals->get_current_view()->setHeadingOffset_deg(0.0);
395 globals->get_viewmgr()->next_view();
400 do_view_prev(bool do_it)
404 globals->get_current_view()->setHeadingOffset_deg(0.0);
405 globals->get_viewmgr()->prev_view();
410 * An fgcommand to toggle fullscreen mode.
414 do_toggle_fullscreen(const SGPropertyNode *arg)
421 * Built-in command: cycle view.
424 do_view_cycle (const SGPropertyNode * arg)
426 globals->get_current_view()->setHeadingOffset_deg(0.0);
427 globals->get_viewmgr()->next_view();
432 * Built-in command: capture screen.
435 do_screen_capture (const SGPropertyNode * arg)
437 return fgDumpSnapShot();
441 do_reload_shaders (const SGPropertyNode*)
443 simgear::reload_shaders();
448 do_dump_scene_graph (const SGPropertyNode*)
455 do_dump_terrain_branch (const SGPropertyNode*)
457 fgDumpTerrainBranch();
459 double lon_deg = fgGetDouble("/position/longitude-deg");
460 double lat_deg = fgGetDouble("/position/latitude-deg");
461 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
462 SGVec3d zero = SGVec3d::fromGeod(geodPos);
464 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
465 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
466 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
472 do_print_visible_scene_info(const SGPropertyNode*)
474 fgPrintVisibleSceneInfoCommand();
479 * Built-in command: hires capture screen.
482 do_hires_screen_capture (const SGPropertyNode * arg)
490 * Reload the tile cache.
493 do_tile_cache_reload (const SGPropertyNode * arg)
495 SGPropertyNode *master_freeze = fgGetNode("/sim/freeze/master");
496 bool freeze = master_freeze->getBoolValue();
497 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
499 master_freeze->setBoolValue(true);
502 globals->get_subsystem("tile-manager")->reinit();
505 master_freeze->setBoolValue(false);
511 * Reload the materials definition
514 do_materials_reload (const SGPropertyNode * arg)
516 SG_LOG(SG_INPUT, SG_INFO, "Reloading Materials");
517 SGMaterialLib* new_matlib = new SGMaterialLib;
518 SGPath mpath( globals->get_fg_root() );
519 mpath.append( fgGetString("/sim/rendering/materials-file") );
520 bool loaded = new_matlib->load(globals->get_fg_root(),
522 globals->get_props());
525 SG_LOG( SG_GENERAL, SG_ALERT,
526 "Error loading materials file " << mpath.str() );
530 globals->set_matlib(new_matlib);
531 FGTileMgr* tileManager = static_cast<FGTileMgr*>(globals->get_subsystem("tile-manager"));
532 tileManager->materialLibChanged();
538 * Built-in command: toggle a bool property value.
540 * property: The name of the property to toggle.
543 do_property_toggle (const SGPropertyNode * arg)
545 SGPropertyNode * prop = get_prop(arg);
546 return prop->setBoolValue(!prop->getBoolValue());
551 * Built-in command: assign a value to a property.
553 * property: the name of the property to assign.
554 * value: the value to assign; or
555 * property[1]: the property to copy from.
558 do_property_assign (const SGPropertyNode * arg)
560 SGPropertyNode * prop = get_prop(arg);
561 const SGPropertyNode * value = arg->getNode("value");
564 return prop->setUnspecifiedValue(value->getStringValue());
567 const SGPropertyNode * prop2 = get_prop2(arg);
569 return prop->setUnspecifiedValue(prop2->getStringValue());
577 * Built-in command: increment or decrement a property value.
579 * If the 'step' argument is present, it will be used; otherwise,
580 * the command uses 'offset' and 'factor', usually from the mouse.
582 * property: the name of the property to increment or decrement.
583 * step: the amount of the increment or decrement (default: 0).
584 * offset: offset from the current setting (used for the mouse; multiplied
586 * factor: scaling amount for the offset (defaults to 1).
587 * min: the minimum allowed value (default: no minimum).
588 * max: the maximum allowed value (default: no maximum).
589 * mask: 'integer' to apply only to the left of the decimal point,
590 * 'decimal' to apply only to the right of the decimal point,
591 * or 'all' to apply to the whole number (the default).
592 * wrap: true if the value should be wrapped when it passes min or max;
593 * both min and max must be present for this to work (default:
597 do_property_adjust (const SGPropertyNode * arg)
599 SGPropertyNode * prop = get_prop(arg);
602 if (arg->hasValue("step"))
603 amount = arg->getDoubleValue("step");
605 amount = (arg->getDoubleValue("factor", 1)
606 * arg->getDoubleValue("offset"));
608 double unmodifiable, modifiable;
609 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
610 &unmodifiable, &modifiable);
611 modifiable += amount;
612 limit_value(&modifiable, arg);
614 prop->setDoubleValue(unmodifiable + modifiable);
621 * Built-in command: multiply a property value.
623 * property: the name of the property to multiply.
624 * factor: the amount by which to multiply.
625 * min: the minimum allowed value (default: no minimum).
626 * max: the maximum allowed value (default: no maximum).
627 * mask: 'integer' to apply only to the left of the decimal point,
628 * 'decimal' to apply only to the right of the decimal point,
629 * or 'all' to apply to the whole number (the default).
630 * wrap: true if the value should be wrapped when it passes min or max;
631 * both min and max must be present for this to work (default:
635 do_property_multiply (const SGPropertyNode * arg)
637 SGPropertyNode * prop = get_prop(arg);
638 double factor = arg->getDoubleValue("factor", 1);
640 double unmodifiable, modifiable;
641 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
642 &unmodifiable, &modifiable);
643 modifiable *= factor;
644 limit_value(&modifiable, arg);
646 prop->setDoubleValue(unmodifiable + modifiable);
653 * Built-in command: swap two property values.
655 * property[0]: the name of the first property.
656 * property[1]: the name of the second property.
659 do_property_swap (const SGPropertyNode * arg)
661 SGPropertyNode * prop1 = get_prop(arg);
662 SGPropertyNode * prop2 = get_prop2(arg);
664 // FIXME: inefficient
665 const string & tmp = prop1->getStringValue();
666 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
667 prop2->setUnspecifiedValue(tmp.c_str()));
672 * Built-in command: Set a property to an axis or other moving input.
674 * property: the name of the property to set.
675 * setting: the current input setting, usually between -1.0 and 1.0.
676 * offset: the offset to shift by, before applying the factor.
677 * factor: the factor to multiply by (use negative to reverse).
680 do_property_scale (const SGPropertyNode * arg)
682 SGPropertyNode * prop = get_prop(arg);
683 double setting = arg->getDoubleValue("setting");
684 double offset = arg->getDoubleValue("offset", 0.0);
685 double factor = arg->getDoubleValue("factor", 1.0);
686 bool squared = arg->getBoolValue("squared", false);
687 int power = arg->getIntValue("power", (squared ? 2 : 1));
689 int sign = (setting < 0 ? -1 : 1);
695 setting = setting * setting * sign;
698 setting = setting * setting * setting;
701 setting = setting * setting * setting * setting * sign;
704 setting = pow(setting, power);
705 if ((power % 2) == 0)
710 return prop->setDoubleValue((setting + offset) * factor);
715 * Built-in command: cycle a property through a set of values.
717 * If the current value isn't in the list, the cycle will
718 * (re)start from the beginning.
720 * property: the name of the property to cycle.
721 * value[*]: the list of values to cycle through.
724 do_property_cycle (const SGPropertyNode * arg)
726 SGPropertyNode * prop = get_prop(arg);
727 std::vector<SGPropertyNode_ptr> values = arg->getChildren("value");
729 bool wrap = arg->getBoolValue("wrap", true);
730 // compatible with knob/pick animations
731 int offset = arg->getIntValue("offset", 1);
734 int nSelections = values.size();
736 if (nSelections < 1) {
737 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
741 // Try to find the current selection
742 for (int i = 0; i < nSelections; i++) {
743 if (compare_values(prop, values[i])) {
749 if (selection < 0) { // default to first selection
754 selection = (selection + nSelections) % nSelections;
756 SG_CLAMP_RANGE(selection, 0, nSelections - 1);
760 prop->setUnspecifiedValue(values[selection]->getStringValue());
766 * Built-in command: randomize a numeric property value.
768 * property: the name of the property value to randomize.
769 * min: the minimum allowed value.
770 * max: the maximum allowed value.
773 do_property_randomize (const SGPropertyNode * arg)
775 SGPropertyNode * prop = get_prop(arg);
776 double min = arg->getDoubleValue("min", DBL_MIN);
777 double max = arg->getDoubleValue("max", DBL_MAX);
778 prop->setDoubleValue(sg_random() * (max - min) + min);
783 * Built-in command: interpolate a property value over time
785 * property: the name of the property value to interpolate.
786 * type: the interpolation type ("numeric", "color", etc.)
787 * easing: name of easing function (see http://easings.net/)
788 * value[0..n] any number of constant values to interpolate
789 * time/rate[0..n] time between each value, number of time elements must
790 * match those of value elements. Instead of time also rate can
791 * be used which automatically calculates the time to change
792 * the property value at the given speed.
794 * property[1..n+1] any number of target values taken from named properties
795 * time/rate[0..n] time between each value, number of time elements must
796 * match those of value elements. Instead of time also rate can
797 * be used which automatically calculates the time to change
798 * the property value at the given speed.
801 do_property_interpolate (const SGPropertyNode * arg)
803 SGPropertyNode * prop = get_prop(arg);
807 simgear::PropertyList time_nodes = arg->getChildren("time");
808 simgear::PropertyList rate_nodes = arg->getChildren("rate");
810 if( !time_nodes.empty() && !rate_nodes.empty() )
811 // mustn't specify time and rate
814 simgear::PropertyList::size_type num_times = time_nodes.empty()
818 simgear::PropertyList value_nodes = arg->getChildren("value");
819 if( value_nodes.empty() )
821 simgear::PropertyList prop_nodes = arg->getChildren("property");
823 // must have one more property node
824 if( prop_nodes.size() != num_times + 1 )
827 value_nodes.reserve(num_times);
828 for( size_t i = 1; i < prop_nodes.size(); ++i )
829 value_nodes.push_back( fgGetNode(prop_nodes[i]->getStringValue()) );
833 if( value_nodes.size() != num_times )
837 deltas.reserve(num_times);
839 if( !time_nodes.empty() )
841 for( size_t i = 0; i < num_times; ++i )
842 deltas.push_back( time_nodes[i]->getDoubleValue() );
846 for( size_t i = 0; i < num_times; ++i )
848 // TODO calculate delta based on property type
849 double delta = value_nodes[i]->getDoubleValue()
851 ? value_nodes[i - 1]->getDoubleValue()
852 : prop->getDoubleValue()
854 deltas.push_back( fabs(delta / rate_nodes[i]->getDoubleValue()) );
858 return prop->interpolate
860 arg->getStringValue("type", "numeric"),
863 arg->getStringValue("easing", "linear")
868 * Built-in command: reinit the data logging system based on the
869 * current contents of the /logger tree.
872 do_data_logging_commit (const SGPropertyNode * arg)
874 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
880 * Built-in command: Add a dialog to the GUI system. Does *not*
881 * display the dialog. The property node should have the same format
882 * as a dialog XML configuration. It must include:
884 * name: the name of the GUI dialog for future reference.
887 do_dialog_new (const SGPropertyNode * arg)
889 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
894 // Note the casting away of const: this is *real*. Doing a
895 // "dialog-apply" command later on will mutate this property node.
896 // I'm not convinced that this isn't the Right Thing though; it
897 // allows client to create a node, pass it to dialog-new, and get
898 // the values back from the dialog by reading the same node.
899 // Perhaps command arguments are not as "const" as they would
901 gui->newDialog((SGPropertyNode*)arg);
906 * Built-in command: Show an XML-configured dialog.
908 * dialog-name: the name of the GUI dialog to display.
911 do_dialog_show (const SGPropertyNode * arg)
913 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
914 gui->showDialog(arg->getStringValue("dialog-name"));
920 * Built-in Command: Hide the active XML-configured dialog.
923 do_dialog_close (const SGPropertyNode * arg)
925 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
926 if(arg->hasValue("dialog-name"))
927 return gui->closeDialog(arg->getStringValue("dialog-name"));
928 return gui->closeActiveDialog();
933 * Update a value in the active XML-configured dialog.
935 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
938 do_dialog_update (const SGPropertyNode * arg)
940 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
942 if (arg->hasValue("dialog-name"))
943 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
945 dialog = gui->getActiveDialog();
948 dialog->updateValues(arg->getStringValue("object-name"));
956 do_open_browser (const SGPropertyNode * arg)
959 if (arg->hasValue("path"))
960 path = arg->getStringValue("path");
962 if (arg->hasValue("url"))
963 path = arg->getStringValue("url");
967 return openBrowser(path);
971 * Apply a value in the active XML-configured dialog.
973 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
976 do_dialog_apply (const SGPropertyNode * arg)
978 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
980 if (arg->hasValue("dialog-name"))
981 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
983 dialog = gui->getActiveDialog();
986 dialog->applyValues(arg->getStringValue("object-name"));
995 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
999 do_gui_redraw (const SGPropertyNode * arg)
1001 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1008 * Adds model to the scenery. The path to the added branch (/models/model[*])
1009 * is returned in property "property".
1012 do_add_model (const SGPropertyNode * arg)
1014 SGPropertyNode * model = fgGetNode("models", true);
1016 for (i = 0; model->hasChild("model",i); i++);
1017 model = model->getChild("model", i, true);
1018 copyProperties(arg, model);
1019 if (model->hasValue("elevation-m"))
1020 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1021 * SG_METER_TO_FEET);
1022 model->getNode("load", true);
1023 model->removeChildren("load");
1024 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1029 * Built-in command: play an audio message (i.e. a wav file) This is
1030 * fire and forget. Call this once per message and it will get dumped
1031 * into a queue. Messages are played sequentially so they do not
1035 do_play_audio_sample (const SGPropertyNode * arg)
1037 SGSoundMgr *smgr = globals->get_soundmgr();
1039 SG_LOG(SG_GENERAL, SG_WARN, "play-audio-sample: sound-manager not running");
1043 string path = arg->getStringValue("path");
1044 string file = arg->getStringValue("file");
1045 float volume = arg->getFloatValue("volume");
1046 // cout << "playing " << path << " / " << file << endl;
1048 FGSampleQueue *queue = globals->get_chatter_queue();
1050 queue = new FGSampleQueue(smgr, "chatter");
1051 queue->tie_to_listener();
1052 globals->set_chatter_queue(queue);
1055 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1056 msg->set_volume( volume );
1061 } catch (const sg_io_exception&) {
1062 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1063 "failed to load" << path << '/' << file);
1069 * Built-in command: commit presets (read from in /sim/presets/)
1072 do_presets_commit (const SGPropertyNode * arg)
1074 if (fgGetBool("/sim/initialized", false)) {
1077 // Nasal can trigger this during initial init, which confuses
1078 // the logic in ReInitSubsystems, since initial state has not been
1079 // saved at that time. Short-circuit everything here.
1080 flightgear::initPosition();
1087 * Built-in command: set log level (0 ... 7)
1090 do_log_level (const SGPropertyNode * arg)
1092 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1099 do_decrease_visibility (const SGPropertyNode * arg)
1101 Environment::Presets::VisibilitySingleton::instance()->adjust( 0.9 );
1106 do_increase_visibility (const SGPropertyNode * arg)
1108 Environment::Presets::VisibilitySingleton::instance()->adjust( 1.1 );
1113 * An fgcommand to allow loading of xml files via nasal,
1114 * the xml file's structure will be made available within
1115 * a property tree node defined under argument "targetnode",
1116 * or in the given argument tree under "data" otherwise.
1118 * @param filename a string to hold the complete path & filename of an XML file
1119 * @param targetnode a string pointing to a location within the property tree
1120 * where to store the parsed XML file. If <targetnode> is undefined, then the
1121 * file contents are stored under a node <data> in the argument tree.
1125 do_load_xml_to_proptree(const SGPropertyNode * arg)
1127 SGPath file(arg->getStringValue("filename"));
1128 if (file.str().empty())
1131 if (file.extension() != "xml")
1132 file.concat(".xml");
1134 std::string icao = arg->getStringValue("icao");
1136 if (file.isRelative()) {
1137 SGPath absPath = globals->resolve_maybe_aircraft_path(file.str());
1138 if (!absPath.isNull())
1142 SG_LOG(SG_IO, SG_ALERT, "loadxml: Cannot find XML property file '"
1143 << file.str() << "'.");
1148 if (!XMLLoader::findAirportData(icao, file.str(), file)) {
1149 SG_LOG(SG_IO, SG_INFO, "loadxml: failed to find airport data for "
1150 << file.str() << " at ICAO:" << icao);
1155 if (!fgValidatePath(file.c_str(), false)) {
1156 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1157 "(unauthorized access)");
1161 SGPropertyNode *targetnode;
1162 if (arg->hasValue("targetnode"))
1163 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1165 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1168 readProperties(file.c_str(), targetnode, true);
1169 } catch (const sg_exception &e) {
1170 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1177 class RemoteXMLRequest:
1178 public simgear::HTTP::MemoryRequest
1181 SGPropertyNode_ptr _complete;
1182 SGPropertyNode_ptr _status;
1183 SGPropertyNode_ptr _failed;
1184 SGPropertyNode_ptr _target;
1186 RemoteXMLRequest(const std::string& url, SGPropertyNode* targetNode) :
1187 simgear::HTTP::MemoryRequest(url),
1192 void setCompletionProp(SGPropertyNode_ptr p)
1197 void setStatusProp(SGPropertyNode_ptr p)
1202 void setFailedProp(SGPropertyNode_ptr p)
1209 virtual void onFail()
1211 SG_LOG(SG_IO, SG_INFO, "network level failure in RemoteXMLRequest");
1213 _failed->setBoolValue(true);
1217 virtual void onDone()
1219 int response = responseCode();
1220 bool failed = false;
1221 if (response == 200) {
1223 const char* buffer = responseBody().c_str();
1224 readProperties(buffer, responseBody().size(), _target, true);
1225 } catch (const sg_exception &e) {
1226 SG_LOG(SG_IO, SG_WARN, "parsing XML from remote, failed: " << e.getFormattedMessage());
1228 response = 406; // 'not acceptable', anything better?
1233 // now the response data is output, signal Nasal / listeners
1234 if (_complete) _complete->setBoolValue(true);
1235 if (_status) _status->setIntValue(response);
1236 if (_failed && failed) _failed->setBoolValue(true);
1242 do_load_xml_from_url(const SGPropertyNode * arg)
1244 FGHTTPClient* http = static_cast<FGHTTPClient*>(globals->get_subsystem("http"));
1246 SG_LOG(SG_IO, SG_ALERT, "xmlhttprequest: HTTP client not running");
1250 std::string url(arg->getStringValue("url"));
1254 SGPropertyNode *targetnode;
1255 if (arg->hasValue("targetnode"))
1256 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1258 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1260 RemoteXMLRequest* req = new RemoteXMLRequest(url, targetnode);
1262 if (arg->hasChild("body"))
1263 req->setBodyData(arg->getChild("body"));
1265 // connect up optional reporting properties
1266 if (arg->hasValue("complete"))
1267 req->setCompletionProp(fgGetNode(arg->getStringValue("complete"), true));
1268 if (arg->hasValue("failure"))
1269 req->setFailedProp(fgGetNode(arg->getStringValue("failure"), true));
1270 if (arg->hasValue("status"))
1271 req->setStatusProp(fgGetNode(arg->getStringValue("status"), true));
1273 http->makeRequest(req);
1279 * An fgcommand to allow saving of xml files via nasal,
1280 * the file's structure will be determined based on what's
1281 * encountered in the passed (source) property tree node
1283 * @param filename a string to hold the complete path & filename of the (new)
1285 * @param sourcenode a string pointing to a location within the property tree
1286 * where to find the nodes that should be written recursively into an XML file
1287 * @param data if no sourcenode is given, then the file contents are taken from
1288 * the argument tree's "data" node.
1292 do_save_xml_from_proptree(const SGPropertyNode * arg)
1294 SGPath file(arg->getStringValue("filename"));
1295 if (file.str().empty())
1298 if (file.extension() != "xml")
1299 file.concat(".xml");
1301 if (!fgValidatePath(file.c_str(), true)) {
1302 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1303 "(unauthorized access)");
1307 SGPropertyNode *sourcenode;
1308 if (arg->hasValue("sourcenode"))
1309 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1310 else if (arg->getNode("data", false))
1311 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1316 writeProperties (file.c_str(), sourcenode, true);
1317 } catch (const sg_exception &e) {
1318 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1326 do_press_cockpit_button (const SGPropertyNode *arg)
1328 const char *prefix = arg->getStringValue("prefix");
1330 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1333 string prop = string(prefix) + "-button";
1336 if (arg->getBoolValue("latching"))
1337 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1341 fgSetDouble(prop.c_str(), value);
1342 fgSetBool(arg->getStringValue("discrete"), value > 0);
1348 do_release_cockpit_button (const SGPropertyNode *arg)
1350 const char *prefix = arg->getStringValue("prefix");
1352 if (arg->getBoolValue("guarded")) {
1353 string prop = string(prefix) + "-guard";
1354 if (fgGetDouble(prop.c_str()) < 1) {
1355 fgSetDouble(prop.c_str(), 1);
1360 if (! arg->getBoolValue("latching")) {
1361 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1362 fgSetBool(arg->getStringValue("discrete"), false);
1368 // Optional profiling commands using gperftools:
1369 // http://code.google.com/p/gperftools/
1371 #if !FG_HAVE_GPERFTOOLS
1373 no_profiling_support()
1379 "No profiling support! Install gperftools and reconfigure/rebuild fgfs."
1385 do_profiler_start(const SGPropertyNode *arg)
1387 #if FG_HAVE_GPERFTOOLS
1388 const char *filename = arg->getStringValue("filename", "fgfs.profile");
1389 ProfilerStart(filename);
1392 no_profiling_support();
1398 do_profiler_stop(const SGPropertyNode *arg)
1400 #if FG_HAVE_GPERFTOOLS
1404 no_profiling_support();
1411 do_set_scenery_paths(const SGPropertyNode* arg)
1413 SGPropertyNode* sim = fgGetNode("/sim", true);
1414 sim->removeChildren("fg-scenery");
1416 globals->clear_fg_scenery();
1418 std::string terrasyncPath(fgGetString("/sim/terrasync/scenery-dir"));
1419 bool seenTerrasyncPath = false;
1421 simgear::PropertyList paths = arg->getChildren("path");
1422 for (size_t i = 0; i < paths.size(); ++i) {
1423 std::string s = paths[i]->getStringValue();
1424 if (s == terrasyncPath) {
1425 seenTerrasyncPath = true;
1428 globals->append_fg_scenery(s);
1431 if (fgGetBool("/sim/terrasync/enabled") && !seenTerrasyncPath) {
1432 globals->append_fg_scenery(terrasyncPath);
1435 if (paths.empty()) {
1436 // no scenery paths set *at all*, use the data in FG_ROOT
1437 SGPath root(globals->get_fg_root());
1438 root.append("Scenery");
1439 globals->append_fg_scenery(root.str());
1445 ////////////////////////////////////////////////////////////////////////
1447 ////////////////////////////////////////////////////////////////////////
1451 * Table of built-in commands.
1453 * New commands do not have to be added here; any module in the application
1454 * can add a new command using globals->get_commands()->addCommand(...).
1458 SGCommandMgr::command_t command;
1460 { "null", do_null },
1461 { "nasal", do_nasal },
1462 { "exit", do_exit },
1463 { "reset", do_reset },
1464 { "reposition", do_reposition },
1465 { "pause", do_pause },
1466 { "load", do_load },
1467 { "save", do_save },
1468 { "save-tape", do_save_tape },
1469 { "load-tape", do_load_tape },
1470 { "panel-load", do_panel_load },
1471 { "preferences-load", do_preferences_load },
1472 { "toggle-fullscreen", do_toggle_fullscreen },
1473 { "view-cycle", do_view_cycle },
1474 { "screen-capture", do_screen_capture },
1475 { "hires-screen-capture", do_hires_screen_capture },
1476 { "tile-cache-reload", do_tile_cache_reload },
1478 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1479 { "set-outside-air-temp-degc", do_set_oat_degc },
1480 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1481 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1483 { "property-toggle", do_property_toggle },
1484 { "property-assign", do_property_assign },
1485 { "property-adjust", do_property_adjust },
1486 { "property-multiply", do_property_multiply },
1487 { "property-swap", do_property_swap },
1488 { "property-scale", do_property_scale },
1489 { "property-cycle", do_property_cycle },
1490 { "property-randomize", do_property_randomize },
1491 { "property-interpolate", do_property_interpolate },
1492 { "data-logging-commit", do_data_logging_commit },
1493 { "dialog-new", do_dialog_new },
1494 { "dialog-show", do_dialog_show },
1495 { "dialog-close", do_dialog_close },
1496 { "dialog-update", do_dialog_update },
1497 { "dialog-apply", do_dialog_apply },
1498 { "open-browser", do_open_browser },
1499 { "gui-redraw", do_gui_redraw },
1500 { "add-model", do_add_model },
1501 { "play-audio-sample", do_play_audio_sample },
1502 { "presets-commit", do_presets_commit },
1503 { "log-level", do_log_level },
1504 { "replay", do_replay },
1506 { "decrease-visibility", do_decrease_visibility },
1507 { "increase-visibility", do_increase_visibility },
1509 { "loadxml", do_load_xml_to_proptree},
1510 { "savexml", do_save_xml_from_proptree },
1511 { "xmlhttprequest", do_load_xml_from_url },
1512 { "press-cockpit-button", do_press_cockpit_button },
1513 { "release-cockpit-button", do_release_cockpit_button },
1514 { "dump-scenegraph", do_dump_scene_graph },
1515 { "dump-terrainbranch", do_dump_terrain_branch },
1516 { "print-visible-scene", do_print_visible_scene_info },
1517 { "reload-shaders", do_reload_shaders },
1518 { "reload-materials", do_materials_reload },
1519 { "set-scenery-paths", do_set_scenery_paths },
1521 { "profiler-start", do_profiler_start },
1522 { "profiler-stop", do_profiler_stop },
1524 { 0, 0 } // zero-terminated
1529 * Initialize the default built-in commands.
1531 * Other commands may be added by other parts of the application.
1536 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1537 for (int i = 0; built_ins[i].name != 0; i++) {
1538 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1539 globals->get_commands()->addCommand(built_ins[i].name,
1540 built_ins[i].command);
1543 typedef bool (*dummy)();
1544 fgTie( "/command/view/next", dummy(0), do_view_next );
1545 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1547 globals->get_props()->setValueReadOnly( "/sim/debug/profiler-available",
1548 bool(FG_HAVE_GPERFTOOLS) );
1551 // end of fg_commands.cxx