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>
25 #include <Cockpit/panel.hxx>
26 #include <Cockpit/panel_io.hxx>
27 #include <Cockpit/hud.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/tilemgr.hxx>
35 #include <Scenery/scenery.hxx>
36 #include <Scripting/NasalSys.hxx>
37 #include <Sound/sample_queue.hxx>
38 #include <Time/sunsolver.hxx>
39 #include <Time/tmp.hxx>
41 #include "fg_init.hxx"
44 #include "fg_commands.hxx"
45 #include "fg_props.hxx"
46 #include "globals.hxx"
49 #include "viewmgr.hxx"
51 #include <Main/viewer.hxx>
59 ////////////////////////////////////////////////////////////////////////
60 // Static helper functions.
61 ////////////////////////////////////////////////////////////////////////
64 static inline SGPropertyNode *
65 get_prop (const SGPropertyNode * arg)
67 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
70 static inline SGPropertyNode *
71 get_prop2 (const SGPropertyNode * arg)
73 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
78 * Get a double value and split it as required.
81 split_value (double full_value, const char * mask,
82 double * unmodifiable, double * modifiable)
84 if (!strcmp("integer", mask)) {
85 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
86 *unmodifiable = full_value - *modifiable;
87 } else if (!strcmp("decimal", mask)) {
88 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
89 *modifiable = full_value - *unmodifiable;
91 if (strcmp("all", mask))
92 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
93 << " assuming 'all'");
95 *modifiable = full_value;
101 * Clamp or wrap a value as specified.
104 limit_value (double * value, const SGPropertyNode * arg)
106 const SGPropertyNode * min_node = arg->getChild("min");
107 const SGPropertyNode * max_node = arg->getChild("max");
109 bool wrap = arg->getBoolValue("wrap");
111 if (min_node == 0 || max_node == 0)
114 if (wrap) { // wrap such that min <= x < max
115 double min_val = min_node->getDoubleValue();
116 double max_val = max_node->getDoubleValue();
117 double resolution = arg->getDoubleValue("resolution");
118 if (resolution > 0.0) {
119 // snap to (min + N*resolution), taking special care to handle imprecision
120 int n = (int)floor((*value - min_val) / resolution + 0.5);
121 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
122 SG_NORMALIZE_RANGE(n, 0, steps);
123 *value = min_val + resolution * n;
125 // plain circular wrapping
126 SG_NORMALIZE_RANGE(*value, min_val, max_val);
128 } else { // clamp such that min <= x <= max
129 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
130 *value = min_node->getDoubleValue();
131 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
132 *value = max_node->getDoubleValue();
137 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
139 switch (value1->getType()) {
140 case simgear::props::BOOL:
141 return (value1->getBoolValue() == value2->getBoolValue());
142 case simgear::props::INT:
143 return (value1->getIntValue() == value2->getIntValue());
144 case simgear::props::LONG:
145 return (value1->getLongValue() == value2->getLongValue());
146 case simgear::props::FLOAT:
147 return (value1->getFloatValue() == value2->getFloatValue());
148 case simgear::props::DOUBLE:
149 return (value1->getDoubleValue() == value2->getDoubleValue());
151 return !strcmp(value1->getStringValue(), value2->getStringValue());
157 ////////////////////////////////////////////////////////////////////////
158 // Command implementations.
159 ////////////////////////////////////////////////////////////////////////
163 * Built-in command: do nothing.
166 do_null (const SGPropertyNode * arg)
172 * Built-in command: run a Nasal script.
175 do_nasal (const SGPropertyNode * arg)
177 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
181 * Built-in command: exit FlightGear.
183 * status: the exit status to return to the operating system (defaults to 0)
186 do_exit (const SGPropertyNode * arg)
188 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
189 fgSetBool("/sim/signals/exit", true);
191 if (fgGetBool("/sim/startup/save-on-exit")) {
193 char* envp = ::getenv( "APPDATA" );
194 if ( envp != NULL ) {
195 SGPath config( envp );
196 config.append( "flightgear.org" );
198 if ( homedir != NULL ) {
199 SGPath config( homedir );
200 config.append( ".fgfs" );
202 config.append( "autosave.xml" );
203 config.create_dir( 0700 );
204 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << config.str());
206 writeProperties(config.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
207 } catch (const sg_exception &e) {
208 guiErrorMessage("Error writing autosave.xml: ", e);
211 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
214 fgExit(arg->getIntValue("status", 0));
220 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
223 do_reset (const SGPropertyNode * arg)
231 * Built-in command: reinitialize one or more subsystems.
233 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
234 * none is specified, reinitialize all of them.
237 do_reinit (const SGPropertyNode * arg)
241 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
242 if (subsystems.size() == 0) {
243 globals->get_subsystem_mgr()->reinit();
245 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
246 const char * name = subsystems[i]->getStringValue();
247 SGSubsystem * subsystem = globals->get_subsystem(name);
248 if (subsystem == 0) {
250 SG_LOG( SG_GENERAL, SG_ALERT,
251 "Subsystem " << name << "not found" );
258 globals->get_event_mgr()->reinit();
265 // these routines look useful ??? but are never used in the code ???
269 * Built-in command: suspend one or more subsystems.
271 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
274 do_suspend (const SGPropertyNode * arg)
278 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
279 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
280 const char * name = subsystems[i]->getStringValue();
281 SGSubsystem * subsystem = globals->get_subsystem(name);
282 if (subsystem == 0) {
284 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
286 subsystem->suspend();
293 * Built-in command: suspend one or more subsystems.
295 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
298 do_resume (const SGPropertyNode * arg)
302 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
303 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
304 const char * name = subsystems[i]->getStringValue();
305 SGSubsystem * subsystem = globals->get_subsystem(name);
306 if (subsystem == 0) {
308 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
320 * Built-in command: load flight.
322 * file (optional): the name of the file to load (relative to current
323 * directory). Defaults to "fgfs.sav"
326 do_load (const SGPropertyNode * arg)
328 string file = arg->getStringValue("file", "fgfs.sav");
329 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
332 if (!fgValidatePath(file.c_str(), false)) {
333 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
334 "(unauthorized access)");
338 ifstream input(file.c_str());
339 if (input.good() && fgLoadFlight(input)) {
341 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
344 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
351 * Built-in command: save flight.
353 * file (optional): the name of the file to save (relative to the
354 * current directory). Defaults to "fgfs.sav".
357 do_save (const SGPropertyNode * arg)
359 string file = arg->getStringValue("file", "fgfs.sav");
360 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
363 if (!fgValidatePath(file.c_str(), false)) {
364 SG_LOG(SG_IO, SG_ALERT, "save: writing '" << file << "' denied "
365 "(unauthorized access)");
369 bool write_all = arg->getBoolValue("write-all", false);
370 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
371 ofstream output(file.c_str());
372 if (output.good() && fgSaveFlight(output, write_all)) {
374 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
377 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
384 * Built-in command: (re)load the panel.
386 * path (optional): the file name to load the panel from
387 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
388 * and if that's unspecified, to "Panels/Default/default.xml".
391 do_panel_load (const SGPropertyNode * arg)
394 arg->getStringValue("path",
395 fgGetString("/sim/panel/path",
396 "Panels/Default/default.xml"));
397 FGPanel * new_panel = fgReadPanel(panel_path);
398 if (new_panel == 0) {
399 SG_LOG(SG_INPUT, SG_ALERT,
400 "Error reading new panel from " << panel_path);
403 SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
404 globals->get_current_panel()->unbind();
405 delete globals->get_current_panel();
406 globals->set_current_panel( new_panel );
407 globals->get_current_panel()->bind();
413 * Built-in command: pass a mouse click to the panel.
415 * button: the mouse button number, zero-based.
416 * is-down: true if the button is down, false if it is up.
417 * x-pos: the x position of the mouse click.
418 * y-pos: the y position of the mouse click.
421 do_panel_mouse_click (const SGPropertyNode * arg)
423 if (globals->get_current_panel() != 0)
424 return globals->get_current_panel()
425 ->doMouseAction(arg->getIntValue("button"),
426 arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
427 arg->getIntValue("x-pos"),
428 arg->getIntValue("y-pos"));
435 * Built-in command: (re)load preferences.
437 * path (optional): the file name to load the panel from (relative
438 * to FG_ROOT). Defaults to "preferences.xml".
441 do_preferences_load (const SGPropertyNode * arg)
444 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
445 globals->get_props());
446 } catch (const sg_exception &e) {
447 guiErrorMessage("Error reading global preferences: ", e);
450 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
458 if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
459 globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
460 if ( globals->get_viewmgr()->get_current() == 1 ) {
461 globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
469 globals->get_current_view()->setHeadingOffset_deg(0.0);
470 globals->get_viewmgr()->next_view();
471 fix_hud_visibility();
477 globals->get_current_view()->setHeadingOffset_deg(0.0);
478 globals->get_viewmgr()->prev_view();
479 fix_hud_visibility();
483 * Built-in command: cycle view.
486 do_view_cycle (const SGPropertyNode * arg)
488 globals->get_current_view()->setHeadingOffset_deg(0.0);
489 globals->get_viewmgr()->next_view();
490 fix_hud_visibility();
495 * Built-in command: capture screen.
498 do_screen_capture (const SGPropertyNode * arg)
500 return fgDumpSnapShot();
504 do_reload_shaders (const SGPropertyNode*)
506 simgear::reload_shaders();
511 do_dump_scene_graph (const SGPropertyNode*)
518 do_dump_terrain_branch (const SGPropertyNode*)
520 fgDumpTerrainBranch();
522 double lon_deg = fgGetDouble("/position/longitude-deg");
523 double lat_deg = fgGetDouble("/position/latitude-deg");
524 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
525 SGVec3d zero = SGVec3d::fromGeod(geodPos);
527 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
528 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
529 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
535 * Built-in command: hires capture screen.
538 do_hires_screen_capture (const SGPropertyNode * arg)
546 * Reload the tile cache.
549 do_tile_cache_reload (const SGPropertyNode * arg)
551 static const SGPropertyNode *master_freeze
552 = fgGetNode("/sim/freeze/master");
553 bool freeze = master_freeze->getBoolValue();
554 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
556 fgSetBool("/sim/freeze/master", true);
558 if ( globals->get_tile_mgr()->init() ) {
559 // Load the local scenery data
560 double visibility_meters = fgGetDouble("/environment/visibility-m");
561 globals->get_tile_mgr()->update( visibility_meters );
563 SG_LOG( SG_GENERAL, SG_ALERT,
564 "Error in Tile Manager initialization!" );
568 fgSetBool("/sim/freeze/master", false);
575 * Set the sea level outside air temperature and assigning that to all
576 * boundary and aloft environment layers.
579 do_set_sea_level_degc (const SGPropertyNode * arg)
581 double temp_sea_level_degc = arg->getDoubleValue("temp-degc", 15.0);
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 );
612 * Set the outside air temperature at the "current" altitude by first
613 * calculating the corresponding sea level temp, and assigning that to
614 * all boundary and aloft environment layers.
617 do_set_oat_degc (const SGPropertyNode * arg)
619 const string &temp_str = arg->getStringValue("temp-degc", "15.0");
621 // check for an altitude specified in the arguments, otherwise use
622 // current aircraft altitude.
623 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
624 if ( altitude_ft == NULL ) {
625 altitude_ft = fgGetNode("/position/altitude-ft");
628 FGEnvironment dummy; // instantiate a dummy so we can leech a method
629 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
630 dummy.set_temperature_degc( atof( temp_str.c_str() ) );
631 double temp_sea_level_degc = dummy.get_temperature_sea_level_degc();
633 //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
634 //cout << "Temp at alt (C) = " << atof( temp_str.c_str() ) << endl;
635 //cout << "Temp sea level (C) = " << temp_sea_level_degc << endl;
637 SGPropertyNode *node, *child;
640 node = fgGetNode( "/environment/config/boundary" );
641 if ( node != NULL ) {
643 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
644 child->setDoubleValue( "temperature-sea-level-degc",
645 temp_sea_level_degc );
651 node = fgGetNode( "/environment/config/aloft" );
652 if ( node != NULL ) {
654 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
655 child->setDoubleValue( "temperature-sea-level-degc",
656 temp_sea_level_degc );
665 * Set the sea level outside air dewpoint and assigning that to all
666 * boundary and aloft environment layers.
669 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
671 double dewpoint_sea_level_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
673 SGPropertyNode *node, *child;
676 node = fgGetNode( "/environment/config/boundary" );
677 if ( node != NULL ) {
679 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
680 child->setDoubleValue( "dewpoint-sea-level-degc",
681 dewpoint_sea_level_degc );
687 node = fgGetNode( "/environment/config/aloft" );
688 if ( node != NULL ) {
690 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
691 child->setDoubleValue( "dewpoint-sea-level-degc",
692 dewpoint_sea_level_degc );
702 * Set the outside air dewpoint at the "current" altitude by first
703 * calculating the corresponding sea level dewpoint, and assigning
704 * that to all boundary and aloft environment layers.
707 do_set_dewpoint_degc (const SGPropertyNode * arg)
709 const string &dewpoint_str = arg->getStringValue("dewpoint-degc", "5.0");
711 // check for an altitude specified in the arguments, otherwise use
712 // current aircraft altitude.
713 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
714 if ( altitude_ft == NULL ) {
715 altitude_ft = fgGetNode("/position/altitude-ft");
718 FGEnvironment dummy; // instantiate a dummy so we can leech a method
719 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
720 dummy.set_dewpoint_degc( atof( dewpoint_str.c_str() ) );
721 double dewpoint_sea_level_degc = dummy.get_dewpoint_sea_level_degc();
723 //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
724 //cout << "Dewpoint at alt (C) = " << atof( dewpoint_str.c_str() ) << endl;
725 //cout << "Dewpoint at sea level (C) = " << dewpoint_sea_level_degc << endl;
727 SGPropertyNode *node, *child;
730 node = fgGetNode( "/environment/config/boundary" );
731 if ( node != NULL ) {
733 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
734 child->setDoubleValue( "dewpoint-sea-level-degc",
735 dewpoint_sea_level_degc );
741 node = fgGetNode( "/environment/config/aloft" );
742 if ( node != NULL ) {
744 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
745 child->setDoubleValue( "dewpoint-sea-level-degc",
746 dewpoint_sea_level_degc );
755 * Update the lighting manually.
758 do_timeofday (const SGPropertyNode * arg)
760 const string &offset_type = arg->getStringValue("timeofday", "noon");
762 static const SGPropertyNode *longitude
763 = fgGetNode("/position/longitude-deg");
764 static const SGPropertyNode *latitude
765 = fgGetNode("/position/latitude-deg");
766 static const SGPropertyNode *cur_time_override
767 = fgGetNode("/sim/time/cur-time-override", true);
769 int orig_warp = globals->get_warp();
770 SGTime *t = globals->get_time_params();
771 time_t cur_time = t->get_cur_time();
772 // cout << "cur_time = " << cur_time << endl;
773 // cout << "orig_warp = " << orig_warp << endl;
776 if ( offset_type == "real" ) {
778 } else if ( offset_type == "dawn" ) {
779 warp = fgTimeSecondsUntilSunAngle( cur_time,
780 longitude->getDoubleValue()
781 * SGD_DEGREES_TO_RADIANS,
782 latitude->getDoubleValue()
783 * SGD_DEGREES_TO_RADIANS,
785 } else if ( offset_type == "morning" ) {
786 warp = fgTimeSecondsUntilSunAngle( cur_time,
787 longitude->getDoubleValue()
788 * SGD_DEGREES_TO_RADIANS,
789 latitude->getDoubleValue()
790 * SGD_DEGREES_TO_RADIANS,
792 } else if ( offset_type == "noon" ) {
793 warp = fgTimeSecondsUntilSunAngle( cur_time,
794 longitude->getDoubleValue()
795 * SGD_DEGREES_TO_RADIANS,
796 latitude->getDoubleValue()
797 * SGD_DEGREES_TO_RADIANS,
799 } else if ( offset_type == "afternoon" ) {
800 warp = fgTimeSecondsUntilSunAngle( cur_time,
801 longitude->getDoubleValue()
802 * SGD_DEGREES_TO_RADIANS,
803 latitude->getDoubleValue()
804 * SGD_DEGREES_TO_RADIANS,
806 } else if ( offset_type == "dusk" ) {
807 warp = fgTimeSecondsUntilSunAngle( cur_time,
808 longitude->getDoubleValue()
809 * SGD_DEGREES_TO_RADIANS,
810 latitude->getDoubleValue()
811 * SGD_DEGREES_TO_RADIANS,
813 } else if ( offset_type == "evening" ) {
814 warp = fgTimeSecondsUntilSunAngle( cur_time,
815 longitude->getDoubleValue()
816 * SGD_DEGREES_TO_RADIANS,
817 latitude->getDoubleValue()
818 * SGD_DEGREES_TO_RADIANS,
820 } else if ( offset_type == "midnight" ) {
821 warp = fgTimeSecondsUntilSunAngle( cur_time,
822 longitude->getDoubleValue()
823 * SGD_DEGREES_TO_RADIANS,
824 latitude->getDoubleValue()
825 * SGD_DEGREES_TO_RADIANS,
828 // cout << "warp = " << warp << endl;
829 globals->set_warp( orig_warp + warp );
831 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
832 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
833 cur_time_override->getLongValue(),
834 globals->get_warp() );
841 * Built-in command: toggle a bool property value.
843 * property: The name of the property to toggle.
846 do_property_toggle (const SGPropertyNode * arg)
848 SGPropertyNode * prop = get_prop(arg);
849 return prop->setBoolValue(!prop->getBoolValue());
854 * Built-in command: assign a value to a property.
856 * property: the name of the property to assign.
857 * value: the value to assign; or
858 * property[1]: the property to copy from.
861 do_property_assign (const SGPropertyNode * arg)
863 SGPropertyNode * prop = get_prop(arg);
864 const SGPropertyNode * prop2 = get_prop2(arg);
865 const SGPropertyNode * value = arg->getNode("value");
868 return prop->setUnspecifiedValue(value->getStringValue());
870 return prop->setUnspecifiedValue(prop2->getStringValue());
877 * Built-in command: increment or decrement a property value.
879 * If the 'step' argument is present, it will be used; otherwise,
880 * the command uses 'offset' and 'factor', usually from the mouse.
882 * property: the name of the property to increment or decrement.
883 * step: the amount of the increment or decrement (default: 0).
884 * offset: offset from the current setting (used for the mouse; multiplied
886 * factor: scaling amount for the offset (defaults to 1).
887 * min: the minimum allowed value (default: no minimum).
888 * max: the maximum allowed value (default: no maximum).
889 * mask: 'integer' to apply only to the left of the decimal point,
890 * 'decimal' to apply only to the right of the decimal point,
891 * or 'all' to apply to the whole number (the default).
892 * wrap: true if the value should be wrapped when it passes min or max;
893 * both min and max must be present for this to work (default:
897 do_property_adjust (const SGPropertyNode * arg)
899 SGPropertyNode * prop = get_prop(arg);
902 if (arg->hasValue("step"))
903 amount = arg->getDoubleValue("step");
905 amount = (arg->getDoubleValue("factor", 1)
906 * arg->getDoubleValue("offset"));
908 double unmodifiable, modifiable;
909 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
910 &unmodifiable, &modifiable);
911 modifiable += amount;
912 limit_value(&modifiable, arg);
914 prop->setDoubleValue(unmodifiable + modifiable);
921 * Built-in command: multiply a property value.
923 * property: the name of the property to multiply.
924 * factor: the amount by which to multiply.
925 * min: the minimum allowed value (default: no minimum).
926 * max: the maximum allowed value (default: no maximum).
927 * mask: 'integer' to apply only to the left of the decimal point,
928 * 'decimal' to apply only to the right of the decimal point,
929 * or 'all' to apply to the whole number (the default).
930 * wrap: true if the value should be wrapped when it passes min or max;
931 * both min and max must be present for this to work (default:
935 do_property_multiply (const SGPropertyNode * arg)
937 SGPropertyNode * prop = get_prop(arg);
938 double factor = arg->getDoubleValue("factor", 1);
940 double unmodifiable, modifiable;
941 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
942 &unmodifiable, &modifiable);
943 modifiable *= factor;
944 limit_value(&modifiable, arg);
946 prop->setDoubleValue(unmodifiable + modifiable);
953 * Built-in command: swap two property values.
955 * property[0]: the name of the first property.
956 * property[1]: the name of the second property.
959 do_property_swap (const SGPropertyNode * arg)
961 SGPropertyNode * prop1 = get_prop(arg);
962 SGPropertyNode * prop2 = get_prop2(arg);
964 // FIXME: inefficient
965 const string & tmp = prop1->getStringValue();
966 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
967 prop2->setUnspecifiedValue(tmp.c_str()));
972 * Built-in command: Set a property to an axis or other moving input.
974 * property: the name of the property to set.
975 * setting: the current input setting, usually between -1.0 and 1.0.
976 * offset: the offset to shift by, before applying the factor.
977 * factor: the factor to multiply by (use negative to reverse).
980 do_property_scale (const SGPropertyNode * arg)
982 SGPropertyNode * prop = get_prop(arg);
983 double setting = arg->getDoubleValue("setting");
984 double offset = arg->getDoubleValue("offset", 0.0);
985 double factor = arg->getDoubleValue("factor", 1.0);
986 bool squared = arg->getBoolValue("squared", false);
987 int power = arg->getIntValue("power", (squared ? 2 : 1));
989 int sign = (setting < 0 ? -1 : 1);
995 setting = setting * setting * sign;
998 setting = setting * setting * setting;
1001 setting = setting * setting * setting * setting * sign;
1004 setting = pow(setting, power);
1005 if ((power % 2) == 0)
1010 return prop->setDoubleValue((setting + offset) * factor);
1015 * Built-in command: cycle a property through a set of values.
1017 * If the current value isn't in the list, the cycle will
1018 * (re)start from the beginning.
1020 * property: the name of the property to cycle.
1021 * value[*]: the list of values to cycle through.
1024 do_property_cycle (const SGPropertyNode * arg)
1026 SGPropertyNode * prop = get_prop(arg);
1027 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
1029 int nSelections = values.size();
1031 if (nSelections < 1) {
1032 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
1036 // Try to find the current selection
1037 for (int i = 0; i < nSelections; i++) {
1038 if (compare_values(prop, values[i])) {
1044 // Default or wrap to the first selection
1045 if (selection < 0 || selection >= nSelections)
1048 prop->setUnspecifiedValue(values[selection]->getStringValue());
1054 * Built-in command: randomize a numeric property value.
1056 * property: the name of the property value to randomize.
1057 * min: the minimum allowed value.
1058 * max: the maximum allowed value.
1061 do_property_randomize (const SGPropertyNode * arg)
1063 SGPropertyNode * prop = get_prop(arg);
1064 double min = arg->getDoubleValue("min", DBL_MIN);
1065 double max = arg->getDoubleValue("max", DBL_MAX);
1066 prop->setDoubleValue(sg_random() * (max - min) + min);
1072 * Built-in command: reinit the data logging system based on the
1073 * current contents of the /logger tree.
1076 do_data_logging_commit (const SGPropertyNode * arg)
1078 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1084 * Built-in command: Add a dialog to the GUI system. Does *not*
1085 * display the dialog. The property node should have the same format
1086 * as a dialog XML configuration. It must include:
1088 * name: the name of the GUI dialog for future reference.
1091 do_dialog_new (const SGPropertyNode * arg)
1093 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1095 // Note the casting away of const: this is *real*. Doing a
1096 // "dialog-apply" command later on will mutate this property node.
1097 // I'm not convinced that this isn't the Right Thing though; it
1098 // allows client to create a node, pass it to dialog-new, and get
1099 // the values back from the dialog by reading the same node.
1100 // Perhaps command arguments are not as "const" as they would
1102 gui->newDialog((SGPropertyNode*)arg);
1107 * Built-in command: Show an XML-configured dialog.
1109 * dialog-name: the name of the GUI dialog to display.
1112 do_dialog_show (const SGPropertyNode * arg)
1114 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1115 gui->showDialog(arg->getStringValue("dialog-name"));
1121 * Built-in Command: Hide the active XML-configured dialog.
1124 do_dialog_close (const SGPropertyNode * arg)
1126 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1127 if(arg->hasValue("dialog-name"))
1128 return gui->closeDialog(arg->getStringValue("dialog-name"));
1129 return gui->closeActiveDialog();
1134 * Update a value in the active XML-configured dialog.
1136 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1139 do_dialog_update (const SGPropertyNode * arg)
1141 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1143 if (arg->hasValue("dialog-name"))
1144 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1146 dialog = gui->getActiveDialog();
1149 dialog->updateValues(arg->getStringValue("object-name"));
1158 * Apply a value in the active XML-configured dialog.
1160 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1163 do_dialog_apply (const SGPropertyNode * arg)
1165 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1167 if (arg->hasValue("dialog-name"))
1168 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1170 dialog = gui->getActiveDialog();
1173 dialog->applyValues(arg->getStringValue("object-name"));
1182 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1186 do_gui_redraw (const SGPropertyNode * arg)
1188 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1195 * Adds model to the scenery. The path to the added branch (/models/model[*])
1196 * is returned in property "property".
1199 do_add_model (const SGPropertyNode * arg)
1201 SGPropertyNode * model = fgGetNode("models", true);
1202 for (int i = 0;; i++) {
1205 if (!model->getChild("model", i, false)) {
1206 model = model->getChild("model", i, true);
1210 copyProperties(arg, model);
1211 if (model->hasValue("elevation-m"))
1212 model->setDoubleValue("elevation-ft", model->getDoubleValue("elevation-m")
1213 * SG_METER_TO_FEET);
1214 model->getNode("load", true);
1215 model->removeChildren("load");
1216 const_cast<SGPropertyNode *>(arg)->setStringValue("property", model->getPath());
1222 * Set mouse cursor coordinates and cursor shape.
1225 do_set_cursor (const SGPropertyNode * arg)
1227 if (arg->hasValue("x") || arg->hasValue("y")) {
1228 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1229 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1230 int x = arg->getIntValue("x", mx->getIntValue());
1231 int y = arg->getIntValue("y", my->getIntValue());
1237 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1238 if (cursor->getType() != simgear::props::NONE)
1239 fgSetMouseCursor(cursor->getIntValue());
1241 cursor->setIntValue(fgGetMouseCursor());
1247 * Built-in command: play an audio message (i.e. a wav file) This is
1248 * fire and forget. Call this once per message and it will get dumped
1249 * into a queue. Messages are played sequentially so they do not
1253 do_play_audio_sample (const SGPropertyNode * arg)
1255 string path = arg->getStringValue("path");
1256 string file = arg->getStringValue("file");
1257 float volume = arg->getFloatValue("volume");
1258 // cout << "playing " << path << " / " << file << endl;
1260 static FGSampleQueue *queue = 0;
1262 SGSoundMgr *smgr = globals->get_soundmgr();
1263 queue = new FGSampleQueue(smgr, "queue");
1264 queue->tie_to_listener();
1267 SGSoundSample *msg = new SGSoundSample(path.c_str(), file.c_str());
1268 msg->set_volume( volume );
1273 } catch (const sg_io_exception&) {
1274 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1275 "failed to load" << path << '/' << file);
1281 * Built-in command: commit presets (read from in /sim/presets/)
1284 do_presets_commit (const SGPropertyNode * arg)
1286 // unbind the current fdm state so property changes
1287 // don't get lost when we subsequently delete this fdm
1288 // and create a new one.
1289 cur_fdm_state->unbind();
1291 // set position from presets
1294 fgReInitSubsystems();
1296 globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
1299 if ( ! fgGetBool("/sim/presets/onground") ) {
1300 fgSetBool( "/sim/freeze/master", true );
1301 fgSetBool( "/sim/freeze/clock", true );
1309 * Built-in command: set log level (0 ... 7)
1312 do_log_level (const SGPropertyNode * arg)
1314 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1320 * Built-in command: replay the FDR buffer
1323 do_replay (const SGPropertyNode * arg)
1325 // freeze the master fdm
1326 fgSetInt( "/sim/freeze/replay-state", 1 );
1328 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
1330 fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
1331 fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
1332 double duration = fgGetDouble( "/sim/replay/duration" );
1333 if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
1334 fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
1336 fgSetDouble( "/sim/replay/time", r->get_start_time() );
1339 // cout << "start = " << r->get_start_time()
1340 // << " end = " << r->get_end_time() << endl;
1347 do_decrease_visibility (const SGPropertyNode * arg)
1349 double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
1350 fgSetDouble("/environment/visibility-m", new_value);
1351 fgDefaultWeatherValue("visibility-m", new_value);
1352 globals->get_subsystem("environment")->reinit();
1358 do_increase_visibility (const SGPropertyNode * arg)
1360 double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1361 fgSetDouble("/environment/visibility-m", new_value);
1362 fgDefaultWeatherValue("visibility-m", new_value);
1363 globals->get_subsystem("environment")->reinit();
1369 do_hud_init(const SGPropertyNode *)
1371 fgHUDInit(0); // minimal HUD
1376 do_hud_init2(const SGPropertyNode *)
1378 fgHUDInit2(0); // normal HUD
1384 * An fgcommand to allow loading of xml files via nasal,
1385 * the xml file's structure will be made available within
1386 * a property tree node defined under argument "targetnode",
1387 * or in the given argument tree under "data" otherwise.
1389 * @param filename a string to hold the complete path & filename of an XML file
1390 * @param targetnode a string pointing to a location within the property tree
1391 * where to store the parsed XML file. If <targetnode> is undefined, then the
1392 * file contents are stored under a node <data> in the argument tree.
1396 do_load_xml_to_proptree(const SGPropertyNode * arg)
1398 SGPath file(arg->getStringValue("filename"));
1399 if (file.str().empty())
1402 if (file.extension() != "xml")
1403 file.concat(".xml");
1405 if (!fgValidatePath(file.c_str(), false)) {
1406 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1407 "(unauthorized access)");
1411 SGPropertyNode *targetnode;
1412 if (arg->hasValue("targetnode"))
1413 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1415 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1418 readProperties(file.c_str(), targetnode, true);
1419 } catch (const sg_exception &e) {
1420 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1429 * An fgcommand to allow saving of xml files via nasal,
1430 * the file's structure will be determined based on what's
1431 * encountered in the passed (source) property tree node
1433 * @param filename a string to hold the complete path & filename of the (new)
1435 * @param sourcenode a string pointing to a location within the property tree
1436 * where to find the nodes that should be written recursively into an XML file
1437 * @param data if no sourcenode is given, then the file contents are taken from
1438 * the argument tree's "data" node.
1442 do_save_xml_from_proptree(const SGPropertyNode * arg)
1444 SGPath file(arg->getStringValue("filename"));
1445 if (file.str().empty())
1448 if (file.extension() != "xml")
1449 file.concat(".xml");
1451 if (!fgValidatePath(file.c_str(), true)) {
1452 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1453 "(unauthorized access)");
1457 SGPropertyNode *sourcenode;
1458 if (arg->hasValue("sourcenode"))
1459 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1460 else if (arg->getNode("data", false))
1461 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1466 writeProperties (file.c_str(), sourcenode, true);
1467 } catch (const sg_exception &e) {
1468 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1476 do_press_cockpit_button (const SGPropertyNode *arg)
1478 const char *prefix = arg->getStringValue("prefix");
1480 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1483 string prop = string(prefix) + "-button";
1486 if (arg->getBoolValue("latching"))
1487 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1491 fgSetDouble(prop.c_str(), value);
1492 fgSetBool(arg->getStringValue("discrete"), value > 0);
1498 do_release_cockpit_button (const SGPropertyNode *arg)
1500 const char *prefix = arg->getStringValue("prefix");
1502 if (arg->getBoolValue("guarded")) {
1503 string prop = string(prefix) + "-guard";
1504 if (fgGetDouble(prop.c_str()) < 1) {
1505 fgSetDouble(prop.c_str(), 1);
1510 if (! arg->getBoolValue("latching")) {
1511 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1512 fgSetBool(arg->getStringValue("discrete"), false);
1519 ////////////////////////////////////////////////////////////////////////
1521 ////////////////////////////////////////////////////////////////////////
1525 * Table of built-in commands.
1527 * New commands do not have to be added here; any module in the application
1528 * can add a new command using globals->get_commands()->addCommand(...).
1532 SGCommandMgr::command_t command;
1534 { "null", do_null },
1535 { "nasal", do_nasal },
1536 { "exit", do_exit },
1537 { "reset", do_reset },
1538 { "reinit", do_reinit },
1539 { "suspend", do_reinit },
1540 { "resume", do_reinit },
1541 { "load", do_load },
1542 { "save", do_save },
1543 { "panel-load", do_panel_load },
1544 { "panel-mouse-click", do_panel_mouse_click },
1545 { "preferences-load", do_preferences_load },
1546 { "view-cycle", do_view_cycle },
1547 { "screen-capture", do_screen_capture },
1548 { "hires-screen-capture", do_hires_screen_capture },
1549 { "tile-cache-reload", do_tile_cache_reload },
1550 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1551 { "set-outside-air-temp-degc", do_set_oat_degc },
1552 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1553 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1554 { "timeofday", do_timeofday },
1555 { "property-toggle", do_property_toggle },
1556 { "property-assign", do_property_assign },
1557 { "property-adjust", do_property_adjust },
1558 { "property-multiply", do_property_multiply },
1559 { "property-swap", do_property_swap },
1560 { "property-scale", do_property_scale },
1561 { "property-cycle", do_property_cycle },
1562 { "property-randomize", do_property_randomize },
1563 { "data-logging-commit", do_data_logging_commit },
1564 { "dialog-new", do_dialog_new },
1565 { "dialog-show", do_dialog_show },
1566 { "dialog-close", do_dialog_close },
1567 { "dialog-update", do_dialog_update },
1568 { "dialog-apply", do_dialog_apply },
1569 { "gui-redraw", do_gui_redraw },
1570 { "add-model", do_add_model },
1571 { "set-cursor", do_set_cursor },
1572 { "play-audio-sample", do_play_audio_sample },
1573 { "presets-commit", do_presets_commit },
1574 { "log-level", do_log_level },
1575 { "replay", do_replay },
1576 { "decrease-visibility", do_decrease_visibility },
1577 { "increase-visibility", do_increase_visibility },
1578 { "hud-init", do_hud_init },
1579 { "hud-init2", do_hud_init2 },
1580 { "loadxml", do_load_xml_to_proptree},
1581 { "savexml", do_save_xml_from_proptree },
1582 { "press-cockpit-button", do_press_cockpit_button },
1583 { "release-cockpit-button", do_release_cockpit_button },
1584 { "dump-scenegraph", do_dump_scene_graph },
1585 { "dump-terrainbranch", do_dump_terrain_branch },
1586 { "reload-shaders", do_reload_shaders },
1587 { 0, 0 } // zero-terminated
1592 * Initialize the default built-in commands.
1594 * Other commands may be added by other parts of the application.
1599 SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1600 for (int i = 0; built_ins[i].name != 0; i++) {
1601 SG_LOG(SG_GENERAL, SG_INFO, " " << built_ins[i].name);
1602 globals->get_commands()->addCommand(built_ins[i].name,
1603 built_ins[i].command);
1606 typedef bool (*dummy)();
1607 fgTie( "/command/view/next", dummy(0), do_view_next );
1608 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1611 // end of fg_commands.cxx