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/structure/exception.hxx>
19 #include <simgear/structure/commands.hxx>
20 #include <simgear/props/props.hxx>
21 #include <simgear/structure/event_mgr.hxx>
23 #include <Cockpit/panel.hxx>
24 #include <Cockpit/panel_io.hxx>
25 #include <Cockpit/hud.hxx>
26 #include <Environment/environment.hxx>
27 #include <FDM/flight.hxx>
29 #include <GUI/new_gui.hxx>
30 #include <GUI/dialog.hxx>
31 #include <Aircraft/replay.hxx>
32 #include <Scenery/tilemgr.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Scripting/NasalSys.hxx>
35 #include <Sound/fg_fx.hxx>
36 #include <Time/sunsolver.hxx>
37 #include <Time/tmp.hxx>
39 #include "fg_init.hxx"
41 #include "fg_commands.hxx"
42 #include "fg_props.hxx"
43 #include "globals.hxx"
46 #include "viewmgr.hxx"
55 ////////////////////////////////////////////////////////////////////////
56 // Static helper functions.
57 ////////////////////////////////////////////////////////////////////////
60 static inline SGPropertyNode *
61 get_prop (const SGPropertyNode * arg)
63 return fgGetNode(arg->getStringValue("property[0]", "/null"), true);
66 static inline SGPropertyNode *
67 get_prop2 (const SGPropertyNode * arg)
69 return fgGetNode(arg->getStringValue("property[1]", "/null"), true);
74 * Get a double value and split it as required.
77 split_value (double full_value, const char * mask,
78 double * unmodifiable, double * modifiable)
80 if (!strcmp("integer", mask)) {
81 *modifiable = (full_value < 0 ? ceil(full_value) : floor (full_value));
82 *unmodifiable = full_value - *modifiable;
83 } else if (!strcmp("decimal", mask)) {
84 *unmodifiable = (full_value < 0 ? ceil(full_value) : floor(full_value));
85 *modifiable = full_value - *unmodifiable;
87 if (strcmp("all", mask))
88 SG_LOG(SG_GENERAL, SG_ALERT, "Bad value " << mask << " for mask;"
89 << " assuming 'all'");
91 *modifiable = full_value;
97 * Clamp or wrap a value as specified.
100 limit_value (double * value, const SGPropertyNode * arg)
102 const SGPropertyNode * min_node = arg->getChild("min");
103 const SGPropertyNode * max_node = arg->getChild("max");
105 bool wrap = arg->getBoolValue("wrap");
107 if (min_node == 0 || max_node == 0)
110 if (wrap) { // wrap such that min <= x < max
111 double min_val = min_node->getDoubleValue();
112 double max_val = max_node->getDoubleValue();
113 double resolution = arg->getDoubleValue("resolution");
114 if (resolution > 0.0) {
115 // snap to (min + N*resolution), taking special care to handle imprecision
116 int n = (int)floor((*value - min_val) / resolution + 0.5);
117 int steps = (int)floor((max_val - min_val) / resolution + 0.5);
118 SG_NORMALIZE_RANGE(n, 0, steps);
119 *value = min_val + resolution * n;
121 // plain circular wrapping
122 SG_NORMALIZE_RANGE(*value, min_val, max_val);
124 } else { // clamp such that min <= x <= max
125 if ((min_node != 0) && (*value < min_node->getDoubleValue()))
126 *value = min_node->getDoubleValue();
127 else if ((max_node != 0) && (*value > max_node->getDoubleValue()))
128 *value = max_node->getDoubleValue();
133 compare_values (SGPropertyNode * value1, SGPropertyNode * value2)
135 switch (value1->getType()) {
136 case SGPropertyNode::BOOL:
137 return (value1->getBoolValue() == value2->getBoolValue());
138 case SGPropertyNode::INT:
139 return (value1->getIntValue() == value2->getIntValue());
140 case SGPropertyNode::LONG:
141 return (value1->getLongValue() == value2->getLongValue());
142 case SGPropertyNode::FLOAT:
143 return (value1->getFloatValue() == value2->getFloatValue());
144 case SGPropertyNode::DOUBLE:
145 return (value1->getDoubleValue() == value2->getDoubleValue());
147 return !strcmp(value1->getStringValue(), value2->getStringValue());
153 ////////////////////////////////////////////////////////////////////////
154 // Command implementations.
155 ////////////////////////////////////////////////////////////////////////
159 * Built-in command: do nothing.
162 do_null (const SGPropertyNode * arg)
168 * Built-in command: run a Nasal script.
171 do_nasal (const SGPropertyNode * arg)
173 return ((FGNasalSys*)globals->get_subsystem("nasal"))->handleCommand(arg);
177 * Built-in command: exit FlightGear.
179 * status: the exit status to return to the operating system (defaults to 0)
182 do_exit (const SGPropertyNode * arg)
184 SG_LOG(SG_INPUT, SG_INFO, "Program exit requested.");
185 fgSetBool("/sim/signals/exit", true);
187 if (fgGetBool("/sim/startup/save-on-exit")) {
189 char* envp = ::getenv( "APPDATA" );
190 if ( envp != NULL ) {
191 SGPath config( envp );
192 config.append( "flightgear.org" );
194 if ( homedir != NULL ) {
195 SGPath config( homedir );
196 config.append( ".fgfs" );
198 config.append( "autosave.xml" );
199 config.create_dir( 0700 );
200 SG_LOG(SG_IO, SG_INFO, "Saving user settings to " << config.str());
202 writeProperties(config.str(), globals->get_props(), false, SGPropertyNode::USERARCHIVE);
203 } catch (const sg_exception &e) {
204 guiErrorMessage("Error writing autosave.xml: ", e);
207 SG_LOG(SG_INPUT, SG_DEBUG, "Finished Saving user settings");
210 fgExit(arg->getIntValue("status", 0));
216 * Reset FlightGear (Shift-Escape or Menu->File->Reset)
219 do_reset (const SGPropertyNode * arg)
227 * Built-in command: reinitialize one or more subsystems.
229 * subsystem[*]: the name(s) of the subsystem(s) to reinitialize; if
230 * none is specified, reinitialize all of them.
233 do_reinit (const SGPropertyNode * arg)
237 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
238 if (subsystems.size() == 0) {
239 globals->get_subsystem_mgr()->reinit();
241 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
242 const char * name = subsystems[i]->getStringValue();
243 SGSubsystem * subsystem = globals->get_subsystem(name);
244 if (subsystem == 0) {
246 SG_LOG( SG_GENERAL, SG_ALERT,
247 "Subsystem " << name << "not found" );
254 globals->get_event_mgr()->reinit();
261 // these routines look useful ??? but are never used in the code ???
265 * Built-in command: suspend one or more subsystems.
267 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
270 do_suspend (const SGPropertyNode * arg)
274 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
275 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
276 const char * name = subsystems[i]->getStringValue();
277 SGSubsystem * subsystem = globals->get_subsystem(name);
278 if (subsystem == 0) {
280 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
282 subsystem->suspend();
289 * Built-in command: suspend one or more subsystems.
291 * subsystem[*] - the name(s) of the subsystem(s) to suspend.
294 do_resume (const SGPropertyNode * arg)
298 vector<SGPropertyNode_ptr> subsystems = arg->getChildren("subsystem");
299 for ( unsigned int i = 0; i < subsystems.size(); i++ ) {
300 const char * name = subsystems[i]->getStringValue();
301 SGSubsystem * subsystem = globals->get_subsystem(name);
302 if (subsystem == 0) {
304 SG_LOG(SG_GENERAL, SG_ALERT, "Subsystem " << name << "not found");
316 * Built-in command: load flight.
318 * file (optional): the name of the file to load (relative to current
319 * directory). Defaults to "fgfs.sav"
322 do_load (const SGPropertyNode * arg)
324 string file = arg->getStringValue("file", "fgfs.sav");
325 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
328 if (!fgValidatePath(file.c_str(), false)) {
329 SG_LOG(SG_IO, SG_ALERT, "load: reading '" << file << "' denied "
330 "(unauthorized access)");
334 ifstream input(file.c_str());
335 if (input.good() && fgLoadFlight(input)) {
337 SG_LOG(SG_INPUT, SG_INFO, "Restored flight from " << file);
340 SG_LOG(SG_INPUT, SG_WARN, "Cannot load flight from " << file);
347 * Built-in command: save flight.
349 * file (optional): the name of the file to save (relative to the
350 * current directory). Defaults to "fgfs.sav".
353 do_save (const SGPropertyNode * arg)
355 string file = arg->getStringValue("file", "fgfs.sav");
356 if (file.size() < 4 || file.substr(file.size() - 4) != ".sav")
359 if (!fgValidatePath(file.c_str(), false)) {
360 SG_LOG(SG_IO, SG_ALERT, "save: reading '" << file << "' denied "
361 "(unauthorized access)");
365 bool write_all = arg->getBoolValue("write-all", false);
366 SG_LOG(SG_INPUT, SG_INFO, "Saving flight");
367 ofstream output(file.c_str());
368 if (output.good() && fgSaveFlight(output, write_all)) {
370 SG_LOG(SG_INPUT, SG_INFO, "Saved flight to " << file);
373 SG_LOG(SG_INPUT, SG_ALERT, "Cannot save flight to " << file);
380 * Built-in command: (re)load the panel.
382 * path (optional): the file name to load the panel from
383 * (relative to FG_ROOT). Defaults to the value of /sim/panel/path,
384 * and if that's unspecified, to "Panels/Default/default.xml".
387 do_panel_load (const SGPropertyNode * arg)
390 arg->getStringValue("path",
391 fgGetString("/sim/panel/path",
392 "Panels/Default/default.xml"));
393 FGPanel * new_panel = fgReadPanel(panel_path);
394 if (new_panel == 0) {
395 SG_LOG(SG_INPUT, SG_ALERT,
396 "Error reading new panel from " << panel_path);
399 SG_LOG(SG_INPUT, SG_INFO, "Loaded new panel from " << panel_path);
400 globals->get_current_panel()->unbind();
401 delete globals->get_current_panel();
402 globals->set_current_panel( new_panel );
403 globals->get_current_panel()->bind();
409 * Built-in command: pass a mouse click to the panel.
411 * button: the mouse button number, zero-based.
412 * is-down: true if the button is down, false if it is up.
413 * x-pos: the x position of the mouse click.
414 * y-pos: the y position of the mouse click.
417 do_panel_mouse_click (const SGPropertyNode * arg)
419 if (globals->get_current_panel() != 0)
420 return globals->get_current_panel()
421 ->doMouseAction(arg->getIntValue("button"),
422 arg->getBoolValue("is-down") ? PU_DOWN : PU_UP,
423 arg->getIntValue("x-pos"),
424 arg->getIntValue("y-pos"));
431 * Built-in command: (re)load preferences.
433 * path (optional): the file name to load the panel from (relative
434 * to FG_ROOT). Defaults to "preferences.xml".
437 do_preferences_load (const SGPropertyNode * arg)
440 fgLoadProps(arg->getStringValue("path", "preferences.xml"),
441 globals->get_props());
442 } catch (const sg_exception &e) {
443 guiErrorMessage("Error reading global preferences: ", e);
446 SG_LOG(SG_INPUT, SG_INFO, "Successfully read global preferences.");
454 if ( !strcmp(fgGetString("/sim/flight-model"), "ada") ) {
455 globals->get_props()->setBoolValue( "/sim/hud/visibility", true );
456 if ( globals->get_viewmgr()->get_current() == 1 ) {
457 globals->get_props()->setBoolValue( "/sim/hud/visibility", false );
465 globals->get_current_view()->setHeadingOffset_deg(0.0);
466 globals->get_viewmgr()->next_view();
467 fix_hud_visibility();
473 globals->get_current_view()->setHeadingOffset_deg(0.0);
474 globals->get_viewmgr()->prev_view();
475 fix_hud_visibility();
479 * Built-in command: cycle view.
482 do_view_cycle (const SGPropertyNode * arg)
484 globals->get_current_view()->setHeadingOffset_deg(0.0);
485 globals->get_viewmgr()->next_view();
486 fix_hud_visibility();
491 * Built-in command: capture screen.
494 do_screen_capture (const SGPropertyNode * arg)
496 return fgDumpSnapShot();
500 do_dump_scene_graph (const SGPropertyNode*)
507 do_dump_terrain_branch (const SGPropertyNode*)
509 fgDumpTerrainBranch();
511 double lon_deg = fgGetDouble("/position/longitude-deg");
512 double lat_deg = fgGetDouble("/position/latitude-deg");
513 SGGeod geodPos = SGGeod::fromDegFt(lon_deg, lat_deg, 0.0);
514 SGVec3d zero = SGVec3d::fromGeod(geodPos);
516 SG_LOG(SG_INPUT, SG_INFO, "Model parameters:");
517 SG_LOG(SG_INPUT, SG_INFO, "Center: " << zero.x() << ", " << zero.y() << ", " << zero.z() );
518 SG_LOG(SG_INPUT, SG_INFO, "Rotation: " << lat_deg << ", " << lon_deg );
524 * Built-in command: hires capture screen.
527 do_hires_screen_capture (const SGPropertyNode * arg)
535 * Reload the tile cache.
538 do_tile_cache_reload (const SGPropertyNode * arg)
540 static const SGPropertyNode *master_freeze
541 = fgGetNode("/sim/freeze/master");
542 bool freeze = master_freeze->getBoolValue();
543 SG_LOG(SG_INPUT, SG_INFO, "ReIniting TileCache");
545 fgSetBool("/sim/freeze/master", true);
547 if ( globals->get_tile_mgr()->init() ) {
548 // Load the local scenery data
549 double visibility_meters = fgGetDouble("/environment/visibility-m");
550 globals->get_tile_mgr()->update( visibility_meters );
552 SG_LOG( SG_GENERAL, SG_ALERT,
553 "Error in Tile Manager initialization!" );
557 fgSetBool("/sim/freeze/master", false);
564 * Set the sea level outside air temperature and assigning that to all
565 * boundary and aloft environment layers.
568 do_set_sea_level_degc (const SGPropertyNode * arg)
570 double temp_sea_level_degc = arg->getDoubleValue("temp-degc", 15.0);
572 SGPropertyNode *node, *child;
575 node = fgGetNode( "/environment/config/boundary" );
576 if ( node != NULL ) {
578 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
579 child->setDoubleValue( "temperature-sea-level-degc",
580 temp_sea_level_degc );
586 node = fgGetNode( "/environment/config/aloft" );
587 if ( node != NULL ) {
589 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
590 child->setDoubleValue( "temperature-sea-level-degc",
591 temp_sea_level_degc );
601 * Set the outside air temperature at the "current" altitude by first
602 * calculating the corresponding sea level temp, and assigning that to
603 * all boundary and aloft environment layers.
606 do_set_oat_degc (const SGPropertyNode * arg)
608 const string &temp_str = arg->getStringValue("temp-degc", "15.0");
610 // check for an altitude specified in the arguments, otherwise use
611 // current aircraft altitude.
612 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
613 if ( altitude_ft == NULL ) {
614 altitude_ft = fgGetNode("/position/altitude-ft");
617 FGEnvironment dummy; // instantiate a dummy so we can leech a method
618 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
619 dummy.set_temperature_degc( atof( temp_str.c_str() ) );
620 double temp_sea_level_degc = dummy.get_temperature_sea_level_degc();
622 //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
623 //cout << "Temp at alt (C) = " << atof( temp_str.c_str() ) << endl;
624 //cout << "Temp sea level (C) = " << temp_sea_level_degc << endl;
626 SGPropertyNode *node, *child;
629 node = fgGetNode( "/environment/config/boundary" );
630 if ( node != NULL ) {
632 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
633 child->setDoubleValue( "temperature-sea-level-degc",
634 temp_sea_level_degc );
640 node = fgGetNode( "/environment/config/aloft" );
641 if ( node != NULL ) {
643 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
644 child->setDoubleValue( "temperature-sea-level-degc",
645 temp_sea_level_degc );
654 * Set the sea level outside air dewpoint and assigning that to all
655 * boundary and aloft environment layers.
658 do_set_dewpoint_sea_level_degc (const SGPropertyNode * arg)
660 double dewpoint_sea_level_degc = arg->getDoubleValue("dewpoint-degc", 5.0);
662 SGPropertyNode *node, *child;
665 node = fgGetNode( "/environment/config/boundary" );
666 if ( node != NULL ) {
668 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
669 child->setDoubleValue( "dewpoint-sea-level-degc",
670 dewpoint_sea_level_degc );
676 node = fgGetNode( "/environment/config/aloft" );
677 if ( node != NULL ) {
679 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
680 child->setDoubleValue( "dewpoint-sea-level-degc",
681 dewpoint_sea_level_degc );
691 * Set the outside air dewpoint at the "current" altitude by first
692 * calculating the corresponding sea level dewpoint, and assigning
693 * that to all boundary and aloft environment layers.
696 do_set_dewpoint_degc (const SGPropertyNode * arg)
698 const string &dewpoint_str = arg->getStringValue("dewpoint-degc", "5.0");
700 // check for an altitude specified in the arguments, otherwise use
701 // current aircraft altitude.
702 const SGPropertyNode *altitude_ft = arg->getChild("altitude-ft");
703 if ( altitude_ft == NULL ) {
704 altitude_ft = fgGetNode("/position/altitude-ft");
707 FGEnvironment dummy; // instantiate a dummy so we can leech a method
708 dummy.set_elevation_ft( altitude_ft->getDoubleValue() );
709 dummy.set_dewpoint_degc( atof( dewpoint_str.c_str() ) );
710 double dewpoint_sea_level_degc = dummy.get_dewpoint_sea_level_degc();
712 //cout << "Altitude = " << altitude_ft->getDoubleValue() << endl;
713 //cout << "Dewpoint at alt (C) = " << atof( dewpoint_str.c_str() ) << endl;
714 //cout << "Dewpoint at sea level (C) = " << dewpoint_sea_level_degc << endl;
716 SGPropertyNode *node, *child;
719 node = fgGetNode( "/environment/config/boundary" );
720 if ( node != NULL ) {
722 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
723 child->setDoubleValue( "dewpoint-sea-level-degc",
724 dewpoint_sea_level_degc );
730 node = fgGetNode( "/environment/config/aloft" );
731 if ( node != NULL ) {
733 while ( ( child = node->getNode( "entry", i ) ) != NULL ) {
734 child->setDoubleValue( "dewpoint-sea-level-degc",
735 dewpoint_sea_level_degc );
744 * Update the lighting manually.
747 do_timeofday (const SGPropertyNode * arg)
749 const string &offset_type = arg->getStringValue("timeofday", "noon");
751 static const SGPropertyNode *longitude
752 = fgGetNode("/position/longitude-deg");
753 static const SGPropertyNode *latitude
754 = fgGetNode("/position/latitude-deg");
755 static const SGPropertyNode *cur_time_override
756 = fgGetNode("/sim/time/cur-time-override", true);
758 int orig_warp = globals->get_warp();
759 SGTime *t = globals->get_time_params();
760 time_t cur_time = t->get_cur_time();
761 // cout << "cur_time = " << cur_time << endl;
762 // cout << "orig_warp = " << orig_warp << endl;
765 if ( offset_type == "real" ) {
767 } else if ( offset_type == "dawn" ) {
768 warp = fgTimeSecondsUntilSunAngle( cur_time,
769 longitude->getDoubleValue()
770 * SGD_DEGREES_TO_RADIANS,
771 latitude->getDoubleValue()
772 * SGD_DEGREES_TO_RADIANS,
774 } else if ( offset_type == "morning" ) {
775 warp = fgTimeSecondsUntilSunAngle( cur_time,
776 longitude->getDoubleValue()
777 * SGD_DEGREES_TO_RADIANS,
778 latitude->getDoubleValue()
779 * SGD_DEGREES_TO_RADIANS,
781 } else if ( offset_type == "noon" ) {
782 warp = fgTimeSecondsUntilSunAngle( cur_time,
783 longitude->getDoubleValue()
784 * SGD_DEGREES_TO_RADIANS,
785 latitude->getDoubleValue()
786 * SGD_DEGREES_TO_RADIANS,
788 } else if ( offset_type == "afternoon" ) {
789 warp = fgTimeSecondsUntilSunAngle( cur_time,
790 longitude->getDoubleValue()
791 * SGD_DEGREES_TO_RADIANS,
792 latitude->getDoubleValue()
793 * SGD_DEGREES_TO_RADIANS,
795 } else if ( offset_type == "dusk" ) {
796 warp = fgTimeSecondsUntilSunAngle( cur_time,
797 longitude->getDoubleValue()
798 * SGD_DEGREES_TO_RADIANS,
799 latitude->getDoubleValue()
800 * SGD_DEGREES_TO_RADIANS,
802 } else if ( offset_type == "evening" ) {
803 warp = fgTimeSecondsUntilSunAngle( cur_time,
804 longitude->getDoubleValue()
805 * SGD_DEGREES_TO_RADIANS,
806 latitude->getDoubleValue()
807 * SGD_DEGREES_TO_RADIANS,
809 } else if ( offset_type == "midnight" ) {
810 warp = fgTimeSecondsUntilSunAngle( cur_time,
811 longitude->getDoubleValue()
812 * SGD_DEGREES_TO_RADIANS,
813 latitude->getDoubleValue()
814 * SGD_DEGREES_TO_RADIANS,
817 // cout << "warp = " << warp << endl;
818 globals->set_warp( orig_warp + warp );
820 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
821 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
822 cur_time_override->getLongValue(),
823 globals->get_warp() );
830 * Built-in command: toggle a bool property value.
832 * property: The name of the property to toggle.
835 do_property_toggle (const SGPropertyNode * arg)
837 SGPropertyNode * prop = get_prop(arg);
838 return prop->setBoolValue(!prop->getBoolValue());
843 * Built-in command: assign a value to a property.
845 * property: the name of the property to assign.
846 * value: the value to assign; or
847 * property[1]: the property to copy from.
850 do_property_assign (const SGPropertyNode * arg)
852 SGPropertyNode * prop = get_prop(arg);
853 const SGPropertyNode * prop2 = get_prop2(arg);
854 const SGPropertyNode * value = arg->getNode("value");
857 return prop->setUnspecifiedValue(value->getStringValue());
859 return prop->setUnspecifiedValue(prop2->getStringValue());
866 * Built-in command: increment or decrement a property value.
868 * If the 'step' argument is present, it will be used; otherwise,
869 * the command uses 'offset' and 'factor', usually from the mouse.
871 * property: the name of the property to increment or decrement.
872 * step: the amount of the increment or decrement (default: 0).
873 * offset: offset from the current setting (used for the mouse; multiplied
875 * factor: scaling amount for the offset (defaults to 1).
876 * min: the minimum allowed value (default: no minimum).
877 * max: the maximum allowed value (default: no maximum).
878 * mask: 'integer' to apply only to the left of the decimal point,
879 * 'decimal' to apply only to the right of the decimal point,
880 * or 'all' to apply to the whole number (the default).
881 * wrap: true if the value should be wrapped when it passes min or max;
882 * both min and max must be present for this to work (default:
886 do_property_adjust (const SGPropertyNode * arg)
888 SGPropertyNode * prop = get_prop(arg);
891 if (arg->hasValue("step"))
892 amount = arg->getDoubleValue("step");
894 amount = (arg->getDoubleValue("factor", 1)
895 * arg->getDoubleValue("offset"));
897 double unmodifiable, modifiable;
898 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
899 &unmodifiable, &modifiable);
900 modifiable += amount;
901 limit_value(&modifiable, arg);
903 prop->setDoubleValue(unmodifiable + modifiable);
910 * Built-in command: multiply a property value.
912 * property: the name of the property to multiply.
913 * factor: the amount by which to multiply.
914 * min: the minimum allowed value (default: no minimum).
915 * max: the maximum allowed value (default: no maximum).
916 * mask: 'integer' to apply only to the left of the decimal point,
917 * 'decimal' to apply only to the right of the decimal point,
918 * or 'all' to apply to the whole number (the default).
919 * wrap: true if the value should be wrapped when it passes min or max;
920 * both min and max must be present for this to work (default:
924 do_property_multiply (const SGPropertyNode * arg)
926 SGPropertyNode * prop = get_prop(arg);
927 double factor = arg->getDoubleValue("factor", 1);
929 double unmodifiable, modifiable;
930 split_value(prop->getDoubleValue(), arg->getStringValue("mask", "all"),
931 &unmodifiable, &modifiable);
932 modifiable *= factor;
933 limit_value(&modifiable, arg);
935 prop->setDoubleValue(unmodifiable + modifiable);
942 * Built-in command: swap two property values.
944 * property[0]: the name of the first property.
945 * property[1]: the name of the second property.
948 do_property_swap (const SGPropertyNode * arg)
950 SGPropertyNode * prop1 = get_prop(arg);
951 SGPropertyNode * prop2 = get_prop2(arg);
953 // FIXME: inefficient
954 const string & tmp = prop1->getStringValue();
955 return (prop1->setUnspecifiedValue(prop2->getStringValue()) &&
956 prop2->setUnspecifiedValue(tmp.c_str()));
961 * Built-in command: Set a property to an axis or other moving input.
963 * property: the name of the property to set.
964 * setting: the current input setting, usually between -1.0 and 1.0.
965 * offset: the offset to shift by, before applying the factor.
966 * factor: the factor to multiply by (use negative to reverse).
969 do_property_scale (const SGPropertyNode * arg)
971 SGPropertyNode * prop = get_prop(arg);
972 double setting = arg->getDoubleValue("setting");
973 double offset = arg->getDoubleValue("offset", 0.0);
974 double factor = arg->getDoubleValue("factor", 1.0);
975 bool squared = arg->getBoolValue("squared", false);
976 int power = arg->getIntValue("power", (squared ? 2 : 1));
978 int sign = (setting < 0 ? -1 : 1);
984 setting = setting * setting * sign;
987 setting = setting * setting * setting;
990 setting = setting * setting * setting * setting * sign;
993 setting = pow(setting, power);
994 if ((power % 2) == 0)
999 return prop->setDoubleValue((setting + offset) * factor);
1004 * Built-in command: cycle a property through a set of values.
1006 * If the current value isn't in the list, the cycle will
1007 * (re)start from the beginning.
1009 * property: the name of the property to cycle.
1010 * value[*]: the list of values to cycle through.
1013 do_property_cycle (const SGPropertyNode * arg)
1015 SGPropertyNode * prop = get_prop(arg);
1016 vector<SGPropertyNode_ptr> values = arg->getChildren("value");
1018 int nSelections = values.size();
1020 if (nSelections < 1) {
1021 SG_LOG(SG_GENERAL, SG_ALERT, "No values for property-cycle");
1025 // Try to find the current selection
1026 for (int i = 0; i < nSelections; i++) {
1027 if (compare_values(prop, values[i])) {
1033 // Default or wrap to the first selection
1034 if (selection < 0 || selection >= nSelections)
1037 prop->setUnspecifiedValue(values[selection]->getStringValue());
1043 * Built-in command: randomize a numeric property value.
1045 * property: the name of the property value to randomize.
1046 * min: the minimum allowed value.
1047 * max: the maximum allowed value.
1050 do_property_randomize (const SGPropertyNode * arg)
1052 SGPropertyNode * prop = get_prop(arg);
1053 double min = arg->getDoubleValue("min", DBL_MIN);
1054 double max = arg->getDoubleValue("max", DBL_MAX);
1055 prop->setDoubleValue(sg_random() * (max - min) + min);
1061 * Built-in command: reinit the data logging system based on the
1062 * current contents of the /logger tree.
1065 do_data_logging_commit (const SGPropertyNode * arg)
1067 FGLogger *log = (FGLogger *)globals->get_subsystem("logger");
1073 * Built-in command: Add a dialog to the GUI system. Does *not*
1074 * display the dialog. The property node should have the same format
1075 * as a dialog XML configuration. It must include:
1077 * name: the name of the GUI dialog for future reference.
1080 do_dialog_new (const SGPropertyNode * arg)
1082 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1084 // Note the casting away of const: this is *real*. Doing a
1085 // "dialog-apply" command later on will mutate this property node.
1086 // I'm not convinced that this isn't the Right Thing though; it
1087 // allows client to create a node, pass it to dialog-new, and get
1088 // the values back from the dialog by reading the same node.
1089 // Perhaps command arguments are not as "const" as they would
1091 gui->newDialog((SGPropertyNode*)arg);
1096 * Built-in command: Show an XML-configured dialog.
1098 * dialog-name: the name of the GUI dialog to display.
1101 do_dialog_show (const SGPropertyNode * arg)
1103 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1104 gui->showDialog(arg->getStringValue("dialog-name"));
1110 * Built-in Command: Hide the active XML-configured dialog.
1113 do_dialog_close (const SGPropertyNode * arg)
1115 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1116 if(arg->hasValue("dialog-name"))
1117 return gui->closeDialog(arg->getStringValue("dialog-name"));
1118 return gui->closeActiveDialog();
1123 * Update a value in the active XML-configured dialog.
1125 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1128 do_dialog_update (const SGPropertyNode * arg)
1130 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1132 if (arg->hasValue("dialog-name"))
1133 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1135 dialog = gui->getActiveDialog();
1138 dialog->updateValues(arg->getStringValue("object-name"));
1147 * Apply a value in the active XML-configured dialog.
1149 * object-name: The name of the GUI object(s) (all GUI objects if omitted).
1152 do_dialog_apply (const SGPropertyNode * arg)
1154 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1156 if (arg->hasValue("dialog-name"))
1157 dialog = gui->getDialog(arg->getStringValue("dialog-name"));
1159 dialog = gui->getActiveDialog();
1162 dialog->applyValues(arg->getStringValue("object-name"));
1171 * Redraw GUI (applying new widget colors). Doesn't reload the dialogs,
1175 do_gui_redraw (const SGPropertyNode * arg)
1177 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
1184 * Set mouse cursor coordinates and cursor shape.
1187 do_set_cursor (const SGPropertyNode * arg)
1189 if (arg->hasValue("x") || arg->hasValue("y")) {
1190 SGPropertyNode *mx = fgGetNode("/devices/status/mice/mouse/x", true);
1191 SGPropertyNode *my = fgGetNode("/devices/status/mice/mouse/y", true);
1192 int x = arg->getIntValue("x", mx->getIntValue());
1193 int y = arg->getIntValue("y", my->getIntValue());
1199 SGPropertyNode *cursor = const_cast<SGPropertyNode *>(arg)->getNode("cursor", true);
1200 if (cursor->getType() != SGPropertyNode::NONE)
1201 fgSetMouseCursor(cursor->getIntValue());
1203 cursor->setIntValue(fgGetMouseCursor());
1209 * Built-in command: play an audio message (i.e. a wav file) This is
1210 * fire and forget. Call this once per message and it will get dumped
1211 * into a queue. Messages are played sequentially so they do not
1215 do_play_audio_sample (const SGPropertyNode * arg)
1217 FGFX *fx = (FGFX *)globals->get_subsystem("fx");
1218 string path = arg->getStringValue("path");
1219 string file = arg->getStringValue("file");
1220 double volume = arg->getDoubleValue("volume");
1221 // cout << "playing " << path << " / " << file << endl;
1223 fx->play_message( path, file, volume );
1226 } catch (const sg_io_exception& e) {
1227 SG_LOG(SG_GENERAL, SG_ALERT, "play-audio-sample: "
1228 "failed to load" << path << '/' << file);
1234 * Built-in command: commit presets (read from in /sim/presets/)
1237 do_presets_commit (const SGPropertyNode * arg)
1239 // unbind the current fdm state so property changes
1240 // don't get lost when we subsequently delete this fdm
1241 // and create a new one.
1242 cur_fdm_state->unbind();
1244 // set position from presets
1247 fgReInitSubsystems();
1249 globals->get_tile_mgr()->update( fgGetDouble("/environment/visibility-m") );
1252 if ( ! fgGetBool("/sim/presets/onground") ) {
1253 fgSetBool( "/sim/freeze/master", true );
1254 fgSetBool( "/sim/freeze/clock", true );
1262 * Built-in command: set log level (0 ... 7)
1265 do_log_level (const SGPropertyNode * arg)
1267 sglog().setLogLevels( SG_ALL, (sgDebugPriority)arg->getIntValue() );
1273 * Built-in command: replay the FDR buffer
1276 do_replay (const SGPropertyNode * arg)
1278 // freeze the master fdm
1279 fgSetInt( "/sim/freeze/replay-state", 1 );
1281 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
1283 fgSetDouble( "/sim/replay/start-time", r->get_start_time() );
1284 fgSetDouble( "/sim/replay/end-time", r->get_end_time() );
1285 double duration = fgGetDouble( "/sim/replay/duration" );
1286 if( duration && duration < (r->get_end_time() - r->get_start_time()) ) {
1287 fgSetDouble( "/sim/replay/time", r->get_end_time() - duration );
1289 fgSetDouble( "/sim/replay/time", r->get_start_time() );
1292 // cout << "start = " << r->get_start_time()
1293 // << " end = " << r->get_end_time() << endl;
1300 do_decrease_visibility (const SGPropertyNode * arg)
1302 double new_value = fgGetDouble("/environment/visibility-m") * 0.9;
1303 fgSetDouble("/environment/visibility-m", new_value);
1304 fgDefaultWeatherValue("visibility-m", new_value);
1305 globals->get_subsystem("environment")->reinit();
1311 do_increase_visibility (const SGPropertyNode * arg)
1313 double new_value = fgGetDouble("/environment/visibility-m") * 1.1;
1314 fgSetDouble("/environment/visibility-m", new_value);
1315 fgDefaultWeatherValue("visibility-m", new_value);
1316 globals->get_subsystem("environment")->reinit();
1322 do_hud_init(const SGPropertyNode *)
1324 fgHUDInit(0); // minimal HUD
1329 do_hud_init2(const SGPropertyNode *)
1331 fgHUDInit2(0); // normal HUD
1337 * An fgcommand to allow loading of xml files via nasal,
1338 * the xml file's structure will be made available within
1339 * a property tree node defined under argument "targetnode",
1340 * or in the given argument tree under "data" otherwise.
1342 * @param filename a string to hold the complete path & filename of an XML file
1343 * @param targetnode a string pointing to a location within the property tree
1344 * where to store the parsed XML file. If <targetnode> is undefined, then the
1345 * file contents are stored under a node <data> in the argument tree.
1349 do_load_xml_to_proptree(const SGPropertyNode * arg)
1351 SGPath file(arg->getStringValue("filename"));
1352 if (file.str().empty())
1355 if (file.extension() != "xml")
1356 file.concat(".xml");
1358 if (!fgValidatePath(file.c_str(), false)) {
1359 SG_LOG(SG_IO, SG_ALERT, "loadxml: reading '" << file.str() << "' denied "
1360 "(unauthorized access)");
1364 SGPropertyNode *targetnode;
1365 if (arg->hasValue("targetnode"))
1366 targetnode = fgGetNode(arg->getStringValue("targetnode"), true);
1368 targetnode = const_cast<SGPropertyNode *>(arg)->getNode("data", true);
1371 readProperties(file.c_str(), targetnode, true);
1372 } catch (const sg_exception &e) {
1373 SG_LOG(SG_IO, SG_WARN, "loadxml: " << e.getFormattedMessage());
1382 * An fgcommand to allow saving of xml files via nasal,
1383 * the file's structure will be determined based on what's
1384 * encountered in the passed (source) property tree node
1386 * @param filename a string to hold the complete path & filename of the (new)
1388 * @param sourcenode a string pointing to a location within the property tree
1389 * where to find the nodes that should be written recursively into an XML file
1390 * @param data if no sourcenode is given, then the file contents are taken from
1391 * the argument tree's "data" node.
1395 do_save_xml_from_proptree(const SGPropertyNode * arg)
1397 SGPath file(arg->getStringValue("filename"));
1398 if (file.str().empty())
1401 if (file.extension() != "xml")
1402 file.concat(".xml");
1404 if (!fgValidatePath(file.c_str(), true)) {
1405 SG_LOG(SG_IO, SG_ALERT, "savexml: writing to '" << file.str() << "' denied "
1406 "(unauthorized access)");
1410 SGPropertyNode *sourcenode;
1411 if (arg->hasValue("sourcenode"))
1412 sourcenode = fgGetNode(arg->getStringValue("sourcenode"), true);
1413 else if (arg->getNode("data", false))
1414 sourcenode = const_cast<SGPropertyNode *>(arg)->getNode("data");
1419 writeProperties (file.c_str(), sourcenode, true);
1420 } catch (const sg_exception &e) {
1421 SG_LOG(SG_IO, SG_WARN, "savexml: " << e.getFormattedMessage());
1429 do_press_cockpit_button (const SGPropertyNode *arg)
1431 const char *prefix = arg->getStringValue("prefix");
1433 if (arg->getBoolValue("guarded") && fgGetDouble((string(prefix) + "-guard").c_str()) < 1)
1436 string prop = string(prefix) + "-button";
1439 if (arg->getBoolValue("latching"))
1440 value = fgGetDouble(prop.c_str()) > 0 ? 0 : 1;
1444 fgSetDouble(prop.c_str(), value);
1445 fgSetBool(arg->getStringValue("discrete"), value > 0);
1451 do_release_cockpit_button (const SGPropertyNode *arg)
1453 const char *prefix = arg->getStringValue("prefix");
1455 if (arg->getBoolValue("guarded")) {
1456 string prop = string(prefix) + "-guard";
1457 if (fgGetDouble(prop.c_str()) < 1) {
1458 fgSetDouble(prop.c_str(), 1);
1463 if (! arg->getBoolValue("latching")) {
1464 fgSetDouble((string(prefix) + "-button").c_str(), 0);
1465 fgSetBool(arg->getStringValue("discrete"), false);
1472 ////////////////////////////////////////////////////////////////////////
1474 ////////////////////////////////////////////////////////////////////////
1478 * Table of built-in commands.
1480 * New commands do not have to be added here; any module in the application
1481 * can add a new command using globals->get_commands()->addCommand(...).
1485 SGCommandMgr::command_t command;
1487 { "null", do_null },
1488 { "nasal", do_nasal },
1489 { "exit", do_exit },
1490 { "reset", do_reset },
1491 { "reinit", do_reinit },
1492 { "suspend", do_reinit },
1493 { "resume", do_reinit },
1494 { "load", do_load },
1495 { "save", do_save },
1496 { "panel-load", do_panel_load },
1497 { "panel-mouse-click", do_panel_mouse_click },
1498 { "preferences-load", do_preferences_load },
1499 { "view-cycle", do_view_cycle },
1500 { "screen-capture", do_screen_capture },
1501 { "hires-screen-capture", do_hires_screen_capture },
1502 { "tile-cache-reload", do_tile_cache_reload },
1503 { "set-sea-level-air-temp-degc", do_set_sea_level_degc },
1504 { "set-outside-air-temp-degc", do_set_oat_degc },
1505 { "set-dewpoint-sea-level-air-temp-degc", do_set_dewpoint_sea_level_degc },
1506 { "set-dewpoint-temp-degc", do_set_dewpoint_degc },
1507 { "timeofday", do_timeofday },
1508 { "property-toggle", do_property_toggle },
1509 { "property-assign", do_property_assign },
1510 { "property-adjust", do_property_adjust },
1511 { "property-multiply", do_property_multiply },
1512 { "property-swap", do_property_swap },
1513 { "property-scale", do_property_scale },
1514 { "property-cycle", do_property_cycle },
1515 { "property-randomize", do_property_randomize },
1516 { "data-logging-commit", do_data_logging_commit },
1517 { "dialog-new", do_dialog_new },
1518 { "dialog-show", do_dialog_show },
1519 { "dialog-close", do_dialog_close },
1520 { "dialog-update", do_dialog_update },
1521 { "dialog-apply", do_dialog_apply },
1522 { "gui-redraw", do_gui_redraw },
1523 { "set-cursor", do_set_cursor },
1524 { "play-audio-sample", do_play_audio_sample },
1525 { "presets-commit", do_presets_commit },
1526 { "log-level", do_log_level },
1527 { "replay", do_replay },
1528 { "decrease-visibility", do_decrease_visibility },
1529 { "increase-visibility", do_increase_visibility },
1530 { "hud-init", do_hud_init },
1531 { "hud-init2", do_hud_init2 },
1532 { "loadxml", do_load_xml_to_proptree},
1533 { "savexml", do_save_xml_from_proptree },
1534 { "press-cockpit-button", do_press_cockpit_button },
1535 { "release-cockpit-button", do_release_cockpit_button },
1536 { "dump-scenegraph", do_dump_scene_graph },
1537 { "dump-terrainbranch", do_dump_terrain_branch },
1538 { 0, 0 } // zero-terminated
1543 * Initialize the default built-in commands.
1545 * Other commands may be added by other parts of the application.
1550 SG_LOG(SG_GENERAL, SG_INFO, "Initializing basic built-in commands:");
1551 for (int i = 0; built_ins[i].name != 0; i++) {
1552 SG_LOG(SG_GENERAL, SG_INFO, " " << built_ins[i].name);
1553 globals->get_commands()->addCommand(built_ins[i].name,
1554 built_ins[i].command);
1557 typedef bool (*dummy)();
1558 fgTie( "/command/view/next", dummy(0), do_view_next );
1559 fgTie( "/command/view/prev", dummy(0), do_view_prev );
1562 // end of fg_commands.cxx