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/structure/event_mgr.hxx>
23 #include <simgear/sound/soundmgr_openal.hxx>
24 #include <simgear/timing/sg_time.hxx>
26 #include <Cockpit/panel.hxx>
27 #include <Cockpit/panel_io.hxx>
28 #include <Environment/environment.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 <Time/sunsolver.hxx>
39 #include "fg_init.hxx"
42 #include "fg_commands.hxx"
43 #include "fg_props.hxx"
44 #include "globals.hxx"
47 #include "viewmgr.hxx"
49 #include <Main/viewer.hxx>
57 ////////////////////////////////////////////////////////////////////////
58 // Static helper functions.
59 ////////////////////////////////////////////////////////////////////////
62 static inline SGPropertyNode *
63 get_prop (const SGPropertyNode * arg)
65 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
68 static inline SGPropertyNode *
69 get_prop2 (const SGPropertyNode * arg)
71 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
76 * Get a double value and split it as required.
79 split_value (double full_value, const char * mask,
80 double * unmodifiable, double * modifiable)
82 if (!strcmp("integer", mask)) {
83 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
84 *unmodifiable = full_value - *modifiable;
85 } else if (!strcmp("decimal", mask)) {
86 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
87 *modifiable = full_value - *unmodifiable;
89 if (strcmp("all", mask))
90 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
91 << " assuming 'all'");
93 *modifiable = full_value;
99 * Clamp or wrap a value as specified.
102 limit_value (double * value, const SGPropertyNode * arg)
104 const SGPropertyNode * min_node = arg->getChild("min");
105 const SGPropertyNode * max_node = arg->getChild("max");
107 bool wrap = arg->getBoolValue("wrap");
109 if (min_node == 0 || max_node == 0)
112 if (wrap) { // wrap such that min <= x < max
113 double min_val = min_node->getDoubleValue();
114 double max_val = max_node->getDoubleValue();
115 double resolution = arg->getDoubleValue("resolution");
116 if (resolution > 0.0) {
117 // snap to (min + N*resolution), taking special care to handle imprecision
118 int n = (int)floor((*value - min_val) / resolution + 0.5);
119 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
120 SG_NORMALIZE_RANGE(n, 0, steps);
121 *value = min_val + resolution * n;
123 // plain circular wrapping
124 SG_NORMALIZE_RANGE(*value, min_val, max_val);
126 } else { // clamp such that min <= x <= max
127 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
128 *value = min_node->getDoubleValue();
129 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
130 *value = max_node->getDoubleValue();
135 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
137 switch (value1->getType()) {
138 case simgear::props::BOOL:
139 return (value1->getBoolValue() == value2->getBoolValue());
140 case simgear::props::INT:
141 return (value1->getIntValue() == value2->getIntValue());
142 case simgear::props::LONG:
143 return (value1->getLongValue() == value2->getLongValue());
144 case simgear::props::FLOAT:
145 return (value1->getFloatValue() == value2->getFloatValue());
146 case simgear::props::DOUBLE:
147 return (value1->getDoubleValue() == value2->getDoubleValue());
149 return !strcmp(value1->getStringValue(), value2->getStringValue());
155 ////////////////////////////////////////////////////////////////////////
156 // Command implementations.
157 ////////////////////////////////////////////////////////////////////////
161 * Built-in command: do nothing.
164 do_null (const SGPropertyNode * arg)
170 * Built-in command: run a Nasal script.
173 do_nasal (const SGPropertyNode * arg)
175 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
179 * Built-in command: exit FlightGear.
181 * status: the exit status to return to the operating system (defaults to 0)
184 do_exit (const SGPropertyNode * arg)
186 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
187 fgSetBool("/sim/signals/exit", true);
189 if (fgGetBool("/sim/startup/save-on-exit")) {
191 char* envp = ::getenv( "APPDATA" );
192 if ( envp != NULL ) {
193 SGPath config( envp );
194 config.append( "flightgear.org" );
196 if ( homedir != NULL ) {
197 SGPath config( homedir );
198 config.append( ".fgfs" );
200 config.append( "autosave.xml" );
201 config.create_dir( 0700 );
202 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << config.str());
204 writeProperties(config.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
205 } catch (const sg_exception &e) {
206 guiErrorMessage("Error writing autosave.xml: ", e);
209 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
213 fgOSExit(arg->getIntValue("status", 0));
219 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
222 do_reset (const SGPropertyNode * arg)
230 * Built-in command: reinitialize one or more subsystems.
232 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
233 * none is specified, reinitialize all of them.
236 do_reinit (const SGPropertyNode * arg)
240 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
241 if (subsystems.size() == 0) {
242 globals->get_subsystem_mgr()->reinit();
244 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
245 const char * name = subsystems[i]->getStringValue();
246 SGSubsystem * subsystem = globals->get_subsystem(name);
247 if (subsystem == 0) {
249 SG_LOG( SG_GENERAL, SG_ALERT,
250 "Subsystem " << name << "not found" );
257 globals->get_event_mgr()->reinit();
264 // these routines look useful ??? but are never used in the code ???
268 * Built-in command: suspend one or more subsystems.
270 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
273 do_suspend (const SGPropertyNode * arg)
277 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
278 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
279 const char * name = subsystems[i]->getStringValue();
280 SGSubsystem * subsystem = globals->get_subsystem(name);
281 if (subsystem == 0) {
283 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
285 subsystem->suspend();
292 * Built-in command: suspend one or more subsystems.
294 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
297 do_resume (const SGPropertyNode * arg)
301 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
302 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
303 const char * name = subsystems[i]->getStringValue();
304 SGSubsystem * subsystem = globals->get_subsystem(name);
305 if (subsystem == 0) {
307 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
319 * Built-in command: load flight.
321 * file (optional): the name of the file to load (relative to current
322 * directory). Defaults to "fgfs.sav"
325 do_load (const SGPropertyNode * arg)
327 string file = arg->getStringValue("file", "fgfs.sav");
328 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
331 if (!fgValidatePath(file.c_str(), false)) {
332 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
333 "(unauthorized access)");
337 ifstream input(file.c_str());
338 if (input.good() && fgLoadFlight(input)) {
340 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
343 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
350 * Built-in command: save flight.
352 * file (optional): the name of the file to save (relative to the
353 * current directory). Defaults to "fgfs.sav".
356 do_save (const SGPropertyNode * arg)
358 string file = arg->getStringValue("file", "fgfs.sav");
359 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
362 if (!fgValidatePath(file.c_str(), false)) {
363 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
364 "(unauthorized access)");
368 bool write_all = arg->getBoolValue("write-all", false);
369 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
370 ofstream output(file.c_str());
371 if (output.good() && fgSaveFlight(output, write_all)) {
373 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
376 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
383 * Built-in command: (re)load the panel.
385 * path (optional): the file name to load the panel from
386 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
387 * and if that's unspecified, to "Panels/Default/default.xml".
390 do_panel_load (const SGPropertyNode * arg)
393 arg->getStringValue("path", fgGetString("/sim/panel/path"));
394 if (panel_path.empty()) {
398 FGPanel * new_panel = fgReadPanel(panel_path);
399 if (new_panel == 0) {
400 SG_LOG(SG_INPUT, SG_ALERT,
401 "Error reading new panel from " << panel_path);
404 SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
405 globals->get_current_panel()->unbind();
406 delete globals->get_current_panel();
407 globals->set_current_panel( new_panel );
408 globals->get_current_panel()->bind();
414 * Built-in command: pass a mouse click to the panel.
416 * button: the mouse button number, zero-based.
417 * is-down: true if the button is down, false if it is up.
418 * x-pos: the x position of the mouse click.
419 * y-pos: the y position of the mouse click.
422 do_panel_mouse_click (const SGPropertyNode * arg)
424 if (globals->get_current_panel() != 0)
425 return globals->get_current_panel()
426 ->doMouseAction(arg->getIntValue("button"),
427 arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
428 arg->getIntValue("x-pos"),
429 arg->getIntValue("y-pos"));
436 * Built-in command: (re)load preferences.
438 * path (optional): the file name to load the panel from (relative
439 * to FG_ROOT). Defaults to "preferences.xml".
442 do_preferences_load (const SGPropertyNode * arg)
445 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
446 globals->get_props());
447 } catch (const sg_exception &e) {
448 guiErrorMessage("Error reading global preferences: ", e);
451 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
458 globals->get_current_view()->setHeadingOffset_deg(0.0);
459 globals->get_viewmgr()->next_view();
465 globals->get_current_view()->setHeadingOffset_deg(0.0);
466 globals->get_viewmgr()->prev_view();
470 * Built-in command: cycle view.
473 do_view_cycle (const SGPropertyNode * arg)
475 globals->get_current_view()->setHeadingOffset_deg(0.0);
476 globals->get_viewmgr()->next_view();
481 * Built-in command: capture screen.
484 do_screen_capture (const SGPropertyNode * arg)
486 return fgDumpSnapShot();
490 do_reload_shaders (const SGPropertyNode*)
492 simgear::reload_shaders();
497 do_dump_scene_graph (const SGPropertyNode*)
504 do_dump_terrain_branch (const SGPropertyNode*)
506 fgDumpTerrainBranch();
508 double lon_deg = fgGetDouble("/position/longitude-deg");
509 double lat_deg = fgGetDouble("/position/latitude-deg");
510 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
511 SGVec3d zero = SGVec3d::fromGeod(geodPos);
513 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
514 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
515 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
521 do_print_visible_scene_info(const SGPropertyNode*)
523 fgPrintVisibleSceneInfoCommand();
528 * Built-in command: hires capture screen.
531 do_hires_screen_capture (const SGPropertyNode * arg)
539 * Reload the tile cache.
542 do_tile_cache_reload (const SGPropertyNode * arg)
544 static const SGPropertyNode *master_freeze
545 = fgGetNode("/sim/freeze/master");
546 bool freeze = master_freeze->getBoolValue();
547 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
549 fgSetBool("/sim/freeze/master", true);
552 globals->get_subsystem("tile-manager")->reinit();
555 fgSetBool("/sim/freeze/master", false);
562 * Set the sea level outside air temperature and assigning that to all
563 * boundary and aloft environment layers.
566 do_set_sea_level_degc ( double temp_sea_level_degc)
568 SGPropertyNode *node, *child;
571 node = fgGetNode( "/environment/config/boundary" );
572 if ( node != NULL ) {
574 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
575 child->setDoubleValue( "temperature-sea-level-degc",
576 temp_sea_level_degc );
582 node = fgGetNode( "/environment/config/aloft" );
583 if ( node != NULL ) {
585 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
586 child->setDoubleValue( "temperature-sea-level-degc",
587 temp_sea_level_degc );
596 do_set_sea_level_degc (const SGPropertyNode * arg)
598 return do_set_sea_level_degc( arg->getDoubleValue("temp-degc", 15.0) );
603 * Set the outside air temperature at the "current" altitude by first
604 * calculating the corresponding sea level temp, and assigning that to
605 * all boundary and aloft environment layers.
608 do_set_oat_degc (const SGPropertyNode * arg)
610 double oat_degc = arg->getDoubleValue("temp-degc", 15.0);
611 // check for an altitude specified in the arguments, otherwise use
612 // current aircraft altitude.
613 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
614 if ( altitude_ft == NULL ) {
615 altitude_ft = fgGetNode("/position/altitude-ft");
618 FGEnvironment dummy; // instantiate a dummy so we can leech a method
619 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
620 dummy.set_temperature_degc( oat_degc );
621 return do_set_sea_level_degc( dummy.get_temperature_sea_level_degc());
625 * Set the sea level outside air dewpoint and assigning that to all
626 * boundary and aloft environment layers.
629 do_set_dewpoint_sea_level_degc (double dewpoint_sea_level_degc)
632 SGPropertyNode *node, *child;
635 node = fgGetNode( "/environment/config/boundary" );
636 if ( node != NULL ) {
638 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
639 child->setDoubleValue( "dewpoint-sea-level-degc",
640 dewpoint_sea_level_degc );
646 node = fgGetNode( "/environment/config/aloft" );
647 if ( node != NULL ) {
649 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
650 child->setDoubleValue( "dewpoint-sea-level-degc",
651 dewpoint_sea_level_degc );
660 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
662 return do_set_dewpoint_sea_level_degc(arg->getDoubleValue("dewpoint-degc", 5.0));
666 * Set the outside air dewpoint at the "current" altitude by first
667 * calculating the corresponding sea level dewpoint, and assigning
668 * that to all boundary and aloft environment layers.
671 do_set_dewpoint_degc (const SGPropertyNode * arg)
673 double dewpoint_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
675 // check for an altitude specified in the arguments, otherwise use
676 // current aircraft altitude.
677 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
678 if ( altitude_ft == NULL ) {
679 altitude_ft = fgGetNode("/position/altitude-ft");
682 FGEnvironment dummy; // instantiate a dummy so we can leech a method
683 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
684 dummy.set_dewpoint_degc( dewpoint_degc );
685 return do_set_dewpoint_sea_level_degc(dummy.get_dewpoint_sea_level_degc());
689 * Update the lighting manually.
692 do_timeofday (const SGPropertyNode * arg)
694 const string &offset_type = arg->getStringValue("timeofday", "noon");
696 static const SGPropertyNode *longitude
697 = fgGetNode("/position/longitude-deg");
698 static const SGPropertyNode *latitude
699 = fgGetNode("/position/latitude-deg");
700 static const SGPropertyNode *cur_time_override
701 = fgGetNode("/sim/time/cur-time-override", true);
703 int orig_warp = globals->get_warp();
704 SGTime *t = globals->get_time_params();
705 time_t cur_time = t->get_cur_time();
706 // cout << "cur_time = " << cur_time << endl;
707 // cout << "orig_warp = " << orig_warp << endl;
710 if ( offset_type == "real" ) {
712 } else if ( offset_type == "dawn" ) {
713 warp = fgTimeSecondsUntilSunAngle( cur_time,
714 longitude->getDoubleValue()
715 * SGD_DEGREES_TO_RADIANS,
716 latitude->getDoubleValue()
717 * SGD_DEGREES_TO_RADIANS,
719 } else if ( offset_type == "morning" ) {
720 warp = fgTimeSecondsUntilSunAngle( cur_time,
721 longitude->getDoubleValue()
722 * SGD_DEGREES_TO_RADIANS,
723 latitude->getDoubleValue()
724 * SGD_DEGREES_TO_RADIANS,
726 } else if ( offset_type == "noon" ) {
727 warp = fgTimeSecondsUntilSunAngle( cur_time,
728 longitude->getDoubleValue()
729 * SGD_DEGREES_TO_RADIANS,
730 latitude->getDoubleValue()
731 * SGD_DEGREES_TO_RADIANS,
733 } else if ( offset_type == "afternoon" ) {
734 warp = fgTimeSecondsUntilSunAngle( cur_time,
735 longitude->getDoubleValue()
736 * SGD_DEGREES_TO_RADIANS,
737 latitude->getDoubleValue()
738 * SGD_DEGREES_TO_RADIANS,
740 } else if ( offset_type == "dusk" ) {
741 warp = fgTimeSecondsUntilSunAngle( cur_time,
742 longitude->getDoubleValue()
743 * SGD_DEGREES_TO_RADIANS,
744 latitude->getDoubleValue()
745 * SGD_DEGREES_TO_RADIANS,
747 } else if ( offset_type == "evening" ) {
748 warp = fgTimeSecondsUntilSunAngle( cur_time,
749 longitude->getDoubleValue()
750 * SGD_DEGREES_TO_RADIANS,
751 latitude->getDoubleValue()
752 * SGD_DEGREES_TO_RADIANS,
754 } else if ( offset_type == "midnight" ) {
755 warp = fgTimeSecondsUntilSunAngle( cur_time,
756 longitude->getDoubleValue()
757 * SGD_DEGREES_TO_RADIANS,
758 latitude->getDoubleValue()
759 * SGD_DEGREES_TO_RADIANS,
762 // cout << "warp = " << warp << endl;
763 globals->set_warp( orig_warp + warp );
765 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
766 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
767 cur_time_override->getLongValue(),
768 globals->get_warp() );
775 * Built-in command: toggle a bool property value.
777 * property: The name of the property to toggle.
780 do_property_toggle (const SGPropertyNode * arg)
782 SGPropertyNode * prop = get_prop(arg);
783 return prop->setBoolValue(!prop->getBoolValue());
788 * Built-in command: assign a value to a property.
790 * property: the name of the property to assign.
791 * value: the value to assign; or
792 * property[1]: the property to copy from.
795 do_property_assign (const SGPropertyNode * arg)
797 SGPropertyNode * prop = get_prop(arg);
798 const SGPropertyNode * prop2 = get_prop2(arg);
799 const SGPropertyNode * value = arg->getNode("value");
802 return prop->setUnspecifiedValue(value->getStringValue());
804 return prop->setUnspecifiedValue(prop2->getStringValue());
811 * Built-in command: increment or decrement a property value.
813 * If the 'step' argument is present, it will be used; otherwise,
814 * the command uses 'offset' and 'factor', usually from the mouse.
816 * property: the name of the property to increment or decrement.
817 * step: the amount of the increment or decrement (default: 0).
818 * offset: offset from the current setting (used for the mouse; multiplied
820 * factor: scaling amount for the offset (defaults to 1).
821 * min: the minimum allowed value (default: no minimum).
822 * max: the maximum allowed value (default: no maximum).
823 * mask: 'integer' to apply only to the left of the decimal point,
824 * 'decimal' to apply only to the right of the decimal point,
825 * or 'all' to apply to the whole number (the default).
826 * wrap: true if the value should be wrapped when it passes min or max;
827 * both min and max must be present for this to work (default:
831 do_property_adjust (const SGPropertyNode * arg)
833 SGPropertyNode * prop = get_prop(arg);
836 if (arg->hasValue("step"))
837 amount = arg->getDoubleValue("step");
839 amount = (arg->getDoubleValue("factor", 1)
840 * arg->getDoubleValue("offset"));
842 double unmodifiable, modifiable;
843 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
844 &unmodifiable, &modifiable);
845 modifiable += amount;
846 limit_value(&modifiable, arg);
848 prop->setDoubleValue(unmodifiable + modifiable);
855 * Built-in command: multiply a property value.
857 * property: the name of the property to multiply.
858 * factor: the amount by which to multiply.
859 * min: the minimum allowed value (default: no minimum).
860 * max: the maximum allowed value (default: no maximum).
861 * mask: 'integer' to apply only to the left of the decimal point,
862 * 'decimal' to apply only to the right of the decimal point,
863 * or 'all' to apply to the whole number (the default).
864 * wrap: true if the value should be wrapped when it passes min or max;
865 * both min and max must be present for this to work (default:
869 do_property_multiply (const SGPropertyNode * arg)
871 SGPropertyNode * prop = get_prop(arg);
872 double factor = arg->getDoubleValue("factor", 1);
874 double unmodifiable, modifiable;
875 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
876 &unmodifiable, &modifiable);
877 modifiable *= factor;
878 limit_value(&modifiable, arg);
880 prop->setDoubleValue(unmodifiable + modifiable);
887 * Built-in command: swap two property values.
889 * property[0]: the name of the first property.
890 * property[1]: the name of the second property.
893 do_property_swap (const SGPropertyNode * arg)
895 SGPropertyNode * prop1 = get_prop(arg);
896 SGPropertyNode * prop2 = get_prop2(arg);
898 // FIXME: inefficient
899 const string & tmp = prop1->getStringValue();
900 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
901 prop2->setUnspecifiedValue(tmp.c_str()));
906 * Built-in command: Set a property to an axis or other moving input.
908 * property: the name of the property to set.
909 * setting: the current input setting, usually between -1.0 and 1.0.
910 * offset: the offset to shift by, before applying the factor.
911 * factor: the factor to multiply by (use negative to reverse).
914 do_property_scale (const SGPropertyNode * arg)
916 SGPropertyNode * prop = get_prop(arg);
917 double setting = arg->getDoubleValue("setting");
918 double offset = arg->getDoubleValue("offset", 0.0);
919 double factor = arg->getDoubleValue("factor", 1.0);
920 bool squared = arg->getBoolValue("squared", false);
921 int power = arg->getIntValue("power", (squared ? 2 : 1));
923 int sign = (setting < 0 ? -1 : 1);
929 setting = setting * setting * sign;
932 setting = setting * setting * setting;
935 setting = setting * setting * setting * setting * sign;
938 setting = pow(setting, power);
939 if ((power % 2) == 0)
944 return prop->setDoubleValue((setting + offset) * factor);
949 * Built-in command: cycle a property through a set of values.
951 * If the current value isn't in the list, the cycle will
952 * (re)start from the beginning.
954 * property: the name of the property to cycle.
955 * value[*]: the list of values to cycle through.
958 do_property_cycle (const SGPropertyNode * arg)
960 SGPropertyNode * prop = get_prop(arg);
961 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
963 int nSelections = values.size();
965 if (nSelections < 1) {
966 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
970 // Try to find the current selection
971 for (int i = 0; i < nSelections; i++) {
972 if (compare_values(prop, values[i])) {
978 // Default or wrap to the first selection
979 if (selection < 0 || selection >= nSelections)
982 prop->setUnspecifiedValue(values[selection]->getStringValue());
988 * Built-in command: randomize a numeric property value.
990 * property: the name of the property value to randomize.
991 * min: the minimum allowed value.
992 * max: the maximum allowed value.
995 do_property_randomize (const SGPropertyNode * arg)
997 SGPropertyNode * prop = get_prop(arg);
998 double min = arg->getDoubleValue("min", DBL_MIN);
999 double max = arg->getDoubleValue("max", DBL_MAX);
1000 prop->setDoubleValue(sg_random() * (max - min) + min);
1006 * Built-in command: reinit the data logging system based on the
1007 * current contents of the /logger tree.
1010 do_data_logging_commit (const SGPropertyNode * arg)
1012 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1018 * Built-in command: Add a dialog to the GUI system. Does *not*
1019 * display the dialog. The property node should have the same format
1020 * as a dialog XML configuration. It must include:
1022 * name: the name of the GUI dialog for future reference.
1025 do_dialog_new (const SGPropertyNode * arg)
1027 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1029 // Note the casting away of const: this is *real*. Doing a
1030 // "dialog-apply" command later on will mutate this property node.
1031 // I'm not convinced that this isn't the Right Thing though; it
1032 // allows client to create a node, pass it to dialog-new, and get
1033 // the values back from the dialog by reading the same node.
1034 // Perhaps command arguments are not as "const" as they would
1036 gui->newDialog((SGPropertyNode*)arg);
1041 * Built-in command: Show an XML-configured dialog.
1043 * dialog-name: the name of the GUI dialog to display.
1046 do_dialog_show (const SGPropertyNode * arg)
1048 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1049 gui->showDialog(arg->getStringValue("dialog-name"));
1055 * Built-in Command: Hide the active XML-configured dialog.
1058 do_dialog_close (const SGPropertyNode * arg)
1060 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1061 if(arg->hasValue("dialog-name"))
1062 return gui->closeDialog(arg->getStringValue("dialog-name"));
1063 return gui->closeActiveDialog();
1068 * Update a value in the active XML-configured dialog.
1070 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1073 do_dialog_update (const SGPropertyNode * arg)
1075 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1077 if (arg->hasValue("dialog-name"))
1078 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1080 dialog = gui->getActiveDialog();
1083 dialog->updateValues(arg->getStringValue("object-name"));
1092 * Apply a value in the active XML-configured dialog.
1094 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1097 do_dialog_apply (const SGPropertyNode * arg)
1099 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1101 if (arg->hasValue("dialog-name"))
1102 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1104 dialog = gui->getActiveDialog();
1107 dialog->applyValues(arg->getStringValue("object-name"));
1116 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1120 do_gui_redraw (const SGPropertyNode * arg)
1122 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1129 * Adds model to the scenery. The path to the added branch (/models/model[*])
1130 * is returned in property "property".
1133 do_add_model (const SGPropertyNode * arg)
1135 SGPropertyNode * model = fgGetNode("models", true);
1136 for (int i = 0;; i++) {
1139 if (!model->getChild("model", i, false)) {
1140 model = model->getChild("model", i, true);
1144 copyProperties(arg, model);
1145 if (model->hasValue("elevation-m"))
1146 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1147 * SG_METER_TO_FEET);
1148 model->getNode("load", true);
1149 model->removeChildren("load");
1150 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1156 * Set mouse cursor coordinates and cursor shape.
1159 do_set_cursor (const SGPropertyNode * arg)
1161 if (arg->hasValue("x") || arg->hasValue("y")) {
1162 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1163 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1164 int x = arg->getIntValue("x", mx->getIntValue());
1165 int y = arg->getIntValue("y", my->getIntValue());
1171 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1172 if (cursor->getType() != simgear::props::NONE)
1173 fgSetMouseCursor(cursor->getIntValue());
1175 cursor->setIntValue(fgGetMouseCursor());
1181 * Built-in command: play an audio message (i.e. a wav file) This is
1182 * fire and forget. Call this once per message and it will get dumped
1183 * into a queue. Messages are played sequentially so they do not
1187 do_play_audio_sample (const SGPropertyNode * arg)
1189 string path = arg->getStringValue("path");
1190 string file = arg->getStringValue("file");
1191 float volume = arg->getFloatValue("volume");
1192 // cout << "playing " << path << " / " << file << endl;
1194 static FGSampleQueue *queue = 0;
1196 SGSoundMgr *smgr = globals->get_soundmgr();
1197 queue = new FGSampleQueue(smgr, "chatter");
1198 queue->tie_to_listener();
1201 SGSoundSample *msg = new SGSoundSample(file.c_str(), path);
1202 msg->set_volume( volume );
1207 } catch (const sg_io_exception&) {
1208 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1209 "failed to load" << path << '/' << file);
1215 * Built-in command: commit presets (read from in /sim/presets/)
1218 do_presets_commit (const SGPropertyNode * arg)
1220 if (fgGetBool("/sim/initialized", false)) {
1221 fgReInitSubsystems();
1223 // Nasal can trigger this during initial init, which confuses
1224 // the logic in ReInitSubsystems, since initial state has not been
1225 // saved at that time. Short-circuit everything here.
1233 * Built-in command: set log level (0 ... 7)
1236 do_log_level (const SGPropertyNode * arg)
1238 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1244 * Built-in command: replay the FDR buffer
1247 do_replay (const SGPropertyNode * arg)
1249 // freeze the master fdm
1250 fgSetInt( "/sim/freeze/replay-state", 1 );
1252 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
1254 fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
1255 fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
1256 double duration = fgGetDouble( "/sim/replay/duration" );
1257 if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
1258 fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
1260 fgSetDouble( "/sim/replay/time", r->get_start_time() );
1263 // cout << "start = " << r->get_start_time()
1264 // << " end = " << r->get_end_time() << endl;
1271 do_decrease_visibility (const SGPropertyNode * arg)
1273 double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
1274 fgSetDouble("/environment/visibility-m", new_value);
1275 fgDefaultWeatherValue("visibility-m", new_value);
1276 globals->get_subsystem("environment")->reinit();
1282 do_increase_visibility (const SGPropertyNode * arg)
1284 double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1285 fgSetDouble("/environment/visibility-m", new_value);
1286 fgDefaultWeatherValue("visibility-m", new_value);
1287 globals->get_subsystem("environment")->reinit();
1293 * An fgcommand to allow loading of xml files via nasal,
1294 * the xml file's structure will be made available within
1295 * a property tree node defined under argument "targetnode",
1296 * or in the given argument tree under "data" otherwise.
1298 * @param filename a string to hold the complete path & filename of an XML file
1299 * @param targetnode a string pointing to a location within the property tree
1300 * where to store the parsed XML file. If <targetnode> is undefined, then the
1301 * file contents are stored under a node <data> in the argument tree.
1305 do_load_xml_to_proptree(const SGPropertyNode * arg)
1307 SGPath file(arg->getStringValue("filename"));
1308 if (file.str().empty())
1311 if (file.extension() != "xml")
1312 file.concat(".xml");
1314 if (file.isRelative()) {
1315 file = globals->resolve_maybe_aircraft_path(file.str());
1318 if (!fgValidatePath(file.c_str(), false)) {
1319 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1320 "(unauthorized access)");
1324 SGPropertyNode *targetnode;
1325 if (arg->hasValue("targetnode"))
1326 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1328 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1331 readProperties(file.c_str(), targetnode, true);
1332 } catch (const sg_exception &e) {
1333 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1342 * An fgcommand to allow saving of xml files via nasal,
1343 * the file's structure will be determined based on what's
1344 * encountered in the passed (source) property tree node
1346 * @param filename a string to hold the complete path & filename of the (new)
1348 * @param sourcenode a string pointing to a location within the property tree
1349 * where to find the nodes that should be written recursively into an XML file
1350 * @param data if no sourcenode is given, then the file contents are taken from
1351 * the argument tree's "data" node.
1355 do_save_xml_from_proptree(const SGPropertyNode * arg)
1357 SGPath file(arg->getStringValue("filename"));
1358 if (file.str().empty())
1361 if (file.extension() != "xml")
1362 file.concat(".xml");
1364 if (!fgValidatePath(file.c_str(), true)) {
1365 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1366 "(unauthorized access)");
1370 SGPropertyNode *sourcenode;
1371 if (arg->hasValue("sourcenode"))
1372 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1373 else if (arg->getNode("data", false))
1374 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1379 writeProperties (file.c_str(), sourcenode, true);
1380 } catch (const sg_exception &e) {
1381 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1389 do_press_cockpit_button (const SGPropertyNode *arg)
1391 const char *prefix = arg->getStringValue("prefix");
1393 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1396 string prop = string(prefix) + "-button";
1399 if (arg->getBoolValue("latching"))
1400 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1404 fgSetDouble(prop.c_str(), value);
1405 fgSetBool(arg->getStringValue("discrete"), value > 0);
1411 do_release_cockpit_button (const SGPropertyNode *arg)
1413 const char *prefix = arg->getStringValue("prefix");
1415 if (arg->getBoolValue("guarded")) {
1416 string prop = string(prefix) + "-guard";
1417 if (fgGetDouble(prop.c_str()) < 1) {
1418 fgSetDouble(prop.c_str(), 1);
1423 if (! arg->getBoolValue("latching")) {
1424 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1425 fgSetBool(arg->getStringValue("discrete"), false);
1432 ////////////////////////////////////////////////////////////////////////
1434 ////////////////////////////////////////////////////////////////////////
1438 * Table of built-in commands.
1440 * New commands do not have to be added here; any module in the application
1441 * can add a new command using globals->get_commands()->addCommand(...).
1445 SGCommandMgr::command_t command;
1447 { "null", do_null },
1448 { "nasal", do_nasal },
1449 { "exit", do_exit },
1450 { "reset", do_reset },
1451 { "reinit", do_reinit },
1452 { "suspend", do_reinit },
1453 { "resume", do_reinit },
1454 { "load", do_load },
1455 { "save", do_save },
1456 { "panel-load", do_panel_load },
1457 { "panel-mouse-click", do_panel_mouse_click },
1458 { "preferences-load", do_preferences_load },
1459 { "view-cycle", do_view_cycle },
1460 { "screen-capture", do_screen_capture },
1461 { "hires-screen-capture", do_hires_screen_capture },
1462 { "tile-cache-reload", do_tile_cache_reload },
1463 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1464 { "set-outside-air-temp-degc", do_set_oat_degc },
1465 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1466 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1467 { "timeofday", do_timeofday },
1468 { "property-toggle", do_property_toggle },
1469 { "property-assign", do_property_assign },
1470 { "property-adjust", do_property_adjust },
1471 { "property-multiply", do_property_multiply },
1472 { "property-swap", do_property_swap },
1473 { "property-scale", do_property_scale },
1474 { "property-cycle", do_property_cycle },
1475 { "property-randomize", do_property_randomize },
1476 { "data-logging-commit", do_data_logging_commit },
1477 { "dialog-new", do_dialog_new },
1478 { "dialog-show", do_dialog_show },
1479 { "dialog-close", do_dialog_close },
1480 { "dialog-update", do_dialog_update },
1481 { "dialog-apply", do_dialog_apply },
1482 { "gui-redraw", do_gui_redraw },
1483 { "add-model", do_add_model },
1484 { "set-cursor", do_set_cursor },
1485 { "play-audio-sample", do_play_audio_sample },
1486 { "presets-commit", do_presets_commit },
1487 { "log-level", do_log_level },
1488 { "replay", do_replay },
1489 { "decrease-visibility", do_decrease_visibility },
1490 { "increase-visibility", do_increase_visibility },
1491 { "loadxml", do_load_xml_to_proptree},
1492 { "savexml", do_save_xml_from_proptree },
1493 { "press-cockpit-button", do_press_cockpit_button },
1494 { "release-cockpit-button", do_release_cockpit_button },
1495 { "dump-scenegraph", do_dump_scene_graph },
1496 { "dump-terrainbranch", do_dump_terrain_branch },
1497 { "print-visible-scene", do_print_visible_scene_info },
1498 { "reload-shaders", do_reload_shaders },
1499 { 0, 0 } // zero-terminated
1504 * Initialize the default built-in commands.
1506 * Other commands may be added by other parts of the application.
1511 SG_LOG(SG_GENERAL, SG_BULK, "Initializing basic built-in commands:");
1512 for (int i = 0; built_ins[i].name != 0; i++) {
1513 SG_LOG(SG_GENERAL, SG_BULK, " " << built_ins[i].name);
1514 globals->get_commands()->addCommand(built_ins[i].name,
1515 built_ins[i].command);
1518 typedef bool (*dummy)();
1519 fgTie( "/command/view/next", dummy(0), do_view_next );
1520 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1523 // end of fg_commands.cxx